dsh-chief 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -34,6 +34,7 @@ import {
34
34
  } from './idle-guard.js'
35
35
  import {
36
36
  loadChiefState,
37
+ resolveWorkspaceConfig,
37
38
  getLinkedCluster,
38
39
  setPeerLink,
39
40
  invalidateChiefModelCatalog,
@@ -45,6 +46,12 @@ import {
45
46
  askOrCommandChief,
46
47
  consolidateBoundsWithChief,
47
48
  organizeArchivesWithChief,
49
+ harvestTurnDetailsToArchive,
50
+ precipitateExperienceWithChief,
51
+ deployChiefWorkspaceState,
52
+ updateWorkspaceFlippedIds,
53
+ maybeRunPreCompaction,
54
+ runTurnReview,
48
55
  proposeBoundToChief,
49
56
  scheduleChiefTurnReview,
50
57
  handleSuggestionDecision,
@@ -54,18 +61,25 @@ import {
54
61
  } from './chief.js'
55
62
  import {
56
63
  bootstrapArchivesFromSharedBoard,
64
+ resolveProjectKey,
65
+ listProjectCabinets,
57
66
  getArchiveMeta,
58
67
  listArchiveHeaders,
59
68
  getArchiveDetail,
60
69
  searchArchives,
61
70
  mutateArchive,
71
+ copyArchivesBetweenSessionsOrCabinets,
62
72
  getTakenOutArchivesForSession,
73
+ getFlippedOutPrecipitatedForSession,
74
+ listPrecipitatedHeaders,
75
+ getPrecipitatedDetail,
76
+ mutatePrecipitated,
63
77
  } from './archives.js'
64
78
 
65
79
  const API = '/api/dsh-chief'
66
80
  const BOARD_VERSION = 1
67
81
  const LOG_CAP = 60
68
- const BODY_LIMIT = 128 * 1024
82
+ const BODY_LIMIT = 24 * 1024 * 1024
69
83
  // How many anchor notes the shared board keeps. Anchors are what a fresh
70
84
  // Session reads before it has any context, so this is a budget, not a list.
71
85
  /**
@@ -144,6 +158,35 @@ function clearPending() {
144
158
  } catch {}
145
159
  }
146
160
 
161
+ function pendingDeployFile() {
162
+ return path.join(path.dirname(boardFile()), 'pending-chief-deploy.json')
163
+ }
164
+
165
+ function readPendingDeploy() {
166
+ try {
167
+ const raw = JSON.parse(fs.readFileSync(pendingDeployFile(), 'utf8'))
168
+ return raw && typeof raw.fromSessionId === 'string' && raw.fromSessionId ? raw : null
169
+ } catch {
170
+ return null
171
+ }
172
+ }
173
+
174
+ function writePendingDeploy(value) {
175
+ try {
176
+ fs.mkdirSync(path.dirname(pendingDeployFile()), { recursive: true })
177
+ fs.writeFileSync(pendingDeployFile(), JSON.stringify(value, null, 2), 'utf8')
178
+ return true
179
+ } catch {
180
+ return false
181
+ }
182
+ }
183
+
184
+ function clearPendingDeploy() {
185
+ try {
186
+ fs.unlinkSync(pendingDeployFile())
187
+ } catch {}
188
+ }
189
+
147
190
  function boardFile() {
148
191
  const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
149
192
  return path.join(home, 'chief', 'board.json')
@@ -354,6 +397,9 @@ function emptyBoard() {
354
397
  objective: '',
355
398
  objectiveBy: '',
356
399
  objectiveAt: 0,
400
+ objectiveUpdatedAt: 0,
401
+ activeCabinetId: '',
402
+ goalApproval: null,
357
403
  // 'plan' or 'goal'. A plan is a list of steps being ticked off; a goal is
358
404
  // one persistent objective steered toward, where rewriting the step list
359
405
  // every turn hides the fact that the objective never moved. The model picks
@@ -635,6 +681,22 @@ function guardCount(value, fallback, min, max) {
635
681
  return Math.min(max, Math.max(min, Math.round(number)))
636
682
  }
637
683
 
684
+ function normalizeGoalApproval(raw) {
685
+ if (!raw || typeof raw !== 'object') return null
686
+ const status = ['pending', 'approved', 'rejected'].includes(raw.status) ? raw.status : ''
687
+ if (!status) return null
688
+ return {
689
+ id: str(raw.id, newId('ga')),
690
+ status,
691
+ objective: str(raw.objective, '').slice(0, 600),
692
+ summary: str(raw.summary, '').slice(0, 600),
693
+ evidence: str(raw.evidence, '').slice(0, 800),
694
+ rejectReason: str(raw.rejectReason, '').slice(0, 300),
695
+ at: typeof raw.at === 'number' ? raw.at : nowMs(),
696
+ decidedAt: typeof raw.decidedAt === 'number' ? raw.decidedAt : 0,
697
+ }
698
+ }
699
+
638
700
  function normalizeBoard(raw) {
639
701
  const board = raw && typeof raw === 'object' ? raw : {}
640
702
  const plan = Array.isArray(board.plan) ? board.plan : []
@@ -647,6 +709,9 @@ function normalizeBoard(raw) {
647
709
  objective: str(board.objective, ''),
648
710
  objectiveBy: str(board.objectiveBy, ''),
649
711
  objectiveAt: typeof board.objectiveAt === 'number' ? board.objectiveAt : 0,
712
+ objectiveUpdatedAt: typeof board.objectiveUpdatedAt === 'number' ? board.objectiveUpdatedAt : (typeof board.objectiveAt === 'number' ? board.objectiveAt : 0),
713
+ activeCabinetId: str(board.activeCabinetId, '').trim(),
714
+ goalApproval: normalizeGoalApproval(board.goalApproval),
650
715
  // Whitelisted, not free-form: an unknown mode would make every consumer
651
716
  // (digest, panel) disagree about which shape the board has.
652
717
  mode: board.mode === 'goal' ? 'goal' : 'plan',
@@ -911,7 +976,8 @@ function runActionUnlocked(input) {
911
976
  if (action === 'archive.search') {
912
977
  const q = str(args.query !== undefined ? args.query : (args.question !== undefined ? args.question : args.text), '')
913
978
  const folder = str(args.folder, '')
914
- const res = searchArchives(q, { folder, limit: 10 }, boardFile())
979
+ const rootSid = resolveRootSessionId(session) || session
980
+ const res = searchArchives(q, { folder, limit: 10 }, archiveTarget(activeRuntime, rootSid, str(args.cabinetId, '')))
915
981
  return {
916
982
  ok: true,
917
983
  archiveSearch: res,
@@ -923,7 +989,7 @@ function runActionUnlocked(input) {
923
989
  const target = str(args.archiveId !== undefined ? args.archiveId : (args.id !== undefined ? args.id : args.title), '').trim()
924
990
  if (!target) return { ok: false, error: 'archive.read requires archiveId, id, or title' }
925
991
  const rootSid = resolveRootSessionId(session) || session
926
- const res = getArchiveDetail(target, rootSid, boardFile())
992
+ const res = getArchiveDetail(target, rootSid, archiveTarget(activeRuntime, rootSid, str(args.cabinetId, '')))
927
993
  if (!res.ok) return { ok: false, error: res.error }
928
994
  return {
929
995
  ok: true,
@@ -946,7 +1012,7 @@ function runActionUnlocked(input) {
946
1012
  points: Array.isArray(args.points) ? args.points : undefined,
947
1013
  by,
948
1014
  rootSessionId: rootSid,
949
- }, boardFile())
1015
+ }, archiveTarget(activeRuntime, rootSid, str(args.cabinetId, '')))
950
1016
  if (!res.ok) return { ok: false, error: res.error }
951
1017
  if (session) {
952
1018
  withBoardLock(file, () => {
@@ -1234,12 +1300,17 @@ function runActionUnlocked(input) {
1234
1300
  if (mode !== 'plan' && mode !== 'goal') return { ok: false, error: 'mode must be plan or goal' }
1235
1301
  const before = board.mode === 'goal' ? 'goal' : 'plan'
1236
1302
  board.mode = mode
1237
- // Logged even when unchanged is pointless, but logged when flipped is the
1238
- // only record of *why* the digest suddenly reads differently.
1303
+ if (mode === 'goal') {
1304
+ if (board.goalApproval && board.goalApproval.status !== 'pending') {
1305
+ board.goalApproval = null
1306
+ }
1307
+ } else if (board.goalApproval && board.goalApproval.status === 'pending') {
1308
+ board.goalApproval = null
1309
+ }
1239
1310
  if (before !== mode) {
1240
1311
  pushLog(
1241
1312
  board,
1242
- '模式改为:' + mode + (mode === 'goal' ? '(这活按持续目标推进,不用步骤列表代替)' : '(回到步骤推进)'),
1313
+ '模式改为:' + mode + (mode === 'goal' ? '(开启长期目标持续督导)' : '(回到按步规划推进)'),
1243
1314
  by,
1244
1315
  session,
1245
1316
  )
@@ -1247,6 +1318,74 @@ function runActionUnlocked(input) {
1247
1318
  return { ok: true, mode, board: saveBoard(board, file) }
1248
1319
  }
1249
1320
 
1321
+ if (action === 'plan.resetForGoal') {
1322
+ const hadSteps = Array.isArray(board.plan) ? board.plan.length : 0
1323
+ board.plan = []
1324
+ board.cursor = {
1325
+ at: nowMs(),
1326
+ step: '',
1327
+ next: '',
1328
+ blocked: '',
1329
+ by,
1330
+ session,
1331
+ }
1332
+ pushLog(board, `已清空陈旧计划步骤(原 ${hadSteps} 步),等待按最新总目标重编`, by, session)
1333
+ return { ok: true, clearedSteps: hadSteps, board: saveBoard(board, file) }
1334
+ }
1335
+
1336
+ if (action === 'goal.proposeApproval') {
1337
+ const obj = str(args.objective, board.objective).trim().slice(0, 600)
1338
+ const summary = str(args.summary, '当前总目标要求已全部完成并已核验,请用户批准结项。').trim().slice(0, 600)
1339
+ const evidence = str(args.evidence, '').trim().slice(0, 800)
1340
+ // Crucial: keep board.mode === 'goal' until the user explicitly approves!
1341
+ board.goalApproval = {
1342
+ id: newId('ga'),
1343
+ status: 'pending',
1344
+ objective: obj,
1345
+ summary,
1346
+ evidence,
1347
+ rejectReason: '',
1348
+ at: nowMs(),
1349
+ decidedAt: 0,
1350
+ }
1351
+ pushLog(board, '🎯 参谋长判定目标已达成,呈请用户批准结项:' + summary.slice(0, 60), by, session)
1352
+ return { ok: true, goalApproval: board.goalApproval, board: saveBoard(board, file) }
1353
+ }
1354
+
1355
+ if (action === 'goal.approve') {
1356
+ const prev = board.goalApproval || { id: newId('ga'), objective: board.objective, summary: '', evidence: '', at: nowMs() }
1357
+ board.goalApproval = {
1358
+ ...prev,
1359
+ status: 'approved',
1360
+ rejectReason: '',
1361
+ decidedAt: nowMs(),
1362
+ }
1363
+ board.mode = 'plan'
1364
+ appendMemory(board, {
1365
+ section: '验证结论',
1366
+ title: '🎯 目标结项批准:' + String(prev.objective || board.objective || '阶段目标').slice(0, 60),
1367
+ text: prev.summary || '用户已批准目标结项并切换回按步规划模式',
1368
+ by,
1369
+ session,
1370
+ })
1371
+ pushLog(board, '✅ 用户已批准目标结项,已退出 Goal 督导模式', by, session)
1372
+ return { ok: true, goalApproval: board.goalApproval, mode: board.mode, board: saveBoard(board, file) }
1373
+ }
1374
+
1375
+ if (action === 'goal.reject') {
1376
+ const reason = str(args.reason, '仍需继续推进完善').trim().slice(0, 300)
1377
+ const prev = board.goalApproval || { id: newId('ga'), objective: board.objective, summary: '', evidence: '', at: nowMs() }
1378
+ board.goalApproval = {
1379
+ ...prev,
1380
+ status: 'rejected',
1381
+ rejectReason: reason,
1382
+ decidedAt: nowMs(),
1383
+ }
1384
+ board.mode = 'goal'
1385
+ pushLog(board, '↩ 用户驳回结项批示(继续 Goal 督导):' + reason.slice(0, 60), by, session)
1386
+ return { ok: true, goalApproval: board.goalApproval, mode: board.mode, board: saveBoard(board, file) }
1387
+ }
1388
+
1250
1389
  if (action === 'settings.set') {
1251
1390
  const next = board.settings || { autoInject: true, guardIdle: true }
1252
1391
  const auto = asBool(args.autoInject)
@@ -1271,10 +1410,27 @@ function runActionUnlocked(input) {
1271
1410
  const objective = str(args.objective, '').trim()
1272
1411
  if (!objective) return { ok: false, error: 'objective required' }
1273
1412
  const clips = []
1413
+ const changed = board.objective !== objective
1274
1414
  board.objective = clipInto(clips, 'objective', objective, CAP_OBJECTIVE)
1275
1415
  board.objectiveBy = session
1276
1416
  board.objectiveAt = nowMs()
1277
- pushLog(board, '目标改为:' + objective.slice(0, 60), by, session)
1417
+ board.objectiveUpdatedAt = board.objectiveAt
1418
+ if (asBool(args.setGoalMode) === true) {
1419
+ board.mode = 'goal'
1420
+ }
1421
+ if (changed && board.goalApproval && board.goalApproval.status !== 'pending') {
1422
+ board.goalApproval = null
1423
+ }
1424
+ if (asBool(args.resetStalePlan) === true) {
1425
+ board.plan = []
1426
+ board.cursor = { at: nowMs(), step: '', next: '', blocked: '', by, session }
1427
+ }
1428
+ pushLog(
1429
+ board,
1430
+ (asBool(args.setGoalMode) === true ? '🎯 设为督导目标:' : '目标改为:') + objective.slice(0, 60),
1431
+ by,
1432
+ session,
1433
+ )
1278
1434
  return clipped({ ok: true, board: saveBoard(board, file) }, clips)
1279
1435
  }
1280
1436
 
@@ -1762,6 +1918,34 @@ function safe(read, fallback) {
1762
1918
  }
1763
1919
  }
1764
1920
 
1921
+ /** Probe whether the DSH host provides the post-rc.2 named subagent tree APIs. */
1922
+ function probeSubagentSupport(rt) {
1923
+ const subagents = rt ? safe(() => rt.get('subagents'), null) : null
1924
+ if (!subagents) {
1925
+ return {
1926
+ present: false,
1927
+ namedSubagentsSupported: false,
1928
+ missingMethods: [],
1929
+ minDshVersion: '0.2.2-rc.2',
1930
+ warning: '',
1931
+ }
1932
+ }
1933
+ const missingMethods = []
1934
+ if (typeof subagents.resolveName !== 'function') missingMethods.push('resolveName')
1935
+ if (typeof subagents.rootOf !== 'function') missingMethods.push('rootOf')
1936
+ if (typeof subagents.namesOf !== 'function') missingMethods.push('namesOf')
1937
+ const ok = missingMethods.length === 0
1938
+ return {
1939
+ present: true,
1940
+ namedSubagentsSupported: ok,
1941
+ missingMethods,
1942
+ minDshVersion: '0.2.2-rc.2',
1943
+ warning: ok
1944
+ ? ''
1945
+ : '当前 DSH 宿主版本不支持命名子代理树接口(缺少 subagents.resolveName / rootOf / namesOf,常见于 0.2.2-rc.1 及更早版本)。面板其余功能可正常使用;如需使用子代理派发 (task.dispatch) 与插话 (team.steer),请将 DSH 升级至 >= 0.2.2-rc.2。',
1946
+ }
1947
+ }
1948
+
1765
1949
  /** The agent a lookup resolves to: the one named, or the one whose turn this is.
1766
1950
  * Kept separate from sessionOf because the boundary report has to NAME the
1767
1951
  * Session it read facts for — the facts were derived from currentInitiator()
@@ -2198,11 +2382,122 @@ function buildTaskDispatchBrief(board, task, extraPrompt) {
2198
2382
  return lines.join('\n')
2199
2383
  }
2200
2384
 
2385
+ function getSessionCwd(runtime, sessionId) {
2386
+ const sid = String(sessionId || '').trim()
2387
+ const rootId = sid ? (resolveRootSessionId(sid) || sid) : ''
2388
+ const rt = runtime || activeRuntime
2389
+ if (rt) {
2390
+ try {
2391
+ const agents = rt.get('agents')
2392
+ const agent = (agents && typeof agents.get === 'function') ? (agents.get(sid) || agents.get(rootId)) : null
2393
+ const headerCwd = agent && agent.session && agent.session.header && agent.session.header.cwd
2394
+ if (typeof headerCwd === 'string' && headerCwd.trim()) return headerCwd.trim()
2395
+ const sessionObj = agent && agent.session ? agent.session : safe(() => sessionOf(rt, sid || rootId), null)
2396
+ const wd = rt.get('workingDirectory')
2397
+ if (wd && typeof wd.get === 'function' && sessionObj) {
2398
+ const wDir = wd.get(sessionObj)
2399
+ if (typeof wDir === 'string' && wDir.trim()) return wDir.trim()
2400
+ }
2401
+ } catch {}
2402
+ }
2403
+ for (const probeId of [sid, rootId].filter(Boolean)) {
2404
+ try {
2405
+ const b = loadBoard(boardFileFor(probeId))
2406
+ 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()
2408
+ } catch {}
2409
+ }
2410
+ return process.cwd()
2411
+ }
2412
+
2413
+ function archiveTarget(runtime, sessionId, explicitCabinetId = '') {
2414
+ const sid = String(sessionId || '').trim()
2415
+ const rootSid = sid ? (resolveRootSessionId(sid) || sid) : ''
2416
+ let cabinetId = typeof explicitCabinetId === 'string' ? explicitCabinetId.trim() : ''
2417
+ if (!cabinetId && rootSid) {
2418
+ try {
2419
+ cabinetId = loadBoard(boardFileFor(rootSid)).activeCabinetId || ''
2420
+ } catch {}
2421
+ }
2422
+ return {
2423
+ customSharedBoardFile: boardFile(),
2424
+ cwd: getSessionCwd(runtime, rootSid || sid),
2425
+ ...(cabinetId ? { cabinetId } : {}),
2426
+ }
2427
+ }
2428
+
2429
+ /** Combine working-cabinet mounted items with explicitly flipped precipitated entries (0 disk reads when empty!). */
2430
+ function collectTakenOutAndFlipped(runtime, rootId, cabinetId = '') {
2431
+ if (!rootId) return []
2432
+ const targetOpt = archiveTarget(runtime, rootId, cabinetId)
2433
+ const working = getTakenOutArchivesForSession(rootId, targetOpt)
2434
+ const state = loadChiefState()
2435
+ const ws = state && state.workspaces && state.workspaces[rootId]
2436
+ 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]
2447
+ }
2448
+
2201
2449
  function makeChiefDeps(runtime) {
2202
2450
  const rt = runtime || activeRuntime
2203
2451
  return {
2204
2452
  runtime: rt,
2205
2453
  getLlm: () => activeLlm || (rt ? rt.get('llm') : null),
2454
+ getAttachments: () => safe(() => (rt ? rt.get('attachments') : null), null),
2455
+ getSessionCwd: (sid) => getSessionCwd(rt, sid),
2456
+ getAgentStatus(sid) {
2457
+ const agents = rt ? rt.get('agents') : null
2458
+ const ag = agents && typeof agents.get === 'function' ? agents.get(sid) : null
2459
+ return (ag && ag.status) || 'idle'
2460
+ },
2461
+ 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
+ }
2489
+ },
2490
+ 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)))
2500
+ },
2206
2501
  resolveRootSessionId,
