@yolk_vat-y/dsh-project-memory 0.7.1 → 0.7.3

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.
Files changed (45) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +0 -0
  3. package/README.md +9 -9
  4. package/README.zh-CN.md +8 -8
  5. package/client/client.js +139 -43
  6. package/client/client.js.map +1 -1
  7. package/cordis.patch.yml +0 -0
  8. package/package.json +2 -2
  9. package/scripts/bench-edits.mjs +0 -0
  10. package/scripts/bench-store.mjs +0 -0
  11. package/skills/project-memory/SKILL.md +38 -10
  12. package/src/audit.js +2 -2
  13. package/src/auto-inject.js +10 -5
  14. package/src/client/MemoryView.tsx +5 -14
  15. package/src/client/TaskComponents.tsx +109 -99
  16. package/src/client/TaskPanel.module.css +10 -4
  17. package/src/client/TaskPanel.tsx +49 -2
  18. package/src/client/locales.ts +2 -0
  19. package/src/client/task-data-store.ts +2 -0
  20. package/src/client/task-window.js +33 -0
  21. package/src/commands/insight-actions.js +43 -41
  22. package/src/commands/task-actions.js +42 -21
  23. package/src/commands/tasks.js +24 -10
  24. package/src/index-pipeline.js +5 -3
  25. package/src/inject-visible.js +16 -18
  26. package/src/insight-store.js +90 -72
  27. package/src/readiness.js +2 -2
  28. package/src/setup/taskbridge.js +51 -5
  29. package/src/setup/team-task.js +220 -0
  30. package/src/store.js +105 -82
  31. package/src/symbols.js +0 -0
  32. package/src/tools/forget.js +9 -1
  33. package/src/tools/index-doc.js +37 -41
  34. package/src/tools/lesson-tools.js +119 -22
  35. package/src/tools/query-memory.js +115 -14
  36. package/src/tools/task-tools.js +83 -16
  37. package/src/util/fs.js +57 -17
  38. package/src/util/hash.js +12 -0
  39. package/src/util/insight-fields.js +56 -1
  40. package/src/util/merge-by-id.js +56 -0
  41. package/src/util/persist.js +2 -1
  42. package/src/util/session-cache.js +4 -3
  43. package/src/util/task-view.js +18 -0
  44. package/src/vector-index.js +6 -5
  45. package/src/watch.js +4 -2
@@ -0,0 +1,33 @@
1
+ /**
2
+ * 任务列表的渐进渲染窗口(纯函数,无 React 依赖)。
3
+ *
4
+ * 任务数据整份都在面板载荷里(`/tasks` 快照,单任务的步骤/文件已由服务端截断),
5
+ * 这里只决定**渲染多少张卡**:首屏 TASK_PAGE_SIZE 张,滚到列表底部由哨兵放出下一批。
6
+ * 不改变服务端给的顺序,也不动已展开卡片的 UI 状态——只是把 DOM 数量跟视口挂钩。
7
+ * 决策边界由 test/client-task-window.test.mjs 钉住。
8
+ */
9
+
10
+ /** 每批渲染的任务卡数。卡片比记忆行高(约 70px 起,展开后更高),批次取小些。 */
11
+ export const TASK_PAGE_SIZE = 12
12
+
13
+ /**
14
+ * 哨兵的预取余量。这里故意是 0:任务数据本来就在载荷里,放下一批是同步的、没有等待,
15
+ * 预取只会让"首屏 12 张"变成"首屏 24 张"(12 张折叠卡约 520px,600px 的预取带宽会立刻
16
+ * 再触发一次)。滚到列表底部时下一批当场出现,用户看不到加载态。
17
+ */
18
+ export const TASK_PREFETCH_MARGIN = '0px'
19
+
20
+ /**
21
+ * 再放一批之后渲染到第几张。
22
+ * @param {number} current - 当前渲染上限。
23
+ * @param {number} total - 当前活跃任务总数。
24
+ * @param {number} [step] - 每批张数,默认 TASK_PAGE_SIZE。
25
+ * @returns {number} 新的渲染上限:不超过 total,也不比 current 小(非法输入按 0 起算)。
26
+ */
27
+ export function nextTaskCount(current, total, step = TASK_PAGE_SIZE) {
28
+ const t = Number.isFinite(total) && total > 0 ? Math.floor(total) : 0
29
+ if (t === 0) return 0
30
+ const s = Number.isFinite(step) && step > 0 ? Math.floor(step) : TASK_PAGE_SIZE
31
+ const c = Number.isFinite(current) && current > 0 ? Math.floor(current) : 0
32
+ return Math.min(t, c + s)
33
+ }
@@ -8,8 +8,9 @@ import { memoryRootFor, normalizeCitationFiles } from '../util/fs.js'
8
8
  import { cfgInsight, GlobalStore, normalizeInsight, defaultGlobalFile, saveInsight, recordDeleted, carryUsageFields, mergeOrPushInto, demoteToProject, demoteToTask, pruneItems, refreshDerivedTrigger, putInsightField, INSIGHT_KINDS } from '../insight-store.js'
9
9
  import { NO_PROJECT_ROOT_NOTE, projectRootFor } from '../setup/taskbridge.js'
10
10
  import { fencedJson, invocationContext } from './invocation.js'
