@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,18 +3,19 @@
3
3
  // 提升 = 字段变更(不跨文件复制);归档 = 软删(archived:true,不进召回/注入),物理删除只在容量溢出;
4
4
  // 写盘前过滤密钥/token/私钥形态,命中即拒绝写入。
5
5
  import { randomUUID } from 'node:crypto'
6
- import { readFileSync, renameSync } from 'node:fs'
6
+ import { readFileSync } from 'node:fs'
7
7
  import path from 'node:path'
8
8
  import os from 'node:os'
9
9
  import { normalizedTokenOverlap, findBestOverlapMatch, insightMatchText } from './similarity.js'
10
- import { acquireDirLock, storeKey, writeJsonAtomic } from './util/fs.js'
10
+ import { acquireDirLock, readJsonFile, storeKey, writeJsonAtomic } from './util/fs.js'
11
11
  import { debugPersistence } from './util/persist.js'
12
12
  import { trackDirty, untrackDirty } from './util/flush.js'
13
13
  import { backfillDerivedTriggers, deriveTrigger } from './readiness.js'
14
14
  import { vectorText } from './vector-index.js'
15
15
  import { tokenize } from './util/search.js'
16
- import { isRecord, isoMs, newerIso } from './util/value.js'
17
- import { pruneKindFields } from './util/insight-fields.js'
16
+ import { isRecord, isoMs } from './util/value.js'
17
+ import { mergeById } from './util/merge-by-id.js'
18
+ import { UNTITLED_TITLE, pruneKindFields, titleOf } from './util/insight-fields.js'
18
19
 
19
20
  export const INSIGHT_KINDS = ['lesson', 'decision', 'procedure', 'experience']
20
21
  export const INSIGHT_SCOPES = ['task', 'project', 'global']