2207
2502
  resolveAgentIdentity,
2208
2503
  refreshSubagentTree,
@@ -2303,7 +2598,13 @@ async function executeSubagentAction(runtime, input, callerAgent, signal) {
2303
2598
  dispatchMode = 'session-inject'
2304
2599
  }
2305
2600
  } else if (subagents && liveCaller) {
2306
- // Case 2: Use DSH native subagent service (continue existing subagent or spawn/fork a new one)
2601
+ // Case 2: Use DSH native subagent service (requires post-rc.2 named subagent API)
2602
+ if (typeof subagents.resolveName !== 'function' || typeof subagents.startActivation !== 'function') {
2603
+ return {
2604
+ ok: false,
2605
+ error: '当前 DSH 宿主不支持命名子代理 API(缺少 subagents.resolveName / startActivation,例如 0.2.2-rc.1 为重构前旧接口),请将 DSH 升级至 >= 0.2.2-rc.2 后再使用子代理派发与插话。',
2606
+ }
2607
+ }
2307
2608
  const providerName = str(args.provider, targetTask.preset === 'fork' ? 'fork' : 'spawn') || 'spawn'
2308
2609
  const preset = str(args.preset, targetTask.preset && targetTask.preset !== 'fork' && targetTask.preset !== 'spawn' ? targetTask.preset : '')
2309
2610
  const candidateName = sanitizeSubagentName(requestedTarget, targetTask.id)
@@ -2409,6 +2710,12 @@ async function executeSubagentAction(runtime, input, callerAgent, signal) {
2409
2710
  if (!targetName) return { ok: false, error: 'team.steer requires agent name or task id with assigned subagent' }
2410
2711
  if (!text) return { ok: false, error: 'team.steer requires message / prompt text' }
2411
2712
  if (!subagents || !liveCaller) return { ok: false, error: 'subagents service or live caller agent unavailable' }
2713
+ if (typeof subagents.resolveName !== 'function') {
2714
+ return {
2715
+ ok: false,
2716
+ error: '当前 DSH 宿主不支持命名子代理 API(缺少 subagents.resolveName,例如 0.2.2-rc.1 为重构前旧接口),请将 DSH 升级至 >= 0.2.2-rc.2 后再使用子代理派发与插话。',
2717
+ }
2718
+ }
2412
2719
 
2413
2720
  let targetId = ''
2414
2721
  try {
@@ -2440,6 +2747,15 @@ async function executeSubagentAction(runtime, input, callerAgent, signal) {
2440
2747
  const targetName = str(args.agent || args.subagent || args.target || (linkedTask && (linkedTask.subagent || linkedTask.owner)), '').trim()
2441
2748
  if (!targetName) return { ok: false, error: 'team.interrupt requires agent name or task id' }
2442
2749
  if (!subagents || !liveCaller) return { ok: false, error: 'subagents service or live caller agent unavailable' }
2750
+ if (typeof subagents.resolveName !== 'function') {
2751
+ return {
2752
+ ok: false,
2753
+ error: '当前 DSH 宿主不支持命名子代理 API(缺少 subagents.resolveName,例如 0.2.2-rc.1 为重构前旧接口),请将 DSH 升级至 >= 0.2.2-rc.2 后再使用子代理派发与插话。',
2754
+ }
2755
+ }
2756
+ if (typeof subagents.interrupt !== 'function') {
2757
+ return { ok: false, error: '当前 DSH 宿主不支持 subagents.interrupt,请升级至 >= 0.2.2-rc.2' }
2758
+ }
2443
2759
 
2444
2760
  let targetId = ''
2445
2761
  try {
@@ -2526,7 +2842,8 @@ function routeTable(runtime) {
2526
2842
  }
2527
2843
  }
2528
2844
  } catch {}
2529
- let pinnedModelRef = (secState.config && secState.config.modelRef) || ''
2845
+ const effCfg = resolveWorkspaceConfig(secState, rootSid)
2846
+ let pinnedModelRef = effCfg.modelRef || ''
2530
2847
  if (pinnedModelRef) {
2531
2848
  try {
2532
2849
  const llmSvc = runtime && runtime.get('llm')
@@ -2537,6 +2854,9 @@ function routeTable(runtime) {
2537
2854
  }
2538
2855
  } catch {}
2539
2856
  }
2857
+ const rootWs = secState.workspaces && secState.workspaces[rootSid]
2858
+ const tacticalModes = effCfg.tacticalModes || {}
2859
+ const hostCompat = probeSubagentSupport(runtime)
2540
2860
  sendJson(res, 200, {
2541
2861
  ok: true,
2542
2862
  board,
@@ -2544,9 +2864,13 @@ function routeTable(runtime) {
2544
2864
  agentIdentity,
2545
2865
  teamTasks: sessionId ? fetchTeamTasks(runtime, { id: sessionId }) : undefined,
2546
2866
  boundaries: boundaries(runtime, sessionId),
2867
+ hostCompat,
2547
2868
  chiefMeta: {
2548
- paceMode: (secState.config && secState.config.paceMode) || 'manual',
2549
- autoPilot: Boolean(secState.config && secState.config.autoPilot),
2869
+ paceMode: effCfg.paceMode || 'manual',
2870
+ autoPilot: Boolean(effCfg.autoPilot),
2871
+ tacticalModes,
2872
+ runtimeGuard: (rootWs && rootWs.runtimeGuard) || {},
2873
+ flippedCount: (rootWs && Array.isArray(rootWs.flippedPrecipitatedIds)) ? rootWs.flippedPrecipitatedIds.length : 0,
2550
2874
  modelRef: pinnedModelRef,
2551
2875
  followModelRef,
2552
2876
  resolvedModelRef: pinnedModelRef || followModelRef || '',
@@ -2554,8 +2878,9 @@ function routeTable(runtime) {
2554
2878
  factsCount,
2555
2879
  mailboxCount,
2556
2880
  linkedPeersCount: Math.max(0, cluster.length - 1),
2881
+ hostCompat,
2557
2882
  },
2558
- archiveMeta: getArchiveMeta(rootSid, boardFile()),
2883
+ archiveMeta: getArchiveMeta(rootSid, archiveTarget(runtime, rootSid, board.activeCabinetId)),
2559
2884
  })
2560
2885
  } catch (error) {
2561
2886
  sendJson(res, 500, { ok: false, error: String(error && error.message ? error.message : error) })
@@ -2582,7 +2907,7 @@ function routeTable(runtime) {
2582
2907
  subagents,
2583
2908
  agentIdentity,
2584
2909
  teamTasks: sessionId ? fetchTeamTasks(runtime, { id: sessionId }) : undefined,
2585
- takenOutArchives: rootSid ? getTakenOutArchivesForSession(rootSid, boardFile()) : [],
2910
+ takenOutArchives: rootSid ? collectTakenOutAndFlipped(runtime, rootSid, fullBoard.activeCabinetId) : [],
2586
2911
  }),
2587
2912
  sessions: board.sessions || {},
2588
2913
  updatedAt: board.updatedAt,
@@ -2687,7 +3012,7 @@ function routeTable(runtime) {
2687
3012
  ok: true,
2688
3013
  text: renderHandoff(board, boundaries(runtime, sessionId), 5200, sessionId, {
2689
3014
  teamTasks: fetchTeamTasks(runtime, sessionId ? { id: sessionId } : null),
2690
- takenOutArchives: rootSid ? getTakenOutArchivesForSession(rootSid, boardFile()) : [],
3015
+ takenOutArchives: rootSid ? collectTakenOutAndFlipped(runtime, rootSid, board.activeCabinetId) : [],
2691
3016
  }),
2692
3017
  handoffAt: board.handoff ? board.handoff.at : 0,
2693
3018
  autoInject: !((board.settings || {}).autoInject === false),
@@ -2779,6 +3104,7 @@ function routeTable(runtime) {
2779
3104
  text: typeof body.text === 'string' ? body.text : '',
2780
3105
  forcedTarget: typeof body.target === 'string' ? body.target : '',
2781
3106
  forcedMode: typeof body.mode === 'string' ? body.mode : 'steer',
3107
+ images: Array.isArray(body.images) ? body.images : [],
2782
3108
  })
2783
3109
  const board = out.ok && sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
2784
3110
  sendJson(res, out.ok ? 200 : 400, board ? { ...out, board } : out)
@@ -2801,6 +3127,7 @@ function routeTable(runtime) {
2801
3127
  subject: typeof body.subject === 'string' ? body.subject : '',
2802
3128
  text: typeof body.text === 'string' ? body.text : '',
2803
3129
  mode: typeof body.mode === 'string' ? body.mode : 'steer',
3130
+ images: Array.isArray(body.images) ? body.images : [],
2804
3131
  })
2805
3132
  const view = await getChiefView(makeChiefDeps(runtime), sessionId, { autoSummarize: false })
2806
3133
  sendJson(res, out.ok ? 200 : 400, { ...out, view })
@@ -2830,10 +3157,11 @@ function routeTable(runtime) {
2830
3157
  if (!guard(req, res)) return
2831
3158
  try {
2832
3159
  const body = await readBody(req)
2833
- const updated = updateChiefConfig(body || {})
2834
- const sessionId = typeof body.session === 'string' ? body.session : ''
3160
+ const sessionId = typeof body?.session === 'string' ? body.session : ''
3161
+ const rootSid = resolveRootSessionId(sessionId) || sessionId
3162
+ const updated = updateChiefConfig({ ...(body || {}), ...(rootSid ? { sessionId: rootSid } : {}) })
2835
3163
  const view = await getChiefView(makeChiefDeps(runtime), sessionId, { autoSummarize: false })
2836
- sendJson(res, 200, { ...updated, view })
3164
+ sendJson(res, updated && updated.ok === false ? 400 : 200, { ...updated, view })
2837
3165
  } catch (error) {
2838
3166
  sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
2839
3167
  }
@@ -2942,10 +3270,15 @@ function routeTable(runtime) {
2942
3270
  const query = url.searchParams.get('q') || ''
2943
3271
  const folder = url.searchParams.get('folder') || ''
2944
3272
  const paperclip = url.searchParams.get('paperclip') || ''
2945
- const out = listArchiveHeaders(rootSid, { query, folder, paperclip }, boardFile())
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)
3276
+ const st = loadChiefState()
3277
+ const ws = rootSid && st.workspaces ? st.workspaces[rootSid] : null
2946
3278
  sendJson(res, 200, {
2947
3279
  ...out,
2948
- archiveMeta: getArchiveMeta(rootSid, boardFile()),
3280
+ flippedPrecipitatedIds: (ws && Array.isArray(ws.flippedPrecipitatedIds)) ? ws.flippedPrecipitatedIds.slice() : [],
3281
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
2949
3282
  })
2950
3283
  return
2951
3284
  }
@@ -2954,9 +3287,41 @@ function routeTable(runtime) {
2954
3287
  const sessionId = typeof body.session === 'string' ? body.session : ''
2955
3288
  const rootSid = resolveRootSessionId(sessionId) || sessionId
2956
3289
  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)
3292
+ const projectKey = resolveProjectKey(targetOpt.cwd)
3293
+
3294
+ if (['flipOut', 'sealBack', 'deletePrecipitated', 'updatePrecipitated'].includes(op)) {
3295
+ const pid = typeof body.id === 'string' ? body.id : (typeof body.precipitatedId === 'string' ? body.precipitatedId : '')
3296
+ const pRes = mutatePrecipitated(projectKey, {
3297
+ ...body,
3298
+ id: pid,
3299
+ precipitatedId: pid,
3300
+ op,
3301
+ rootSessionId: rootSid,
3302
+ }, targetOpt)
3303
+ if (!pRes.ok) {
3304
+ sendJson(res, 400, pRes)
3305
+ return
3306
+ }
3307
+ if (rootSid) {
3308
+ if (op === 'flipOut' && pid) updateWorkspaceFlippedIds(rootSid, { flippedId: pid })
3309
+ else if ((op === 'sealBack' || op === 'deletePrecipitated') && pid) updateWorkspaceFlippedIds(rootSid, { sealId: pid })
3310
+ }
3311
+ const stAfter = loadChiefState()
3312
+ const wsAfter = rootSid && stAfter.workspaces ? stAfter.workspaces[rootSid] : null
3313
+ const archives = listArchiveHeaders(rootSid, { includePrecipitated: true }, targetOpt)
3314
+ sendJson(res, 200, {
3315
+ ...pRes,
3316
+ archives,
3317
+ flippedPrecipitatedIds: (wsAfter && Array.isArray(wsAfter.flippedPrecipitatedIds)) ? wsAfter.flippedPrecipitatedIds.slice() : [],
3318
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
3319
+ })
3320
+ return
3321
+ }
2957
3322
 
2958
3323
  if (op === 'precipitateNotes') {
2959
- // Sweep active board.notes (session and/or shared) into cold-stored archives.json
3324
+ // Sweep active board.notes (session and/or shared) into active working cabinet
2960
3325
  const noteIds = Array.isArray(body.noteIds) ? new Set(body.noteIds.map(String)) : null
2961
3326
  let sweptCount = 0
2962
3327
  const sweepFromFile = (targetFile) => {
@@ -2979,13 +3344,13 @@ function routeTable(runtime) {
2979
3344
  paperclip: (note.pinned || (note.tags || []).includes('anchor')) ? 'gold' : undefined,
2980
3345
  by: note.by || 'user',
2981
3346
  rootSessionId: rootSid,
2982
- }, boardFile())
3347
+ }, targetOpt)
2983
3348
  if (saved.ok) sweptCount += 1
2984
3349
  else keep.push(note)
2985
3350
  }
2986
3351
  if (keep.length !== b.notes.length) {
2987
3352
  b.notes = keep
2988
- pushLog(b, `🗄️ 已将 ${sweptCount} 篇便签沉淀封存入「档案」柜`, 'operator', sessionId)
3353
+ pushLog(b, `🗄️ 已将 ${sweptCount} 篇便签收纳进「档案」工作柜`, 'operator', sessionId)
2989
3354
  saveBoard(b, targetFile)
2990
3355
  }
2991
3356
  })