11
+ import { taskVisibility } from '../setup/team-task.js'
11
12
  import { isoMs } from '../util/value.js'
12
- import { pruneKindFields } from '../util/insight-fields.js'
13
+ import { bodyFieldOf, pruneKindFields } from '../util/insight-fields.js'
13
14
  import { forgetVectorRows } from '../vector-index.js'
14
15
 
15
16
  /** 容量旋钮的防御性取值:cfg 可能只带显式测试字段。 */
@@ -55,7 +56,7 @@ function insSummary(ins, extra = {}) {
55
56
  if (s.kind === 'procedure' && Array.isArray(s.steps) && s.steps.length) {
56
57
  return `步骤 ${s.steps.length} 条:${String(s.steps[0]).slice(0, 80)}`
57
58
  }
58
- const byKind = s.kind === 'lesson' ? s.fix : s.kind === 'decision' ? s.reason : s.kind === 'experience' ? s.solution : s.body
59
+ const byKind = s[bodyFieldOf(s.kind)]
59
60
  const cands = [byKind, s.fix, s.solution, s.reason, s.body, s.choice, s.pattern, s.problem]
60
61
  for (const v of cands) if (v && v !== s.title) return v
61
62
  return ''
@@ -76,8 +77,10 @@ function insSummary(ins, extra = {}) {
76
77
  }
77
78
  }
78
79
 
