dsh-chief 1.2.0 → 1.3.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.
@@ -0,0 +1,580 @@
1
+ /**
2
+ * board-schema.js
3
+ *
4
+ * Pure schema constants, field caps, DAG normalization, and board summary helpers for dsh-chief.
5
+ */
6
+
7
+ import { normalizeMemory } from './memory.js'
8
+
9
+ export const API = '/api/dsh-chief'
10
+
11
+ export const BACKEND_BUILD = '1.3.0'
12
+
13
+ export const BOARD_VERSION = 1
14
+
15
+ const LOG_CAP = 60
16
+
17
+ export const BODY_LIMIT = 24 * 1024 * 1024
18
+
19
+ // How many anchor notes the shared board keeps. Anchors are what a fresh
20
+ // Session reads before it has any context, so this is a budget, not a list.
21
+ /**
22
+ * Keeps the anchor set at the size the digest can actually show.
23
+ *
24
+ * Two paths add anchors — note.pin and a pinned note.write — and only the first
25
+ * used to run this, so the shared board grew past the cap and every note's
26
+ * share of the fixed ANCHOR_RESERVE shrank. The eviction also used to skip every
27
+ * pinned note, which after the above meant it could never drop anything: the
28
+ * notes it was meant to trim were exactly the ones a pinned write leaves
29
+ * pinned=true on. Age is the tie-breaker that always exists: the oldest anchor
30
+ * goes first, pinned ones included, because a board that names thirteen lessons
31
+ * has already outgrown the point where a reader can hold them. An anchor older
32
+ * than the cap loses the tag rather than the note: the lesson stays readable in
33
+ * the panel and out of the digest, and its pinned flag goes with it, because
34
+ * pinned only ranks notes inside the anchor set.
35
+ */
36
+ export function enforceAnchorCap(notes) {
37
+ const anchors = notes.filter(item => (item.tags || []).includes('anchor'))
38
+ if (anchors.length <= ANCHOR_CAP) return notes
39
+ // Newest first, drop the tail. Ties on updatedAt (a burst of pins inside one
40
+ // millisecond) fall back to board order, which already puts the newest first,
41
+ // so the tie itself resolves the same way the timestamps would.
42
+ const ordered = anchors.slice().sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0))
43
+ const demoteIds = new Set(ordered.slice(ANCHOR_CAP).map(item => item.id))
44
+ return notes.map(item => {
45
+ if (!demoteIds.has(item.id)) return item
46
+ const tags = (item.tags || []).filter(tag => tag !== 'anchor')
47
+ const demoted = Object.assign({}, item, { tags })
48
+ delete demoted.pinned
49
+ return demoted
50
+ })
51
+ }
52
+
53
+ const ANCHOR_CAP = 12
54
+
55
+ export const STATUSES = ['todo', 'doing', 'blocked', 'done']
56
+
57
+ export const PRIORITIES = ['high', 'normal', 'low']
58
+
59
+ let seq = 0
60
+
61
+ export function newId(prefix) {
62
+ seq += 1
63
+ return prefix + '-' + Date.now().toString(36) + '-' + seq.toString(36)
64
+ }
65
+
66
+ export function nowMs() {
67
+ return Date.now()
68
+ }
69
+
70
+ export function emptyBoard() {
71
+ return {
72
+ version: BOARD_VERSION,
73
+ updatedAt: nowMs(),
74
+ objective: '',
75
+ objectiveBy: '',
76
+ objectiveAt: 0,
77
+ objectiveUpdatedAt: 0,
78
+ activeCabinetId: '',
79
+ goalApproval: null,
80
+ // 'plan' or 'goal'. A plan is a list of steps being ticked off; a goal is
81
+ // one persistent objective steered toward, where rewriting the step list
82
+ // every turn hides the fact that the objective never moved. The model picks
83
+ // it, the digest leads with it, the panel shows it. Listed here and in
84
+ // normalizeBoard or it would be dropped on the next load.
85
+ mode: 'plan',
86
+ bounds: { allowed: [], forbidden: [], notes: [] },
87
+ // autoInject ON: the digest is the point of the board. A section the model
88
+ // only sees when someone remembers to flip a switch is a section the model
89
+ // forgets mid-task, which is the failure this plugin exists to prevent.
90
+ settings: { autoInject: true, guardIdle: true, guardMaxPerSession: 3, guardShortAnswer: 600 },
91
+ // Where the work actually stands right now. A plan says what the shape of
92
+ // the job is; the cursor says which step is open, what the very next action
93
+ // is, and what is blocking it. Long tasks die from losing that one line, so
94
+ // it is a first-class field and the digest leads with it.
95
+ cursor: { at: 0, step: '', next: '', blocked: '', by: '', session: '' },
96
+ handoff: {
97
+ at: 0,
98
+ by: '',
99
+ session: '',
100
+ customText: '',
101
+ pinned: false,
102
+ pinnedAt: 0,
103
+ pinnedBy: '',
104
+ updatedAt: 0,
105
+ source: 'auto',
106
+ syncOnDigest: false,
107
+ },
108
+ plan: [],
109
+ tasks: [],
110
+ notes: [],
111
+ memory: [],
112
+ sessions: {},
113
+ log: [],
114
+ }
115
+ }
116
+
117
+ // Leading markdown a note body may carry when it is used as its own headline:
118
+ // '- item', '## heading', '> quote', '* bullet', plus full-width spaces.
119
+ export const LEADING_MARKER = /^[#>*\u3000 \t-]+/u
120
+
121
+ export function str(value, fallback) {
122
+ return typeof value === 'string' ? value : fallback
123
+ }
124
+
125
+ // Caps the action layer applies BEFORE storing text. They mirror the clamps in
126
+ // normalizeTask / normalizeNote / normalizeBoard / memory.js, and they exist as
127
+ // a second copy on purpose: the normalize pass cannot report anything (it holds
128
+ // no result), so the write path does the clipping itself and records what it
129
+ // dropped on the way out.
130
+ export const CAP_TASK_TITLE = 240
131
+
132
+ export const CAP_TASK_NOTE = 2000
133
+
134
+ export const CAP_TASK_INTENT = 600
135
+
136
+ export const CAP_TASK_EVIDENCE = 600
137
+
138
+ export const CAP_ASSUMPTION = 300
139
+
140
+ export const CAP_NOTE_TITLE = 200
141
+
142
+ export const CAP_NOTE_BODY = 20000
143
+
144
+ export const CAP_PLAN_STEP = 400
145
+
146
+ export const CAP_OBJECTIVE = 2000
147
+
148
+ export const CAP_CURSOR = 400
149
+
150
+ export const CAP_LOG_TEXT = 400
151
+
152
+ export const CAP_MEMORY_TITLE = 80
153
+
154
+ export const CAP_MEMORY_TEXT = 700 // memory.js MEMORY_TEXT
155
+
156
+ /* Clip one string to cap and, when it actually lost characters, add a line to
157
+ * the caller's clip list. Returns the clipped value so the call site reads like
158
+ * the plain assignment it replaces. */
159
+ export function clipInto(clips, field, text, cap) {
160
+ const value = typeof text === 'string' ? text : ''
161
+ if (value.length <= cap) return value
162
+ if (Array.isArray(clips)) clips.push({ field, sent: value.length, kept: cap })
163
+ return value.slice(0, cap)
164
+ }
165
+
166
+ /* Attach the clip list to a result only when something was clipped, so every
167
+ * untouched write keeps its exact old shape. */
168
+ export function clipped(result, clips) {
169
+ if (Array.isArray(clips) && clips.length > 0) result.truncated = clips
170
+ return result
171
+ }
172
+
173
+ /* Transport tolerance. Arguments that reach the tools as text are still the
174
+ * same intent: "true" means true, "['a','b']" means two tags. Reading both
175
+ * shapes here keeps a caller's mistake (a flattened list) from being stored as
176
+ * a one-item list, or worse, dropped entirely. */
177
+ export function asBool(value) {
178
+ if (value === true || value === false) return value
179
+ if (typeof value === 'number') return value !== 0
180
+ if (typeof value === 'string') {
181
+ const text = value.trim().toLowerCase()
182
+ if (text === 'true' || text === '1' || text === 'yes' || text === 'y' || text === 'on') return true
183
+ if (text === 'false' || text === '0' || text === 'no' || text === 'n' || text === 'off') return false
184
+ }
185
+ return undefined
186
+ }
187
+
188
+ /* Every count that reaches the tools as text still means the same number, so
189
+ * "5" and 5 are the same setting. Out-of-range values are clamped by the guard
190
+ * itself, but reading them here keeps the log line honest. */
191
+ export function asCount(value) {
192
+ if (typeof value === 'number' && Number.isFinite(value)) return Math.round(value)
193
+ if (typeof value === 'string') {
194
+ const text = value.trim()
195
+ if (!text) return undefined
196
+ const number = Number(text)
197
+ if (Number.isFinite(number)) return Math.round(number)
198
+ }
199
+ return undefined
200
+ }
201
+
202
+ export function asList(value) {
203
+ if (Array.isArray(value)) return value
204
+ if (typeof value !== 'string') return undefined
205
+ const text = value.trim()
206
+ if (!text) return undefined
207
+ if (text.startsWith('[')) {
208
+ try {
209
+ const parsed = JSON.parse(text)
210
+ if (Array.isArray(parsed)) return parsed
211
+ } catch {}
212
+ }
213
+ // A flattened list is still a list: split on the separators a caller would
214
+ // have used rather than storing the whole line as one item.
215
+ return text
216
+ .split(/[,,\n]/u)
217
+ .map(part => part.trim())
218
+ .filter(part => part !== '')
219
+ }
220
+
221
+ export function normalizeTags(list) {
222
+ // Deduplicated: note.pin appends 'anchor' to a list that may already carry it
223
+ // (a note written with tags then pinned), and a repeated tag renders as
224
+ // "anchor/anchor" in the panel and counts twice against the tag column.
225
+ const seen = new Set()
226
+ return list
227
+ .filter(tag => typeof tag === 'string' && tag.trim() !== '')
228
+ .map(tag => tag.trim().slice(0, 40))
229
+ .filter(tag => {
230
+ if (seen.has(tag)) return false
231
+ seen.add(tag)
232
+ return true
233
+ })
234
+ .slice(0, 12)
235
+ }
236
+
237
+ export function normalizeTask(raw) {
238
+ const task = raw && typeof raw === 'object' ? raw : {}
239
+ const status = STATUSES.includes(task.status) ? task.status : 'todo'
240
+ return {
241
+ id: str(task.id, newId('t')),
242
+ title: str(task.title, '').slice(0, 240),
243
+ note: str(task.note, '').slice(0, 2000),
244
+ status,
245
+ priority: PRIORITIES.includes(task.priority) ? task.priority : 'normal',
246
+ owner: str(task.owner, ''),
247
+ session: str(task.session, ''),
248
+ subagent: str(task.subagent, '').slice(0, 120),
249
+ preset: str(task.preset, '').slice(0, 80),
250
+ dispatchedAt: typeof task.dispatchedAt === 'number' ? task.dispatchedAt : 0,
251
+ intent: str(task.intent, '').slice(0, 600),
252
+ evidence: str(task.evidence, '').slice(0, 600),
253
+ blockedBy: Array.isArray(task.blockedBy) ? task.blockedBy.map(item => str(item, '')).filter(Boolean) : [],
254
+ parentId: str(task.parentId, '').slice(0, 200),
255
+ assumptions: Array.isArray(task.assumptions) ? task.assumptions.map(a => ({
256
+ text: str(a && a.text, '').slice(0, CAP_ASSUMPTION),
257
+ verified: a && a.verified === true,
258
+ verifiedAt: typeof (a && a.verifiedAt) === 'number' ? a.verifiedAt : 0,
259
+ note: str(a && a.note, '').slice(0, CAP_ASSUMPTION),
260
+ })).filter(a => a.text) : [],
261
+ createdAt: typeof task.createdAt === 'number' ? task.createdAt : nowMs(),
262
+ updatedAt: typeof task.updatedAt === 'number' ? task.updatedAt : nowMs(),
263
+ }
264
+ }
265
+
266
+ /**
267
+ * Keep DAG dependency statuses coherent whenever tasks are added or updated:
268
+ * - A 'todo' task whose blockedBy contains unfinished tasks becomes 'blocked'.
269
+ * - A 'blocked' task whose blockedBy is non-empty and now ALL 'done' unlocks to 'todo'.
270
+ */
271
+ export function reconcileTaskDependencies(board, by, session) {
272
+ if (!board || !Array.isArray(board.tasks)) return []
273
+ const byId = new Map(board.tasks.map(t => [t.id, t]))
274
+ const unlocked = []
275
+ for (const task of board.tasks) {
276
+ if (!task || task.status === 'done') continue
277
+ const deps = (Array.isArray(task.blockedBy) ? task.blockedBy : []).filter(id => id && id !== task.id && byId.has(id))
278
+ task.blockedBy = deps
279
+ if (!deps.length) continue
280
+ const allDone = deps.every(id => {
281
+ const dep = byId.get(id)
282
+ return dep && dep.status === 'done'
283
+ })
284
+ if (!allDone && task.status === 'todo') {
285
+ task.status = 'blocked'
286
+ task.updatedAt = nowMs()
287
+ } else if (allDone && task.status === 'blocked') {
288
+ task.status = 'todo'
289
+ task.updatedAt = nowMs()
290
+ unlocked.push(task)
291
+ }
292
+ }
293
+ if (unlocked.length && typeof pushLog === 'function') {
294
+ pushLog(
295
+ board,
296
+ '依赖齐备自动解锁:' + unlocked.map(t => '#' + t.id + ' ' + t.title.slice(0, 30)).join('、'),
297
+ by || 'system',
298
+ session || '',
299
+ )
300
+ }
301
+ return unlocked
302
+ }
303
+
304
+ export function normalizeNote(raw) {
305
+ const note = raw && typeof raw === 'object' ? raw : {}
306
+ const tags = Array.isArray(note.tags) ? note.tags : []
307
+ return {
308
+ id: str(note.id, newId('n')),
309
+ title: str(note.title, '').slice(0, 200),
310
+ body: str(note.body, '').slice(0, 20000),
311
+ tags: normalizeTags(tags),
312
+ by: str(note.by, ''),
313
+ session: str(note.session, ''),
314
+ // Kept, because pin marks pinned anchors ahead of the rest in anchorLines,
315
+ // and the mark used to be dropped here on the way to disk — a note pinned
316
+ // once and never re-matched by title lost its rank on the next save.
317
+ // Omitted (not false) so ordinary notes stay out of the file unchanged.
318
+ pinned: note.pinned === true ? true : undefined,
319
+ readBy: Array.isArray(note.readBy) ? note.readBy.map(item => str(item, '')).filter(Boolean) : [],
320
+ createdAt: typeof note.createdAt === 'number' ? note.createdAt : nowMs(),
321
+ updatedAt: typeof note.updatedAt === 'number' ? note.updatedAt : nowMs(),
322
+ }
323
+ }
324
+
325
+ export const BOUND_FIELDS = ['allowed', 'forbidden', 'notes']
326
+
327
+ /** Normalize boundary field names, accepting `'must'` as an alias for `'allowed'` (必做事项). */
328
+ export function normalizeBoundFieldName(raw) {
329
+ const f = str(raw, '').trim().toLowerCase()
330
+ if (f === 'must' || f === 'must_do' || f === 'mustdo') return 'allowed'
331
+ return BOUND_FIELDS.includes(f) ? f : ''
332
+ }
333
+
334
+ // Hard cap on one bounds column. Two different jobs read this number: loading
335
+ // clamps to it (an old or hand-edited board file must never be able to throw
336
+ // while being read), and every write path checks it BEFORE storing anything.
337
+ // The clamp used to be the only guard, which meant bounds.set accepted 25
338
+ // entries and stored 20 under the caller's name — and a bound list is a promise
339
+ // about what must not be done, so the five missing entries are not "lost text":
340
+ // they are restrictions the caller believes are in force and are not.
341
+ export const BOUND_CAP = 20
342
+
343
+ export function normalizeList(value) {
344
+ return Array.isArray(value)
345
+ ? value.filter(item => typeof item === 'string' && item.trim() !== '').map(item => item.trim().slice(0, 400)).slice(0, BOUND_CAP)
346
+ : []
347
+ }
348
+
349
+ export function normalizeBounds(raw) {
350
+ const bounds = raw && typeof raw === 'object' ? raw : {}
351
+ return {
352
+ allowed: normalizeList(bounds.allowed),
353
+ forbidden: normalizeList(bounds.forbidden),
354
+ notes: normalizeList(bounds.notes),
355
+ }
356
+ }
357
+
358
+ function dedupeNotes(list) {
359
+ const seen = new Set()
360
+ const out = []
361
+ for (const note of list) {
362
+ const key = note.title ? 'title:' + note.title : 'id:' + note.id
363
+ if (seen.has(key)) continue
364
+ seen.add(key)
365
+ out.push(note)
366
+ }
367
+ return out
368
+ }
369
+
370
+ function normalizeSessions(raw) {
371
+ const source = raw && typeof raw === 'object' ? raw : {}
372
+ const out = {}
373
+ for (const id of Object.keys(source).slice(0, 40)) {
374
+ const entry = source[id] && typeof source[id] === 'object' ? source[id] : {}
375
+ out[id] = {
376
+ lastSeen: typeof entry.lastSeen === 'number' ? entry.lastSeen : nowMs(),
377
+ cwd: str(entry.cwd, ''),
378
+ turns: typeof entry.turns === 'number' ? entry.turns : 0,
379
+ }
380
+ }
381
+ return out
382
+ }
383
+
384
+ /** One bounded integer setting, defaulted on read so an old board still loads. */
385
+ export function guardCount(value, fallback, min, max) {
386
+ const number = Number(value)
387
+ if (!Number.isFinite(number)) return fallback
388
+ return Math.min(max, Math.max(min, Math.round(number)))
389
+ }
390
+
391
+ function normalizeGoalApproval(raw) {
392
+ if (!raw || typeof raw !== 'object') return null
393
+ const status = ['pending', 'approved', 'rejected'].includes(raw.status) ? raw.status : ''
394
+ if (!status) return null
395
+ return {
396
+ id: str(raw.id, newId('ga')),
397
+ status,
398
+ objective: str(raw.objective, '').slice(0, 600),
399
+ summary: str(raw.summary, '').slice(0, 600),
400
+ evidence: str(raw.evidence, '').slice(0, 800),
401
+ rejectReason: str(raw.rejectReason, '').slice(0, 300),
402
+ at: typeof raw.at === 'number' ? raw.at : nowMs(),
403
+ decidedAt: typeof raw.decidedAt === 'number' ? raw.decidedAt : 0,
404
+ }
405
+ }
406
+
407
+ export function normalizeBoard(raw) {
408
+ const board = raw && typeof raw === 'object' ? raw : {}
409
+ const plan = Array.isArray(board.plan) ? board.plan : []
410
+ const tasks = Array.isArray(board.tasks) ? board.tasks : []
411
+ const log = Array.isArray(board.log) ? board.log : []
412
+ const notes = Array.isArray(board.notes) ? board.notes : []
413
+ return {
414
+ version: BOARD_VERSION,
415
+ updatedAt: typeof board.updatedAt === 'number' ? board.updatedAt : nowMs(),
416
+ objective: str(board.objective, ''),
417
+ objectiveBy: str(board.objectiveBy, ''),
418
+ objectiveAt: typeof board.objectiveAt === 'number' ? board.objectiveAt : 0,
419
+ objectiveUpdatedAt: typeof board.objectiveUpdatedAt === 'number' ? board.objectiveUpdatedAt : (typeof board.objectiveAt === 'number' ? board.objectiveAt : 0),
420
+ activeCabinetId: str(board.activeCabinetId, '').trim(),
421
+ goalApproval: normalizeGoalApproval(board.goalApproval),
422
+ // Whitelisted, not free-form: an unknown mode would make every consumer
423
+ // (digest, panel) disagree about which shape the board has.
424
+ mode: board.mode === 'goal' ? 'goal' : 'plan',
425
+ bounds: normalizeBounds(board.bounds),
426
+ // Unknown settings keys are dropped on purpose; every flag the plugin reads
427
+ // must be listed here or it silently disappears on the next load.
428
+ settings: {
429
+ // Defaults to ON now that the section is registered unconditionally: the
430
+ // flag records the operator's preference, and an OLD board that stored
431
+ // false must not read back as "off" while the digest is still injected.
432
+ autoInject: !(board.settings && board.settings.autoInject === false),
433
+ guardIdle: !(board.settings && board.settings.guardIdle === false),
434
+ // Counts, not flags: the guard's two numbers live on the same board so an
435
+ // operator can loosen them without editing the package. Clamped when read.
436
+ guardMaxPerSession: guardCount(board.settings && board.settings.guardMaxPerSession, 3, 0, 20),
437
+ guardShortAnswer: guardCount(board.settings && board.settings.guardShortAnswer, 600, 0, 10000),
438
+ },
439
+ handoff: {
440
+ at: board.handoff && typeof board.handoff.at === 'number' ? board.handoff.at : 0,
441
+ by: str(board.handoff && board.handoff.by, ''),
442
+ session: str(board.handoff && board.handoff.session, ''),
443
+ customText: str(board.handoff && board.handoff.customText, '').slice(0, 16000),
444
+ pinned: board.handoff ? board.handoff.pinned === true : false,
445
+ frozenFromAuto: board.handoff ? board.handoff.frozenFromAuto === true : false,
446
+ pinnedAt: board.handoff && typeof board.handoff.pinnedAt === 'number' ? board.handoff.pinnedAt : 0,
447
+ pinnedBy: str(board.handoff && board.handoff.pinnedBy, ''),
448
+ updatedAt: board.handoff && typeof board.handoff.updatedAt === 'number' ? board.handoff.updatedAt : 0,
449
+ source: ['human', 'chief', 'auto'].includes(str(board.handoff && board.handoff.source, '')) ? board.handoff.source : 'auto',
450
+ syncOnDigest: board.handoff ? board.handoff.syncOnDigest === true : false,
451
+ },
452
+ cursor: {
453
+ at: board.cursor && typeof board.cursor.at === 'number' ? board.cursor.at : 0,
454
+ step: str(board.cursor && board.cursor.step, '').slice(0, 400),
455
+ next: str(board.cursor && board.cursor.next, '').slice(0, 400),
456
+ blocked: str(board.cursor && board.cursor.blocked, '').slice(0, 400),
457
+ by: str(board.cursor && board.cursor.by, ''),
458
+ session: str(board.cursor && board.cursor.session, ''),
459
+ },
460
+ plan: plan
461
+ .map(step => ({
462
+ id: str(step && step.id, newId('s')),
463
+ text: str(step && step.text, '').slice(0, 400),
464
+ done: step && step.done === true,
465
+ }))
466
+ .filter(step => step.text !== ''),
467
+ tasks: tasks.map(normalizeTask).filter(task => task.title !== ''),
468
+ notes: dedupeNotes(notes.map(normalizeNote).filter(note => note.title !== '' || note.body !== '')),
469
+ // Rolling conversation memory. Not in the notes list on purpose: notes are
470
+ // hand-written and the human owns them, memory is written by the host as
471
+ // turns close and only the panel and the digest read it.
472
+ memory: normalizeMemory(board.memory),
473
+ sessions: normalizeSessions(board.sessions),
474
+ log: log.slice(-LOG_CAP).map(entry => ({
475
+ at: typeof entry.at === 'number' ? entry.at : nowMs(),
476
+ by: str(entry.by, ''),
477
+ session: str(entry.session, ''),
478
+ text: str(entry.text, '').slice(0, 400),
479
+ })),
480
+ }
481
+ }
482
+
483
+ export function pushLog(board, text, by, session) {
484
+ board.log.push({ at: nowMs(), by: str(by, ''), session: str(session, ''), text: str(text, '') })
485
+ if (board.log.length > LOG_CAP) board.log = board.log.slice(-LOG_CAP)
486
+ }
487
+
488
+ /** One log line per intervention, naming the shape the guard caught. */
489
+ export function guardLogText(verdict, turn, remaining) {
490
+ const tail = ',已催一步(本会话还剩 ' + remaining + ' 次)'
491
+ if (verdict && verdict.kind === 'loop') {
492
+ const loop = verdict.loop || {}
493
+ return '空转拦截:第 ' + turn + ' 轮同一个调用连着做了 ' + (loop.count || 0) + ' 次('
494
+ + String(loop.name || '?').slice(0, 40) + ')结果没变' + tail
495
+ }
496
+ if (verdict && verdict.kind === 'no-goal') {
497
+ return '空转拦截:第 ' + turn + ' 轮板子处在 goal 模式却没有目标' + tail
498
+ }
499
+ if (verdict && verdict.kind === 'no-plan') {
500
+ return '空转拦截:第 ' + turn + ' 轮动手了但参谋看板上没有规划' + tail
501
+ }
502
+ if (verdict && verdict.kind === 'stale-plan') {
503
+ return '空转拦截:第 ' + turn + ' 轮做了事但规划没动(还有 '
504
+ + (verdict.work ? verdict.work.total : 0) + ' 项未完成)' + tail
505
+ }
506
+ return '空转拦截:第 ' + turn + ' 轮没有工具调用、回答 '
507
+ + (verdict && verdict.answer ? verdict.answer.chars : 0) + ' 字就收工' + tail
508
+ }
509
+
510
+ /* ------------------------------------------------------------------ boundaries */
511
+
512
+ export function safe(read, fallback) {
513
+ try {
514
+ const value = read()
515
+ return value === undefined ? fallback : value
516
+ } catch {
517
+ return fallback
518
+ }
519
+ }
520
+
521
+ const NOTE_LIMIT = 20
522
+
523
+ const LOG_LIMIT = 12
524
+
525
+ export function summary(board, subagents) {
526
+ const counts = { todo: 0, doing: 0, blocked: 0, done: 0 }
527
+ for (const task of board.tasks) counts[task.status] = (counts[task.status] || 0) + 1
528
+ return {
529
+ counts,
530
+ open: board.tasks.filter(task => task.status !== 'done').length,
531
+ tasks: board.tasks.map(task => ({
532
+ id: task.id,
533
+ title: task.title,
534
+ status: task.status,
535
+ priority: task.priority,
536
+ owner: task.owner,
537
+ subagent: task.subagent || '',
538
+ preset: task.preset || '',
539
+ session: task.session,
540
+ parentId: task.parentId || '',
541
+ blockedBy: Array.isArray(task.blockedBy) ? task.blockedBy : [],
542
+ intent: task.intent || '',
543
+ evidence: task.evidence || '',
544
+ assumptions: Array.isArray(task.assumptions) ? task.assumptions : [],
545
+ note: task.note,
546
+ dispatchedAt: task.dispatchedAt || 0,
547
+ updatedAt: task.updatedAt,
548
+ })),
549
+ ...(Array.isArray(subagents) ? { subagents } : {}),
550
+ objective: board.objective,
551
+ bounds: board.bounds || { allowed: [], forbidden: [], notes: [] },
552
+ ...(board.pinnedBounds ? { pinnedBounds: board.pinnedBounds } : {}),
553
+ plan: board.plan,
554
+ notes: board.notes.slice(0, NOTE_LIMIT).map(note => ({
555
+ id: note.id,
556
+ title: note.title,
557
+ body: note.body.length > 400 ? note.body.slice(0, 400) + '…' : note.body,
558
+ tags: note.tags,
559
+ by: note.by,
560
+ session: note.session,
561
+ updatedAt: note.updatedAt,
562
+ })),
563
+ notesCount: board.notes.length,
564
+ notesLimit: NOTE_LIMIT,
565
+ log: board.log.slice(-LOG_LIMIT),
566
+ logCount: board.log.length,
567
+ memory: (board.memory || []).slice(-12).map(item => ({
568
+ id: item.id,
569
+ at: item.at,
570
+ turn: item.turn,
571
+ section: item.section,
572
+ title: item.title,
573
+ text: item.text,
574
+ tools: item.tools,
575
+ by: item.by,
576
+ })),
577
+ memoryCount: (board.memory || []).length,
578
+ updatedAt: board.updatedAt,
579
+ }
580
+ }