@@ -2993,13 +3358,13 @@ function routeTable(runtime) {
2993
3358
  if (sessionId) sweepFromFile(boardFileFor(sessionId))
2994
3359
  sweepFromFile(boardFile())
2995
3360
  const board = sessionId ? boardForSession(boardFileFor(sessionId)) : emptyBoard()
2996
- const archives = listArchiveHeaders(rootSid, {}, boardFile())
3361
+ const archives = listArchiveHeaders(rootSid, { includePrecipitated: true }, targetOpt)
2997
3362
  sendJson(res, 200, {
2998
3363
  ok: true,
2999
3364
  sweptCount,
3000
3365
  board,
3001
3366
  archives,
3002
- archiveMeta: getArchiveMeta(rootSid, boardFile()),
3367
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
3003
3368
  })
3004
3369
  return
3005
3370
  }
@@ -3008,16 +3373,30 @@ function routeTable(runtime) {
3008
3373
  ...body,
3009
3374
  op,
3010
3375
  rootSessionId: rootSid,
3011
- }, boardFile())
3376
+ }, targetOpt)
3012
3377
  if (!out.ok) {
3013
3378
  sendJson(res, 400, out)
3014
3379
  return
3015
3380
  }
3016
- const archives = listArchiveHeaders(rootSid, {}, boardFile())
3381
+ const usedCabId = out.activeCabinetId || out.cabinetId || ''
3382
+ if (rootSid && usedCabId && op !== 'listCabinets') {
3383
+ const bFile = boardFileFor(rootSid)
3384
+ withBoardLock(bFile, () => {
3385
+ const b = loadBoard(bFile)
3386
+ if (op === 'switchCabinet' || op === 'createCabinet' || !b.activeCabinetId) {
3387
+ b.activeCabinetId = usedCabId
3388
+ saveBoard(b, bFile)
3389
+ }
3390
+ })
3391
+ }
3392
+ const finalOpt = archiveTarget(runtime, rootSid || sessionId, out.activeCabinetId || cabinetId || out.cabinetId)
3393
+ const archives = listArchiveHeaders(rootSid, { includePrecipitated: true }, finalOpt)
3394
+ const board = sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
3017
3395
  sendJson(res, 200, {
3018
3396
  ...out,
3019
3397
  archives,
3020
- archiveMeta: getArchiveMeta(rootSid, boardFile()),
3398
+ ...(board ? { board } : {}),
3399
+ archiveMeta: getArchiveMeta(rootSid, finalOpt),
3021
3400
  })