79
- function findTaskInsight(store, id) {
80
+ function findTaskInsight(store, id, taskVisible = null) {
80
81
  for (const t of store.getTasks() || []) {
82
+ // 面板动作也可能被别队会话的客户端触发:任务级条目按任务可见性过滤。
83
+ if (taskVisible && !taskVisible(t)) continue
81
84
  const hit = (t.insights || []).find((i) => i.id === id)
82
85
  if (hit) return { task: t, insight: hit }
83
86
  }
@@ -120,11 +123,14 @@ function compareInsightRecency(a, b) {
120
123
  */
121
124
  export function listInsights(store, gs, scope, opts = {}) {
122
125
  const s = scope || 'project'
126
+ const taskVisible = opts.taskVisible || null
123
127
  // 先收集「原始条目 + 附加字段」,**排序在摘要之前**:摘要会丢掉 createdAt,
124
128
  // 而这个字段是稳定全序的第二级键。
125
129
  const collected = []
126
130
  if (s === 'task') {
127
131
  for (const t of store.getTasks() || []) {
132
+ // 面板载荷会写进会话历史:别队的团队任务条目不能出现在列表里。
133
+ if (taskVisible && !taskVisible(t)) continue
128
134
  for (const i of t.insights || []) collected.push({ raw: i, extra: { taskId: t.id, taskTitle: t.title } })
129
135
  }
130
136
  } else if (s === 'global') {
@@ -148,14 +154,14 @@ export function listInsights(store, gs, scope, opts = {}) {
148
154
  * archive | restore | delete;scope: task|project|global(列表里条目的当前 scope)。
149
155
  * demote 到 task 需要 taskId;promote/global 之上无层级时返回错误。
150
156
  */
151
- export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
157
+ export function actInsight({ store, gs, action, scope, id, taskId, cfg, taskVisible = null }) {
152
158
  const act = action || ''
153
159
  const s = scope || 'project'
154
160
  if (!id) return { ok: false, text: '需要 id' }
155
161
  const invalid = () => ({ ok: false, text: `insight ${id} 不在 ${s} 层(可能已移动/删除)` })
156
162
 
157
163
  if (s === 'task') {
158
- const found = findTaskInsight(store, id)
164
+ const found = findTaskInsight(store, id, taskVisible)
159
165
  if (!found) return invalid()
160
166
  const { task, insight } = found
161
167
  if (act === 'confirm') {
@@ -250,7 +256,7 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
250
256
  if (act === 'demote') {
251
257
  // project → task(需目标任务);去重/去留统一走 insight-store 的唯一实现。
252
258
  const task = store.getTask(taskId)
253
- if (!task) return { ok: false, text: '降级到任务需要 taskId' }
259
+ if (!task || (taskVisible && !taskVisible(task))) return { ok: false, text: '降级到任务需要 taskId' }
254
260
  const moved = demoteToTask(store, taskId, id, new Date().toISOString(), cfg)
255
261
  if (!moved.ok) return { ok: false, text: moved.error }
256
262
  return {
@@ -310,7 +316,7 @@ export function saveMemoryItem({ store, gs, cfg, scope, fields }) {
310
316
  const EDIT_FIELDS = new Set(['title', 'kind', 'body', 'pattern', 'fix', 'problem', 'solution', 'choice', 'reason', 'confidence', 'steps', 'trigger', 'tags', 'files', 'symbols'])
311
317
 
312
318
  /** 编辑既有条目(title/kind/正文/trigger 等白名单字段)。任务级按 id 在任务池定位。 */
313
- export function editMemoryItem({ store, gs, scope, id, fields, root }) {
319
+ export function editMemoryItem({ store, gs, scope, id, fields, root, taskVisible = null }) {
314
320
  if (!fields || typeof fields !== 'object') return { ok: false, text: 'edit 需要字段对象' }
315
321
  const applyTo = (item) => {
316
322
  let changed = false
@@ -374,7 +380,7 @@ export function editMemoryItem({ store, gs, scope, id, fields, root }) {
374
380
  const s = scope || 'project'
375
381
  if (!['task', 'project', 'global'].includes(s)) return { ok: false, text: `未知 scope: ${s}(只认 task/project/global)` }
376
382
  if (s === 'task') {
377
- const found = findTaskInsight(store, id)
383
+ const found = findTaskInsight(store, id, taskVisible)
378
384
  if (!found) return { ok: false, text: `insight ${id} 不在任务层` }
379
385
  const applied = applyTo(found.insight)
380
386
  if (!applied.changed) return { ok: false, text: '没有可更新的字段' }
@@ -411,13 +417,31 @@ export function insightCommandDefinition(config, ctx) {
411
417
  input: { hint: 'list [scope] [offset] [limit] | <动作> <scope> <id> [taskId]' },
412
418
  handler: (invocation) => {
413
419
  try {
414
- const { cwd } = invocationContext(invocation)
420
+ const { cwd, agent } = invocationContext(invocation)
421
+ const taskVisible = agent ? taskVisibility({ agent }) : null
415
422
  const lineRaw = (invocation?.rawInput || '').trim()
416
423
  const raw = lineRaw.split(/\s+/).filter(Boolean)
417
424
  const root = projectRootFor(cwd, config)
418
425
  if (!root) return { kind: 'error', text: NO_PROJECT_ROOT_NOTE }
419
426
  if (!raw[0]) return { kind: 'error', text: '[insight] 用法见面板' }
420
427
  const verb = raw[0]
428
+ // 每个动词都是「打开两个 store → 变更 → 落盘 → 把写盘失败翻成错误」这条流水线。
429
+ // 四处各写一份时,提交顺序与错误文案会漂移(漏一次 `commit` 就是静默丢写),只留这一份。
430
+ const openStores = () => {
431
+ const cfg = cfgInsight(config)
432
+ const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
433
+ // 与工具/自动注入同一个 global 解析顺序:显式配置优先,否则默认文件。
434
+ const gs = new GlobalStore(cfg.globalFile || defaultGlobalFile()).load()
435
+ return { store, gs, cfg }
436
+ }
437
+ const commitBoth = (store, gs, res) => {
438
+ store.commit(() => 0) // 项目侧(tasks/insights)落盘
439
+ gs.commit() // global 侧若有变更落盘
440
+ if (res.ok && (store.lastSaveOk === false || gs.lastCommitOk === false)) {
441
+ return { kind: 'error', text: `${res.text};但写盘失败(权限/磁盘/锁),重启后会丢失` }
442
+ }
443
+ return res.ok ? { kind: 'success', text: res.text } : { kind: 'error', text: res.text }
444
+ }
421
445
  if (verb === 'list') {
422
446
  if (raw[1] !== undefined && !['task', 'global', 'project'].includes(raw[1])) {
423
447
  return { kind: 'error', text: `[insight] 未知 scope: ${raw[1]}(只认 task/project/global)` }
@@ -437,9 +461,8 @@ export function insightCommandDefinition(config, ctx) {
437
461
  if (!Number.isFinite(n) || n <= 0) return { kind: 'error', text: '[insight] limit 必须是正整数' }
438
462
  limit = Math.min(n, INSIGHT_PAGE_MAX)
439
463
  }
440
- const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
441
- const gs = new GlobalStore(cfgInsight(config).globalFile || defaultGlobalFile()).load()
442
- const payload = listInsights(store, gs, scope, { offset, limit })
464
+ const { store, gs } = openStores()
465
+ const payload = listInsights(store, gs, scope, { offset, limit, taskVisible })
443
466
  const shown = offset + payload.items.length
444
467
  const range = limit === null ? '' : `(显示 ${shown}/${payload.total})`
445
468
  return { kind: 'success', text: fencedJson(`记忆 ${scope}:${payload.count} 条${range}`, JSON.stringify(payload)) }
@@ -466,17 +489,10 @@ export function insightCommandDefinition(config, ctx) {
466
489
  droppedFiles = norm.dropped.length
467
490
  fields = { ...fields, files: norm.files }
468
491
  }
469
- const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
470
- const gs = new GlobalStore(cfgInsight(config).globalFile || defaultGlobalFile()).load()
471
- const res = saveMemoryItem({ store, gs, cfg: cfgInsight(config), scope, fields })
472
- store.commit(() => 0)
473
- gs.commit()
474
- if (res.ok && (store.lastSaveOk === false || gs.lastCommitOk === false)) {
475
- return { kind: 'error', text: `${res.text};但写盘失败(权限/磁盘/锁),重启后会丢失` }
476
- }
477
- return res.ok
478
- ? { kind: 'success', text: res.text + (droppedFiles ? `;${droppedFiles} 个 files 是项目外路径,已丢弃` : '') }
479
- : { kind: 'error', text: res.text }
492
+ const { store, gs, cfg } = openStores()
493
+ const res = saveMemoryItem({ store, gs, cfg, scope, fields })
494
+ if (res.ok && droppedFiles) res.text += `;${droppedFiles} 个 files 是项目外路径,已丢弃`
495
+ return commitBoth(store, gs, res)
480
496
  }
481
497
  if (verb === 'edit') {
482
498
  // /insight edit <scope> <id> <json>
@@ -491,15 +507,8 @@ export function insightCommandDefinition(config, ctx) {
491
507
  } catch {
492
508
  return { kind: 'error', text: '[insight] edit 需要 JSON 参数(由面板生成)' }
493
509
  }
494
- const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
495
- const gs = new GlobalStore(cfgInsight(config).globalFile || defaultGlobalFile()).load()
496
- const res = editMemoryItem({ store, gs, scope, id, fields, root })
497
- store.commit(() => 0)
498
- gs.commit()
499
- if (res.ok && (store.lastSaveOk === false || gs.lastCommitOk === false)) {
500
- return { kind: 'error', text: `${res.text};但写盘失败(权限/磁盘/锁),重启后会丢失` }
501
- }
502
- return res.ok ? { kind: 'success', text: res.text } : { kind: 'error', text: res.text }
510
+ const { store, gs } = openStores()
511
+ return commitBoth(store, gs, editMemoryItem({ store, gs, scope, id, fields, root, taskVisible }))
503
512
  }
504
513
  const scope = raw[1]
505
514
  const id = raw[2]
@@ -507,15 +516,8 @@ export function insightCommandDefinition(config, ctx) {
507
516
  if (!['confirm', 'promote', 'demote', 'archive', 'restore', 'delete'].includes(verb) || !id) {
508
517
  return { kind: 'error', text: '[insight] 用法: /tasks insight <动作|save|edit> …' }
509
518
  }
510
- const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
511
- const gs = new GlobalStore(cfgInsight(config).globalFile || defaultGlobalFile()).load()
512
- const res = actInsight({ store, gs, action: verb, scope, id, taskId, cfg: cfgInsight(config) })
513
- store.commit(() => 0) // 项目侧(tasks/insights)落盘
514
- gs.commit() // global 侧若有变更落盘
515
- if (res.ok && (store.lastSaveOk === false || gs.lastCommitOk === false)) {
516
- return { kind: 'error', text: `${res.text};但写盘失败(权限/磁盘/锁),重启后会丢失` }
517
- }
518
- return res.ok ? { kind: 'success', text: res.text } : { kind: 'error', text: res.text }
519
+ const { store, gs, cfg } = openStores()
520
+ return commitBoth(store, gs, actInsight({ store, gs, action: verb, scope, id, taskId, cfg, taskVisible }))
519
521
  } catch (err) {
520
522
  return { kind: 'error', text: `[insight] ${err?.message || err}` }
521
523
  }
@@ -7,7 +7,16 @@ import { renderTaskSnapshot, buildTaskPayload } from './tasks.js'
7
7
  import { fireReflect } from '../reflection-pipeline.js'
8
8
  import { resolveRoute } from '../llm-route.js'
9
9
  import { fencedJson, invocationContext } from './invocation.js'
10
- import { STEP_STATUSES, stepContent, stepProgress, stepStatus } from '../util/task-view.js'
10
+ import { recheckTeamAnchor, taskVisibility, taskVisibleTo } from '../setup/team-task.js'
11
+ import { STEP_STATUSES, sortTasksByRecency, stepContent, stepProgress, stepStatus } from '../util/task-view.js'
12
+
13
+ /**
14
+ * 团队任务的步骤不是本地数据:锚点只存任务级记忆,步骤属于宿主团队任务板。
15
+ * 面板的单步编辑/整份回写都走这里拒绝,避免把某个成员的清单写进共享锚点。
16
+ */
17
+ function teamStepsError(task) {
18
+ return { kind: 'error', text: `[task] 「${task.title}」是团队任务:步骤由宿主团队任务板维护,记忆锚点只存任务级记忆` }
19
+ }
11
20
 
12
21
  function describeTask(t) {
13
22
  const { done, total } = stepProgress(t)
@@ -31,9 +40,11 @@ function restAfter(raw, n) {
31
40
  return raw.slice(i).replace(/^\s+/, '')
32
41
  }
33
42
 
34
- function withTaskSnapshot(config, cwd, sid, store, note) {
35
- const tasks = store.getTasks()
36
- const active = tasks.filter((t) => !t.archived)
43
+ function withTaskSnapshot(config, cwd, sid, store, note, exec = null) {
44
+ // 快照会写进会话历史:团队锚点只保留本会话可见的那些(与 /tasks 同一判据)。
45
+ const visible = exec ? taskVisibility(exec) : null
46
+ const tasks = visible ? store.getTasks().filter(visible) : store.getTasks()
47
+ const active = sortTasksByRecency(tasks.filter((t) => !t.archived))
37
48
  const archived = tasks.length - active.length
38
49
  const boundId = sid ? store.getBoundTaskId(sid) : null
39
50
  const root = projectRootFor(cwd, config)
@@ -61,14 +72,14 @@ export function taskCommandDefinition(config, ctx) {
61
72
  input: { hint: 'switch|archive <任务id> | unbind' },
62
73
  handler: (invocation) => {
63
74
  try {
64
- const { session, sid, cwd } = invocationContext(invocation)
75
+ const { agent, session, sid, cwd } = invocationContext(invocation)
65
76
  const raw = (invocation?.rawInput || '').trim()
66
77
  const [verb, taskId, ...rest] = raw.split(/\s+/)
67
78
 
68
79
  // 无参数:等同 /tasks(不报错、不强制输入任务 id)——
69
80
  // switch/archive/unbind 由卡片按钮自动调用,用户无需手敲。
70
81
  if (!verb) {
71
- const snap = renderTaskSnapshot(config, cwd, sid)
82
+ const snap = renderTaskSnapshot(config, cwd, sid, agent ? { agent } : null)
72
83
  if (snap.kind === 'success') {
73
84
  snap.text = `[任务] 用法: /task switch|archive <任务id> | unbind(卡片按钮会自动调用;不带参数等同 /tasks)\n\n${snap.text}`
74
85
  }
@@ -88,14 +99,15 @@ export function taskCommandDefinition(config, ctx) {
88
99
  session.append('todo/write', { todos: [] })
89
100
  }
90
101
  const note = '已取消当前任务绑定并清空会话任务清单(需要时可让模型重新规划)'
91
- return withTaskSnapshot(config, cwd, sid, store, note)
102
+ return withTaskSnapshot(config, cwd, sid, store, note, agent ? { agent } : null)
92
103
  }
93
104
 
94
105
  // 单步原子写:客户端不再回写整份 steps,避免两个并发动作互相覆盖。
95
106
  if (verb === 'step' || verb === 'step-move' || verb === 'step-text') {
96
107
  if (!taskId) return { kind: 'error', text: `[task] ${verb} 需要任务 id` }
97
108
  const task = store.getTask(taskId)
98
- if (!task) return { kind: 'error', text: `[task] 找不到任务: ${taskId}` }
109
+ if (!task || !taskVisibleTo(task, { agent })) return { kind: 'error', text: `[task] 找不到任务: ${taskId}` }
110
+ if (task.teamTaskId) return teamStepsError(task)
99
111
  if (!Array.isArray(task.steps)) task.steps = []
100
112
  if (verb === 'step') {
101
113
  const index = Number(rest[0])
@@ -141,7 +153,7 @@ export function taskCommandDefinition(config, ctx) {
141
153
  store.markTasksDirty()
142
154
  store.save()
143
155
  if (shouldAdoptToHost(config)) adoptStepsToSession(session, task)
144
- return withTaskSnapshot(config, cwd, sid, store, `已更新「${task.title}」步骤`)
156
+ return withTaskSnapshot(config, cwd, sid, store, `已更新「${task.title}」步骤`, agent ? { agent } : null)
145
157
  }
146
158
 
147
159
  // /task rename <任务id> <json标题> —— 双击任务标题改名
@@ -156,7 +168,7 @@ export function taskCommandDefinition(config, ctx) {
156
168
  title = title.trim()
157
169
  if (!title) return { kind: 'error', text: '[task] 标题不能为空' }
158
170
  const task = store.getTask(taskId)
159
- if (!task) return { kind: 'error', text: `[task] 找不到任务: ${taskId}` }
171
+ if (!task || !taskVisibleTo(task, { agent })) return { kind: 'error', text: `[task] 找不到任务: ${taskId}` }
160
172
  const oldTitle = task.title
161
173
  task.title = title
162
174
  task.updatedAt = new Date().toISOString()
@@ -164,8 +176,9 @@ export function taskCommandDefinition(config, ctx) {
164
176
  // 直接改 task 内容 → 必须标脏:save() 没脏标记会早退(改动静默丢失),驻留账也停在旧水位。
165
177
  store.markTasksDirty()
166
178
  store.save()
167
- const note = `已改名「${oldTitle}」→「${title}」`
168
- return withTaskSnapshot(config, cwd, sid, store, note)
179
+ const teamNote = task.teamTaskId ? '(仅本地记忆标题,宿主团队任务未变)' : ''
180
+ const note = `已改名「${oldTitle}」→「${title}」${teamNote}`
181
+ return withTaskSnapshot(config, cwd, sid, store, note, agent ? { agent } : null)
169
182
  }
170
183
 
171
184
  // /task todos <json> —— 卡片双击编辑步骤后,把整份新清单写回绑定任务并推宿主
@@ -189,7 +202,8 @@ export function taskCommandDefinition(config, ctx) {
189
202
  return { kind: 'error', text: '[task] 未绑定任务,无法编辑步骤;先在卡片上“切换到此任务”' }
190
203
  }
191
204
  const task = store.getTask(boundId)
192
- if (!task) return { kind: 'error', text: '[task] 绑定任务不存在' }
205
+ if (!task || !taskVisibleTo(task, { agent })) return { kind: 'error', text: '[task] 绑定任务不存在' }
206
+ if (task.teamTaskId) return teamStepsError(task)
193
207
  task.steps = norm
194
208
  task.updatedAt = new Date().toISOString()
195
209
  task.lastActiveAt = task.updatedAt
@@ -199,12 +213,16 @@ export function taskCommandDefinition(config, ctx) {
199
213
  adoptStepsToSession(session, task, { force: true })
200
214
  }
201
215
  const note = `已更新「${task.title}」步骤(${norm.length} 条)`
202
- return withTaskSnapshot(config, cwd, sid, store, note)
216
+ return withTaskSnapshot(config, cwd, sid, store, note, agent ? { agent } : null)
203
217
  }
204
218
 
205
219
  if (verb === 'switch') {
206
220
  const task = store.getTask(taskId)
207
- if (!task) return { kind: 'error', text: `[task] 找不到任务: ${taskId}(/tasks 查看)` }
221
+ if (!task || !taskVisibleTo(task, { agent })) return { kind: 'error', text: `[task] 找不到任务: ${taskId}(/tasks 查看)` }
222
+ // 原始锚点不经过宿主视图:绑定前补一次复核,宿主已删的任务不再切进来。
223
+ const check = recheckTeamAnchor({ agent }, task)
224
+ if (!check.ok && check.reason === 'not-found') return { kind: 'error', text: `[task] 团队任务已不存在: ${task.title}` }
225
+ if (!check.ok) return { kind: 'error', text: `[task] 读取团队任务失败: ${check.error}` }
208
226
  const prevBound = sid ? store.getBoundTaskId(sid) : null
209
227
  if (task.archived) task.archived = false
210
228
  if (sid) {
@@ -219,16 +237,18 @@ export function taskCommandDefinition(config, ctx) {
219
237
  fireReflect(config, { llm: ctx?.llm }, root, prevBound, 'switch-away', resolveRoute(session ? { agent: { session } } : undefined, config))
220
238
  }
221
239
  // 反向接管:切换成功后把任务步骤推成宿主 todo/write(dsh 清单跟随);空步骤也要推空。
222
- if (shouldAdoptToHost(config)) {
240
+ // 团队锚点只共享记忆:推空清单会清掉当前成员自己的 todo,跳过。
241
+ if (shouldAdoptToHost(config) && !task.teamTaskId) {
223
242
  adoptStepsToSession(session, task, { force: true })
224
243
  }
225
- const note = `已切换绑定: ${describeTask(task)}${sid ? '' : '(拿不到会话 id,未持久绑定)'}`
226
- return withTaskSnapshot(config, cwd, sid, store, note)
244
+ const teamNote = task.teamTaskId ? ';团队任务只共享任务级记忆(步骤请用宿主团队任务板)' : ''
245
+ const note = `已切换绑定: ${describeTask(task)}${sid ? '' : '(拿不到会话 id,未持久绑定)'}${teamNote}`
246
+ return withTaskSnapshot(config, cwd, sid, store, note, agent ? { agent } : null)
227
247
  }
228
248
 
229
249
  if (verb === 'archive') {
230
250
  const task = store.getTask(taskId)
231
- if (!task) return { kind: 'error', text: `[task] 找不到任务: ${taskId}(/tasks 查看)` }
251
+ if (!task || !taskVisibleTo(task, { agent })) return { kind: 'error', text: `[task] 找不到任务: ${taskId}(/tasks 查看)` }
232
252
  if (task.archived) return { kind: 'error', text: `[task] 已归档: ${task.title}` }
233
253
  task.archived = true
234
254
  task.updatedAt = new Date().toISOString()
@@ -238,8 +258,9 @@ export function taskCommandDefinition(config, ctx) {
238
258
  store.save()
239
259
  // 反思钩子:归档即收割(默认关)
240
260
  fireReflect(config, { llm: ctx?.llm }, root, taskId, 'archive', resolveRoute(session ? { agent: { session } } : undefined, config))
241
- const note = `已归档: ${describeTask(task)}(select_task 可恢复)`
242
- return withTaskSnapshot(config, cwd, sid, store, note)
261
+ const teamNote = task.teamTaskId ? ';仅本地记忆锚点,宿主团队任务未变' : ''
262
+ const note = `已归档: ${describeTask(task)}(select_task 可恢复)${teamNote}`
263
+ return withTaskSnapshot(config, cwd, sid, store, note, agent ? { agent } : null)
243
264
  }
244
265
 
245
266
  return { kind: 'error', text: `[task] 未知动作: ${verb}(switch|archive)` }
@@ -5,7 +5,8 @@ import { memoryRootFor } from '../util/fs.js'
5
5
  import { ProjectMemoryStore } from '../store.js'
6
6
  import { NO_PROJECT_ROOT_NOTE, projectRootFor } from '../setup/taskbridge.js'
7
7
  import { fencedJson, invocationContext } from './invocation.js'
8
- import { stepContent, stepProgress, stepStatus, timeAgo } from '../util/task-view.js'
8
+ import { sortTasksByRecency, stepContent, stepProgress, stepStatus, timeAgo } from '../util/task-view.js'
9
+ import { taskVisibility } from '../setup/team-task.js'
9
10
 
10
11
  // 快照会原样写进会话历史(command/done),没有上限时一个异常任务就能把单条消息撑到几十 MB。
11
12
  // 截断只发生在**展示载荷**里,不碰 store;超出部分由 totals 告知调用方。
@@ -32,6 +33,7 @@ export function buildTaskPayload(tasks, boundId, archived, root = null) {
32
33
  updatedAt: t.updatedAt,
33
34
  archived: t.archived || false,
34
35
  insights: insights.slice.map((i) => ({ id: i.id, kind: i.kind || 'lesson', title: i.title || '', draft: i.draft === true })),
36
+ ...(t.teamTaskId ? { teamTaskId: t.teamTaskId, teamTaskStatus: t.teamTaskStatus || null } : {}),
35
37
  ...(truncated ? {
36
38
  totals: {
37
39
  steps: steps.total,
@@ -53,14 +55,21 @@ export function buildTaskPayload(tasks, boundId, archived, root = null) {
53
55
 
54
56
  /**
55
57
  * 生成 /tasks 类快照的完整输出文本(人类可读总览 + JSON 载荷)。
56
- * 任务动作命令复用同一函数,面板只需解析尾部 JSON 即可刷新。
58
+ * `exec`(`{ agent }`)给定时就只保留该会话可见的任务:快照会写进会话历史,
59
+ * 别队的团队锚点连同 insight id/标题都不能从这里漏给模型;没有 agent 上下文时按旧行为展示全部。
60
+ * @param {object} config
61
+ * @param {string} cwd
62
+ * @param {string|null} sid
63
+ * @param {object|null} [exec]
57
64
  */
58
- export function renderTaskSnapshot(config, cwd, sid) {
65
+ export function renderTaskSnapshot(config, cwd, sid, exec = null) {
59
66
  const root = projectRootFor(cwd, config)
60
67
  if (!root) return { kind: 'error', text: NO_PROJECT_ROOT_NOTE }
61
68
  const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
62
- const tasks = store.getTasks()
63
- const active = tasks.filter((t) => !t.archived)
69
+ const visible = exec ? taskVisibility(exec) : null
70
+ const tasks = visible ? store.getTasks().filter(visible) : store.getTasks()
71
+ // 最近活跃的在前:面板/`/tasks`/list_tasks 三处同一份顺序(见 util/task-view.js)。
72
+ const active = sortTasksByRecency(tasks.filter((t) => !t.archived))
64
73
  const archived = tasks.length - active.length
65
74
  const boundId = sid ? store.getBoundTaskId(sid) : null
66
75
  const bound = boundId ? tasks.find((t) => t.id === boundId) : null
@@ -70,16 +79,21 @@ export function renderTaskSnapshot(config, cwd, sid) {
70
79
  const note = `项目 ${root}\n任务记录: 0 套${archived ? `(归档 ${archived})` : ''}。让模型开始干活并维护 todo 清单后会自动建档。`
71
80
  return { kind: 'success', text: fencedJson(note, payload) }
72
81
  }
73
- const lines = [`项目 ${root}`, `任务: ${active.length} 套${archived ? `(归档 ${archived})` : ''}`, '']
82
+ const teamCount = active.filter((t) => t.teamTaskId).length
83
+ const teamNote = teamCount ? `(含团队任务 ${teamCount} 套)` : ''
84
+ const lines = [`项目 ${root}`, `任务: ${active.length} 套${archived ? `(归档 ${archived})` : ''}${teamNote}`, '']
74
85
  for (const t of active) {
75
86
  const { done, total } = stepProgress(t)
76
- const progress = total ? `${done}/${total}` : '无步骤'
87
+ // 团队锚点不存步骤:别把"宿主团队任务板上的进度"显示成"无步骤"。
88
+ const progress = total ? `${done}/${total}` : (t.teamTaskId ? '见宿主团队任务板' : '无步骤')
77
89
  const inProgress = (t.steps || []).find((s) => stepStatus(s) === 'in_progress')
78
90
  const step = inProgress ? ` · 当前: ${stepContent(inProgress)}` : ''
79
91
  const marker = bound && bound.id === t.id ? '(本会话绑定)' : ''
92
+ // 团队任务与自建任务同名时不至于被看成一件事:标注它来自宿主的团队任务板。
93
+ const team = t.teamTaskId ? `(团队任务 ${t.teamTaskId}${t.teamTaskStatus ? ` · ${t.teamTaskStatus}` : ''})` : ''
80
94
  const files = (t.files || []).slice(0, 8)
81
95
  const fileLine = files.length ? `\n 文件: ${files.join(', ')}${t.files.length > 8 ? ' …' : ''}` : ''
82
- lines.push(`● ${t.title}${marker} 步骤 ${progress}${step} · ${timeAgo(t.lastActiveAt || t.updatedAt)}${fileLine}`)
96
+ lines.push(`● ${t.title}${marker}${team} 步骤 ${progress}${step} · ${timeAgo(t.lastActiveAt || t.updatedAt)}${fileLine}`)
83
97
  }
84
98
  lines.push('', '续接/改名/归档:直接告诉模型(list_tasks / select_task / archive_task)。')
85
99
  const humanText = lines.join('\n')
@@ -93,8 +107,8 @@ export function tasksCommandDefinition(config, ctx) {
93
107
  description: '查看本项目的任务清单(几套任务、进度、涉及文件、当前绑定)',
94
108
  handler: (invocation) => {
95
109
  try {
96
- const { cwd, sid } = invocationContext(invocation)
97
- return renderTaskSnapshot(config, cwd, sid)
110
+ const { agent, cwd, sid } = invocationContext(invocation)
111
+ return renderTaskSnapshot(config, cwd, sid, agent ? { agent } : null)
98
112
  } catch (err) {
99
113
  return { kind: 'error', text: `[tasks] ${err?.message || err}` }
100
114
  }
@@ -44,8 +44,10 @@ function exceedsSizeCap(size, config) {
44
44
  * @param {number} [args.size] 调用方已 statSync 时传入,避免重复 stat。
45
45
  * @param {number} [args.mtimeMs] 调用方已 statSync 时传入;与 `record.mtimeMs` 构成"未改"快路径。
46
46
  * @param {boolean} [args.force] index_repo 的 reindex:忽略哈希跳过。
47
+ * @param {boolean} [args.noMtimeFastPath] 禁用"mtime+size 未变即跳过"的快路径:显式 index_doc
48
+ * 必须按内容判重(rsync -t 之类的还原会保留 mtime,快路径会把改过的内容当未变)。
47
49
  */
48
- export async function planFileIndex({ rel, filePath, kind, config, record, existingEntries = [], size, mtimeMs, force = false }) {
50
+ export async function planFileIndex({ rel, filePath, kind, config, record, existingEntries = [], size, mtimeMs, force = false, noMtimeFastPath = false }) {
49
51
  if (!kind) return { key: UNSUPPORTED }
50
52
  let fileSize = size
51
53
  let fileMtime = mtimeMs
@@ -54,14 +56,14 @@ export async function planFileIndex({ rel, filePath, kind, config, record, exist
54
56
  if (typeof fileSize !== 'number') fileSize = st.size
55
57
  if (typeof fileMtime !== 'number') fileMtime = st.mtimeMs
56
58
  }
57
- if (exceedsSizeCap(fileSize, config)) return { key: OVERSIZE }
59
+ if (exceedsSizeCap(fileSize, config)) return { key: OVERSIZE, size: fileSize }
58
60
 
59
61
  // 旧 store 的 doc 条目缺 terms → 即使哈希未变也重抽一次(一次性回填)。
60
62
  const backfill = kind === 'doc' && docEntriesNeedBackfill(existingEntries)
61
63
  // 快路径:mtime + size 都没动就不读盘、不哈希。懒索引由 `fs/observed` 触发,重复读同一个
62
64
  // 文件不该每次整读 + sha256。代价与 make/tsc 同一取舍(rsync -t 保留 mtime 的还原察觉不到,
63
65
  // 需要时用 reindex: true 强制重读)。
64
- if (!force && !backfill && record && typeof record.mtimeMs === 'number' && record.mtimeMs === fileMtime && record.size === fileSize) {
66
+ if (!force && !noMtimeFastPath && !backfill && record && typeof record.mtimeMs === 'number' && record.mtimeMs === fileMtime && record.size === fileSize) {
65
67
  return { key: UNCHANGED }
66
68
  }
67
69
 
@@ -159,6 +159,19 @@ export function isLegacyBodyVisible(state, body) {
159
159
  return Boolean(state && body && state.legacyBlocks.has(lineHash(body)))
160
160
  }
161
161
 
162
+ /**
163
+ * 清空一张会话的「已可见」账本。六张表必须一起清:只清一部分会让下一轮把旧块当成"已经发过"
164
+ * 而不再重发(假可见),或把新块当成"已确认"(对账错)。抽成函数是为了将来加第七张表时不会漏。
165
+ */
166
+ function resetVisible(state) {
167
+ state.items.clear()
168
+ state.legacy.clear()
169
+ state.legacyBlocks.clear()
170
+ state.blocks.clear()
171
+ state.confirmedBlocks.clear()
172
+ state.entries.clear()
173
+ }
174
+
162
175
  export function ensureVisible(session, state) {
163
176
  const surface = surfaceOf(session)
164
177
  if (!surface || state.degraded) return false
@@ -174,12 +187,7 @@ export function ensureVisible(session, state) {
174
187
  if (!state.ready || state.dirty || (state.genSupported && gen !== state.surfaceGen)
175
188
  || (!state.genSupported && (surface.nodes.length < state.nodeCount
176
189
  || (state.firstSeq !== null && surface.nodes[0] !== state.firstSeq)))) {
177
- state.items.clear()
178
- state.legacy.clear()
179
- state.legacyBlocks.clear()
180
- state.blocks.clear()
181
- state.confirmedBlocks.clear()
182
- state.entries.clear()
190
+ resetVisible(state)
183
191
  state.firstSeq = null
184
192
  state.nodeCount = 0
185
193
  state.dirty = false
@@ -189,12 +197,7 @@ export function ensureVisible(session, state) {
189
197
  scanNodes(session, state)
190
198
  } catch {
191
199
  state.degraded = true
192
- state.items.clear()
193
- state.legacy.clear()
194
- state.legacyBlocks.clear()
195
- state.blocks.clear()
196
- state.confirmedBlocks.clear()
197
- state.entries.clear()
200
+ resetVisible(state)
198
201
  return false
199
202
  }
200
203
  settlePending(state)
@@ -206,12 +209,7 @@ export function ensureVisible(session, state) {
206
209
  scanNodes(session, state, state.nodeCount)
207
210
  } catch {
208
211
  state.degraded = true
209
- state.items.clear()
210
- state.legacy.clear()
211
- state.legacyBlocks.clear()
212
- state.blocks.clear()
213
- state.confirmedBlocks.clear()
214
- state.entries.clear()
212
+ resetVisible(state)
215
213
  return false
216
214
  }
217
215
  }