@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
@@ -3,23 +3,22 @@ import { TEXT_OUTPUT, persistenceNote, rootParam } from './output.js'
3
3
  import { openProjectContext } from './context.js'
4
4
  import { normalizeCitationFiles } from '../util/fs.js'
5
5
  import { truncate } from '../util/text.js'
6
- import { saveInsight, defaultGlobalFile, GlobalStore } from '../insight-store.js'
6
+ import { saveInsight, containsSecretFields, defaultGlobalFile, GlobalStore } from '../insight-store.js'
7
7
  import { ensureGlobalInit } from '../global-seed.js'
8
8
  import { INSIGHT_KINDS, INSIGHT_SCOPES } from '../insight-store.js'
9
9
  import { sessionIdOf } from '../util/task-view.js'
10
+ import { ensureTeamTaskRecord, isTeamTaskId, memoryTaskIdFor, recheckTeamAnchor, resolveTeamTask, taskVisibility, teamIdOf } from '../setup/team-task.js'
10
11
  import { createVectorRerank, vectorItemsFrom } from '../vector-index.js'
11
12
  import { createWriteCosine } from '../auto-inject.js'
12
13
 
13
14
  export function lessonTool(config) {
14
- const kindDesc = 'lesson (pitfall → fix) | decision (choice + reason) | procedure (steps) | experience (problem → solution); default lesson.'
15
- const scopeDesc =
16
- 'task | project | global; default: task when a task is bound, else project; passing id updates in place.'
15
+ const kindDesc = 'lesson | decision | procedure | experience; default lesson.'
16
+ const scopeDesc = 'task | project | global; default: bound task, else project.'
17
17
  return defineTool({
18
18
  name: 'save_lesson',
19
19
  description:
20
- 'One lesson / decision / procedure (a single insight). Keep only the criterion and command that stay true next time; run-specific values (version numbers, counts, branch names) stay out. '
21
- + 'It compares against existing memory first: high similarity overwrites (old value kept in prev), a near match returns the nearest id. '
22
- + 'If an entry you saw is wrong, stale or too thin to act on, pass its id and write again to update it in place instead of adding a new one; use forget to delete.',
20
+ 'Save one insight (lesson / decision / procedure / experience); pass an existing `id` to update '
21
+ + 'in place. Details: project-memory skill.',
23
22
  parameters: {
24
23
  id: { type: 'string', description: 'existing entry id (in-place update)' },
25
24
  title: { type: 'string', description: 'one-line title' },
@@ -38,20 +37,19 @@ export function lessonTool(config) {
38
37
  type: 'object',
39
38
  additionalProperties: false,
40
39
  properties: {
41
- ops: { type: 'array', items: { type: 'string' }, description: 'file-write|file-delete|shell-run|git-commit|git-push|release|npm-publish|go-public|deploy|migrate|render-doc|index-doc|read-image|fetch-web|run-bench|query-memory' },
42
- writes: { type: 'array', items: { type: 'string' }, description: 'project-relative paths; `*` wildcards are allowed' },
43
- intents: { type: 'array', items: { type: 'string' }, description: 'intent words (CJK ≥2, latin ≥5)' },
40
+ ops: { type: 'array', items: { type: 'string' }, description: 'action names (see project-memory skill)' },
41
+ writes: { type: 'array', items: { type: 'string' }, description: 'project-relative paths; `*` wildcards allowed' },
42
+ intents: { type: 'array', items: { type: 'string' }, description: 'intent words (see project-memory skill)' },
44
43
  },
45
- description: 'the only trigger surface: any of the three; without it the entry is retrieval-only.',
46
44
  },
47
45
  guard: {
48
46
  type: 'object',
49
47
  additionalProperties: false,
50
48
  properties: {
51
- paths: { type: 'array', items: { type: 'string' }, description: 'write target must match one of them' },
49
+ paths: { type: 'array', items: { type: 'string' } },
52
50
  not_paths: { type: 'array', items: { type: 'string' } },
53
- hosts: { type: 'array', items: { type: 'string' }, description: 'e.g. wsl' },
54
- tags: { type: 'array', items: { type: 'string' }, description: 'profile tag intersection' },
51
+ hosts: { type: 'array', items: { type: 'string' } },
52
+ tags: { type: 'array', items: { type: 'string' } },
55
53
  },
56
54
  description: 'narrowing conditions: all must hold.',
57
55
  },
@@ -65,7 +63,7 @@ export function lessonTool(config) {
65
63
  },
66
64
  description: 'injects before acting when matched; when is the only trigger surface.',
67
65
  },
68
- task_id: { type: 'string', description: 'target task id' },
66
+ task_id: { type: 'string', description: 'target task id (local, or host team task-<n>)' },
69
67
  files: { type: 'array', items: { type: 'string' }, description: 'related files (project-relative)' },
70
68
  symbols: { type: 'array', items: { type: 'string' }, description: 'related symbols' },
71
69
  confidence: { type: 'number', description: '0..1' },
@@ -76,10 +74,6 @@ export function lessonTool(config) {
76
74
  const { root, memoryDir, store, cfg } = openProjectContext(exec, args, config)
77
75
  // 写入期约束:files 只收项目内相对路径(schema 早就这么承诺,此前没有校验)。
78
76
  const citationFiles = normalizeCitationFiles(args.files, root)
79
- const sid = sessionIdOf(exec)
80
- const boundTaskId = sid ? store.getBoundTaskId(sid) : undefined
81
- const taskId = args.task_id || boundTaskId
82
-
83
77
  const raw = {
84
78
  id: args.id,
85
79
  title: args.title,
@@ -94,14 +88,112 @@ export function lessonTool(config) {
94
88
  symbols: args.symbols,
95
89
  confidence: args.confidence,
96
90
  }
97
- // 就地更新只要求 id(可以只改一个字段);新建仍然要求有个能当标题的东西。
91
+ // 内容与密文校验放在"懒建团队锚点"之前:被拒绝的写入不该在任务树里留下没人写过的空锚点。
92
+ // 用 saveInsight 同一个 containsSecretFields 判据预检(它内部仍会再查一次,防御)。
98
93
  if (!args.id && !raw.title && !raw.pattern && !raw.choice) {
99
94
  return truncate(JSON.stringify({ success: false, error: '需要 title / pattern / choice 之一(或给 id 做就地更新)' }), config.maxOutputChars || 8000)
100
95
  }
96
+ const secretField = containsSecretFields(raw)
97
+ if (secretField) {
98
+ // 保持与 saveInsight 拒绝时同一条输出形状(`Failed: …`),别让预检改变旧调用的可解析性。
99
+ return truncate(`Failed: 内容疑似包含密钥/token/私钥形态数据(字段: ${secretField}),已拒绝写入`, config.maxOutputChars || 8000)
100
+ }
101
101
  // 只有新建才补默认 kind;带 id 的就地更新必须“只覆盖传了的字段”,
102
102
  // 否则一次改 fix/reason 会把 decision/procedure 静默降级成 lesson。
103
103
  if (!args.id && !INSIGHT_KINDS.includes(raw.kind)) raw.kind = 'lesson'
104
104
 
105
+ const sid = sessionIdOf(exec)
106
+ const now = new Date().toISOString()
107
+ const boundTaskId = sid ? store.getBoundTaskId(sid) : undefined
108
+ // 空白 task_id 等同没给:否则它会被当成合法 id 一路走到"任务不存在",或者(读路径)
109
+ // 把会话绑定顶掉。任务 id 的形状是 tsk_… / task-<n> / team:…,都不含空白。
110
+ const explicitTaskId = typeof args.task_id === 'string' ? args.task_id.trim() : args.task_id
111
+ // 团队树只解析一次:下面的准入判定、按 id 更新与跨任务去重共用同一份可见性。
112
+ const taskVisible = taskVisibility(exec)
113
+ let taskId = explicitTaskId || boundTaskId
114
+ let anchorNote = ''
115
+ // 本次调用是否已经问过宿主这个团队任务还在不在:team id 的解析/懒建本身会问一次,
116
+ // 原始锚点 id 与会话绑定这两条路径没问过,后面统一补一次复核。
117
+ let hostChecked = false
118
+ // 团队任务 id(task-<n>)不是本地任务 id:已有锚点就复用,没有就按宿主视图**懒建**。
119
+ // 显式 task_id 本身已经表达了"要写这条任务",不再要求先 select_task —— 队友 claim 后
120
+ // 直接按宿主 id 写,lead 也能按同一个 id 读(读路径见 query_memory 的 task_id)。
121
+ // 只有"确实要写任务级"时才解析/建锚点:显式 project/global 或带 id 的就地更新不碰任务树,
122
+ // 否则一次 project 写入会顺手建出一条没人写的任务记录。
123
+ const wantsTaskScope = !args.id && (!args.scope || args.scope === 'task')
124
+ if (taskId && wantsTaskScope && isTeamTaskId(taskId)) {
125
+ const teamId = teamIdOf(exec)
126
+ const existing = memoryTaskIdFor(store, taskId, teamId)
127
+ if (existing !== taskId) {
128
+ // 锚点可能比宿主的删除事件活得久(team/task 只追加到 lead 会话):软删 / 换了团队时
129
+ // 不能再往旧锚点写。unavailable / no-caller 是离线降级,允许继续用已有锚点。
130
+ const resolved = resolveTeamTask(exec, taskId)
131
+ hostChecked = true
132
+ if (!resolved.ok && resolved.reason === 'not-found') {
133
+ return truncate(JSON.stringify({ success: false, error: `Task not found: ${taskId}(团队任务不存在或不属于本团队)` }), config.maxOutputChars || 8000)
134
+ }
135
+ taskId = existing
136
+ } else {
137
+ const resolved = resolveTeamTask(exec, taskId)
138
+ hostChecked = true
139
+ if (!resolved.ok) {
140
+ // 宿主 RPC 失败不是"任务不存在":分开报,模型才知道该重试而不是改写 id。
141
+ if (resolved.reason === 'error') {
142
+ return truncate(JSON.stringify({ success: false, error: `读取团队任务失败: ${resolved.error}` }), config.maxOutputChars || 8000)
143
+ }
144
+ const why = resolved.reason === 'unavailable'
145
+ ? '当前宿主没有团队服务;团队任务只在安装了团队插件的会话里可写'
146
+ : resolved.reason === 'no-caller'
147
+ ? '这次调用没有 agent 上下文,无法解析团队任务'
148
+ : '团队任务不存在或不属于本团队'
149
+ return truncate(JSON.stringify({ success: false, error: `Task not found: ${taskId}(${why})` }), config.maxOutputChars || 8000)
150
+ }
151
+ // 团队任务编号只在团队内唯一:拿不到团队树就拒绝,别写出可能串台的锚点。
152
+ if (!teamId) {
153
+ return truncate(JSON.stringify({
154
+ success: false,
155
+ error: `Task not found: ${taskId}(无法确定所属团队树:subagents 服务不可用,团队任务无法写入)`,
156
+ }), config.maxOutputChars || 8000)
157
+ }
158
+ const ensured = ensureTeamTaskRecord(store, resolved.view, { teamId, root, sid, now })
159
+ taskId = ensured.task.id
160
+ anchorNote = ';已新建团队任务记忆锚点(未绑定会话)'
161
+ // 去重若把条目并到 project / 别的任务,这条锚点会以空 insights 落盘。不删:它是宿主任务的
162
+ // 镜像(select_task 也会建),且按 id 删盘可能误删并发进程刚写进同一锚点的条目;
163
+ // 输出侧只在 created 且落进本任务时才说"已新建",不会骗模型。
164
+ }
165
+ }
166
+
167
+ // 任务级写入的准入:可见性对所有来源(显式 id / 原始锚点 / 会话绑定)一致;
168
+ // 原始锚点与绑定不经过宿主视图,还要补一次宿主复核——删除事件不一定能到达每个进程。
169
+ // 归档守卫 saveInsight 里也会查,但那里拿到的是解析后的锚点键(team:…);对调用方要报
170
+ // 它传进来的 id,模型才知道该解归档哪一条。
171
+ if (!args.id && wantsTaskScope && taskId) {
172
+ const target = store.getTask(taskId)
173
+ if (target && !taskVisible(target)) {
174
+ return truncate(JSON.stringify({
175
+ success: false,
176
+ error: `Task not found: ${explicitTaskId || taskId}(团队任务不存在或不属于本团队)`,
177
+ }), config.maxOutputChars || 8000)
178
+ }
179
+ if (target && !hostChecked) {
180
+ const check = recheckTeamAnchor(exec, target)
181
+ if (!check.ok && check.reason === 'not-found') {
182
+ return truncate(JSON.stringify({
183
+ success: false,
184
+ error: `Task not found: ${explicitTaskId || taskId}(团队任务不存在或不属于本团队)`,
185
+ }), config.maxOutputChars || 8000)
186
+ }
187
+ if (!check.ok) {
188
+ return truncate(JSON.stringify({ success: false, error: `读取团队任务失败: ${check.error}` }), config.maxOutputChars || 8000)
189
+ }
190
+ }
191
+ if (target && target.archived) {
192
+ // 与 saveInsight / 密文预检同一条失败形状:`Failed:`,别让归档提示变成另一种可解析性。
193
+ return truncate(`Failed: 任务已归档: ${explicitTaskId || taskId}(先 select_task 解归档再写入)`, config.maxOutputChars || 8000)
194
+ }
195
+ }
196
+
105
197
  let scope = args.scope
106
198
  if (!scope) scope = taskId ? 'task' : 'project'
107
199
  if (!args.id && scope === 'task' && !taskId) {
@@ -119,8 +211,10 @@ export function lessonTool(config) {
119
211
  }
120
212
 
121
213
  let result
214
+ // 就地更新按 id 找条目、跨任务去重扫任务池,都要过同一道团队可见性:别队的私有条目
215
+ // 既不能被这条写入改写,也不能在 hint 里被回显出来。
122
216
  store.commit((s) => {
123
- result = saveInsight({ store: s, globalStore, raw, scope, taskId, cfg, source: 'agent', cosine })
217
+ result = saveInsight({ store: s, globalStore, raw, scope, taskId, cfg, source: 'agent', cosine, taskVisible })
124
218
  return result
125
219
  })
126
220
  // global 变更(global scope 直写或 project 自动提升)单独落盘
@@ -133,7 +227,10 @@ export function lessonTool(config) {
133
227
  const note = citationFiles.dropped.length
134
228
  ? `\n(${citationFiles.dropped.length} 个 files 既不是项目内相对路径也不是项目内绝对路径,已丢弃:${citationFiles.dropped.slice(0, 3).join(', ')}${citationFiles.dropped.length > 3 ? ' …' : ''})`
135
229
  : ''
136
- return truncate(body + note + persistenceNote(store, globalStore), config.maxOutputChars || 8000)
230
+ // 只在写入确实落进这条任务时才报告建锚点:密钥/校验失败、或去重把条目并到 project /
231
+ // 别的任务时,说"已新建锚点"会让模型以为任务级记忆已经写好(实际没有)。
232
+ const anchorSuffix = result.ok && result.action === 'created' && result.taskId === taskId ? anchorNote : ''
233
+ return truncate(body + anchorSuffix + note + persistenceNote(store, globalStore), config.maxOutputChars || 8000)
137
234
  },
138
235
  })
139
236
  }
@@ -11,7 +11,8 @@ import { cfgEngine } from '../auto-inject.js'
11
11
  import { createVectorRerank, vectorItemsFrom } from '../vector-index.js'
12
12
  import { resolveLinkedSymbols } from '../link.js'
13
13
  import { truncate } from '../util/text.js'
14
- import { stepContent, stepStatus } from '../util/task-view.js'
14
+ import { stepContent, stepStatus, sessionIdOf } from '../util/task-view.js'
15
+ import { isTeamTaskId, recheckTeamAnchor, resolveTeamTask, taskVisibleTo, teamIdOf, teamMemoryTaskId } from '../setup/team-task.js'
15
16
  import { cfgValue } from '../util/config.js'
16
17
  function toAbs(root, rel) {
17
18
  return path.isAbsolute(rel) ? rel : path.join(root, rel)
@@ -57,13 +58,94 @@ function previousLine(item) {
57
58
  return parts.length ? parts.join('; ').slice(0, 300) : ''
58
59
  }
59
60
 
61
+ /**
62
+ * 显式 `task_id`(本地 id 或宿主 `task-<n>`)→ 本次召回可见的任务记录 id。
63
+ *
64
+ * 只读路径**不建锚点**:团队任务还没有锚点,说明还没有任何任务级记忆,给一行提示而不是报错,
65
+ * 其余层照常返回。团队 id 先过归属校验(未知 / 别的团队 / 软删按 `Task not found` 处理),
66
+ * 避免把不存在的任务当成空作用域、把拼错的 id 静默吞掉。
67
+ * @returns {{taskId: string|null, note: string} | {error: string}}
68
+ */
69
+ function resolveTaskScope(store, rawId, exec) {
70
+ const id = String(rawId ?? '').trim()
71
+ if (!id) return { taskId: null, note: '' }
72
+ if (isTeamTaskId(id)) {
73
+ const teamId = teamIdOf(exec)
74
+ const anchor = teamId ? teamMemoryTaskId(teamId, id) : null
75
+ const record = anchor ? store.getTask(anchor) : null
76
+ // 锚点可能比宿主的删除事件活得久(team/task 只追加到 lead 会话):有锚点时也回查一次,
77
+ // 宿主说 not-found(软删 / 换了团队)就别再读旧记忆。unavailable / no-caller 是离线降级,允许读。
78
+ const resolved = resolveTeamTask(exec, id)
79
+ if (!resolved.ok) {
80
+ // 宿主 RPC 失败不是"任务不存在":分开报,模型才知道该重试而不是改写 id。
81
+ if (resolved.reason === 'error') return { error: `读取团队任务失败: ${resolved.error}` }
82
+ if (!record || resolved.reason === 'not-found') {
83
+ const why = resolved.reason === 'unavailable'
84
+ ? '当前宿主没有团队服务;团队任务只在安装了团队插件的会话里可查'
85
+ : resolved.reason === 'no-caller'
86
+ ? '这次调用没有 agent 上下文,无法解析团队任务'
87
+ : '团队任务不存在或不属于本团队'
88
+ return { error: `Task not found: ${id}(${why})` }
89
+ }
90
+ }
91
+ if (!record) {
92
+ // 服务在、任务也在,但拿不到团队树就无法映射到锚点:不能说"还没有记忆"(那是在猜)。
93
+ if (!teamId) return { error: `Task not found: ${id}(无法确定所属团队树:subagents 服务不可用,团队任务无法按 id 读取)` }
94
+ return { taskId: null, note: `团队任务 ${id} 还没有任务级记忆(save_lesson 带 task_id 写入后才会有)` }
95
+ }
96
+ // 锚点键自带团队树,理论上必属本团队;跨进程合并/手改数据仍可能让 teamId 漂移,按不可见处理。
97
+ if (!taskVisibleTo(record, exec)) return { error: `Task not found: ${id}(团队任务不存在或不属于本团队)` }
98
+ return record.archived
99
+ ? { taskId: null, note: `团队任务 ${id} 已归档:任务级记忆不参与召回` }
100
+ : { taskId: anchor, note: '' }
101
+ }
102
+ const record = store.getTask(id)
103
+ if (!record) return { error: `任务不存在: ${id}(list_tasks 查看全部)` }
104
+ // 原始锚点 id(team:<root>:task-<n>)也能被显式传进来:团队锚点只对本团队可见。
105
+ if (!taskVisibleTo(record, exec)) {
106
+ return { error: `Task not found: ${id}(团队任务不存在或不属于本团队)` }
107
+ }
108
+ // 这条路径不经过宿主视图:补一次复核,宿主已删的团队任务不再返回旧记忆。
109
+ const check = recheckTeamAnchor(exec, record)
110
+ if (!check.ok && check.reason === 'not-found') {
111
+ return { error: `Task not found: ${id}(团队任务不存在或不属于本团队)` }
112
+ }
113
+ if (!check.ok) return { error: `读取团队任务失败: ${check.error}` }
114
+ return record.archived
115
+ ? { taskId: null, note: `任务已归档: ${id}(先 select_task 解归档再读)` }
116
+ : { taskId: id, note: '' }
117
+ }
118
+
119
+ /**
120
+ * 默认(会话绑定)作用域。绑定也可能过期:团队锚点按宿主复核降级成一行提示,
121
+ * 不阻断文档/项目层结果;本地任务照旧。绑定到别队锚点(历史数据/手改 binding)
122
+ * 按不可见处理,不能借"以前绑过"继续读。
123
+ * @returns {{taskId: string|null, note: string}}
124
+ */
125
+ function resolveBoundTaskScope(store, exec, boundTaskId) {
126
+ if (!boundTaskId) return { taskId: null, note: '' }
127
+ const record = store.getTask(boundTaskId)
128
+ if (!record) return { taskId: null, note: '' }
129
+ if (!taskVisibleTo(record, exec)) {
130
+ return { taskId: null, note: `绑定的任务 ${boundTaskId} 不属于本团队:任务级记忆不参与召回` }
131
+ }
132
+ if (record.archived) return { taskId: null, note: `任务已归档: ${boundTaskId}(先 select_task 解归档再读)` }
133
+ const check = recheckTeamAnchor(exec, record)
134
+ if (!check.ok && check.reason === 'not-found') {
135
+ return { taskId: null, note: `团队任务 ${boundTaskId} 已不存在:任务级记忆不参与召回(先 select_task 确认)` }
136
+ }
137
+ if (!check.ok) {
138
+ return { taskId: null, note: `读取团队任务失败: ${check.error}(任务级记忆本次不参与召回)` }
139
+ }
140
+ return { taskId: boundTaskId, note: '' }
141
+ }
142
+
60
143
  export function queryMemoryTool(ctx, config) {
61
144
  return defineTool({
62
145
  name: 'query_memory',
63
146
  description:
64
- 'Search project memory: docs, symbols, experience and insights. Returns cited sources or insight ids. '
65
- + 'Use before grepping for orientation, a spec constraint, or a past decision. '
66
- + 'After a query, update stale or wrong entries right away (save_lesson with that id).',
147
+ 'Search project memory (docs, symbols, experience, insights); returns cited sources or insight ids. '
148
+ + 'Use before grepping; update stale entries in place.',
67
149
  parameters: {
68
150
  query: {
69
151
  type: 'string',
@@ -74,11 +156,15 @@ export function queryMemoryTool(ctx, config) {
74
156
  type: {
75
157
  type: 'string',
76
158
  enum: ['all', 'doc', 'symbol', 'experience', 'insight', 'task'],
77
- description: 'all|doc|symbol|experience|insight|task; default all',
159
+ description: 'layer; default all',
160
+ },
161
+ task_id: {
162
+ type: 'string',
163
+ description: 'task id (local or host task-<n>); default: session-bound task',
78
164
  },
79
165
  limit: {
80
166
  type: 'number',
81
- description: 'max results per layer, default 8, capped at 20; `all` can return up to 3x (docs/symbols, insights, experience)',
167
+ description: 'max per layer (default 8, max 20)',
82
168
  },
83
169
  },
84
170
  output: TEXT_OUTPUT,
@@ -98,13 +184,26 @@ export function queryMemoryTool(ctx, config) {
98
184
  const type = args.type || 'all'
99
185
  const limit = Math.max(1, Math.min(Number(args.limit) || 8, 20))
100
186
 
187
+ // task 级 insight 的可见性:显式 task_id 优先,否则用会话绑定;global 级始终可见。
188
+ // 先校验 task_id 再决定要不要调 LLM 扩写查询 —— 拼错的 id 不该先花一次模型调用。
189
+ // 空白串等同没给:否则"显式覆盖绑定"会把任务级可见性静默清空。
190
+ const sessionId = sessionIdOf(exec)
191
+ const boundTaskId = sessionId && typeof store.getBoundTaskId === 'function' ? store.getBoundTaskId(sessionId) : null
192
+ const explicitTaskId = typeof args.task_id === 'string' ? args.task_id.trim() : ''
193
+ // type='task' 列的是任务记录,task_id 选的是任务级记忆(insight/experience 层);
194
+ // 两者同时出现时不能静默忽略 task_id —— 那会变成"能失败、不能生效"的死参数。
195
+ if (explicitTaskId && type === 'task') {
196
+ return 'task_id selects task-level memory (insight / experience layers); type:"task" lists task records. Use one or the other (list_tasks shows task records).'
197
+ }
198
+ const taskScope = explicitTaskId ? resolveTaskScope(store, explicitTaskId, exec) : resolveBoundTaskScope(store, exec, boundTaskId)
199
+ if (taskScope.error) return taskScope.error
200
+ // 作用域提示只对查 task insight 的层有意义:doc/symbol 查询不该被"任务还没有记忆"占首行。
201
+ const taskNoteApplies = type === 'all' || type === 'insight' || type === 'experience'
202
+ const scopeNote = taskNoteApplies && taskScope.note ? `${taskScope.note}\n\n` : ''
203
+
101
204
  const queries = cfgValue(config, 'llmQueryExpansion')
102
205
  ? await expandQuery(ctx.llm, args.query, config.expansionCount, { route: resolveRoute(exec, config) })
103
206
  : [args.query]
104
-
105
- // 会话绑定决定 task 级 insight 的可见性;global 级始终可见。
106
- const sessionId = exec?.agent?.session?.id
107
- const boundTaskId = sessionId && typeof store.getBoundTaskId === 'function' ? store.getBoundTaskId(sessionId) : null
108
207
  const globalStore = new GlobalStore(cfgInsight(config).globalFile || defaultGlobalFile()).load()
109
208
  const wantMemory = type === 'all' || type === 'doc' || type === 'symbol'
110
209
  /** 本根记忆层(doc/symbol)的命中数:0 且存在子索引时,末尾要指路。 */
@@ -124,7 +223,7 @@ export function queryMemoryTool(ctx, config) {
124
223
  store,
125
224
  globalStore,
126
225
  queries,
127
- boundTaskId,
226
+ boundTaskId: taskScope.taskId,
128
227
  limit,
129
228
  rerank,
130
229
  layers: [
@@ -293,14 +392,16 @@ export function queryMemoryTool(ctx, config) {
293
392
  : '. Use pm_stats to see what the store contains.'
294
393
  const nestedNote = wantMemory && memHitCount === 0 ? nestedIndexNote(root, config) : ''
295
394
  return (
395
+ scopeNote +
296
396
  `No memory matches for "${args.query}" in ${root}. ${hint}\n` +
297
397
  `Store overview: ${overview.files} files indexed, ${overview.entries} entries, ${overview.experience} experience notes${tail}${nestedNote}`
298
398
  )
299
399
  }
300
400
  // 提示放在**最前**:`truncate()` 截的是尾部,而 insight/procedure 类条目单条就能到 600+
301
401
  // 字符,放末尾会被整段截掉(实测 8000 字符预算下必被截)。
302
- const note = wantMemory && memHitCount === 0 ? nestedIndexNote(root, config).trimStart() + '\n\n' : ''
303
- return truncate(note + lines.join('\n\n'), config.maxOutputChars)
402
+ // 保留旧的 no-doc-hit 前缀(含空 nestedNote 时的两个换行),避免旧调用输出被无谓改写。
403
+ const nestedNote = wantMemory && memHitCount === 0 ? nestedIndexNote(root, config).trimStart() + '\n\n' : ''
404
+ return truncate(scopeNote + nestedNote + lines.join('\n\n'), config.maxOutputChars)
304
405
  },
305
406
  })
306
- }
407
+ }
@@ -2,17 +2,24 @@ import { defineTool } from '@deepseek-ai/dsh-tools'
2
2
  import { TEXT_OUTPUT, rootParam } from './output.js'
3
3
  import { openProjectContext } from './context.js'
4
4
  import { truncate } from '../util/text.js'
5
- import { sessionIdOf, stepProgress, timeAgo } from '../util/task-view.js'
6
- import { genTaskId, hash8, adoptStepsToSession, shouldAdoptToHost } from '../setup/taskbridge.js'
5
+ import { sessionIdOf, sortTasksByRecency, stepProgress, timeAgo } from '../util/task-view.js'
6
+ import { genTaskId, adoptStepsToSession, shouldAdoptToHost } from '../setup/taskbridge.js'
7
+ import { hash8 } from '../util/hash.js'
8
+ import { ensureTeamTaskRecord, isTeamTaskId, memoryTaskIdFor, recheckTeamAnchor, resolveTeamTask, taskVisibility, taskVisibleTo, teamIdOf } from '../setup/team-task.js'
7
9
  import { fireReflect } from '../reflection-pipeline.js'
8
10
  import { resolveRoute } from '../llm-route.js'
9
- import { createHash } from 'node:crypto'
10
11
 
11
12
  function summaryOf(task) {
12
13
  const { done, total } = stepProgress(task)
13
14
  const files = (task.files || []).length
14
15
  const mark = task.archived ? ' [归档]' : ''
15
- return `### ${task.title}${mark}\n- 进度: ${done}/${total} 完成\n- 文件: ${files} 个\n- 最后活动: ${timeAgo(task.lastActiveAt || task.updatedAt)}`
16
+ const team = task.teamTaskId
17
+ ? `(团队任务 ${task.teamTaskId}${task.teamTaskStatus ? ` · ${task.teamTaskStatus}` : ''})`
18
+ : ''
19
+ const progress = total || !task.teamTaskId ? `${done}/${total} 完成` : '见宿主团队任务板'
20
+ return `### ${task.title}${mark}${team}\n- 进度: ${progress}`
21
+ + `\n- 文件: ${files} 个`
22
+ + `\n- 最后活动: ${timeAgo(task.lastActiveAt || task.updatedAt)}`
16
23
  }
17
24
 
18
25
  export function listTasksTool(config) {
@@ -26,7 +33,9 @@ export function listTasksTool(config) {
26
33
  output: TEXT_OUTPUT,
27
34
  async execute(args, exec) {
28
35
  const { store } = openProjectContext(exec, args, config)
29
- const tasks = store.getTasks()
36
+ // 团队锚点只对所属团队可见:列表也是模型读任务的入口,不能把别队的私有任务标题带出去。
37
+ const visible = taskVisibility(exec)
38
+ const tasks = sortTasksByRecency(store.getTasks().filter(visible))
30
39
  if (!tasks.length) {
31
40
  return '任务记录: 0 套(先做一步再建清单,或用 select_task 新建)'
32
41
  }
@@ -43,8 +52,8 @@ export function selectTaskTool(config, host) {
43
52
  name: 'select_task',
44
53
  description:
45
54
  'Bind the session to a task (its todo list and files read afterwards sync into it). Exact taskId '
46
- + '(optionally renames/unarchives via title), or an exact title match (creates one if absent); '
47
- + 'returns the task card used to rebuild the checklist.',
55
+ + '(local id, or a host team task `task-<n>` that shares task-scoped memory with teammates), '
56
+ + 'or an exact title match (creates one if absent); returns the task card used to rebuild the checklist.',
48
57
  parameters: {
49
58
  taskId: { type: 'string', description: 'exact task id' },
50
59
  title: { type: 'string', description: 'exact title; creates if absent' },
@@ -64,25 +73,69 @@ export function selectTaskTool(config, host) {
64
73
 
65
74
  let task = null
66
75
  let hint = ''
76
+ // 冲突告警只在绑定时由宿主视图算出来,不落盘(见 setup/team-task.js 的模块注释)。
77
+ let teamWarnings = null
67
78
  if (args.taskId) {
68
- task = store.getTask(args.taskId)
69
- if (!task) return error(`Task not found: ${args.taskId}`)
79
+ if (isTeamTaskId(args.taskId)) {
80
+ const resolved = resolveTeamTask(exec, args.taskId)
81
+ if (!resolved.ok) {
82
+ if (resolved.reason === 'error') return error(`读取团队任务失败: ${resolved.error}`)
83
+ if (resolved.reason === 'unavailable') {
84
+ return error(`Task not found: ${args.taskId}(当前宿主没有团队服务;团队任务只在安装了团队插件的会话里可绑定)`)
85
+ }
86
+ if (resolved.reason === 'no-caller') {
87
+ return error(`Task not found: ${args.taskId}(这次调用没有 agent 上下文,无法解析团队任务;请在宿主 agent 的工具调用里执行)`)
88
+ }
89
+ return error(`Task not found: ${args.taskId}(团队任务不存在或不属于本团队)`)
90
+ }
91
+ // 团队任务 id 是团队内编号,锚点键必须带上团队树;拿不到根会话就拒绝,
92
+ // 否则同一个项目里两个团队的 task-2 会共用一条记忆。
93
+ const teamId = teamIdOf(exec)
94
+ if (!teamId) {
95
+ return error(`Task not found: ${args.taskId}(无法确定所属团队树:subagents 服务不可用,团队任务无法绑定)`)
96
+ }
97
+ const ensured = ensureTeamTaskRecord(store, resolved.view, { teamId, root, sid, now })
98
+ task = ensured.task
99
+ teamWarnings = Array.isArray(resolved.view.writeScopeWarnings)
100
+ ? resolved.view.writeScopeWarnings.filter((w) => typeof w === 'string')
101
+ : []
102
+ // 团队任务的记忆键是共享的:lead 写的任务级经验,队友 claim 后 select_task 同一 id 就能读到。
103
+ hint = ensured.created ? '已关联团队任务(新建共享记忆锚点)' : '已关联团队任务(沿用已有任务记忆)'
104
+ } else {
105
+ task = store.getTask(args.taskId)
106
+ // 原始锚点 id(select_task 回给模型的那个记忆任务 id)也可能被显式传回来:
107
+ // 别队锚点按找不到处理,不能靠猜 id 把会话绑到别人的私有记忆上。
108
+ if (!task || !taskVisibleTo(task, exec)) return error(`Task not found: ${args.taskId}`)
109
+ // 这条路径不经过宿主视图,绑定/续做前补一次复核:宿主已删的任务不再绑进会话。
110
+ const check = recheckTeamAnchor(exec, task)
111
+ if (!check.ok && check.reason === 'not-found') {
112
+ return error(`Task not found: ${args.taskId}(团队任务不存在或不属于本团队)`)
113
+ }
114
+ if (!check.ok) return error(`读取团队任务失败: ${check.error}`)
115
+ }
70
116
  if (task.archived) {
71
117
  task.archived = false
72
- hint = '已解归档'
118
+ // 追加而不是覆盖:团队任务分支已经写了一条 hint,别把它冲掉。
119
+ hint = hint ? `${hint};已解归档` : '已解归档'
73
120
  }
74
121
  if (args.title && args.title !== task.title) {
75
122
  task.title = args.title // 改名(自动标题可能带指令前缀,续接时可顺手改干净)
76
123
  hint = (hint ? hint + ';' : '') + `已改名「${args.title}」`
77
124
  }
78
125
  } else {
79
- const matches = store.getTasks().filter((t) => t.title === args.title)
126
+ const matchVisible = taskVisibility(exec)
127
+ const matches = store.getTasks().filter((t) => t.title === args.title && matchVisible(t))
80
128
  if (matches.length > 1) {
81
129
  const candidates = matches.map((t) => ({ taskId: t.id, title: t.title, updatedAt: t.updatedAt, archived: t.archived }))
82
130
  return truncate(JSON.stringify({ success: false, error: '多个同名任务', candidates }), config.maxOutputChars)
83
131
  }
84
132
  if (matches.length === 1) {
85
133
  task = matches[0]
134
+ const check = recheckTeamAnchor(exec, task)
135
+ if (!check.ok && check.reason === 'not-found') {
136
+ return error(`Task not found: ${task.id}(团队任务不存在或不属于本团队)`)
137
+ }
138
+ if (!check.ok) return error(`读取团队任务失败: ${check.error}`)
86
139
  if (task.archived) {
87
140
  task.archived = false
88
141
  hint = '已解归档'
@@ -119,8 +172,9 @@ export function selectTaskTool(config, host) {
119
172
  store.markTasksDirty()
120
173
  store.save()
121
174
 
122
- // 反向接管:绑定成功后,把任务步骤推成宿主 todo/write(dsh 清单跟随我们的任务)
123
- if (shouldAdoptToHost(config)) {
175
+ // 反向接管:绑定成功后,把任务步骤推成宿主 todo/write(dsh 清单跟随我们的任务)。
176
+ // 团队任务锚点只做记忆作用域:不推清单 —— 队友自己的 todo 不该被一个空的本地锚点清掉。
177
+ if (shouldAdoptToHost(config) && !task.teamTaskId) {
124
178
  adoptStepsToSession(exec?.agent?.session || exec?.ctx?.session, task, { force: true })
125
179
  }
126
180
 
@@ -135,7 +189,20 @@ export function selectTaskTool(config, host) {
135
189
  steps: task.steps,
136
190
  files: task.files,
137
191
  insights: task.insights || [], // v0.5:任务级 lessons/decisions/procedures
138
- hint: hint + ';请据此用 todo_write 重建本会话清单',
192
+ // 团队任务的身份与 advisory 写作用域:模型据此判断"这条经验归哪个团队任务"以及是否越界。
193
+ ...(task.teamTaskId ? {
194
+ team: {
195
+ id: task.teamTaskId,
196
+ status: task.teamTaskStatus || null,
197
+ owner: task.teamOwnerName || null,
198
+ writeScopes: task.teamWriteScopes || [],
199
+ warnings: teamWarnings || [],
200
+ },
201
+ } : {}),
202
+ // 团队锚点不吸收步骤(见 taskbridge 的 todo/write),别再让它按本地任务的方式重建清单。
203
+ hint: task.teamTaskId
204
+ ? `${hint};团队任务只共享任务级记忆,步骤请用宿主团队任务板维护`
205
+ : `${hint};请据此用 todo_write 重建本会话清单`,
139
206
  ...(store.lastSaveOk === false ? { persisted: false, warning: '内存已绑定,但 tasks.json 未落盘(权限/磁盘/锁);退出前会重试。' } : {}),
140
207
  }
141
208
  return truncate(JSON.stringify(card), config.maxOutputChars)
@@ -173,8 +240,8 @@ export function archiveTaskTool(config, host) {
173
240
  output: TEXT_OUTPUT,
174
241
  async execute(args, exec) {
175
242
  const { root, store } = openProjectContext(exec, args, config)
176
- const task = store.getTask(args.taskId)
177
- if (!task) return truncate(JSON.stringify({ success: false, error: 'Task not found' }), config.maxOutputChars)
243
+ const task = store.getTask(memoryTaskIdFor(store, args.taskId, teamIdOf(exec)))
244
+ if (!task || !taskVisibleTo(task, exec)) return truncate(JSON.stringify({ success: false, error: 'Task not found' }), config.maxOutputChars)
178
245
  if (task.archived) return truncate(JSON.stringify({ success: false, error: 'Already archived' }), config.maxOutputChars)
179
246
  task.archived = true
180
247
  task.updatedAt = new Date().toISOString()