3022
3401
  } catch (error) {
3023
3402
  sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
@@ -3032,8 +3411,13 @@ function routeTable(runtime) {
3032
3411
  const url = new URL(req.url || '/', 'http://127.0.0.1')
3033
3412
  const id = url.searchParams.get('id') || ''
3034
3413
  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'
3035
3416
  const rootSid = resolveRootSessionId(sessionId) || sessionId
3036
- const out = getArchiveDetail(id, rootSid, boardFile())
3417
+ const targetOpt = archiveTarget(runtime, rootSid || sessionId, cabinetId)
3418
+ const out = isPrecip
3419
+ ? getPrecipitatedDetail(resolveProjectKey(targetOpt.cwd), id, rootSid, targetOpt)
3420
+ : getArchiveDetail(id, rootSid, targetOpt)
3037
3421
  sendJson(res, out.ok ? 200 : 404, out)
3038
3422
  } catch (error) {
3039
3423
  sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
@@ -3048,8 +3432,11 @@ function routeTable(runtime) {
3048
3432
  const body = await readBody(req)
3049
3433
  const sessionId = typeof body.session === 'string' ? body.session : ''
3050
3434
  const rootSid = resolveRootSessionId(sessionId) || sessionId
3435
+ const cabinetId = typeof body.cabinetId === 'string' ? body.cabinetId : ''
3436
+ const targetOpt = archiveTarget(runtime, rootSid || sessionId, cabinetId)
3051
3437
  const out = await organizeArchivesWithChief(makeChiefDeps(runtime), {
3052
3438
  sessionId: rootSid,
3439
+ cabinetId,
3053
3440
  ids: Array.isArray(body.ids) ? body.ids : [],
3054
3441
  folder: typeof body.folder === 'string' ? body.folder : '',
3055
3442
  scope: typeof body.scope === 'string' ? body.scope : 'unorganized',
@@ -3057,7 +3444,58 @@ function routeTable(runtime) {
3057
3444
  })
3058
3445
  sendJson(res, out.ok ? 200 : 400, {
3059
3446
  ...out,
3060
- archiveMeta: getArchiveMeta(rootSid, boardFile()),
3447
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
3448
+ })
3449
+ } catch (error) {
3450
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
3451
+ }
3452
+ },
3453
+ },
3454
+ {
3455
+ path: API + '/archives/harvest',
3456
+ handler: async (req, res) => {
3457
+ if (!guard(req, res)) return
3458
+ try {
3459
+ const body = await readBody(req)
3460
+ const sessionId = typeof body.session === 'string' ? body.session : ''
3461
+ const rootSid = resolveRootSessionId(sessionId) || sessionId
3462
+ const cabinetId = typeof body.cabinetId === 'string' ? body.cabinetId : ''
3463
+ const targetOpt = archiveTarget(runtime, rootSid || sessionId, cabinetId)
3464
+ const out = await harvestTurnDetailsToArchive(makeChiefDeps(runtime), {
3465
+ sessionId: rootSid,
3466
+ cabinetId,
3467
+ trigger: 'manual',
3468
+ focusHint: typeof body.focusHint === 'string' ? body.focusHint : '',
3469
+ })
3470
+ sendJson(res, out.ok ? 200 : 400, {
3471
+ ...out,
3472
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
3473
+ })
3474
+ } catch (error) {
3475
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
3476
+ }
3477
+ },
3478
+ },
3479
+ {
3480
+ path: API + '/archives/precipitate',
3481
+ handler: async (req, res) => {
3482
+ if (!guard(req, res)) return
3483
+ try {
3484
+ const body = await readBody(req)
3485
+ const sessionId = typeof body.session === 'string' ? body.session : ''
3486
+ const rootSid = resolveRootSessionId(sessionId) || sessionId
3487
+ const cabinetId = typeof body.cabinetId === 'string' ? body.cabinetId : ''
3488
+ const targetOpt = archiveTarget(runtime, rootSid || sessionId, cabinetId)
3489
+ const out = await precipitateExperienceWithChief(makeChiefDeps(runtime), {
3490
+ sessionId: rootSid,
3491
+ op: typeof body.op === 'string' ? body.op : 'cabinet',
3492
+ cabinetId,
3493
+ folder: typeof body.folder === 'string' ? body.folder : '',
3494
+ clearSource: Boolean(body.clearSource),
3495
+ })
3496
+ sendJson(res, out.ok ? 200 : 400, {
3497
+ ...out,
3498
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
3061
3499
  })
3062
3500
  } catch (error) {
3063
3501
  sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
@@ -3095,8 +3533,12 @@ function syncObjective(name, args, sessionId) {
3095
3533
  board.objective = objective.slice(0, 2000)
3096
3534
  board.objectiveBy = String(sessionId || '')
3097
3535
  board.objectiveAt = nowMs()
3098
- if (wantGoalMode) board.mode = 'goal'
3099
- pushLog(board, '长期目标(/goal)改为:' + objective.slice(0, 60) + (previous && previous !== objective ? '(原:' + previous.slice(0, 40) + ')' : ''), 'agent', sessionId)
3536
+ if (wantGoalMode) {
3537
+ board.mode = 'goal'
3538
+ if (board.goalApproval && board.goalApproval.status !== 'pending') board.goalApproval = null
3539
+ }
3540
+ board.objectiveUpdatedAt = board.objectiveAt
3541
+ pushLog(board, '长期目标改为:' + objective.slice(0, 60) + (previous && previous !== objective ? '(原:' + previous.slice(0, 40) + ')' : ''), 'agent', sessionId)
3100
3542
  saveBoard(board, file)
3101
3543
  })
3102
3544
  }
@@ -3967,18 +4409,156 @@ async function injectInto(agent, text) {
3967
4409
  return { ok: false, error: 'inject 不接受完整消息形状(纯文本会写坏会话日志,不试)' }
3968
4410
  }
3969
4411
 
4412
+ /**
4413
+ * System-level handover & state deployment to a target Chief workspace (`一键部署参谋`).
4414
+ * Copies active objective, mode, plan steps, unfinished tasks (scrubbing stale `doing` / child handles),
4415
+ * cursor, bounds, and Chief facts/narrative/chat — while optionally copying working cabinet archives
4416
+ * per `archiveTransferPolicy` ('none' | 'mounted' | 'drawer' | 'all') and strictly NEVER leaking precipitated cold vault.
4417
+ */
4418
+ export function deployStateToTargetChief(runtime, {
4419
+ fromSessionId = '',
4420
+ toSessionId = '',
4421
+ archiveTransferPolicy = 'none',
4422
+ archiveDrawer = '',
4423
+ toCabinetId = '',
4424
+ customNote = '',
4425
+ } = {}) {
4426
+ const fromRoot = resolveRootSessionId(fromSessionId) || String(fromSessionId || '').trim()
4427
+ const toRoot = resolveRootSessionId(toSessionId) || String(toSessionId || '').trim()
4428
+ if (!fromRoot || !toRoot || fromRoot === toRoot) {
4429
+ return { ok: false, error: '跨会话移交需要两个不同的会话 ID' }
4430
+ }
4431
+
4432
+ const srcBoard = boardForSession(boardFileFor(fromRoot))
4433
+ const destFile = boardFileFor(toRoot)
4434
+ let copiedTaskCount = 0
4435
+ let copiedStepCount = 0
4436
+
4437
+ withBoardLock(destFile, () => {
4438
+ const dest = loadBoard(destFile)
4439
+ if (srcBoard.objective) {
4440
+ dest.objective = srcBoard.objective
4441
+ dest.objectiveBy = srcBoard.objectiveBy || fromRoot
4442
+ dest.objectiveAt = srcBoard.objectiveAt || nowMs()
4443
+ dest.objectiveUpdatedAt = nowMs()
4444
+ }
4445
+ dest.mode = srcBoard.mode === 'goal' ? 'goal' : 'plan'
4446
+ dest.goalApproval = null
4447
+
4448
+ if (Array.isArray(srcBoard.plan) && srcBoard.plan.length > 0) {
4449
+ dest.plan = srcBoard.plan.map(step => ({
4450
+ id: step.id || newId('s'),
4451
+ text: step.text,
4452
+ done: Boolean(step.done),
4453
+ }))
4454
+ copiedStepCount = dest.plan.length
4455
+ }
4456
+
4457
+ const srcTasks = Array.isArray(srcBoard.tasks) ? srcBoard.tasks : []
4458
+ const unfinished = srcTasks.filter(t => t && t.status !== 'done')
4459
+ const unfinishedIds = new Set(unfinished.map(t => t.id))
4460
+ const existingIds = new Set((dest.tasks || []).map(t => t.id))
4461
+ for (const rawTask of unfinished) {
4462
+ if (existingIds.has(rawTask.id)) continue
4463
+ const remainingBlockers = (rawTask.blockedBy || []).filter(bid => unfinishedIds.has(bid))
4464
+ const droppedDoneCount = (rawTask.blockedBy || []).length - remainingBlockers.length
4465
+ dest.tasks.push(normalizeTask({
4466
+ ...rawTask,
4467
+ status: rawTask.status === 'doing' ? 'todo' : rawTask.status,
4468
+ session: '',
4469
+ subagent: '',
4470
+ blockedBy: remainingBlockers,
4471
+ note: droppedDoneCount > 0
4472
+ ? [rawTask.note, `[接力已自动解除 ${droppedDoneCount} 项已完成前置依赖]`].filter(Boolean).join(' ')
4473
+ : rawTask.note,
4474
+ updatedAt: nowMs(),
4475
+ }))
4476
+ copiedTaskCount += 1
4477
+ }
4478
+
4479
+ if (srcBoard.cursor && (srcBoard.cursor.step || srcBoard.cursor.next || srcBoard.cursor.blocked)) {
4480
+ dest.cursor = {
4481
+ ...srcBoard.cursor,
4482
+ at: nowMs(),
4483
+ by: 'deploy',
4484
+ session: fromRoot,
4485
+ }
4486
+ }
4487
+
4488
+ // Merge local non-pinned bounds from source session board into destination session board
4489
+ const srcLocal = srcBoard.localBounds || { allowed: [], forbidden: [], notes: [] }
4490
+ const destBounds = normalizeBounds(dest.bounds)
4491
+ for (const col of BOUND_FIELDS) {
4492
+ const merged = new Set(destBounds[col] || [])
4493
+ for (const item of (srcLocal[col] || [])) merged.add(item)
4494
+ destBounds[col] = [...merged].slice(0, BOUND_CAP)
4495
+ }
4496
+ dest.bounds = destBounds
4497
+
4498
+ // Carry non-anchor handoff context notes selectively if target has room
4499
+ dest.handoff = { at: nowMs(), by: 'deploy', session: fromRoot }
4500
+ pushLog(
4501
+ dest,
4502
+ `🚀 已系统级移交部署自会话 ${fromRoot.slice(0, 12)}:计划 ${copiedStepCount} 步、未完任务 ${copiedTaskCount} 项`,
4503
+ 'deploy',
4504
+ toRoot,
4505
+ )
4506
+ saveBoard(dest, destFile)
4507
+ })
4508
+
4509
+ const chiefRes = deployChiefWorkspaceState(makeChiefDeps(runtime), {
4510
+ fromRootId: fromRoot,
4511
+ toRootId: toRoot,
4512
+ fromTitle: sessionName(runtime, fromRoot) || fromRoot,
4513
+ customText: customNote,
4514
+ objective: srcBoard.objective || '',
4515
+ })
4516
+
4517
+ let archiveCopyRes = { ok: true, policy: 'none', copiedCount: 0 }
4518
+ const policy = ['none', 'mounted', 'drawer', 'all'].includes(archiveTransferPolicy)
4519
+ ? archiveTransferPolicy
4520
+ : 'none'
4521
+ if (policy !== 'none') {
4522
+ archiveCopyRes = copyArchivesBetweenSessionsOrCabinets({
4523
+ fromRootSessionId: fromRoot,
4524
+ toRootSessionId: toRoot,
4525
+ fromCwd: getSessionCwd(runtime, fromRoot),
4526
+ toCwd: getSessionCwd(runtime, toRoot),
4527
+ fromCabinetId: srcBoard.activeCabinetId || '',
4528
+ toCabinetId: toCabinetId || loadBoard(boardFileFor(toRoot)).activeCabinetId || '',
4529
+ policy,
4530
+ drawer: archiveDrawer,
4531
+ customSharedBoardFile: boardFile(),
4532
+ })
4533
+ }
4534
+
4535
+ return {
4536
+ ok: true,
4537
+ fromSessionId: fromRoot,
4538
+ toSessionId: toRoot,
4539
+ copiedTaskCount,
4540
+ copiedStepCount,
4541
+ chiefDeployed: chiefRes,
4542
+ archiveTransfer: archiveCopyRes,
4543
+ }
4544
+ }
4545
+
3970
4546
  export async function transferChief(runtime, args, sessionId) {
3971
4547
  const passed = args && typeof args === 'object' ? args : {}
3972
4548
  const target = typeof passed.target === 'string' ? passed.target.trim() : 'new'
3973
- // The packet is rendered from the sender's own board — the receiving board
3974
- // stays untouched (per-session isolation; the transfer text is what moves).
3975
- // Read through boardForSession so the packet still carries the operator's
3976
- // bounds and the machine objective when this session never wrote its own.
4549
+ const deployChief = asBool(passed.deployChief) !== false
4550
+ const archiveTransferPolicy = ['none', 'mounted', 'drawer', 'all'].includes(str(passed.archiveTransferPolicy, 'none'))
4551
+ ? str(passed.archiveTransferPolicy, 'none')
4552
+ : 'none'
4553
+ const archiveDrawer = str(passed.archiveDrawer, '')
4554
+ const toCabinetId = str(passed.toCabinetId, '')
4555
+ const customNote = str(passed.customNote, '')
4556
+
3977
4557
  const board = boardForSession(boardFileFor(sessionId))
3978
4558
  const rootSid = resolveRootSessionId(sessionId) || sessionId
3979
4559
  const packet = renderHandoff(board, boundaries(runtime, sessionId), 5200, sessionId, {
3980
4560
  teamTasks: fetchTeamTasks(runtime, sessionId ? { id: sessionId } : null),
3981
- takenOutArchives: rootSid ? getTakenOutArchivesForSession(rootSid, boardFile()) : [],
4561
+ takenOutArchives: rootSid ? collectTakenOutAndFlipped(runtime, rootSid, board.activeCabinetId) : [],
3982
4562
  })
3983
4563
  const by = typeof passed.by === 'string' && passed.by ? passed.by : 'user'
3984
4564
 
@@ -3986,25 +4566,41 @@ export async function transferChief(runtime, args, sessionId) {
3986
4566
  if (!writePending({ at: nowMs(), by, session: sessionId, text: packet })) {
3987
4567
  return { ok: false, error: '待领取文件写入失败' }
3988
4568
  }
4569
+ if (deployChief && rootSid) {
4570
+ writePendingDeploy({
4571
+ at: nowMs(),
4572
+ by,
4573
+ fromSessionId: rootSid,
4574
+ archiveTransferPolicy,
4575
+ archiveDrawer,
4576
+ toCabinetId,
4577
+ customNote,
4578
+ })
4579
+ }
3989
4580
  const owner = boardFileFor(sessionId)
3990
4581
  withBoardLock(owner, () => {
3991
4582
  const next = loadBoard(owner)
3992
- pushLog(next, '交接单已投放:等下一个新会话领取', by, sessionId)
4583
+ pushLog(next, '交接单与参谋接力包已投放:等下一个新会话自动部署领取', by, sessionId)
3993
4584
  saveBoard(next, owner)
3994
4585
  })
3995
- return { ok: true, mode: 'pending', text: packet }
4586
+ return { ok: true, mode: 'pending', deployQueued: deployChief, text: packet }
3996
4587
  }
3997
4588
 
3998
- // One-click handover: open the successor conversation here instead of
3999
- // asking the operator to create one by hand and then find it in a picker.
4000
- // The packet is parked BEFORE the create call: if creation dies half way the
4001
- // next conversation still picks it up, and if it succeeds the
4002
- // agent/created listener races us for the file — whoever clears it wins,
4003
- // so the packet is never injected twice.
4004
4589
  if (target === 'create') {
4005
4590
  const controller = runtime.get('sessionController')
4006
4591
  const parked = writePending({ at: nowMs(), by, session: sessionId, text: packet })
4007
4592
  if (!parked) return { ok: false, error: '待领取文件写入失败' }
4593
+ if (deployChief && rootSid) {
4594
+ writePendingDeploy({
4595
+ at: nowMs(),
4596
+ by,
4597
+ fromSessionId: rootSid,
4598
+ archiveTransferPolicy,
4599
+ archiveDrawer,
4600
+ toCabinetId,
4601
+ customNote,
4602
+ })
4603
+ }
4008
4604
  if (!controller || typeof controller.create !== 'function') {
4009
4605
  return { ok: false, error: '这个部署没有 sessionController,交接单已放进待领取', mode: 'pending', text: packet }
4010
4606
  }
@@ -4021,16 +4617,28 @@ export async function transferChief(runtime, args, sessionId) {
4021
4617
  }
4022
4618
  const createdId = str(created && created.sessionId, '')
4023
4619
  if (!createdId) return { ok: false, error: '新会话没有返回 id', mode: 'pending', text: packet }
4620
+
4621
+ let deployResult = null
4622
+ if (deployChief && rootSid && readPendingDeploy()) {
4623
+ clearPendingDeploy()
4624
+ deployResult = deployStateToTargetChief(runtime, {
4625
+ fromSessionId: rootSid,
4626
+ toSessionId: createdId,
4627
+ archiveTransferPolicy,
4628
+ archiveDrawer,
4629
+ toCabinetId,
4630
+ customNote,
4631
+ })
4632
+ }
4633
+
4024
4634
  const owner = boardFileFor(sessionId)
4025
- // The listener got there first: the packet is gone and that conversation
4026
- // already carries it.
4027
4635
  if (!readPending()) {
4028
4636
  withBoardLock(owner, () => {
4029
4637
  const next = loadBoard(owner)
4030
- pushLog(next, '交接单已由新会话 ' + createdId.replace(/^session-/, '').slice(0, 8) + ' 领取', by, sessionId)
4638
+ pushLog(next, '交接单与参谋已由新会话 ' + createdId.replace(/^session-/, '').slice(0, 8) + ' 领取部署', by, sessionId)
4031
4639
  saveBoard(next, owner)
4032
4640
  })
4033
- return { ok: true, mode: 'created', sessionId: createdId, delivered: true, text: packet }
4641
+ return { ok: true, mode: 'created', sessionId: createdId, delivered: true, deployResult, text: packet }
4034
4642
  }
4035
4643
  const agents = runtime.get('agents')
4036
4644
  const fresh = agents && typeof agents.get === 'function' ? agents.get(createdId) : undefined
@@ -4040,20 +4648,38 @@ export async function transferChief(runtime, args, sessionId) {
4040
4648
  const next = loadBoard(owner)
4041
4649
  pushLog(
4042
4650
  next,
4043
- (delivered.ok ? '交接单已交给新会话 ' : '新会话已建(交接单仍待领取):') + createdId.replace(/^session-/, '').slice(0, 8),
4651
+ (delivered.ok ? '交接单与参谋已部署至新会话 ' : '新会话已建(交接单仍待领取):') + createdId.replace(/^session-/, '').slice(0, 8),
4044
4652
  by,
4045
4653
  sessionId,
4046
4654
  )
4047
4655
  saveBoard(next, owner)
4048
4656
  })
4049
- return { ok: delivered.ok, mode: delivered.ok ? 'created' : 'pending', sessionId: createdId, text: packet }
4657
+ return { ok: delivered.ok, mode: delivered.ok ? 'created' : 'pending', sessionId: createdId, deployResult, text: packet }
4658
+ }
4659
+
4660
+ let deployResult = null
4661
+ if (deployChief && rootSid && target !== rootSid) {
4662
+ deployResult = deployStateToTargetChief(runtime, {
4663
+ fromSessionId: rootSid,
4664
+ toSessionId: target,
4665
+ archiveTransferPolicy,
4666
+ archiveDrawer,
4667
+ toCabinetId,
4668
+ customNote,
4669
+ })
4050
4670
  }
4051
4671
 
4052
4672
  const agents = runtime.get('agents')
4053
4673
  const agent = agents && typeof agents.get === 'function' ? agents.get(target) : undefined
4054
4674
  if (!agent) {
4055
4675
  writePending({ at: nowMs(), by, session: sessionId, text: packet, failedTarget: target })
4056
- return { ok: false, error: '目标会话没有活的 agent:已改成待领取,下次新会话可取', mode: 'pending', text: packet }
4676
+ return {
4677
+ ok: Boolean(deployResult && deployResult.ok),
4678
+ error: deployResult && deployResult.ok ? '' : '目标会话没有活的 agent:已改成待领取,下次新会话可取',
4679
+ mode: 'pending',
4680
+ deployResult,
4681
+ text: packet,
4682
+ }
4057
4683
  }
4058
4684
  const delivered = await injectInto(agent, packet)
4059
4685
  const owner = boardFileFor(sessionId)
@@ -4061,7 +4687,7 @@ export async function transferChief(runtime, args, sessionId) {
4061
4687
  const next = loadBoard(owner)
4062
4688
  pushLog(
4063
4689
  next,
4064
- (delivered.ok ? '交接单已投放到会话 ' : '投放失败(' + delivered.error + '):') + String(target).replace(/^session-/, '').slice(0, 8),
4690
+ (delivered.ok ? '交接单与参谋已投放到会话 ' : '投放失败(' + delivered.error + '):') + String(target).replace(/^session-/, '').slice(0, 8),
4065
4691
  by,
4066
4692
  sessionId,
4067
4693
  )
@@ -4069,9 +4695,9 @@ export async function transferChief(runtime, args, sessionId) {
4069
4695
  })
4070
4696
  if (!delivered.ok) {
4071
4697
  writePending({ at: nowMs(), by, session: sessionId, text: packet, failedTarget: target })
4072
- return { ok: false, error: delivered.error, mode: 'pending', text: packet }
4698
+ return { ok: false, error: delivered.error, mode: 'pending', deployResult, text: packet }
4073
4699
  }
4074
- return { ok: true, mode: 'injected', target, text: packet }
4700
+ return { ok: true, mode: 'injected', target, deployResult, text: packet }
4075
4701
  }
4076
4702
 
4077
4703
  /* ------------------------------------------------------------------------ apply */
@@ -4213,7 +4839,7 @@ export function apply(ctx) {
4213
4839
  const subagents = getSubagentRoster(runtime, rootId, board)
4214
4840
  const secState = loadChiefState()
4215
4841
  const linkedPeersCount = Math.max(0, getLinkedCluster(secState, rootId || 'global').length - 1)
4216
- const takenOutArchives = rootId ? getTakenOutArchivesForSession(rootId, boardFile()) : []
4842
+ const takenOutArchives = rootId ? collectTakenOutAndFlipped(runtime, rootId, board.activeCabinetId) : []
4217
4843
  if (rootId) refreshSubagentTree(runtime, rootId, board).catch(() => {})
4218
4844
  return renderDigest(board, { teamTasks, agentIdentity, subagents, linkedPeersCount, takenOutArchives })
4219
4845
  },
@@ -4235,19 +4861,32 @@ export function apply(ctx) {
4235
4861
  } catch {}
4236
4862
  }), 'dsh-chief: plan & subagent mirror')
