dsh-chief 1.4.0 → 1.6.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.
@@ -10,6 +10,7 @@ import {
10
10
  POINTS_CAP,
11
11
  PRECIPITATED_CAP,
12
12
  SECRET_PATTERN,
13
+ DEFAULT_ARCHIVE_FOLDERS,
13
14
  nextId,
14
15
  str,
15
16
  clamp,
@@ -26,6 +27,7 @@ import {
26
27
  normalizeTags,
27
28
  firstMeaningfulSentence,
28
29
  extractStructuredPoints,
30
+ deriveHookFromStructuredItem,
29
31
  invokeArchiveMutatorHook,
30
32
  } from './archive-core.js'
31
33
  import { loadGlobalVaultRaw, loadArchiveStore } from './archive-cabinets.js'
@@ -42,6 +44,17 @@ export function hasAnyPrecipitatedFilesOnDisk(targetOpt) {
42
44
  }
43
45
  }
44
46
 
47
+ function mapPrecipitatedCategoryToFolder(category = '', rawFolder = '') {
48
+ const f = str(rawFolder, '').trim()
49
+ if (f) return f.slice(0, 64)
50
+ const cat = str(category, '').trim().toLowerCase()
51
+ if (cat === 'coords' || cat === 'env') return 'coords'
52
+ if (cat === 'incidents' || cat === 'troubleshooting' || cat === 'pitfalls') return 'incidents'
53
+ if (cat === 'contracts' || cat === 'architecture' || cat === 'contract') return 'contracts'
54
+ if (cat === 'plans' || cat === 'workflow') return 'plans'
55
+ return 'ops'
56
+ }
57
+
45
58
  function normalizePrecipitatedEntry(raw) {
46
59
  if (!raw || typeof raw !== 'object') return null
47
60
  const title = clamp(raw.title || '', 180)
@@ -51,8 +64,22 @@ function normalizePrecipitatedEntry(raw) {
51
64
  .map((p, idx) => normalizePoint(p, idx))
52
65
  .filter(Boolean)
53
66
  .slice(0, POINTS_CAP)
54
- const validCategories = ['coords', 'incidents', 'contracts', 'ops', 'plans', 'architecture', 'env', 'contract', 'troubleshooting', 'workflow', 'general']
67
+ const validCategories = ['coords', 'incidents', 'contracts', 'ops', 'plans', 'architecture', 'env', 'contract', 'troubleshooting', 'workflow', 'patterns', 'pitfalls', 'toolchain', 'general']
55
68
  const category = validCategories.includes(raw.category) ? raw.category : 'general'
69
+ const folder = mapPrecipitatedCategoryToFolder(category, raw.folder)
70
+ const paperclip = ['gold', 'silver', 'copper'].includes(raw.paperclip) ? raw.paperclip : 'gold'
71
+ const tags = normalizeTags(Array.isArray(raw.tags) ? raw.tags : [])
72
+ const summary = clamp(raw.summary || (points[0] && points[0].cue) || firstMeaningfulSentence(rawBody) || title, 180)
73
+ const normPoints = points.length ? points : extractStructuredPoints(title, rawBody)
74
+ const hook = deriveHookFromStructuredItem({
75
+ ...raw,
76
+ title: title || '跨会话可复用工程经验',
77
+ summary,
78
+ folder,
79
+ tags,
80
+ points: normPoints,
81
+ body: rawBody,
82
+ }, true)
56
83
  const flippedOutSessions = Array.isArray(raw.flippedOutSessions)
57
84
  ? [...new Set(raw.flippedOutSessions.map(s => str(s, '').trim()).filter(Boolean))].slice(0, 32)
58
85
  : []
@@ -61,15 +88,20 @@ function normalizePrecipitatedEntry(raw) {
61
88
  id: str(raw.id, '').trim() || nextId('prec'),
62
89
  title: title || '跨会话可复用工程经验',
63
90
  category,
64
- summary: clamp(raw.summary || (points[0] && points[0].cue) || firstMeaningfulSentence(rawBody) || title, 180),
65
- points: points.length ? points : extractStructuredPoints(title, rawBody),
91
+ folder,
92
+ paperclip,
93
+ summary,
94
+ points: normPoints,
66
95
  rawBody,
67
96
  purified: raw.purified !== false,
68
97
  sourceCabinetId: str(raw.sourceCabinetId || raw.sourceCabinet, '').trim(),
69
98
  sourceDrawer: str(raw.sourceDrawer, '').trim(),
70
99
  sourceSession: str(raw.sourceSession, '').trim(),
71
100
  sourceTitles: Array.isArray(raw.sourceTitles) ? raw.sourceTitles.map(t => clamp(t, 80)).slice(0, 40) : [],
72
- tags: normalizeTags(Array.isArray(raw.tags) ? raw.tags : []),
101
+ tags,
102
+ hasHook: true,
103
+ hookKeywords: hook.hookKeywords,
104
+ hookCue: hook.hookCue,
73
105
  flippedOutSessions,
74
106
  by: clamp(raw.by || 'chief', 40),
75
107
  createdAt: Number(raw.createdAt) || Date.now(),
@@ -249,15 +281,21 @@ export function copyPrecipitatedToVault(projectKey = 'proj-default', payload = {
249
281
  }
250
282
  }
251
283
 
252
- /** Listed ONLY for Chief background sealed-archive watch (never injected into Lead prompt unless placed on desk). */
253
- export function collectSealedWatchSummary(rootSessionId = '', projectKey = 'proj-default', targetOpt, opts = {}) {
284
+ /**
285
+ * Listed ONLY for Chief background hook/sealed-archive watch (never injected into Lead prompt unless placed on desk).
286
+ * Three-tier hook contract:
287
+ * - Session vault: Chief always sees session sealed entries (Lead sees only Chief-curated hooks).
288
+ * - Global vault: Chief sees ONLY entries that already have Chief-curated hooks (`hasHook === true`), zero raw leak!
289
+ * - Precipitated vault: 100% human-only (0 disk read, 0 hook leak to Chief or Lead).
290
+ */
291
+ export function collectSealedWatchSummary(rootSessionId = '', _projectKey = 'proj-default', targetOpt, opts = {}) {
254
292
  const sid = cleanRootSessionId(rootSessionId)
255
293
  const base = resolveTargetOpts(targetOpt)
256
294
  const capPerVault = Math.max(2, Math.min(Number(opts.limitPerVault) || 8, 16))
257
295
 
258
296
  let sessionSealed = []
259
297
  let globalSealed = []
260
- let precipSealed = []
298
+ const precipSealed = []
261
299
 
262
300
  if (sid) {
263
301
  try {
@@ -273,7 +311,16 @@ export function collectSealedWatchSummary(rootSessionId = '', projectKey = 'proj
273
311
  sessionSealed = (sStore.items || [])
274
312
  .filter(it => !Array.isArray(it.takenOutSessions) || !it.takenOutSessions.includes(sid))
275
313
  .slice(0, capPerVault)
276
- .map(it => ({ id: it.id, scope: 'session', title: it.title, folder: it.folder, summary: it.summary }))
314
+ .map(it => ({
315
+ id: it.id,
316
+ scope: 'session',
317
+ title: it.title,
318
+ folder: it.folder,
319
+ summary: it.summary,
320
+ hasHook: Boolean(it.hasHook),
321
+ hookKeywords: Array.isArray(it.hookKeywords) ? it.hookKeywords : [],
322
+ hookCue: it.hookCue || '',
323
+ }))
277
324
  }
278
325
  } catch {}
279
326
  }
@@ -281,21 +328,28 @@ export function collectSealedWatchSummary(rootSessionId = '', projectKey = 'proj
281
328
  try {
282
329
  const gStore = loadGlobalVaultRaw(base)
283
330
  globalSealed = (gStore.items || [])
284
- .filter(it => !sid || !Array.isArray(it.takenOutSessions) || !it.takenOutSessions.includes(sid))
331
+ .filter(it =>
332
+ it.hasHook === true
333
+ && (!sid || !Array.isArray(it.takenOutSessions) || !it.takenOutSessions.includes(sid))
334
+ )
285
335
  .slice(0, capPerVault)
286
- .map(it => ({ id: it.id, scope: 'global', title: it.title, folder: it.folder, summary: it.summary, chiefMounted: Boolean(sid && Array.isArray(it.chiefMountedSessions) && it.chiefMountedSessions.includes(sid)) }))
336
+ .map(it => ({
337
+ id: it.id,
338
+ scope: 'global',
339
+ title: it.title,
340
+ folder: it.folder,
341
+ hasHook: true,
342
+ hookKeywords: Array.isArray(it.hookKeywords) ? it.hookKeywords : [],
343
+ hookCue: it.hookCue || '',
344
+ chiefMounted: Boolean(
345
+ sid && (
346
+ (Array.isArray(it.chiefMountedSessions) && it.chiefMountedSessions.includes(sid))
347
+ || (Array.isArray(it.chiefPulledSessions) && it.chiefPulledSessions.includes(sid))
348
+ )
349
+ ),
350
+ }))
287
351
  } catch {}
288
352
 
289
- if (hasAnyPrecipitatedFilesOnDisk(base)) {
290
- try {
291
- const pStore = loadPrecipitatedStoreRaw(projectKey || base.projectKey || 'proj-default', base)
292
- precipSealed = (pStore.items || [])
293
- .filter(it => !sid || !Array.isArray(it.flippedOutSessions) || !it.flippedOutSessions.includes(sid))
294
- .slice(0, capPerVault)
295
- .map(it => ({ id: it.id, scope: 'precipitated', title: it.title, category: it.category, summary: it.summary }))
296
- } catch {}
297
- }
298
-
299
353
  return { sessionSealed, globalSealed, precipSealed }
300
354
  }
301
355
 
@@ -305,22 +359,33 @@ export function listPrecipitatedHeaders(projectKey = 'proj-default', rootSession
305
359
  if (!fs.existsSync(file)) return []
306
360
  const sid = str(rootSessionId, '').trim()
307
361
  const store = loadPrecipitatedStoreRaw(projectKey, targetOpt)
308
- return store.items.map(it => ({
309
- id: it.id,
310
- title: it.title,
311
- category: it.category,
312
- summary: it.summary,
313
- purified: it.purified,
314
- sourceCabinetId: it.sourceCabinetId,
315
- sourceDrawer: it.sourceDrawer,
316
- sourceTitles: it.sourceTitles,
317
- tags: it.tags,
318
- pointCount: Array.isArray(it.points) ? it.points.length : 0,
319
- flippedOut: Boolean(sid && Array.isArray(it.flippedOutSessions) && it.flippedOutSessions.includes(sid)),
320
- points: (it.points || []).map(p => ({ id: p.id, title: p.title, cue: p.cue, detail: p.detail })),
321
- createdAt: it.createdAt,
322
- updatedAt: it.updatedAt,
323
- }))
362
+ return store.items.map(it => {
363
+ const flippedOut = Boolean(sid && Array.isArray(it.flippedOutSessions) && it.flippedOutSessions.includes(sid))
364
+ return {
365
+ id: it.id,
366
+ title: it.title,
367
+ category: it.category,
368
+ folder: it.folder || mapPrecipitatedCategoryToFolder(it.category),
369
+ paperclip: it.paperclip || 'gold',
370
+ summary: it.summary,
371
+ hasHook: true,
372
+ hookKeywords: Array.isArray(it.hookKeywords) ? it.hookKeywords : [],
373
+ hookCue: it.hookCue || '',
374
+ purified: it.purified,
375
+ sourceCabinetId: it.sourceCabinetId,
376
+ sourceDrawer: it.sourceDrawer,
377
+ sourceTitles: it.sourceTitles,
378
+ tags: it.tags,
379
+ pointCount: Array.isArray(it.points) ? it.points.length : 0,
380
+ flippedOut,
381
+ viewerStatus: flippedOut
382
+ ? { code: 'human_unsealed', tone: 'amber', label: '🔓 人类已翻出 · 仅本局参阅' }
383
+ : { code: 'human_only', tone: 'ice', label: '🧊 仅人类可见 · 钩子速览' },
384
+ points: (it.points || []).map(p => ({ id: p.id, title: p.title, cue: p.cue, detail: p.detail })),
385
+ createdAt: it.createdAt,
386
+ updatedAt: it.updatedAt,
387
+ }
388
+ })
324
389
  }
325
390
 
326
391
  export function getPrecipitatedDetail(projectKey = 'proj-default', id = '', rootSessionId = '', targetOpt) {
@@ -412,6 +477,20 @@ export function mutatePrecipitated(projectKey = 'proj-default', payload = {}, ta
412
477
  return { ok: true, removedId: removed.id, title: removed.title }
413
478
  }
414
479
 
480
+ if (op === 'moveFolder' || op === 'setFolder') {
481
+ const item = store.items.find(it => it.id === id)
482
+ if (!item) return { ok: false, error: '未找到沉淀经验:' + id }
483
+ const folder = str(payload.folder, '').trim()
484
+ if (!folder) return { ok: false, error: '请选择目标抽屉' }
485
+ item.folder = folder.slice(0, 64)
486
+ if (['gold', 'silver', 'copper'].includes(payload.paperclip)) {
487
+ item.paperclip = payload.paperclip
488
+ }
489
+ item.updatedAt = Date.now()
490
+ savePrecipitatedStoreRaw(resolvedKey, store, targetOpt)
491
+ return { ok: true, id: item.id, folder: item.folder, item }
492
+ }
493
+
415
494
  if (op === 'updatePrecipitated') {
416
495
  const item = store.items.find(it => it.id === id)
417
496
  if (!item) return { ok: false, error: '未找到沉淀经验:' + id }
package/auto-continue.js CHANGED
@@ -183,7 +183,7 @@ export function classifyTurnEndReason(reason, eventData = null) {
183
183
  return { kind, nestedKind, failure }
184
184
  }
185
185
 
186
- function buildContinuePrompt(trigger, toolSummary = {}, failure = null) {
186
+ function buildContinuePrompt(trigger, toolSummary = {}, failure = null, taskId = '') {
187
187
  const pendingCount = Number(toolSummary.pendingCount) || 0
188
188
  const doneCount = Number(toolSummary.doneCount) || 0
189
189
 
@@ -216,7 +216,8 @@ function buildContinuePrompt(trigger, toolSummary = {}, failure = null) {
216
216
  guardText = `\n[幂等安全提醒] 上一轮已有工具调用完成${doneList},请先核实已有产出,切勿重复执行会覆盖或叠加副作用的步骤。`
217
217
  }
218
218
 
219
- return `[DSH 参谋长 · 断线续跑] ${lead}${guardText}`
219
+ const envelopeTag = taskId ? `[EXECUTION_REQUEST #${taskId}] ` : '[EXECUTION_REQUEST] '
220
+ return `${envelopeTag}[DSH 参谋长 · 断线续跑执行请求] ${lead}${guardText}`
220
221
  }
221
222
 
222
223
  /**
@@ -322,12 +323,18 @@ export function createAutoContinueEngine(options = {}) {
322
323
  return { ok: false, skipped: 'chief-stopped' }
323
324
  }
324
325
 
326
+ let verdict = null
325
327
  if (!bypassGate && typeof canAutoContinue === 'function') {
326
- const verdict = await Promise.resolve(canAutoContinue({ sessionId, rootId, trigger, detail }))
328
+ verdict = await Promise.resolve(canAutoContinue({ sessionId, rootId, trigger, detail }))
327
329
  if (verdict && verdict.allowed === false) {
328
330
  st.stats.skippedStopped += 1
329
331
  if (verdict.logMessage) onLog(sessionId, verdict.logMessage)
330
- return { ok: false, skipped: verdict.skipped || 'permission-mode', approvalId: verdict.approvalId }
332
+ return {
333
+ ok: false,
334
+ skipped: verdict.skipped || 'permission-mode',
335
+ approvalId: verdict.approvalId,
336
+ ...(verdict.taskId ? { taskId: verdict.taskId } : {}),
337
+ }
331
338
  }
332
339
  }
333
340
 
@@ -349,7 +356,8 @@ export function createAutoContinueEngine(options = {}) {
349
356
  return { ok: false, skipped: 'no-followup' }
350
357
  }
351
358
 
352
- const text = buildContinuePrompt(trigger, st.lastToolSummary, st.lastFailure) + (detail ? `\n补充上下文:${clampText(detail, 180)}` : '')
359
+ const envelopeTaskId = (verdict && verdict.taskId) ? String(verdict.taskId) : ''
360
+ const text = buildContinuePrompt(trigger, st.lastToolSummary, st.lastFailure, envelopeTaskId) + (detail ? `\n补充上下文:${clampText(detail, 180)}` : '')
353
361
  const fallbackId = `ac-${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`
354
362
  let envelope = null
355
363
  if (typeof createMessage === 'function') {
package/board-actions.js CHANGED
@@ -16,6 +16,7 @@ import {
16
16
  } from './chief.js'
17
17
  import {
18
18
  resolveProjectKey,
19
+ listArchiveHeaders,
19
20
  getArchiveDetail,
20
21
  searchArchives,
21
22
  mutateArchive,
@@ -61,6 +62,7 @@ import {
61
62
  normalizeTags,
62
63
  normalizeTask,
63
64
  reconcileTaskDependencies,
65
+ resolveActivePlanStepId,
64
66
  normalizeNote,
65
67
  BOUND_FIELDS,
66
68
  normalizeBoundFieldName,
@@ -143,6 +145,7 @@ export function createBoardActions(deps) {
143
145
  || action === 'memory.ask'
144
146
  || action === 'archive.search'
145
147
  || action === 'archive.read'
148
+ || action === 'archive.pull'
146
149
  || action === 'archive.save'
147
150
  ) {
148
151
  return runActionUnlocked(args)
@@ -186,13 +189,46 @@ export function createBoardActions(deps) {
186
189
  }
187
190
  }
188
191
 
192
+ if (action === 'archive.pull') {
193
+ const target = str(args.archiveId !== undefined ? args.archiveId : (args.id !== undefined ? args.id : args.title), '').trim()
194
+ if (!target) return { ok: false, error: 'archive.pull requires archiveId, id, or title' }
195
+ const reqScope = str(args.vaultScope || args.scope, 'session').trim().toLowerCase()
196
+ if (reqScope === 'global' || reqScope === 'precipitated' || reqScope === 'cold') {
197
+ return { ok: false, denied: true, error: '主代理禁止直接拉取全局或冷藏档案柜卷宗,请仅拉取本局档案柜带钩子卷宗' }
198
+ }
199
+ const rootSid = resolveRootSessionId(session) || session
200
+ if (!rootSid) return { ok: false, error: '当前未绑定对话会话,无法拉取本局档案柜' }
201
+ const res = mutateArchive({
202
+ op: 'pullByLead',
203
+ vaultScope: 'session',
204
+ rootSessionId: rootSid,
205
+ id: target,
206
+ archiveId: target,
207
+ title: target,
208
+ }, archiveTarget(deps.hostState.activeRuntime, rootSid, { cabinetId: str(args.cabinetId, ''), vaultScope: 'session' }))
209
+ if (!res || !res.ok) return { ok: false, error: (res && res.error) || '拉取本局档案失败' }
210
+ return {
211
+ ok: true,
212
+ archiveItem: res.item,
213
+ board: session ? loadBoard(file) : emptyBoard(),
214
+ }
215
+ }
216
+
189
217
  if (action === 'archive.read') {
190
218
  const target = str(args.archiveId !== undefined ? args.archiveId : (args.id !== undefined ? args.id : args.title), '').trim()
191
219
  if (!target) return { ok: false, error: 'archive.read requires archiveId, id, or title' }
220
+ const reqScope = str(args.vaultScope || args.scope, 'session').trim().toLowerCase()
221
+ if (reqScope === 'global' || reqScope === 'precipitated' || reqScope === 'cold') {
222
+ return { ok: false, denied: true, error: '主代理禁止跨柜读取全局或冷藏档案柜' }
223
+ }
192
224
  const rootSid = resolveRootSessionId(session) || session
193
225
  if (!rootSid) return { ok: false, error: '当前未绑定对话会话,无法读取本会话档案柜' }
194
- const res = getArchiveDetail(target, rootSid, archiveTarget(deps.hostState.activeRuntime, rootSid, { cabinetId: str(args.cabinetId, ''), vaultScope: 'session' }))
226
+ const archOpt = archiveTarget(deps.hostState.activeRuntime, rootSid, { cabinetId: str(args.cabinetId, ''), vaultScope: 'session' })
227
+ const res = getArchiveDetail(target, rootSid, archOpt)
195
228
  if (!res.ok) return { ok: false, error: res.error }
229
+ if (res.item && res.item.hasHook) {
230
+ mutateArchive({ op: 'pullByLead', vaultScope: 'session', rootSessionId: rootSid, id: res.item.id }, archOpt)
231
+ }
196
232
  return {
197
233
  ok: true,
198
234
  archiveItem: res.item,
@@ -245,6 +281,19 @@ export function createBoardActions(deps) {
245
281
 
246
282
  const board = loadBoard(file)
247
283
 
284
+ const resolveStepRef = (rawRef, fallbackId = '') => {
285
+ const ref = str(rawRef, '').trim()
286
+ if (!ref) return fallbackId
287
+ const plan = Array.isArray(board && board.plan) ? board.plan : []
288
+ if (plan.some(s => s && s.id === ref)) return ref
289
+ const m = ref.match(/^(?:step[-_]?|#)?(\d{1,3})$/i)
290
+ if (m) {
291
+ const idx = Number(m[1]) - 1
292
+ if (idx >= 0 && idx < plan.length && plan[idx] && plan[idx].id) return plan[idx].id
293
+ }
294
+ return ref.slice(0, 120)
295
+ }
296
+
248
297
  if (action === 'task.reset') {
249
298
  const mode = str(args.mode, 'clear').trim().toLowerCase()
250
299
  const hadCount = Array.isArray(board.tasks) ? board.tasks.length : 0
@@ -273,6 +322,15 @@ export function createBoardActions(deps) {
273
322
  if (!title) return { ok: false, error: 'title required' }
274
323
  const clips = []
275
324
  const ownerVal = str(args.subagent || args.target || args.owner, by)
325
+ const parentIdVal = str(args.parentId, '').slice(0, 200)
326
+ const parentTask = parentIdVal ? board.tasks.find(t => t && t.id === parentIdVal) : null
327
+ const autoStepId = (parentTask && parentTask.planStepId) || resolveActivePlanStepId(board)
328
+ const planStepIdVal = args.planStepId !== undefined
329
+ ? resolveStepRef(args.planStepId, '')
330
+ : autoStepId
331
+ const targetPlanStepIdVal = args.targetPlanStepId !== undefined
332
+ ? resolveStepRef(args.targetPlanStepId, '')
333
+ : ''
276
334
  const task = normalizeTask({
277
335
  id: str(args.id, '') ? str(args.id, '').slice(0, 64) : newId('t'),
278
336
  title: clipInto(clips, 'task.title', title, CAP_TASK_TITLE),
@@ -286,7 +344,9 @@ export function createBoardActions(deps) {
286
344
  intent: clipInto(clips, 'task.intent', str(args.intent, ''), CAP_TASK_INTENT),
287
345
  evidence: clipInto(clips, 'task.evidence', str(args.evidence, ''), CAP_TASK_EVIDENCE),
288
346
  blockedBy: Array.isArray(args.blockedBy) ? args.blockedBy : (typeof args.blockedBy === 'string' && args.blockedBy ? args.blockedBy.split(',').map(s => s.trim()) : []),
289
- parentId: str(args.parentId, '').slice(0, 200),
347
+ parentId: parentIdVal,
348
+ planStepId: planStepIdVal,
349
+ targetPlanStepId: targetPlanStepIdVal,
290
350
  assumptions: str(args.assumption, '') ? [{ text: str(args.assumption, '').slice(0, CAP_ASSUMPTION), verified: false, verifiedAt: 0, note: '' }] : [],
291
351
  createdAt: nowMs(),
292
352
  updatedAt: nowMs(),
@@ -350,6 +410,10 @@ export function createBoardActions(deps) {
350
410
 
351
411
  const ownerVal = str(item.subagent || item.target || item.owner, existing ? existing.owner : '')
352
412
  const subagentVal = str(item.subagent || item.target || (ownerVal && ownerVal !== 'agent' && ownerVal !== 'operator' ? ownerVal : ''), existing ? existing.subagent : '')
413
+ const parentForStep = resolvedParent ? board.tasks.find(t => t && t.id === resolvedParent) : null
414
+ const defaultStepForNew = (parentForStep && parentForStep.planStepId) || resolveActivePlanStepId(board)
415
+ const itemStepId = item.planStepId !== undefined ? resolveStepRef(item.planStepId, '') : undefined
416
+ const itemTargetStepId = item.targetPlanStepId !== undefined ? resolveStepRef(item.targetPlanStepId, '') : undefined
353
417
 
354
418
  if (existing) {
355
419
  existing.title = clipInto(clips, 'task.title', title, CAP_TASK_TITLE)
@@ -360,6 +424,8 @@ export function createBoardActions(deps) {
360
424
  if (subagentVal) existing.subagent = subagentVal.slice(0, 120)
361
425
  if (typeof item.preset === 'string') existing.preset = item.preset.slice(0, 80)
362
426
  if (rawParent || item.parentId === '') existing.parentId = resolvedParent.slice(0, 200)
427
+ if (itemStepId !== undefined) existing.planStepId = itemStepId
428
+ if (itemTargetStepId !== undefined) existing.targetPlanStepId = itemTargetStepId
363
429
  if (item.blockedBy !== undefined) existing.blockedBy = resolvedDeps
364
430
  if (STATUSES.includes(item.status)) existing.status = item.status
365
431
  if (PRIORITIES.includes(item.priority)) existing.priority = item.priority
@@ -380,6 +446,8 @@ export function createBoardActions(deps) {
380
446
  evidence: clipInto(clips, 'task.evidence', str(item.evidence, ''), CAP_TASK_EVIDENCE),
381
447
  blockedBy: resolvedDeps,
382
448
  parentId: resolvedParent,
449
+ planStepId: itemStepId !== undefined ? itemStepId : defaultStepForNew,
450
+ targetPlanStepId: itemTargetStepId !== undefined ? itemTargetStepId : '',
383
451
  assumptions: str(item.assumption, '') ? [{ text: str(item.assumption, '').slice(0, CAP_ASSUMPTION), verified: false, verifiedAt: 0, note: '' }] : [],
384
452
  createdAt: nowMs(),
385
453
  updatedAt: nowMs(),
@@ -392,11 +460,29 @@ export function createBoardActions(deps) {
392
460
  reconcileTaskDependencies(board, by, session)
393
461
  if (!board.plan.length && board.tasks.length) {
394
462
  const roots = board.tasks.filter(t => !t.parentId)
395
- board.plan = (roots.length ? roots : board.tasks).slice(0, 12).map(t => ({
396
- id: 's-' + t.id,
397
- text: t.title + (t.owner ? ' (@' + t.owner + ')' : ''),
398
- done: t.status === 'done',
399
- }))
463
+ const stageSeeds = (roots.length ? roots : board.tasks).slice(0, 12)
464
+ board.plan = stageSeeds.map(t => {
465
+ const sid = 's-' + t.id
466
+ if (!t.planStepId) t.planStepId = sid
467
+ return {
468
+ id: sid,
469
+ text: t.title + (t.owner ? ' (@' + t.owner + ')' : ''),
470
+ done: t.status === 'done',
471
+ }
472
+ })
473
+ const byTaskId = new Map(board.tasks.map(t => [t.id, t]))
474
+ const resolveRootStep = (task, seen = new Set()) => {
475
+ if (!task) return ''
476
+ if (task.planStepId) return task.planStepId
477
+ if (task.parentId && byTaskId.has(task.parentId) && !seen.has(task.id)) {
478
+ seen.add(task.id)
479
+ const inherited = resolveRootStep(byTaskId.get(task.parentId), seen)
480
+ if (inherited) task.planStepId = inherited
481
+ return inherited
482
+ }
483
+ return ''
484
+ }
485
+ for (const t of board.tasks) resolveRootStep(t)
400
486
  }
401
487
  pushLog(board, '规划任务图:共更新/新增 ' + touchedTasks.length + ' 个任务节点', by, session)
402
488
  return clipped({ ok: true, tasks: touchedTasks, board: saveBoard(board, file) }, clips)
@@ -456,6 +542,8 @@ export function createBoardActions(deps) {
456
542
  task.assumptions.push({ text: clipInto(clips, 'task.assumption', args.assumption.trim(), CAP_ASSUMPTION), verified: false, verifiedAt: 0, note: '' })
457
543
  }
458
544
  if (typeof args.parentId === 'string') task.parentId = args.parentId.trim().slice(0, 200)
545
+ if (typeof args.planStepId === 'string') task.planStepId = resolveStepRef(args.planStepId, '')
546
+ if (typeof args.targetPlanStepId === 'string') task.targetPlanStepId = resolveStepRef(args.targetPlanStepId, '')
459
547
  if (typeof args.owner === 'string') task.owner = str(args.owner, '').slice(0, 200)
460
548
  if (typeof args.target === 'string') {
461
549
  task.owner = str(args.target, '').slice(0, 200)
@@ -523,10 +611,12 @@ export function createBoardActions(deps) {
523
611
  // A bare string in a flattened list is one step, not a step with no
524
612
  // text: the old shape filtered it out and wiped the plan.
525
613
  const step = typeof raw === 'string' ? { text: raw } : (raw && typeof raw === 'object' ? raw : {})
614
+ const cleanSummary = typeof step.summary === 'string' ? step.summary.trim().slice(0, 240) : ''
526
615
  return {
527
616
  id: str(step.id, newId('s')),
528
617
  text: clipInto(clips, 'plan.step', str(step.text, ''), CAP_PLAN_STEP),
529
618
  done: asBool(step.done) === true,
619
+ ...(cleanSummary ? { summary: cleanSummary } : {}),
530
620
  }
531
621
  })
532
622
  .filter(step => step.text !== '')
@@ -1513,10 +1603,30 @@ export function createBoardActions(deps) {
1513
1603
  return [...working, ...takenGlobal, ...mappedFlipped]
1514
1604
  }
1515
1605
 
1516
- /** 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. */
1606
+ /** Collect digest-safe archive context for Lead/Subagent prompt: ONLY desk-spotlight items + Chief-curated session hooks (0 raw/global/cold leak!). */
1517
1607
  function collectDigestArchiveContext(runtime, rootId, cabinetId = '') {
1518
1608
  const takenOutArchives = rootId ? collectTakenOutAndFlipped(runtime, rootId, cabinetId) : []
1519
- const sessionArchiveBriefs = []
1609
+ let sessionHookedArchives = []
1610
+ let desktopUsedTokens = 0
1611
+ if (rootId && rootId !== 'global') {
1612
+ try {
1613
+ const targetOpt = archiveTarget(runtime, rootId, { cabinetId, vaultScope: 'session' })
1614
+ const hdrRes = listArchiveHeaders(rootId, { vaultScope: 'session', includeCounts: false }, targetOpt)
1615
+ if (hdrRes && hdrRes.ok) {
1616
+ desktopUsedTokens = Number(hdrRes.desktop && hdrRes.desktop.usedTokens) || 0
1617
+ sessionHookedArchives = (Array.isArray(hdrRes.items) ? hdrRes.items : [])
1618
+ .filter(it => it && it.hasHook && !it.takenOut)
1619
+ .slice(0, 6)
1620
+ .map(it => ({
1621
+ id: it.id,
1622
+ title: it.title,
1623
+ folder: it.folder,
1624
+ hookKeywords: Array.isArray(it.hookKeywords) ? it.hookKeywords : [],
1625
+ hookCue: it.hookCue || '',
1626
+ }))
1627
+ }
1628
+ } catch {}
1629
+ }
1520
1630
  let smartCompactActive = false
1521
1631
  let chiefPermissionMode = DEFAULT_CHIEF_PERMISSION_MODE
1522
1632
  if (rootId) {
@@ -1532,7 +1642,7 @@ export function createBoardActions(deps) {
1532
1642
  })
1533
1643
  } catch {}
1534
1644
  }
1535
- return { takenOutArchives, sessionArchiveBriefs, smartCompactActive, chiefPermissionMode }
1645
+ return { takenOutArchives, sessionHookedArchives, desktopUsedTokens, smartCompactActive, chiefPermissionMode }
1536
1646
  }
1537
1647
 
1538
1648
  /* ------------------------------------------------------------------- auto sync */