@yolk_vat-y/dsh-project-memory 0.6.1 → 0.6.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.
@@ -0,0 +1,165 @@
1
+ /**
2
+ * 记忆列表的分页窗口工具(纯函数,无 React 依赖)。
3
+ *
4
+ * 为什么要单独成模块:客户端测试跑的是一个**手写的 React 替身**
5
+ * (`useState` 的 setter 是 no-op、`useEffect` 由测试手动触发,见 test/client-toolview.test.mjs),
6
+ * 它验证不了"滚到底 → 追加渲染"这类行为。所以把分页的**决策**收敛成纯函数:
7
+ * 拼命令、算下一页窗口、追加去重、判定是否还有更多——边界由
8
+ * test/client-paging.test.mjs 直接钉住,组件只负责把结果接到渲染上。
9
+ *
10
+ * 协议约定(与宿主 src/commands/insight-actions.js 的 `list` 分支一一对应):
11
+ * `/tasks insight list <scope> <offset> <limit>` → 载荷 `{ scope, count, total, offset, items, nextOffset }`
12
+ * `nextOffset === null` 表示到底;载荷缺这些字段(老宿主)时按"一次性返回全部"降级处理。
13
+ */
14
+
15
+ /** 每页条数。宿主侧 INSIGHT_PAGE_MAX=200 是防滥用的封顶,正常永远走这个值。 */
16
+ export const PAGE_SIZE = 30
17
+
18
+ /**
19
+ * 单次请求的条数上限,必须与宿主 `INSIGHT_PAGE_MAX`(src/commands/insight-actions.js)一致。
20
+ *
21
+ * 客户端 bundle 跑在浏览器里,不能 import 服务端模块,所以这里是第二份常量;
22
+ * test/insight-paging.test.mjs 有一条交叉断言把两边钉在一起。
23
+ *
24
+ * 宿主对超限的 `limit` 是**静默**夹到 200、并照常回报 `nextOffset`。动作后的重放是"替换"
25
+ * (MemoryView 用 `parsed.items` 整份 setRows),于是加载了 500 条的用户点一次动作,
26
+ * 列表会被打回 200 条——请求值必须先在这里夹住,不能指望宿主替我们兜。
27
+ */
28
+ export const HOST_PAGE_MAX = 200
29
+
30
+ /**
31
+ * 预取提前量:哨兵进入视口**下方 600px** 就开始取下一页,
32
+ * 让用户在真正滚到底之前数据已经到位——这是"无感"的来源,不是滚到底再转圈。
33
+ */
34
+ export const PREFETCH_MARGIN = '600px 0px'
35
+
36
+ /**
37
+ * 加载指示的延迟显示阈值(毫秒)。本地数据通常几十毫秒就回来,
38
+ * 立即显示加载行只会造成"闪一下";超过这个时间才认为用户真的在等。
39
+ */
40
+ export const SPINNER_DELAY_MS = 150
41
+
42
+ /**
43
+ * 拼一页的请求命令行。数据通道是命令文本,协议只在这里拼一次。
44
+ * @param {string} scope - `task` | `project` | `global`。
45
+ * @param {number} offset - 起始下标。
46
+ * @param {number} limit - 本页条数。
47
+ * @returns {string} 可直接交给 remote.commands.execute 的命令行。
48
+ */
49
+ export function insightListLine(scope, offset, limit) {
50
+ return `/tasks insight list ${scope} ${offset} ${limit}`
51
+ }
52
+
53
+ /**
54
+ * 追加一页并**按 id 去重**。去重是必需的不是防御性的:前缀重放(见
55
+ * {@link reloadWindowRequest})与并发刷新都可能让同一 id 出现两次,重复行会带上
56
+ * 重复的按钮,点错一个就是误删。
57
+ * @param {ReadonlyArray<{id?: string}>} prev - 已渲染条目。
58
+ * @param {ReadonlyArray<{id?: string}>} page - 新到的一页。
59
+ * @returns {Array} 追加后的数组;无新增时**原样返回** prev(避免无意义的重渲染)。
60
+ */
61
+ export function appendUnique(prev, page) {
62
+ if (!Array.isArray(page) || page.length === 0) return prev
63
+ const seen = new Set(prev.map((row) => row && row.id))
64
+ const fresh = page.filter((row) => row && !seen.has(row.id))
65
+ if (fresh.length === 0) return prev
66
+ return [...prev, ...fresh]
67
+ }
68
+
69
+ /**
70
+ * 动作(archive/delete/promote…)之后的重载窗口:刷新**已加载的整个前缀**,
71
+ * 而不是重置成第一页——后者会把正在看第 5 页的用户直接弹回顶部。
72
+ *
73
+ * 用 offset 分页而不是 keyset 游标,正是为了让这条路可行:游标只能"往后翻",
74
+ * 表达不了"把 0..N 重取一遍"。删除/归档导致的窗口收缩下,前缀重取依然不重不漏。
75
+ *
76
+ * **上限**:宿主单页最多 {@link HOST_PAGE_MAX} 条,超过就静默截断。所以已加载数超过上限时
77
+ * 这一窗只重放前 200 条(`limit` 夹住),载荷回报的 `nextOffset` 会让哨兵继续把 200..N
78
+ * 追加回来——宁可多一轮分页,也不能发一个"请求 500、只回 200"的值把列表打回 200 条。
79
+ * @param {number} loadedCount - 当前已渲染条数。
80
+ * @param {number} [pageSize] - 每页条数下界,保证至少取一页。
81
+ * @returns {{offset: number, limit: number}} 重放请求窗口(limit ≤ HOST_PAGE_MAX)。
82
+ */
83
+ export function reloadWindowRequest(loadedCount, pageSize = PAGE_SIZE) {
84
+ const count = Number.isFinite(loadedCount) && loadedCount > 0 ? Math.floor(loadedCount) : 0
85
+ return { offset: 0, limit: Math.min(HOST_PAGE_MAX, Math.max(pageSize, count)) }
86
+ }
87
+
88
+ /**
89
+ * 把宿主载荷归一成窗口状态,兼容三种形态:
90
+ * - 新宿主分页:有 `total` + `nextOffset`;
91
+ * - 新宿主不分页(省略 limit):`nextOffset === null`;
92
+ * - 老宿主/老 bundle:两个字段都没有 → 视为"一次给全,没有下一页"。
93
+ * @param {any} data - 已解析的 JSON 载荷。
94
+ * @param {number} fallbackOffset - 请求时的 offset(载荷没给 offset 时用它)。
95
+ * @returns {{items: any[], total: number, offset: number, nextOffset: number|null}} 归一化窗口。
96
+ */
97
+ export function normalizeWindow(data, fallbackOffset = 0) {
98
+ const items = Array.isArray(data && data.items) ? data.items : []
99
+ const rawTotal = data && typeof data.total === 'number' ? data.total : data && typeof data.count === 'number' ? data.count : items.length
100
+ const total = Number.isFinite(rawTotal) && rawTotal >= 0 ? rawTotal : items.length
101
+ const offset = data && Number.isFinite(data.offset) ? data.offset : fallbackOffset
102
+ const next = data && data.nextOffset
103
+ const nextOffset = typeof next === 'number' && Number.isFinite(next) && next >= 0 ? next : null
104
+ return { items, total, offset, nextOffset }
105
+ }
106
+
107
+ /**
108
+ * 页脚文案用的"已显示 N / 总数"。
109
+ * @param {number} loaded - 已渲染条数。
110
+ * @param {number} total - 服务端总数。
111
+ * @returns {{loaded: number, total: number}} 归一化后的计数(total 不会小于 loaded)。
112
+ */
113
+ export function progressCounts(loaded, total) {
114
+ const l = Number.isFinite(loaded) && loaded > 0 ? Math.floor(loaded) : 0
115
+ const t = Number.isFinite(total) && total > 0 ? Math.floor(total) : 0
116
+ return { loaded: l, total: Math.max(l, t) }
117
+ }
118
+
119
+ /**
120
+ * 请求闸门:协调首屏 / 追加 / 动作后重放这几类**会重叠**的请求。
121
+ *
122
+ * 这里踩过一个坑,规则就是照着它定的:早期实现用"有在途请求就直接 return"的布尔守卫。
123
+ * 于是"上一页还在飞的时候切 scope(或点动作)"时,新请求被**直接丢掉**,而过期响应又
124
+ * 被作用域检查丢掉 → 新列表永远空白,只能手动刷新才出来。正确语义是两件事分开:
125
+ * - **过期响应丢弃**(靠序号 + 作用域判定);
126
+ * - **新请求照发**(只有同一个 key 正在飞时才去重,避免哨兵连续触发重复取同一页)。
127
+ * @returns {{begin: Function, end: Function, isStale: Function}} 闸门。
128
+ */
129
+ export function createRequestGate() {
130
+ let seq = 0
131
+ let inflightKey = null
132
+ return {
133
+ /**
134
+ * 申请发起一次请求。
135
+ * @param {string} key - 请求身份(scope|offset|limit|append)。
136
+ * @returns {number|false} 该请求的序号;同一 key 已在飞时返回 false(去重)。
137
+ */
138
+ begin(key) {
139
+ if (inflightKey === key) return false
140
+ inflightKey = key
141
+ seq += 1
142
+ return seq
143
+ },
144
+ /**
145
+ * 请求结束。
146
+ * @param {string} key - 请求身份。
147
+ * @param {number} ticket - begin 返回的序号。
148
+ * @returns {boolean} 它是否仍是最后一次请求(决定加载标志该不该回落)。
149
+ */
150
+ end(key, ticket) {
151
+ if (inflightKey === key) inflightKey = null
152
+ return ticket === seq
153
+ },
154
+ /**
155
+ * 该响应是否已过期。
156
+ * @param {number} ticket - 发出时的序号。
157
+ * @param {string} requestedScope - 发出时的作用域。
158
+ * @param {string} currentScope - 当前作用域。
159
+ * @returns {boolean} true=必须整份丢弃。
160
+ */
161
+ isStale(ticket, requestedScope, currentScope) {
162
+ return ticket !== seq || requestedScope !== currentScope
163
+ },
164
+ }
165
+ }
@@ -4,6 +4,7 @@
4
4
  * - 无 UI 状态,无 localStorage,纯内存 + BroadcastChannel 同步