4237
4863
 
4238
- // 2b) A transferred packet waits for exactly one new Session.
4864
+ // 2b) A transferred packet + staged Chief deployment waits for one new Session.
4239
4865
  ctx.effect(() => ctx.on('agent/created', async payload => {
4240
4866
  try {
4241
4867
  const agent = payload && payload.agent
4242
4868
  if (!agent || !agent.id) return
4869
+ const id = String(agent.id)
4870
+
4871
+ const pendingDeploy = readPendingDeploy()
4872
+ if (pendingDeploy && pendingDeploy.fromSessionId && pendingDeploy.fromSessionId !== id) {
4873
+ clearPendingDeploy()
4874
+ try {
4875
+ deployStateToTargetChief(runtime, {
4876
+ fromSessionId: pendingDeploy.fromSessionId,
4877
+ toSessionId: id,
4878
+ archiveTransferPolicy: pendingDeploy.archiveTransferPolicy || 'none',
4879
+ archiveDrawer: pendingDeploy.archiveDrawer || '',
4880
+ toCabinetId: pendingDeploy.toCabinetId || '',
4881
+ customNote: pendingDeploy.customNote || '',
4882
+ })
4883
+ } catch {}
4884
+ }
4885
+
4243
4886
  const pending = readPending()
4244
4887
  if (!pending) return
4245
4888
  const delivered = await injectInto(agent, pending.text)
4246
4889
  if (delivered.ok) clearPending()
4247
- // The claim is logged on the NEW session's own board, not the sender's.
4248
- // A brand-new Session's turn-stopping write can land while this runs, so
4249
- // the claim re-reads under the lock and keeps whatever else got there.
4250
- const id = String(agent.id)
4251
4890
  const file = boardFileFor(id)
4252
4891
  const short = id.replace(/^session-/, '').slice(0, 8)
4253
4892
  withBoardLock(file, () => {
@@ -4321,6 +4960,8 @@ export function apply(ctx) {
4321
4960
  const entry = board.sessions[id] || { lastSeen: 0, cwd: '', turns: 0 }
4322
4961
  entry.lastSeen = nowMs()
4323
4962
  entry.turns = (entry.turns || 0) + 1
4963
+ const resolvedCwd = getSessionCwd(runtime, id)
4964
+ if (resolvedCwd) entry.cwd = resolvedCwd
4324
4965
  board.sessions[id] = entry
4325
4966
  const ids = Object.keys(board.sessions)
4326
4967
  if (ids.length > 40) {
@@ -4450,4 +5091,14 @@ export function apply(ctx) {
4450
5091
  toolCtx.effect(() => toolCtx.tools.register(tool), 'dsh-chief: tool ' + tool.name)
4451
5092
  }
4452
5093
  })
5094
+
5095
+ // Runtime capability probe for DSH >= 0.2.2-rc.2 named subagent APIs
5096
+ ctx.inject(['subagents'], () => {
5097
+ const compat = probeSubagentSupport(runtime)
5098
+ if (compat.present && !compat.namedSubagentsSupported) {
5099
+ try {
5100
+ console.warn('[dsh-chief] ' + compat.warning)
5101
+ } catch {}
5102
+ }
5103
+ })
4453
5104
  }