@@ -97,8 +98,9 @@ export function normalizeInsight(raw, extra = {}) {
97
98
  kind,
98
99
  scope: extra.scope || 'project',
99
100
  // 标题推导必须覆盖 `save_lesson` 的三种最小输入(title / pattern / choice),否则只给 choice 的
100
- // decision 会落成 `(untitled)`;顺序与 `vectorText` 兜底链一致(写入侧向量文本也走这里)。
101
- title: String(raw.title || raw.pattern || raw.problem || raw.choice || raw.topic || '(untitled)').slice(0, 200),
101
+ // decision 会落成 `(untitled)`。兜底链与 trim/截断规则住在 `titleOf` 里,`vectorText` 调用同一份:
102
+ // 两边链一漂移,同一条记忆写入与重启后就会编码成两份不同的向量文本。
103
+ title: titleOf(raw) || UNTITLED_TITLE,
102
104
  source: extra.source || raw.source || 'agent',
103
105
  draft: raw.draft === true || extra.draft === true,
104
106
  confidence: num(raw.confidence, num(extra.confidence, 0.8)),
@@ -431,14 +433,18 @@ export function reinforceOnly(existing, base, nowIso) {
431
433
  return existing
432
434
  }
433
435
 
434
- function allTaskInsights(store) {
436
+ function allTaskInsights(store, taskVisible = null) {
435
437
  const out = []
436
- for (const t of store.getTasks() || []) for (const ins of t.insights || []) out.push(ins)
438
+ for (const t of store.getTasks() || []) {
439
+ if (taskVisible && !taskVisible(t)) continue
440
+ for (const ins of t.insights || []) out.push(ins)
441
+ }
437
442
  return out
438
443
  }
439
444
 
440
- function taskContaining(store, insightId) {
445
+ function taskContaining(store, insightId, taskVisible = null) {
441
446
  for (const t of store.getTasks() || []) {
447
+ if (taskVisible && !taskVisible(t)) continue
442
448
  if ((t.insights || []).some((i) => i.id === insightId)) return t
443
449
  }
444
450
  return null
@@ -510,27 +516,6 @@ export function pruneItems(items, max, nowIso, { protectedIds = new Set() } = {}
510
516
  /** 进程内按文件路径复用;整份文档读改写,两个实例会互相覆盖。 */
511
517
  const globalStoreCache = new Map()
512
518
 
513
- function readJson(file, fallback) {
514
- let raw
515
- try {
516
- raw = readFileSync(file, 'utf8')
517
- } catch {
518
- return fallback
519
- }
520
- try {
521
- return JSON.parse(raw)
522
- } catch {
523
- const backup = `${file}.${Date.now()}.corrupt`
524
- try {
525
- renameSync(file, backup)
526
- console.error(`[dsh-project-memory] corrupted ${path.basename(file)} moved to ${path.basename(backup)}; starting fresh`)
527
- } catch {
528
- // 保留现场,回退默认
529
- }
530
- return fallback
531
- }
532
- }
533
-
534
519
  function normalizeDoc(doc) {
535
520
  if (doc && typeof doc === 'object' && Array.isArray(doc.items)) {
536
521
  if (typeof doc.version !== 'number') doc.version = 1
@@ -557,6 +542,12 @@ export class GlobalStore {
557
542
  /** 锁竞争后的有限次延迟重试(与 ProjectMemoryStore.save 同一套节拍)。 */
558
543
  this._retryTimer = null
559
544
  this._retryAttempts = 0
545
+ /**
546
+ * 读失败(非 ENOENT)后的只读降级:此时内存里是空库,任何落盘都会把磁盘上的整库覆盖掉。
547
+ * 与 ProjectMemoryStore 的 `_readOnly` 同义,权限修好后同一进程可自愈。
548
+ */
549
+ this._readOnly = false
550
+ this._readOnlyWarned = false
560
551
  }
561
552
 
562
553
  load() {
@@ -571,7 +562,12 @@ export class GlobalStore {
571
562
  this._dirty = hot._dirty
572
563
  return hot
573
564
  }
574
- this.doc = normalizeDoc(readJson(this.file, null))
565
+ this.doc = normalizeDoc(readJsonFile(this.file, null, {
566
+ onReadError: (err) => {
567
+ this._readOnly = true
568
+ this._warnReadOnly(err)
569
+ },
570
+ }))
575
571
  // 与 project 级一致:global 条目也要补派生 trigger(提示通道用它提升召回;确定性、幂等)。
576
572
  if (backfillDerivedTriggers(this.doc)) this.markDirty()
577
573
  this._baseIds = new Set(this.doc.items.map((it) => it?.id).filter(Boolean))
@@ -600,6 +596,28 @@ export class GlobalStore {
600
596
  return this.lastCommitOk === true
601
597
  }
602
598
 
599
+ /** 读失败告警只打一次(每个 store 实例)。 */
600
+ _warnReadOnly(err) {
601
+ if (this._readOnlyWarned) return
602
+ this._readOnlyWarned = true
603
+ const why = err ? ` (${err.code || err.message || err})` : ''
604
+ console.error(
605
+ `[dsh-project-memory] global store ${this.file} is unreadable${why}; writes are disabled until permissions are fixed. `
606
+ + 'Nothing was overwritten.',
607
+ )
608
+ }
609
+
610
+ /** 磁盘重新可读(或文件已被删掉)即解除只读,让权限修好后无需重启。 */
611
+ _recoveredFromReadOnly() {
612
+ try {
613
+ readFileSync(this.file)
614
+ } catch (err) {
615
+ if (err?.code !== 'ENOENT') return false
616
+ }
617
+ this._readOnly = false
618
+ return true
619
+ }
620
+
603
621
  /** 锁竞争失败后的有限次延迟重试:没有重试就会永久丢这次写入。 */
604
622
  _scheduleRetry() {
605
623
  const delays = [100, 500, 2000, 6000, 12000]
@@ -623,6 +641,14 @@ export class GlobalStore {
623
641
  */
624
642
  commit(fn, options = {}) {
625
643
  const res = fn ? fn(this.doc, this) : undefined
644
+ // 读失败(非 ENOENT)时整库内容未知:拒绝落盘,否则会用内存里的空库覆盖磁盘上的整库。
645
+ // 每次写前重试一次读,权限修好后同一进程自愈(与 ProjectMemoryStore 一致)。
646
+ if (this._readOnly && !this._recoveredFromReadOnly()) {
647
+ this.lastCommitOk = false
648
+ trackDirty(this)
649
+ this._warnReadOnly()
650
+ return res
651
+ }
626
652
  if (!this._dirty && res === undefined) return res
627
653
  // 本进程从基线里删掉的 id(removeMemory 直接 splice,没有单独的删除 API)。
628
654
  const current = new Set(this.doc.items.map((it) => it?.id).filter(Boolean))
@@ -644,29 +670,17 @@ export class GlobalStore {
644
670
  return res
645
671
  }
646
672
  try {
647
- const rawDisk = readJson(this.file, null)
648
- const disk = isRecord(rawDisk) && Array.isArray(rawDisk.items) ? rawDisk : null
649
- if (disk) {
650
- const byId = new Map()
651
- for (const it of disk.items) if (it?.id) byId.set(it.id, it)
652
- for (const it of this.doc.items) {
653
- if (!it?.id) continue
654
- if (this._deletedIds.has(it.id)) {
655
- byId.delete(it.id)
656
- continue
657
- }
658
- const prev = byId.get(it.id)
659
- if (!prev) {
660
- // 磁盘没有:本进程新建的才补写;否则是对方删了,丢掉内存里的旧副本。
661
- if (this._createdIds.has(it.id)) byId.set(it.id, it)
662
- continue
663
- }
664
- if (newerIso(it.updatedAt, prev.updatedAt) >= 0) byId.set(it.id, it)
665
- }
666
- for (const id of this._deletedIds) byId.delete(id)
667
- this.doc.items = [...byId.values()]
673
+ const rawDisk = readJsonFile(this.file, null)
674
+ const merged = mergeById({
675
+ diskItems: isRecord(rawDisk) && Array.isArray(rawDisk.items) ? rawDisk.items : null,
676
+ localItems: this.doc.items,
677
+ deletedIds: this._deletedIds,
678
+ createdIds: this._createdIds,
679
+ })
680
+ if (merged) {
681
+ this.doc.items = merged
668
682
  } else {
669
- // 文件缺失/不可读/损坏(readJson 已把损坏件备份)时,不能把"空 doc"当成
683
+ // 文件缺失/不可读/损坏(readJsonFile 已把损坏件备份)时,不能把"空 doc"当成
670
684
  // "对端把所有条目都删了":那会把整库旧条目静默清掉。保留内存里的完整副本重写。
671
685
  // 项目 store 在同样场景也是保留内存整份写回(见 _mergeAuxFromDisk 的 isRecord 守卫)。
672
686
  this.doc.items = this.doc.items.filter((it) => isRecord(it) && it.id)
@@ -697,7 +711,7 @@ export class GlobalStore {
697
711
  * 模型不该为了改一条记忆先搞清它在哪一层;scope 用条目自己声明的。
698
712
  * @returns {{scope: string, item: object, taskId?: string}|null}
699
713
  */
700
- export function findInsightAnywhere({ store, globalStore } = {}, id) {
714
+ export function findInsightAnywhere({ store, globalStore, taskVisible = null } = {}, id) {
701
715
  if (!id) return null
702
716
  if (globalStore && typeof globalStore.items === 'function') {
703
717
  const it = globalStore.items().find((i) => i && i.id === id)
@@ -709,6 +723,8 @@ export function findInsightAnywhere({ store, globalStore } = {}, id) {
709
723
  }
710
724
  const tasks = store && typeof store.getTasks === 'function' ? store.getTasks() || [] : []
711
725
  for (const t of tasks) {
726
+ // 任务级条目按任务可见性过滤:别队的私有记忆不能被一个 id 串到(改/删同一条路径)。
727
+ if (taskVisible && !taskVisible(t)) continue
712
728
  const it = (t.insights || []).find((i) => i && i.id === id)
713
729
  if (it) return { scope: it.scope || 'task', item: it, taskId: t.id }
714
730
  }
@@ -799,9 +815,10 @@ export function recordDeleted({ store, globalStore } = {}, entries = []) {
799
815
  * @param {object} o
800
816
  * @param {string} o.idOrQuery - 精确 id,或用于匹配的关键词
801
817
  * @param {number} [o.maxMatches] - 关键词命中上限;超过则**一条都不删**,只回报候选
818
+ * @param {(task: object) => boolean} [o.taskVisible] - 任务级条目的可见性过滤(团队隔离);缺省不过滤
802
819
  * @returns {{ok: boolean, removed?: object[], matches?: object[], tooMany?: boolean, keptIn?: string[]}}
803
820
  */
804
- export function removeMemory({ store, globalStore, idOrQuery, maxMatches = 10 } = {}) {
821
+ export function removeMemory({ store, globalStore, idOrQuery, maxMatches = 10, taskVisible = null } = {}) {
805
822
  const query = String(idOrQuery ?? '').trim()
806
823
  if (!query) return { ok: false, removed: [], matches: [] }
807
824
  const at = (home, item, taskId) => ({
@@ -814,6 +831,8 @@ export function removeMemory({ store, globalStore, idOrQuery, maxMatches = 10 }
814
831
  for (const it of (store && typeof store.insightItems === 'function' ? store.insightItems() : []) || []) pools.project.push(at('project', it))
815
832
  for (const it of (globalStore && typeof globalStore.items === 'function' ? globalStore.items() : []) || []) pools.global.push(at('global', it))
816
833
  for (const t of (store && typeof store.getTasks === 'function' ? store.getTasks() : []) || []) {
834
+ // 别队的任务级条目不在删除候选里:按 id / 关键词都不能删到本会话看不见的任务。
835
+ if (taskVisible && !taskVisible(t)) continue
817
836
  for (const it of t.insights || []) pools.task.push(at('task', it, t.id))
818
837
  }
819
838
 
@@ -830,17 +849,14 @@ export function removeMemory({ store, globalStore, idOrQuery, maxMatches = 10 }
830
849
 
831
850
  // 2) 关键词:查询侧覆盖率 ≥ 0.5(与旧经验层同判据)
832
851
  const matches = []
833
- const textOf = (home, id) => {
834
- if (home === 'project') return memoryText((store.insightItems() || []).find((x) => x.id === id))
835
- if (home === 'global') return memoryText((globalStore.items() || []).find((x) => x.id === id))
836
- for (const t of store.getTasks() || []) {
837
- const it = (t.insights || []).find((x) => x.id === id)
838
- if (it) return memoryText(it)
839
- }
840
- return ''
852
+ const textOf = (x) => {
853
+ if (x.home === 'project') return memoryText((store.insightItems() || []).find((it) => it.id === x.id))
854
+ if (x.home === 'global') return memoryText((globalStore.items() || []).find((it) => it.id === x.id))
855
+ const task = store.getTask(x.taskId)
856
+ return memoryText((task?.insights || []).find((it) => it.id === x.id))
841
857
  }
842
858
  for (const list of Object.values(pools)) {
843
- for (const x of list) if (queryCoverage(query, textOf(x.home, x.id)) >= 0.5) matches.push(x)
859
+ for (const x of list) if (queryCoverage(query, textOf(x)) >= 0.5) matches.push(x)
844
860
  }
845
861
  if (matches.length > maxMatches) return { ok: false, tooMany: true, matches, removed: [] }
846
862
  const keptIn = removeEntries({ store, globalStore }, matches)
@@ -895,9 +911,10 @@ function removeEntries({ store, globalStore }, entries) {
895
911
  * global 走 globalStore。`raw.id` 给定时走**就地更新**(忽略 scope 路由:条目留在原 home,
896
912
  * 只覆盖显式给的字段,旧值进 `prev`)。`cosine` 给定时启用向量带:≥ autoMergeCos 且领先第二名
897
913
  * ≥ autoMergeMargin → 自动覆盖;≥ hintCos → 新建但回报近邻 id;都不给就是纯词法行为。
914
+ * `taskVisible(task)` 给定时,按 id 更新与跨任务去重只考虑可见任务(团队隔离);缺省不过滤。
898
915
  * 返回 { ok, action, id, replaced, near, hint }。
899
916
  */
900
- export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, source = 'agent', nowIso, cosine = null }) {
917
+ export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, source = 'agent', nowIso, cosine = null, taskVisible = null }) {
901
918
  if (!isRecord(raw)) return { ok: false, error: '内容必须是对象(不能是 null/数组/字符串)' }
902
919
  const cfg2 = cfg || cfgInsight({})
903
920
  const now = nowIso || new Date().toISOString()
@@ -906,7 +923,7 @@ export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, sourc
906
923
  return { ok: false, error: `内容疑似包含密钥/token/私钥形态数据(字段: ${secretField}),已拒绝写入` }
907
924
  }
908
925
  if (raw && raw.id) {
909
- const found = findInsightAnywhere({ store, globalStore }, raw.id)
926
+ const found = findInsightAnywhere({ store, globalStore, taskVisible }, raw.id)
910
927
  if (!found) return { ok: false, error: `找不到要更新的条目: ${raw.id}(可能已被删除/提升;用 query_memory 重新确认 id)` }
911
928
  const wasDraft = found.item.draft === true
912
929
  const replaced = applyUpdate(found.item, raw, now)
@@ -941,7 +958,7 @@ export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, sourc
941
958
  // 归档任务 = 已停止续做:写进去的条目在 recall(visibleInsights)里永远不可见,
942
959
  // 必须让调用方先 select_task 解归档,而不是报“Saved”后石沉大海。
943
960
  if (task.archived) return { ok: false, error: `任务已归档: ${taskId}(先 select_task 解归档再写入)` }
944
- return saveTaskInsight(store, globalStore, task, raw, cfg2, now, source, cosine)
961
+ return saveTaskInsight(store, globalStore, task, raw, cfg2, now, source, cosine, taskVisible)
945
962
  }
946
963
  return saveProjectInsight(store, globalStore, raw, cfg2, now, source, cosine)
947
964
  }
@@ -1006,7 +1023,7 @@ function buildHint(res, pruned, promoted) {
1006
1023
 
1007
1024
  // ---- scope = task ----
1008
1025
 
1009
- function saveTaskInsight(store, globalStore, task, raw, cfg, now, source, cosine) {
1026
+ function saveTaskInsight(store, globalStore, task, raw, cfg, now, source, cosine, taskVisible = null) {
1010
1027
  // 反思产出是**待确认草稿**:只落在当前任务,绝不参与 project/global/跨任务的自动合并或
1011
1028
  // 自动提升,否则一条 LLM 生成的 draft 可以覆盖作者手写的 project 级知识。
1012
1029
  const draftOnly = raw.draft === true || source === 'reflect'
@@ -1051,14 +1068,15 @@ function saveTaskInsight(store, globalStore, task, raw, cfg, now, source, cosine
1051
1068
  }
1052
1069
  }
1053
1070
  // 3) 跨任务池去重(同一坑只留一份,sourceTaskIds 累积)。非草稿写入不得把正文并进 draft,
1054
- // 否则新知识永远停在待审状态。
1055
- const pool = allTaskInsights(store).filter((it) => it.draft !== true)
1071
+ // 否则新知识永远停在待审状态。池子只收调用者可见的任务:跨队去重会让别队的私有条目
1072
+ // 被这条写入改写(并在 hint 里回显它的 id),团队隔离在这里也要成立。
1073
+ const pool = allTaskInsights(store, taskVisible).filter((it) => it.draft !== true)
1056
1074
  const poolNear = vectorNear(vectorText(base), pool, cosine)
1057
1075
  const poolTarget = autoMergeTarget(poolNear, cfg)
1058
1076
  if (poolTarget) {
1059
1077
  const { replaced } = mergeInto(poolTarget.item, base, cfg, now)
1060
1078
  store.markTasksDirty()
1061
- const holder = taskContaining(store, poolTarget.item.id)
1079
+ const holder = taskContaining(store, poolTarget.item.id, taskVisible)
1062
1080
  if (holder) {
1063
1081
  const promoted = promoteAllTasksToProject(store, globalStore, cfg, now)
1064
1082
  return { ok: true, action: 'auto-merged', id: poolTarget.item.id, taskId: holder.id, scope: 'task', replaced, cos: Number(poolTarget.top1.toFixed(3)), hint: `相似度 ${poolTarget.top1.toFixed(3)},已自动覆盖任务 ${holder.id} 的既有条目${replaced.length ? `(覆盖字段 ${replaced.join('/')})` : ''}${promoted ? `;自动提升 project ${promoted} 条` : ''}` }
@@ -1067,7 +1085,7 @@ function saveTaskInsight(store, globalStore, task, raw, cfg, now, source, cosine
1067
1085
  const hit = findBestOverlapMatch(text, pool)
1068
1086
  if (hit && hit.score >= cfg.dedupOverlap) {
1069
1087
  const { replaced } = mergeInto(hit.item, base, cfg, now)
1070
- const holder = taskContaining(store, hit.item.id)
1088
+ const holder = taskContaining(store, hit.item.id, taskVisible)
1071
1089
  if (holder) {
1072
1090
  store.markTasksDirty()
1073
1091
  const holderId = holder.id
package/src/readiness.js CHANGED
@@ -64,8 +64,8 @@ export function extractPaths(text) {
64
64
 
65
65
  /**
66
66
  * 组装就绪上下文:人类意图 + 已观察动作。三处来源都做动作/路径归一,调用方只需给文本。
67
- * **证据来源决定准入**:observed(结构化工具调用)可以触发全文注入;人类消息里的动作词只允许
68
- * 4 个"不可逆外部动作"触发全文(见 {@link PRE_ACTION_OPS}),其余只进提示通道。
67
+ * **证据来源决定准入**:observed(结构化工具调用)可以触发全文注入;人类消息里的动作词只有
68
+ * `PRE_ACTION_OPS` 里的不可逆外部动作能触发全文注入,其余只进提示通道。
69
69
  * @param {object} input `humanText` 本轮人类消息;`actionText` 旧调用方的工具调用文本(测试/老宿主,
70
70
  * 生产路径不再传);`ops`/`targets` 结构化工具调用归一出的动作与写目标(可信);
71
71
  * `actions`/`paths` 调用方已归一化的动作 id 与路径(可选,会被并集)。
@@ -3,7 +3,7 @@
3
3
  // tool/call data.arguments 为 JSON 字符串;fs 工具名 read/write/edit/read_image,参数 file_path。
4
4
  import path from 'node:path'
5
5
  import { existsSync, statSync } from 'node:fs'
6
- import { createHash, randomUUID } from 'node:crypto'
6
+ import { randomUUID } from 'node:crypto'
7
7
  import { memoryRootFor, resolveProjectMemoryRoot } from '../util/fs.js'
8
8
  import { sessionWorkingDir } from '../util/session-dir.js'
9
9
  import { ProjectMemoryStore } from '../store.js'
@@ -11,6 +11,7 @@ import { BoundedMap } from '../util/session-cache.js'
11
11
  import { stepContent, stepStatus } from '../util/task-view.js'
12
12
  import { patchFilePaths } from '../util/patch.js'
13
13
  import { flushDirtyStores } from '../util/flush.js'
14
+ import { hash8 } from '../util/hash.js'
14
15
 
15
16
  // apply_patch 的参数是整段补丁文本,路径在正文里(见 util/patch.js),单独分支处理。
16
17
  const FS_FILE_TOOLS = new Set(['read', 'write', 'edit', 'read_image', 'str_replace_editor', 'apply_patch'])
@@ -19,10 +20,6 @@ const READ_TOOLS = new Set(['read', 'read_image'])
19
20
  const MAX_FILES_PER_TASK = 100
20
21
  const TITLE_MAX = 24
21
22
 
22
- export function hash8(text) {
23
- return createHash('sha256').update(String(text)).digest('hex').slice(0, 8)
24
- }
25
-
26
23
  export function slugifyTitle(text) {
27
24
  return String(text || '')
28
25
  .toLowerCase()
@@ -248,6 +245,9 @@ export function onSessionEvent(config, session, event, meta, ctx) {
248
245
  if (!Array.isArray(todos)) return
249
246
  store.commit((s) => {
250
247
  let task = s.getBoundTaskId(sessionId) ? s.getTask(s.getBoundTaskId(sessionId)) : null
248
+ // 团队锚点只存记忆:步骤与 lastTodoAt 属于单个 agent 的清单。多个成员绑同一锚点时,
249
+ // 队友的 todo 会覆盖 lead 的清单,并把 lastTodoAt 顶到别人会话里(任务卡回声判据失效)。
250
+ if (task?.teamTaskId) return
251
251
  if (!task || task.archived) {
252
252
  // 空写 = 清空清单:不自动建档(避免"未绑定会话清空 todo"误建垃圾任务)
253
253
  if (todos.length === 0) return
@@ -281,6 +281,52 @@ export function onSessionEvent(config, session, event, meta, ctx) {
281
281
  return
282
282
  }
283
283
 
284
+ // 团队任务板的变化(宿主把每次变更的完整快照 append 成 team/task):只同步本地记忆锚点。
285
+ // 完成不改归档(任务做完记忆仍然有用);删除(tombstone)才归档 + 解绑,与 archive_task 同语义。
286
+ if (type === 'team/task') {
287
+ const snapshot = event.data?.task
288
+ const teamTaskId = snapshot?.id
289
+ // 宿主把 TeamId 定义为团队树根会话 id:任务编号只在团队内唯一,匹配必须带上它。
290
+ const teamId = event.data?.teamId
291
+ if (typeof teamTaskId !== 'string' || typeof teamId !== 'string') return
292
+ // 没有本地锚点就没有可同步的东西:纯团队项目不该为一次任务变更去碰 store。
293
+ if (!store.getTasks().some((t) => t.teamId === teamId && t.teamTaskId === teamTaskId)) return
294
+ store.commit((s) => {
295
+ const record = s.getTasks().find((t) => t.teamId === teamId && t.teamTaskId === teamTaskId)
296
+ if (!record) return
297
+ let changed = false
298
+ const status = typeof snapshot.status === 'string' ? snapshot.status : null
299
+ if (status && record.teamTaskStatus !== status) {
300
+ record.teamTaskStatus = status
301
+ changed = true
302
+ }
303
+ const owner = typeof snapshot.ownerName === 'string' ? snapshot.ownerName : null
304
+ if (owner && record.teamOwnerName !== owner) {
305
+ record.teamOwnerName = owner
306
+ changed = true
307
+ }
308
+ const scopes = Array.isArray(snapshot.writeScopes) ? snapshot.writeScopes.filter((p) => typeof p === 'string') : null
309
+ if (scopes && JSON.stringify(record.teamWriteScopes || []) !== JSON.stringify(scopes)) {
310
+ record.teamWriteScopes = scopes
311
+ changed = true
312
+ }
313
+ if (snapshot.status === 'deleted') {
314
+ // 团队任务没了,还绑着的会话不该继续往一个已删任务的记忆里写。
315
+ // 绑定清理不能只在"首次归档"时做:已归档但仍有绑定(手改/跨进程合并)也要解掉。
316
+ if (!record.archived) {
317
+ record.archived = true
318
+ changed = true
319
+ }
320
+ if (s.removeBindingsForTask(record.id)) changed = true
321
+ }
322
+ if (changed) {
323
+ record.updatedAt = now
324
+ s.markTasksDirty()
325
+ }
326
+ })
327
+ return
328
+ }
329
+
284
330
  if (type === 'tool/call') {
285
331
  const taskId = store.getBoundTaskId(sessionId)
286
332
  if (!taskId) return
@@ -0,0 +1,220 @@
1
+ /**
2
+ * 宿主团队任务(`task-<n>`)→ 本地记忆任务键的唯一映射。
3
+ *
4
+ * 为什么需要这一层:任务级记忆(`save_lesson` 的 `scope: 'task'`)挂在 `tasks.json` 某条任务
5
+ * 记录的 `insights[]` 上,只有**会话绑定到该任务、或本次调用显式传 `task_id`** 时才看得见它;
6
+ * 而绑定原本只认本地 `tsk_…` 任务。团队模式下 lead 与队友是两个会话,它们唯一的公共任务身份
7
+ * 是宿主的团队任务板(`TeamTaskId` 形如 `task-<n>`)。不做映射,lead 写在任务上的经验队友就
8
+ * 看不到,只能 promote 到 project —— 一个任务的经验被抬成全项目知识,作用域丢失。
9
+ *
10
+ * 软依赖:`ctx.get('agentTeams')` 缺失(没装团队插件 / 老宿主)、调用者不是团队会话、对端任务
11
+ * 不存在或属于别的团队时,这里只返回 `unavailable` / `not-found`,`select_task` 维持原行为。
12
+ * 记录是**记忆挂载点**:镜像宿主的 status / owner / writeScopes(只做展示与提示),
13
+ * 但不吸收某个成员的步骤/自维护时刻(那是单个 agent 的清单,见 taskbridge 的 todo/write 分支);
14
+ * 冲突告警由宿主的视图现算,不落盘(快照里没有它,存下来只会过期)。
15
+ * 它也不进 taskbridge 的自动建档路径(子代理仍不建档;绑定只能由显式 `select_task` 建立,
16
+ * 而锚点另有"任务级 `save_lesson` 懒建"这一个入口)。
17
+ */
18
+ import { hash8 } from '../util/hash.js'
19
+
20
+ /** 宿主 `TeamTaskId` 的形状:`task-<n>`。 */
21
+ const TEAM_TASK_ID_RE = /^task-\d+$/
22
+
23
+ /** 这个 id 是不是宿主的团队任务 id。 */
24
+ export function isTeamTaskId(value) {
25
+ return typeof value === 'string' && TEAM_TASK_ID_RE.test(value)
26
+ }
27
+
28
+ /** 团队任务 → 本地记忆任务记录的 id。
29
+ *
30
+ * **必须带团队树**:宿主 `TeamTaskId` 是团队内编号(`task-1`、`task-2`…),同一个项目里
31
+ * 两个顶层会话各自开团队时编号会重复;只用任务 id 会让两个团队的记忆/状态互相覆盖。
32
+ * @param {string} teamId - 团队树根会话 id(宿主把 `TeamId` 定义为 root session id)。
33
+ * @param {string} teamTaskId - `task-<n>`。
34
+ * @returns {string} `team:<teamId>:task-<n>`。
35
+ */
36
+ export function teamMemoryTaskId(teamId, teamTaskId) {
37
+ return `team:${teamId}:${teamTaskId}`
38
+ }
39
+
40
+ /**
41
+ * 调用者所属团队树的 id(root session id)。`getTask` 用它把团队内任务编号变成全局唯一键。
42
+ * 软探测 `subagents` 服务(团队插件本身依赖它),拿不到就返回 null,由调用方当作"无法解析"。
43
+ * @param {object} exec - 工具执行上下文。
44
+ * @returns {string|null}
45
+ */
46
+ export function teamIdOf(exec) {
47
+ const caller = exec?.agent
48
+ const ctx = hostCtxOf(exec)
49
+ if (!caller || !ctx || typeof ctx.get !== 'function') return null
50
+ try {
51
+ const subagents = ctx.get('subagents')
52
+ const root = subagents && typeof subagents.rootOf === 'function' ? subagents.rootOf(caller) : null
53
+ const id = root?.session?.id
54
+ return typeof id === 'string' && id ? id : null
55
+ } catch {
56
+ return null
57
+ }
58
+ }
59
+
60
+ function hostCtxOf(exec) {
61
+ return exec?.agent?.ctx || exec?.ctx || null
62
+ }
63
+
64
+ /**
65
+ * 软探测 `ctx.get('agentTeams')`。cordis 里读它不需要 inject;没有 `ctx.get`(老宿主)
66
+ * 或服务未装配时返回 null,整条团队路径因此不存在。
67
+ */
68
+ export function teamServiceOf(exec) {
69
+ const ctx = hostCtxOf(exec)
70
+ if (!ctx || typeof ctx.get !== 'function') return null
71
+ try {
72
+ return ctx.get('agentTeams') || null
73
+ } catch {
74
+ return null
75
+ }
76
+ }
77
+
78
+ /**
79
+ * 读一个团队任务并确认归属。`getTask(caller, id)` 按 caller 所在的 subagent 树取板,
80
+ * 所以不存在的 id、别的团队的任务都会抛 `TEAM_TASK_NOT_FOUND` —— 这里归一成 `not-found`,
81
+ * 让模型看到的错误与本地任务一致;软删(`status: 'deleted'`)同样按找不到处理。
82
+ * @returns {{ok: true, view: object} | {ok: false, reason: 'unavailable'|'no-caller'|'not-found'|'error', error?: string}}
83
+ */
84
+ export function resolveTeamTask(exec, teamTaskId) {
85
+ const service = teamServiceOf(exec)
86
+ const caller = exec?.agent
87
+ if (!service || typeof service.getTask !== 'function') return { ok: false, reason: 'unavailable' }
88
+ // 宿主契约要求 caller 是 live Agent;PTC/嵌套调用可能没有 agent,这时不是"没装团队插件"。
89
+ if (!caller || typeof caller !== 'object') return { ok: false, reason: 'no-caller' }
90
+ try {
91
+ const view = service.getTask(caller, teamTaskId)
92
+ if (!view || typeof view !== 'object' || view.status === 'deleted') return { ok: false, reason: 'not-found' }
93
+ return { ok: true, view }
94
+ } catch (err) {
95
+ if (err?.code === 'TEAM_TASK_NOT_FOUND') return { ok: false, reason: 'not-found' }
96
+ return { ok: false, reason: 'error', error: err?.message || String(err) }
97
+ }
98
+ }
99
+
100
+ /** 宿主视图里随任务变化、需要带给模型看的那几个字段(advisory,不参与准入判定)。 */
101
+ function teamFieldsOf(view) {
102
+ const fields = {}
103
+ if (typeof view.status === 'string') fields.teamTaskStatus = view.status
104
+ if (typeof view.ownerName === 'string') fields.teamOwnerName = view.ownerName
105
+ if (Array.isArray(view.writeScopes)) {
106
+ fields.teamWriteScopes = view.writeScopes.filter((p) => typeof p === 'string')
107
+ }
108
+ return fields
109
+ }
110
+
111
+ /**
112
+ * 把工具参数里的任务引用归一成本地记忆任务 id:本地 id 原样返回;宿主团队 id(`task-<n>`)
113
+ * 如果已经有锚点,返回 `team:task-<n>`;没有锚点则原样返回,由调用方按"找不到"给出可执行的错误。
114
+ * 只做映射,不创建锚点 —— 创建需要宿主视图,入口是 `select_task` 或任务级 `save_lesson`。
115
+ * @param {object} store - 项目 store。
116
+ * @param {unknown} taskId - 工具参数里的任务 id。
117
+ * @param {string|null} teamId - 调用者所属团队树(`teamIdOf`);团队 id 缺省时不做映射。
118
+ * @returns {unknown} 归一后的 id。
119
+ */
120
+ export function memoryTaskIdFor(store, taskId, teamId) {
121
+ if (typeof taskId !== 'string' || !taskId) return taskId
122
+ if (store.getTask(taskId)) return taskId
123
+ if (!isTeamTaskId(taskId) || !teamId) return taskId
124
+ const anchor = teamMemoryTaskId(teamId, taskId)
125
+ return store.getTask(anchor) ? anchor : taskId
126
+ }
127
+
128
+ /**
129
+ * 这条本地记录是不是**别的团队**的锚点。
130
+ *
131
+ * 团队锚点自带 `teamId`(团队树根会话 id)。显式传原始锚点 id(`team:<root>:task-<n>`,
132
+ * 也就是 `select_task` 回给模型的那个"记忆任务 id")时,必须和调用者所在团队一致——
133
+ * 否则同一项目里两个团队的私有任务记忆会被一个猜到的 id 串读。本地任务(无 `teamId`)恒可见。
134
+ * @param {object} record - 本地任务记录(可能不是团队锚点)。
135
+ * @param {string|null} teamId - 调用者所属团队树;拿不到时团队锚点按不可见处理。
136
+ * @returns {boolean} true = 可以访问。
137
+ */
138
+ export function teamAnchorVisible(record, teamId) {
139
+ if (!record || !record.teamId) return true
140
+ return teamId != null && record.teamId === teamId
141
+ }
142
+
143
+ /**
144
+ * 任务记录对调用者是否可用:本地任务恒可见;团队锚点只对所属团队树可见。
145
+ * 拿不到团队树时团队锚点按不可见处理(fail-closed)——访问判定宁可报"找不到",
146
+ * 也不能让一个猜到的 id / 标题串到别的团队的私有记忆。
147
+ * @param {object} record - 本地任务记录。
148
+ * @param {object} exec - 工具执行上下文或命令调用(需要 `agent`)。
149
+ * @returns {boolean}
150
+ */
151
+ export function taskVisibleTo(record, exec) {
152
+ return teamAnchorVisible(record, teamIdOf(exec))
153
+ }
154
+
155
+ /**
156
+ * 生成"这条任务对该会话是否可见"的判定函数:团队树只解析一次,适合在任务池 / 任务列表
157
+ * 的循环里反复判定(每次 `taskVisibleTo` 都会重新探测 subagents 服务)。
158
+ * @param {object} exec - 工具执行上下文或命令调用(需要 `agent`)。
159
+ * @returns {(record: object) => boolean}
160
+ */
161
+ export function taskVisibility(exec) {
162
+ const teamId = teamIdOf(exec)
163
+ return (record) => teamAnchorVisible(record, teamId)
164
+ }
165
+
166
+ /**
167
+ * 已落盘团队锚点的宿主复核:只有宿主**明确**说"没有这个任务"才算失效;拿不到宿主
168
+ * (`unavailable` / `no-caller` / RPC 失败)是离线降级,不能据此把已有记忆判死。
169
+ * 用于显式原始锚点、会话绑定这两条不经过宿主视图解析的路径。
170
+ * @param {object} exec - 工具执行上下文。
171
+ * @param {object} record - 本地任务记录(可带 `teamTaskId`)。
172
+ * @returns {{ok: true, degraded?: string} | {ok: false, reason: 'not-found'|'error', error?: string}}
173
+ */
174
+ export function recheckTeamAnchor(exec, record) {
175
+ if (!record || !record.teamTaskId) return { ok: true }
176
+ const resolved = resolveTeamTask(exec, record.teamTaskId)
177
+ if (resolved.ok) return { ok: true }
178
+ if (resolved.reason === 'not-found') return { ok: false, reason: 'not-found' }
179
+ if (resolved.reason === 'error') return { ok: false, reason: 'error', error: resolved.error }
180
+ return { ok: true, degraded: resolved.reason }
181
+ }
182
+
183
+ /**
184
+ * 团队任务对应的本地记忆任务记录:已有就复用,没有就按宿主视图懒建一条。
185
+ *
186
+ * 标题只在新建时取宿主的 `subject`;之后不跟着变 —— 用户可能已经用 `select_task` 的 `title`
187
+ * 改过名,每次 select 都覆盖会把人工命名冲掉。缺 subject 时用 `团队任务 <id>` 占位。
188
+ * status / owner / writeScopes 每次都从视图刷新(它们是宿主的运行时事实,本地不持有判断)。
189
+ * 复用分支只改内存、不标脏:调用方(select_task)随后统一 `markTasksDirty()` + save。
190
+ * @returns {{task: object, created: boolean}}
191
+ */
192
+ export function ensureTeamTaskRecord(store, view, { teamId, root, sid, now }) {
193
+ const id = teamMemoryTaskId(teamId, view.id)
194
+ const existing = store.getTask(id)
195
+ if (existing) {
196
+ Object.assign(existing, teamFieldsOf(view))
197
+ return { task: existing, created: false }
198
+ }
199
+ const subject = typeof view.subject === 'string' ? view.subject.trim() : ''
200
+ const task = {
201
+ id,
202
+ teamId,
203
+ teamTaskId: view.id,
204
+ projectHash: hash8(root),
205
+ projectRoot: root,
206
+ title: subject || `团队任务 ${view.id}`,
207
+ steps: null,
208
+ files: [],
209
+ fileMeta: {},
210
+ archived: false,
211
+ insights: [],
212
+ lastSessionId: sid || null,
213
+ createdAt: now,
214
+ updatedAt: now,
215
+ lastActiveAt: now,
216
+ ...teamFieldsOf(view),
217
+ }
218
+ store.addTask(task)
219
+ return { task, created: true }
220
+ }