5
5
  */
6
6
  import { useSyncExternalStore } from 'react'
7
+ import { broadcastAppliesTo, payloadRoot } from './task-scope.js'
7
8
 
8
9
  export interface TaskStep {
9
10
  content: string
@@ -37,6 +38,8 @@ export interface TaskPayload {
37
38
  tasks: Task[]
38
39
  boundId: string | null
39
40
  archived: number
41
+ /** 项目根。旧宿主没有这个键(null):跨标签页同步在未知根时退回"只按会话"处理。 */
42
+ root?: string | null
40
43
  }
41
44
 
42
45
  export function parseTaskPayloadText(text?: string | null): TaskPayload | null {
@@ -52,7 +55,12 @@ export function parseTaskPayloadText(text?: string | null): TaskPayload | null {
52
55
  try {
53
56
  const data = JSON.parse(jsonBlock)
54
57
  if (!Array.isArray(data.tasks)) return null
55
- return { tasks: data.tasks, boundId: data.boundId ?? null, archived: data.archived ?? 0 }
58
+ return {
59
+ tasks: data.tasks,
60
+ boundId: data.boundId ?? null,
61
+ archived: data.archived ?? 0,
62
+ root: payloadRoot(data.root),
63
+ }
56
64
  } catch {
57
65
  return null
58
66
  }
@@ -62,6 +70,8 @@ interface TaskDataState {
62
70
  tasks: Task[]
63
71
  boundTaskId: string | null
64
72
  archivedCount: number
73
+ /** 这份数据的项目根:广播按它做作用域,避免多项目标签页互相覆盖。 */
74
+ root: string | null
65
75
  lastUpdate: number
66
76
  }
67
77
 
@@ -71,6 +81,7 @@ let dataState: TaskDataState = {
71
81
  tasks: [],
72
82
  boundTaskId: null,
73
83
  archivedCount: 0,
84
+ root: null,
74
85
  lastUpdate: 0,
75
86
  }
76
87
 
@@ -84,31 +95,36 @@ function setDataState(next: TaskDataState | ((prev: TaskDataState) => TaskDataSt
84
95
  tasks: Array.isArray(patch?.tasks) ? patch.tasks : [],
85
96
  boundTaskId: patch?.boundTaskId ?? null,
86
97
  archivedCount: typeof patch?.archivedCount === 'number' ? patch.archivedCount : 0,
98
+ root: payloadRoot(patch?.root),
87
99
  lastUpdate: typeof patch?.lastUpdate === 'number' ? patch.lastUpdate : 0,
88
100
  }
89
101
  for (const listener of dataListeners) listener()
90
102
  }
91
103
 
92
- function broadcastDataUpdate(tasks: Task[], archivedCount: number): void {
104
+ function broadcastDataUpdate(tasks: Task[], archivedCount: number, root: string | null): void {
93
105
  if (!SYNC_CHANNEL) return
94
106
  SYNC_CHANNEL.postMessage({
95
107
  type: 'PROJECT_TASKS_UPDATED',
96
- payload: { tasks: Array.isArray(tasks) ? tasks : [], archivedCount },
108
+ payload: { tasks: Array.isArray(tasks) ? tasks : [], archivedCount, root },
97
109
  })
98
110
  }
99
111
 
100
112
  if (SYNC_CHANNEL) {
101
113
  SYNC_CHANNEL.onmessage = (event) => {
102
114
  const msg = event.data
103
- if (msg?.type === 'PROJECT_TASKS_UPDATED' && msg.payload) {
104
- const { tasks, archivedCount } = msg.payload
105
- setDataState(prev => ({
106
- ...prev,
107
- tasks: Array.isArray(tasks) ? tasks : [],
108
- archivedCount: typeof archivedCount === 'number' ? archivedCount : prev.archivedCount,
109
- lastUpdate: Date.now(),
110
- }))
111
- }
115
+ if (msg?.type !== 'PROJECT_TASKS_UPDATED' || !msg.payload) return
116
+ const { tasks, archivedCount, root } = msg.payload
117
+ // 频道名是固定的(同一浏览器同源的所有 dsh 页面共用一个),所以**必须**按项目根过滤:
118
+ // 否则在 A 项目点一下刷新,B 项目的标签页面板就被贴上 A 的任务列表(而它还保留自己的
119
+ // boundTaskId,看起来像"绑定丢了")。两侧都已知根且不同 → 丢弃;本页还不知道根(还没
120
+ // 同步过)→ 也丢弃,让它自己那一次 /tasks 决定归属,不先借别人的数据。
121
+ if (!broadcastAppliesTo(dataState.root, root)) return
122
+ setDataState(prev => ({
123
+ ...prev,
124
+ tasks: Array.isArray(tasks) ? tasks : [],
125
+ archivedCount: typeof archivedCount === 'number' ? archivedCount : prev.archivedCount,
126
+ lastUpdate: Date.now(),
127
+ }))
112
128
  }
113
129
  }
114
130
 
@@ -121,22 +137,25 @@ export const taskDataStore = {
121
137
  return dataState
122
138
  },
123
139
  actions: {
124
- setTasks(payload: { tasks: Task[]; boundTaskId: string | null; archivedCount: number }): void {
140
+ setTasks(payload: { tasks: Task[]; boundTaskId: string | null; archivedCount: number; root?: string | null }): void {
125
141
  const nextTasks = payload.tasks || []
126
142
  const nextArchived = payload.archivedCount ?? 0
143
+ const nextRoot = payloadRoot(payload.root)
127
144
  setDataState({
128
145
  tasks: nextTasks,
129
146
  boundTaskId: payload.boundTaskId ?? null,
130
147
  archivedCount: nextArchived,
148
+ root: nextRoot,
131
149
  lastUpdate: Date.now(),
132
150
  })
133
- broadcastDataUpdate(nextTasks, nextArchived)
151
+ broadcastDataUpdate(nextTasks, nextArchived, nextRoot)
134
152
  },
135
153
  reset(): void {
136
154
  setDataState({
137
155
  tasks: [],
138
156
  boundTaskId: null,
139
157
  archivedCount: 0,
158
+ root: null,
140
159
  lastUpdate: 0,
141
160
  })
142
161
  },
@@ -0,0 +1,32 @@
1
+ /**
2
+ * 跨标签页任务广播的**项目作用域**判定(纯函数,无 React / 无 BroadcastChannel 依赖)。
3
+ *
4
+ * 为什么需要它:同步频道名是固定的(同一浏览器同源的所有 dsh 页面共用一个
5
+ * `dsh-pm-tasks-data`),而消息体只带任务数组。没有作用域判定时,在 A 项目点一下刷新,
6
+ * B 项目的标签页面板就会被贴上 A 的任务列表——它自己保留着 B 的 `boundTaskId`,
7
+ * 于是表现为"绑定莫名丢了"。频道名不能按项目拆:项目根是数据到达后才知道的,
8
+ * 而 `new BroadcastChannel` 在模块加载期就要定名。
9
+ *
10
+ * 判据刻意**严格**:消息里没有根、或本页还没确定根,都不接受。
11
+ * - 无根:老宿主/老 bundle 的载荷,宁可不同步也不猜;
12
+ * - 本页未知根:它自己那一次 `/tasks` 会决定归属,不先借别人的数据(避免短暂显示错项目)。
13
+ * 两侧都已知且相等时才接受——这正是"同一项目的两个标签页"。
14
+ *
15
+ * @param {string|null|undefined} localRoot - 本页当前数据的项目根(未同步过为 null)
16
+ * @param {unknown} incomingRoot - 广播消息里的项目根
17
+ * @returns {boolean} true = 这条广播属于同一个项目,可以套用
18
+ */
19
+ export function broadcastAppliesTo(localRoot, incomingRoot) {
20
+ if (typeof incomingRoot !== 'string' || incomingRoot === '') return false
21
+ if (typeof localRoot !== 'string' || localRoot === '') return false
22
+ return localRoot === incomingRoot
23
+ }
24
+
25
+ /**
26
+ * 从 `/tasks` 载荷里取项目根(旧宿主没有该键)。
27
+ * @param {unknown} value - `payload.root`
28
+ * @returns {string|null} 非空字符串才算根
29
+ */
30
+ export function payloadRoot(value) {
31
+ return typeof value === 'string' && value !== '' ? value : null
32
+ }
@@ -4,10 +4,16 @@
4
4
  // (命令 handler:store.commit + gs.commit)统一负责,便于单测。
5
5
  import { ProjectMemoryStore } from '../store.js'
6
6
  import { memoryRootFor, normalizeCitationFiles } from '../util/fs.js'
7
- import { cfgInsight, GlobalStore, normalizeInsight, defaultGlobalFile, saveInsight, INSIGHT_KINDS } from '../insight-store.js'
7
+ import { cfgInsight, GlobalStore, normalizeInsight, defaultGlobalFile, saveInsight, recordDeleted, INSIGHT_KINDS } from '../insight-store.js'
8
8
  import { NO_PROJECT_ROOT_NOTE, projectRootFor } from '../setup/taskbridge.js'
9
9
  import { fencedJson, invocationContext } from './invocation.js'
10
10
 
11
+ /**
12
+ * 记忆列表单页上限。面板每页只请求 30 条(客户端 PAGE_SIZE),远小于它——
13
+ * 封顶只用于挡住畸形/滥用调用,避免单个响应被抓成超大载荷。
14
+ */
15
+ export const INSIGHT_PAGE_MAX = 200
16
+
11
17
  function insSummary(ins, extra = {}) {
12
18
  const s = ins || {}
13
19
  return {
@@ -53,20 +59,72 @@ function findTaskInsight(store, id) {
53
59
  return null
54
60
  }
55
61
 
56
- /** 列出某 scope 的记忆(task 聚合所有任务草稿;project/global 各自池)。 */
57
- export function listInsights(store, gs, scope) {
62
+ /**
63
+ * 时间戳解析:非法/缺失一律 0,让排序键永远是可比较的数字。
64
+ * @param {unknown} value - ISO 时间字符串。
65
+ * @returns {number} 毫秒时间戳;不可解析时 0。
66
+ */
67
+ function tsOf(value) {
68
+ const t = Date.parse(value == null ? '' : String(value))
69
+ return Number.isFinite(t) ? t : 0
70
+ }
71
+
72
+ /**
73
+ * 记忆列表的**全序**比较器:新 → 旧。
74
+ *
75
+ * 分页要求这个比较器给出**确定性全序**,否则相邻两页会重叠或漏条目:
76
+ * 1. `updatedAt` 降序(编辑会把条目顶到最前,符合"刚学到的先看到");
77
+ * 2. `createdAt` 降序(同一批写入的条目按创建时间分先后);
78
+ * 3. `id` 升序兜底 —— 前两级都相同的条目(同毫秒写入)也必须有个稳定次序。
79
+ * @param {{raw: object}} a - 左侧条目。
80
+ * @param {{raw: object}} b - 右侧条目。
81
+ * @returns {number} 排序结果。
82
+ */
83
+ function compareInsightRecency(a, b) {
84
+ const ua = tsOf(a.raw?.updatedAt) || tsOf(a.raw?.createdAt)
85
+ const ub = tsOf(b.raw?.updatedAt) || tsOf(b.raw?.createdAt)
86
+ if (ua !== ub) return ub - ua
87
+ const ca = tsOf(a.raw?.createdAt)
88
+ const cb = tsOf(b.raw?.createdAt)
89
+ if (ca !== cb) return cb - ca
90
+ return String(a.raw?.id ?? '').localeCompare(String(b.raw?.id ?? ''))
91
+ }
92
+
93
+ /**
94
+ * 列出某 scope 的记忆(task 聚合所有任务草稿;project/global 各自池)。
95
+ *
96
+ * 顺序为**新 → 旧**(见 {@link compareInsightRecency})。分页参数可选:
97
+ * 不给 `limit` 时返回全部(保持既有调用方与测试的行为),给了就只返回
98
+ * `[offset, offset+limit)` 这一段,并回报 `total` 与 `nextOffset`。
99
+ * 载荷是纯函数产物,持久化由命令 handler 负责。
100
+ * @param {object} store - 项目 store。
101
+ * @param {object|null} gs - global store。
102
+ * @param {'task'|'project'|'global'} [scope] - 作用域,默认 project。
103
+ * @param {{offset?: number, limit?: number|null}} [opts] - 分页窗口;`limit` 为 null/undefined 表示不分页。
104
+ * @returns {{scope: string, count: number, total: number, offset: number, items: object[], nextOffset: number|null}} 载荷。
105
+ */
106
+ export function listInsights(store, gs, scope, opts = {}) {
58
107
  const s = scope || 'project'
59
- const items = []
108
+ // 先收集「原始条目 + 附加字段」,**排序在摘要之前**:摘要会丢掉 createdAt,
109
+ // 而这个字段是稳定全序的第二级键。
110
+ const collected = []
60
111
  if (s === 'task') {
61
112
  for (const t of store.getTasks() || []) {
62
- for (const i of t.insights || []) items.push(insSummary(i, { taskId: t.id, taskTitle: t.title }))
113
+ for (const i of t.insights || []) collected.push({ raw: i, extra: { taskId: t.id, taskTitle: t.title } })
63
114
  }
64
115
  } else if (s === 'global') {
65
- for (const i of (gs ? gs.items() : [])) items.push(insSummary(i))
116
+ for (const i of (gs ? gs.items() : [])) collected.push({ raw: i, extra: {} })
66
117
  } else {
67
- for (const i of store.insightItems()) items.push(insSummary(i))
118
+ for (const i of store.insightItems()) collected.push({ raw: i, extra: {} })
68
119
  }
69
- return { scope: s, count: items.length, items }
120
+ collected.sort(compareInsightRecency)
121
+
122
+ const total = collected.length
123
+ const limit = typeof opts.limit === 'number' && opts.limit > 0 ? opts.limit : null
124
+ const offset = Number.isFinite(opts.offset) && opts.offset > 0 ? Math.floor(opts.offset) : 0
125
+ const window = limit === null ? collected.slice(offset) : collected.slice(offset, offset + limit)
126
+ const nextOffset = offset + window.length < total ? offset + window.length : null
127
+ return { scope: s, count: total, total, offset, items: window.map((r) => insSummary(r.raw, r.extra)), nextOffset }
70
128
  }
71
129
 
72
130
  /**
@@ -92,6 +150,8 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
92
150
  return { ok: true, text: `已审核:${insight.title}` }
93
151
  }
94
152
  if (act === 'delete') {
153
+ // 面板删除与 forget 同一套留痕:真删,但最近 5 条可在同目录 deleted.json 里找回来。
154
+ recordDeleted({ store, globalStore: gs }, [{ ...insight, home: 'task', taskId: task.id }])
95
155
  task.insights = (task.insights || []).filter((i) => i.id !== id)
96
156
  store.markTasksDirty()
97
157
  return { ok: true, text: `已删除任务级条目 ${id}` }
@@ -133,6 +193,7 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
133
193
  return { ok: true, text: `已${act === 'archive' ? '归档' : '恢复'}` }
134
194
  }
135
195
  if (act === 'delete') {
196
+ recordDeleted({ store, globalStore: gs }, [{ ...ins, home: 'project' }])
136
197
  items.splice(idx, 1)
137
198
  store.replaceInsightItems(items)
138
199
  return { ok: true, text: `已删除 project 条目 ${id}` }
@@ -185,6 +246,7 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
185
246
  return { ok: true, text: `已${act === 'archive' ? '归档' : '恢复'}` }
186
247
  }
187
248
  if (act === 'delete') {
249
+ recordDeleted({ store, globalStore: gs }, [{ ...ins, home: 'global' }])
188
250
  items.splice(idx, 1)
189
251
  gs.markDirty()
190
252
  return { ok: true, text: `已删除 global 条目 ${id}` }
@@ -327,8 +389,8 @@ export function editMemoryItem({ store, gs, scope, id, fields, root }) {
327
389
  export function insightCommandDefinition(config, ctx) {
328
390
  return {
329
391
  name: 'insight',
330
- description: '记忆视图动作(面板按钮调用):/tasks insight list project|global|task;/tasks insight <confirm|promote|demote|archive|restore|delete> <scope> <id> [taskId]',
331
- input: { hint: 'list [scope] | <动作> <scope> <id> [taskId]' },
392
+ description: '记忆视图动作(面板按钮调用):/tasks insight list project|global|task [offset] [limit];/tasks insight <confirm|promote|demote|archive|restore|delete> <scope> <id> [taskId]',
393
+ input: { hint: 'list [scope] [offset] [limit] | <动作> <scope> <id> [taskId]' },
332
394
  handler: (invocation) => {
333
395
  try {
334
396
  const { cwd } = invocationContext(invocation)
@@ -340,10 +402,26 @@ export function insightCommandDefinition(config, ctx) {
340
402
  const verb = raw[0]
341
403
  if (verb === 'list') {
342
404
  const scope = raw[1] === 'task' || raw[1] === 'global' || raw[1] === 'project' ? raw[1] : 'project'
405
+ // 分页参数可选:省略即维持"返回全部"的旧行为(老客户端 bundle 仍按此调用)。
406
+ // 显式给 limit 时封顶 INSIGHT_PAGE_MAX,避免一次请求把整个池子拉成超大载荷。
407
+ let offset = 0
408
+ let limit = null
409
+ if (raw[2] !== undefined) {
410
+ const n = Number.parseInt(raw[2], 10)
411
+ if (!Number.isFinite(n) || n < 0) return { kind: 'error', text: '[insight] offset 必须是不小于 0 的整数' }
412
+ offset = n
413
+ }
414
+ if (raw[3] !== undefined) {
415
+ const n = Number.parseInt(raw[3], 10)
416
+ if (!Number.isFinite(n) || n <= 0) return { kind: 'error', text: '[insight] limit 必须是正整数' }
417
+ limit = Math.min(n, INSIGHT_PAGE_MAX)
418
+ }
343
419
  const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
344
420
  const gs = new GlobalStore(cfgInsight(config).globalFile || defaultGlobalFile()).load()
345
- const payload = listInsights(store, gs, scope)
346
- return { kind: 'success', text: fencedJson(`记忆 ${scope}:${payload.count} 条`, JSON.stringify(payload)) }
421
+ const payload = listInsights(store, gs, scope, { offset, limit })
422
+ const shown = offset + payload.items.length
423
+ const range = limit === null ? '' : `(显示 ${shown}/${payload.total})`
424
+ return { kind: 'success', text: fencedJson(`记忆 ${scope}:${payload.count} 条${range}`, JSON.stringify(payload)) }
347
425
  }
348
426
  if (verb === 'save') {
349
427
  // /insight save <scope> <json>(新建/合并;project|global)
@@ -3,6 +3,7 @@
3
3
  * 「解析 CommandInvocation → 会话与 cwd」和「拼 JSON 围栏载荷」两段代码。
4
4
  * 集中在这里,语义只在一处维护。
5
5
  */
6
+ import { sessionWorkingDir } from '../util/session-dir.js'
6
7
 
7
8
  /**
8
9
  * 从命令调用里解出会话上下文。
@@ -20,7 +21,9 @@ export function invocationContext(invocation) {
20
21
  // 旧写法只在 agent.ctx 不存在时退回:服务在、但 get 返回 undefined 时 session 直接是 undefined,
21
22
  // /task switch|todos|unbind 于是静默跳过 session.append(宿主 todo 同步失效)。
22
23
  const session = fromService || agent?.session || null
23
- const cwd = session?.header?.cwd || agent?.session?.header?.cwd
24
+ // 当前工作目录走 util/session-dir.js:0.2.1+ 由 workingDirectory 投影决定(cd 后会变),
25
+ // 老宿主回退 header.cwd —— 面板/任务桥的"本项目"必须与工具侧同一口径。
26
+ const cwd = sessionWorkingDir(session, { agent })
24
27
  return { agent, sid, session, cwd }
25
28
  }
26
29
 
@@ -36,8 +36,9 @@ function withTaskSnapshot(config, cwd, sid, store, note) {
36
36
  const active = tasks.filter((t) => !t.archived)
37
37
  const archived = tasks.length - active.length
38
38
  const boundId = sid ? store.getBoundTaskId(sid) : null
39
- const human = `项目 ${projectRootFor(cwd)}\n${note}\n任务: ${active.length} 套${archived ? `(归档 ${archived})` : ''}`
40
- const payload = buildTaskPayload(active, boundId, archived)
39
+ const root = projectRootFor(cwd)
40
+ const human = `项目 ${root}\n${note}\n任务: ${active.length} 套${archived ? `(归档 ${archived})` : ''}`
41
+ const payload = buildTaskPayload(active, boundId, archived, root)
41
42
  return { kind: 'success', text: fencedJson(human, payload) }
42
43
  }
43
44
 
@@ -7,7 +7,7 @@ import { NO_PROJECT_ROOT_NOTE, projectRootFor } from '../setup/taskbridge.js'
7
7
  import { fencedJson, invocationContext } from './invocation.js'
8
8
  import { stepContent, stepProgress, stepStatus, timeAgo } from '../util/task-view.js'
9
9
 
10
- export function buildTaskPayload(tasks, boundId, archived) {
10
+ export function buildTaskPayload(tasks, boundId, archived, root = null) {
11
11
  return JSON.stringify({
12
12
  tasks: tasks.map((t) => ({
13
13
  id: t.id,
@@ -21,6 +21,9 @@ export function buildTaskPayload(tasks, boundId, archived) {
21
21
  })),
22
22
  boundId: boundId || null,
23
23
  archived,
24
+ // 项目根:客户端用它把跨标签页广播限定在同一个项目里(不同项目共用一个浏览器时,
25
+ // 没有这个键就会把 A 项目的任务贴到 B 项目的面板上)。
26
+ root: root || null,
24
27
  })
25
28
  }
26
29
 
@@ -56,7 +59,7 @@ export function renderTaskSnapshot(config, cwd, sid) {
56
59
  }
57
60
  lines.push('', '续接/改名/归档:直接告诉模型(list_tasks / select_task / archive_task)。')
58
61
  const humanText = lines.join('\n')
59
- const payload = buildTaskPayload(active, boundId, archived)
62
+ const payload = buildTaskPayload(active, boundId, archived, root)
60
63
  return { kind: 'success', text: fencedJson(humanText, payload) }
61
64
  }
62
65
 
package/src/index.js CHANGED
@@ -63,6 +63,16 @@ export const Config = Schema.object({
63
63
  insight: Schema.object({
64
64
  dedupOverlap: Schema.number().default(0.7),
65
65
  reinforceBand: Schema.number().default(0.65),
66
+ // 向量带(需 leanvec;未装自动退化成上面的纯词法带)。下面四个键自 0.6.x 起就在
67
+ // cfgInsight(src/insight-store.js)里读取、README 与 types.js 也写了,却一直没进
68
+ // Schema。与 0.5.8 给 autoContext 补声明是同一类问题:未声明键在 schemastery 层会透传,
69
+ // 但走 cordis.patch.yml 时能不能活到代码取决于宿主是否按「not a declared property」校验
70
+ // ——无论哪种,文档里的旋钮与 Schema 已经不一致,等于半真半假。默认值以 cfgInsight 的
71
+ // 兜底值为权威,这里只负责把键暴露出来。
72
+ autoMergeCos: Schema.number().default(0.9),
73
+ autoMergeMargin: Schema.number().default(0.05),
74
+ hintCos: Schema.number().default(0.7),
75
+ maxForgetMatches: Schema.number().default(10),
66
76
  maxProject: Schema.number().default(100),
67
77
  maxGlobalProcedures: Schema.number().default(200),
68
78
  promoteConfidence: Schema.number().default(0.7),