@yolk_vat-y/dsh-project-memory 0.6.12 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +58 -20
- package/README.md +14 -105
- package/README.zh-CN.md +14 -105
- package/client/client.js +228 -95
- package/client/client.js.map +1 -1
- package/package.json +2 -2
- package/scripts/file-peak.mjs +1 -1
- package/scripts/tool-schema-size.mjs +1 -1
- package/skills/project-memory/SKILL.md +1 -1
- package/skills/project-memory/scripts/pm-digest.mjs +20 -6
- package/src/audit.js +10 -2
- package/src/auto-inject.js +124 -38
- package/src/client/MemoryView.tsx +119 -40
- package/src/client/TaskCommandNode.tsx +6 -4
- package/src/client/TaskComponents.tsx +13 -16
- package/src/client/TaskPanel.tsx +41 -15
- package/src/client/client.ts +4 -7
- package/src/client/paging.js +1 -14
- package/src/client/settings-card.tsx +9 -0
- package/src/client/task-data-store.ts +57 -7
- package/src/client/task-hooks.ts +0 -2
- package/src/client/task-scope.js +16 -1
- package/src/client/task-ui-store.ts +1 -1
- package/src/commands/insight-actions.js +85 -60
- package/src/commands/task-actions.js +7 -5
- package/src/commands/tasks.js +34 -10
- package/src/doc-index.js +3 -1
- package/src/enhancer.js +0 -12
- package/src/index-failures.js +1 -1
- package/src/index-pipeline.js +11 -2
- package/src/index.js +60 -14
- package/src/inject-visible.js +282 -0
- package/src/insight-store.js +129 -32
- package/src/lazy.js +29 -23
- package/src/llm-route.js +1 -1
- package/src/ops.js +18 -5
- package/src/parsers/pdfjs-parser.js +3 -33
- package/src/project-memory-service.js +195 -0
- package/src/project-profile.js +0 -4
- package/src/setup/taskbridge.js +38 -6
- package/src/store.js +638 -135
- package/src/symbols.js +2 -4
- package/src/tools/forget.js +3 -6
- package/src/tools/index-doc.js +61 -18
- package/src/tools/index-repo.js +16 -12
- package/src/tools/lesson-tools.js +5 -5
- package/src/tools/output.js +28 -0
- package/src/tools/query-memory.js +6 -9
- package/src/tools/remember.js +3 -6
- package/src/tools/stats.js +3 -6
- package/src/tools/task-tools.js +15 -8
- package/src/tools/watch-repo.js +15 -12
- package/src/util/flush.js +1 -1
- package/src/util/fs.js +135 -20
- package/src/util/message-source.js +20 -0
- package/src/util/relative-time.js +24 -0
- package/src/util/search.js +0 -1
- package/src/util/task-view.js +8 -15
- package/src/vector-index.js +2 -2
- package/src/watch.js +25 -8
- package/client/client.d.ts +0 -27
- package/client/client.d.ts.map +0 -1
- package/client/style.css +0 -395
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yolk_vat-y/dsh-project-memory",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Persistent project memory for dsh agents: index docs (PDF/Markdown/text) and code symbols into a searchable per-workspace store, recall them with cited sources, and keep experience entries (problems -> solutions) searchable on demand.",
|
|
5
5
|
"author": "00080000 <3388065969@qq.com>",
|
|
6
6
|
"type": "module",
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
"url": "https://github.com/00080000/dsh-project-memory.git"
|
|
21
21
|
},
|
|
22
22
|
"scripts": {
|
|
23
|
-
"test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/util-value.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/insight-paging.test.mjs && node test/config-schema.test.mjs && node test/host-contract.test.mjs && node test/session-dir.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/chunker.test.mjs && node test/client-hints.test.mjs && node test/client-paging.test.mjs && node test/client-task-sync.test.mjs && node test/recall.test.mjs && node test/recall-vector-fusion.test.mjs && node test/vector-index.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/signal-source.test.mjs && node test/skill.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/client-toolview.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/client-degraded.test.mjs && node test/settings-card.test.mjs && node test/watch-idle.test.mjs && node test/citation-paths.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/root-policy.test.mjs && node test/gitignore-index.test.mjs && node test/store-gitignore.test.mjs && node test/atomic-write.test.mjs && node test/store-cache.test.mjs && node test/store-concurrent.test.mjs && node test/store-lock.test.mjs && node test/windows-compat.test.mjs && node test/tool-schema-size.test.mjs && node test/enhancer.test.mjs && node test/multilingual-ru.test.mjs && node test/tokenizer-equivalence.test.mjs && node test/lazy-batch.test.mjs && node test/pdfjs-host.test.mjs && node test/index-failures.test.mjs && node test/audit-2026-11-02.test.mjs && node test/memorydir-guard.test.mjs && node test/audit-2026-11-05.test.mjs",
|
|
23
|
+
"test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/util-value.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/insight-paging.test.mjs && node test/config-schema.test.mjs && node test/host-contract.test.mjs && node test/session-dir.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/chunker.test.mjs && node test/client-hints.test.mjs && node test/client-paging.test.mjs && node test/client-task-sync.test.mjs && node test/recall.test.mjs && node test/recall-vector-fusion.test.mjs && node test/vector-index.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/signal-source.test.mjs && node test/skill.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/client-toolview.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/client-degraded.test.mjs && node test/settings-card.test.mjs && node test/watch-idle.test.mjs && node test/citation-paths.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/root-policy.test.mjs && node test/gitignore-index.test.mjs && node test/store-gitignore.test.mjs && node test/atomic-write.test.mjs && node test/store-cache.test.mjs && node test/store-concurrent.test.mjs && node test/store-lock.test.mjs && node test/windows-compat.test.mjs && node test/tool-schema-size.test.mjs && node test/enhancer.test.mjs && node test/multilingual-ru.test.mjs && node test/tokenizer-equivalence.test.mjs && node test/lazy-batch.test.mjs && node test/pdfjs-host.test.mjs && node test/index-failures.test.mjs && node test/audit-2026-11-02.test.mjs && node test/memorydir-guard.test.mjs && node test/audit-2026-11-05.test.mjs && node test/fix-2026-11-10-shell-write-ops.test.mjs && node test/fix-2026-11-10-trigger-derived-refresh.test.mjs && node test/fix-2026-11-10-manual-promote-dedup.test.mjs && node test/fix-2026-11-10-old-host-human.test.mjs && node test/fix-2026-11-10-project-memory-service.test.mjs && node test/lazy-ignore-scope.test.mjs && node test/watch-missing-root-warn.test.mjs && node test/inject-visible.test.mjs && node test/inject-reconcile.test.mjs && node test/shard-bucket.test.mjs && node test/audit-2026-11-10.test.mjs && node test/audit-2026-11-11.test.mjs",
|
|
24
24
|
"eval:injection": "node test/injection-scenarios.test.mjs",
|
|
25
25
|
"typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.client.json",
|
|
26
26
|
"selfcheck:triggers": "node test/injection-scenarios.test.mjs --selfcheck",
|
package/scripts/file-peak.mjs
CHANGED
|
@@ -47,7 +47,7 @@ function startSampler() {
|
|
|
47
47
|
|
|
48
48
|
async function measure({ label, stages }) {
|
|
49
49
|
if (typeof globalThis.gc !== 'function') {
|
|
50
|
-
throw new Error('需要 --expose-gc:node --expose-gc
|
|
50
|
+
throw new Error('需要 --expose-gc:node --expose-gc scripts/file-peak.mjs')
|
|
51
51
|
}
|
|
52
52
|
globalThis.gc()
|
|
53
53
|
const base = process.memoryUsage()
|
|
@@ -57,7 +57,7 @@ const BUILDERS = [
|
|
|
57
57
|
['remember', () => rememberTool(config)],
|
|
58
58
|
['forget', () => forgetTool(config)],
|
|
59
59
|
['watch_repo', () => watchRepoTool(watchManager, config)],
|
|
60
|
-
['
|
|
60
|
+
['pm_stats', () => statsTool(config)],
|
|
61
61
|
['save_lesson', () => lessonTool(config)],
|
|
62
62
|
]
|
|
63
63
|
|
|
@@ -35,7 +35,7 @@ Query it before re-deriving; write to it only after something has been verified.
|
|
|
35
35
|
2. **Refresh the index if it looks empty or stale**
|
|
36
36
|
- `index_repo root:"<project>"` — incremental; unchanged files are skipped.
|
|
37
37
|
- `index_doc file_path:"…"` — one document, even outside the corpus.
|
|
38
|
-
- `
|
|
38
|
+
- `pm_stats` — counts, last index time, per-file list.
|
|
39
39
|
3. **Write back what will still be true next session**
|
|
40
40
|
- `save_lesson` — one insight. Give `kind` (`lesson` / `decision` / `procedure`), a one-line
|
|
41
41
|
`title`, and the body: `pattern` + `fix`, or `choice` + `reason`, or `steps`.
|
|
@@ -78,24 +78,38 @@ const days = (iso) => {
|
|
|
78
78
|
return Number.isFinite(t) ? Math.max(0, Math.round((Date.now() - t) / 86_400_000)) : null
|
|
79
79
|
}
|
|
80
80
|
|
|
81
|
+
/**
|
|
82
|
+
* v3 的 shards/ 是**桶**文件(bucket-NNNNN.json),不是"一个源文件一个分片"。
|
|
83
|
+
* `buckets` 是落盘文件数,`indexedFiles` 是桶里唯一的源文件数;混进来的 v2 旧分片单独计数,
|
|
84
|
+
* 不能当成 v3 桶(旧实现把两者混在 `files` 里,统计口径会随遗留文件漂移)。
|
|
85
|
+
*/
|
|
81
86
|
function shardStats(dir) {
|
|
82
87
|
try {
|
|
83
|
-
let
|
|
88
|
+
let buckets = 0
|
|
89
|
+
let legacy = 0
|
|
84
90
|
let bytes = 0
|
|
91
|
+
const indexed = new Set()
|
|
85
92
|
for (const name of readdirSync(dir)) {
|
|
86
93
|
if (!name.endsWith('.json')) continue
|
|
94
|
+
const file = path.join(dir, name)
|
|
87
95
|
try {
|
|
88
|
-
const st = statSync(
|
|
96
|
+
const st = statSync(file)
|
|
89
97
|
if (!st.isFile()) continue
|
|
90
|
-
files++
|
|
91
98
|
bytes += st.size
|
|
99
|
+
if (/^bucket-\d+\.json$/.test(name)) buckets++
|
|
100
|
+
else legacy++
|
|
101
|
+
const doc = readJson(file, null)
|
|
102
|
+
for (const item of Array.isArray(doc?.items) ? doc.items : []) {
|
|
103
|
+
if (typeof item?.relPath === 'string' && item.relPath) indexed.add(item.relPath)
|
|
104
|
+
}
|
|
105
|
+
if (typeof doc?.relPath === 'string' && doc.relPath) indexed.add(doc.relPath)
|
|
92
106
|
} catch {
|
|
93
107
|
/* 分片在统计途中消失:跳过 */
|
|
94
108
|
}
|
|
95
109
|
}
|
|
96
|
-
return {
|
|
110
|
+
return { buckets, legacyFiles: legacy, indexedFiles: indexed.size, bytes }
|
|
97
111
|
} catch {
|
|
98
|
-
return {
|
|
112
|
+
return { buckets: 0, legacyFiles: 0, indexedFiles: 0, bytes: 0 }
|
|
99
113
|
}
|
|
100
114
|
}
|
|
101
115
|
|
|
@@ -185,7 +199,7 @@ line('project', root)
|
|
|
185
199
|
if (resolved.name !== DEFAULT_MEMORY_DIR || resolved.detected) {
|
|
186
200
|
line('location', `${resolved.name}${resolved.detected ? ' (auto-detected)' : ''}`)
|
|
187
201
|
}
|
|
188
|
-
line('store', `${shards.
|
|
202
|
+
line('store', `${shards.buckets ? `${shards.buckets} buckets` : `${shards.legacyFiles} shards`} · ${shards.indexedFiles} indexed files · ${kb(shards.bytes)} · ${insights.total} insights · ${tasks.total} tasks`)
|
|
189
203
|
if (insights.total) {
|
|
190
204
|
const kinds = Object.entries(insights.kinds).map(([k, n]) => `${k} ${n}`).join(' · ')
|
|
191
205
|
line('insights', `${kinds}${insights.archived ? ` · archived ${insights.archived}` : ''}`)
|
package/src/audit.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// 绝不影响宿主请求;单文件超限就地轮转一份 `.1`,不引入后台任务。
|
|
4
4
|
import { appendFileSync, existsSync, mkdirSync, renameSync, statSync } from 'node:fs'
|
|
5
5
|
import path from 'node:path'
|
|
6
|
-
import { hasProjectMarker } from './util/fs.js'
|
|
6
|
+
import { ensureSelfIgnoreDir, hasProjectMarker } from './util/fs.js'
|
|
7
7
|
|
|
8
8
|
export const AUDIT_FILE = 'injection-audit.jsonl'
|
|
9
9
|
const DEFAULT_MAX_BYTES = 256 * 1024
|
|
@@ -109,7 +109,9 @@ export function shadowRecordFrom(input) {
|
|
|
109
109
|
candidatesTotal: candidates.length,
|
|
110
110
|
// 触发通道的丢弃不在 candidates 里(候选只收提示通道),单列;有界,避免长候选池撑爆一行。
|
|
111
111
|
dropped: dropped.slice(0, 40),
|
|
112
|
+
droppedTotal: dropped.length,
|
|
112
113
|
silence: input.silence || null,
|
|
114
|
+
...(input.reconcile ? { reconcile: input.reconcile } : {}),
|
|
113
115
|
}
|
|
114
116
|
}
|
|
115
117
|
|
|
@@ -137,6 +139,9 @@ function appendJsonlRecord({ memoryDir, record, cfg, root, fileFor, defaultMaxBy
|
|
|
137
139
|
if (!auditDirReady(memoryDir, root)) return false
|
|
138
140
|
try {
|
|
139
141
|
mkdirSync(memoryDir, { recursive: true })
|
|
142
|
+
// 审计会在 load() 之前建目录;补这一行,否则新 store 的首个进程生命周期里
|
|
143
|
+
// `.gitignore` 缺席,影子日志可能被 `git add -A` 带走。
|
|
144
|
+
ensureSelfIgnoreDir(memoryDir)
|
|
140
145
|
const file = fileFor(memoryDir)
|
|
141
146
|
rotateIfOversized(file, c.maxBytes || defaultMaxBytes)
|
|
142
147
|
appendFileSync(file, `${JSON.stringify(record)}\n`)
|
|
@@ -178,16 +183,19 @@ export function auditRecordFrom(input) {
|
|
|
178
183
|
})),
|
|
179
184
|
// `budget` 掉落带量纲(remaining / need),必须原样落地,否则"细缝可诊断"只活在内存里。
|
|
180
185
|
// 只对带数字的条目落键——多数掉落没有量纲,不该为它们付两个 null。
|
|
181
|
-
|
|
186
|
+
// 与 shadow 同口径截断:1000 条候选时整行可到 113KB,单行就能吃掉审计窗口的一半。
|
|
187
|
+
dropped: dropped.slice(0, 40).map((d) => ({
|
|
182
188
|
id: d.id,
|
|
183
189
|
channel: d.channel,
|
|
184
190
|
reason: d.reason,
|
|
185
191
|
...(typeof d.remaining === 'number' ? { remaining: d.remaining } : {}),
|
|
186
192
|
...(typeof d.need === 'number' ? { need: d.need } : {}),
|
|
187
193
|
})),
|
|
194
|
+
droppedTotal: dropped.length,
|
|
188
195
|
// 会话级额度快照与"本轮为什么沉默":注入频率本身是可观测指标,不该只能靠感觉。
|
|
189
196
|
budget: input.budget || null,
|
|
190
197
|
silence: input.silence || null,
|
|
198
|
+
...(input.reconcile ? { reconcile: input.reconcile } : {}),
|
|
191
199
|
}
|
|
192
200
|
}
|
|
193
201
|
|
package/src/auto-inject.js
CHANGED
|
@@ -11,6 +11,8 @@ import { stepContent } from './util/task-view.js'
|
|
|
11
11
|
import { insightMatchText, normalizedTokenOverlap } from './similarity.js'
|
|
12
12
|
import { createVectorCosine, createVectorRerank, vectorItemsFrom } from './vector-index.js'
|
|
13
13
|
import { BoundedMap, SessionCache } from './util/session-cache.js'
|
|
14
|
+
import { createVisibleState, ensureVisible, isBlockVisible, isEntryVisible, isItemVisible, isLegacyBodyVisible, lineHash, onSessionEvent, provenanceOf, recordInjected, takeRollback } from './inject-visible.js'
|
|
15
|
+
import { SOURCE_KIND, isOwnInjection } from './util/message-source.js'
|
|
14
16
|
import { sessionWorkingDir } from './util/session-dir.js'
|
|
15
17
|
import { cfgInsight, GlobalStore, defaultGlobalFile, recordHit } from './insight-store.js'
|
|
16
18
|
import { projectTags } from './project-profile.js'
|
|
@@ -36,21 +38,7 @@ export const PLUGIN_NAME = 'dsh-project-memory'
|
|
|
36
38
|
* 值取 `plugin:<包名>`:这正是宿主 v3→v4 迁移改写本插件历史消息的结果,新写与迁移后是同一个
|
|
37
39
|
* 生产者身份,自激闸门(isOwnInjection)不必按新旧分叉。
|
|
38
40
|
*/
|
|
39
|
-
export
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
* 这条消息是不是本插件自己注入的?三种写法都要认,因为同一条历史消息在不同阶段形状不同:
|
|
43
|
-
* `plugin:dsh-project-memory`(现在写的,也是迁移结果)、`project-memory`(保留的别名,将来换 kind
|
|
44
|
-
* 时自激闸门不失效)、`plugin: 'dsh-project-memory'`(迁移前尚未落盘的旧形状)。
|
|
45
|
-
* @param {object|undefined|null} source - message.source
|
|
46
|
-
* @returns {boolean}
|
|
47
|
-
*/
|
|
48
|
-
export function isOwnInjection(source) {
|
|
49
|
-
if (!source || typeof source !== 'object') return false
|
|
50
|
-
return source.kind === SOURCE_KIND
|
|
51
|
-
|| source.kind === 'project-memory'
|
|
52
|
-
|| source.plugin === 'dsh-project-memory'
|
|
53
|
-
}
|
|
41
|
+
export { SOURCE_KIND, isOwnInjection }
|
|
54
42
|
|
|
55
43
|
/** 注入正文的最小可用长度:预算塞不下就宁可不注入(记 dropped)——stub 只消耗 token 不传递信息。 */
|
|
56
44
|
const MIN_BODY_CHARS = { trigger: 48, hint: 120 }
|
|
@@ -480,7 +468,6 @@ export function buildInjection(opts) {
|
|
|
480
468
|
// 模型会一直看到旧文件列表;只有热点文件集合/顺序变化时才重发整块。
|
|
481
469
|
const echo = stepBudget > 0 && cfg.entryOn !== false && shouldEchoTaskCard(task, cfg)
|
|
482
470
|
const entry = echo ? buildEntryContent(task, cfg) : ''
|
|
483
|
-
const entryStable = entry
|
|
484
471
|
let used = entry.length
|
|
485
472
|
let itemUsed = 0
|
|
486
473
|
let itemCount = 0
|
|
@@ -537,8 +524,8 @@ export function buildInjection(opts) {
|
|
|
537
524
|
}
|
|
538
525
|
// 整块只受单轮预算(maxTokens)约束;会话条目额度已在 place() 里单独扣过。
|
|
539
526
|
const clamp = (t) => (t.length > stepBudget ? `${t.slice(0, stepBudget)}\n…(截断)` : t)
|
|
540
|
-
const dedupeText = clamp([
|
|
541
|
-
return { text: clamp(total.join('\n')), entry,
|
|
527
|
+
const dedupeText = clamp([entry, ...parts].filter(Boolean).join('\n'))
|
|
528
|
+
return { text: clamp(total.join('\n')), entry, labels, reasons, dropped, candidates, scoreQuery, dedupeText, itemChars: itemUsed }
|
|
542
529
|
}
|
|
543
530
|
|
|
544
531
|
// 每会话状态的会话数上限:六张表共用。
|
|
@@ -563,6 +550,8 @@ class InjectionSessions {
|
|
|
563
550
|
// "整块指纹变了"不等于"内容都是新的":滑动窗口 / 任务卡更新都会让同一份 procedure 被重发
|
|
564
551
|
// (实测 66 步注入 20 次,同一份 1732 字重发 3 次)。
|
|
565
552
|
this.items = cache(() => new BoundedMap(INJECTED_ITEMS_MAX))
|
|
553
|
+
// 本轮注入前的 lastHitAt:宿主丢弃这条注入时要一起回滚,否则条目会留下“刚用过”的假活跃度。
|
|
554
|
+
this.hitAt = cache(() => new Map())
|
|
566
555
|
// 会话步数:为 reinjectItemsAfter 提供时间轴。
|
|
567
556
|
this.step = cache(() => 0)
|
|
568
557
|
// 会话级条目额度:条数 / 字符 / 上次"条目注入"的步号。常驻任务卡不占额度——
|
|
@@ -576,6 +565,8 @@ class InjectionSessions {
|
|
|
576
565
|
this.humanText = cache()
|
|
577
566
|
// 本会话是否已通告"记忆根是推定的"(会话工作目录,无项目标记)。状态声明只发一次。
|
|
578
567
|
this.rootNoticed = cache(() => false)
|
|
568
|
+
// 注入可见性(D3-2):surface 是真相源,缓存只做 fallback。
|
|
569
|
+
this.visible = cache(() => createVisibleState())
|
|
579
570
|
this._all = Object.values(this)
|
|
580
571
|
}
|
|
581
572
|
|
|
@@ -596,12 +587,18 @@ function installCallObserver(ctx, sessions) {
|
|
|
596
587
|
try {
|
|
597
588
|
const sessionId = session && session.id
|
|
598
589
|
if (!sessionId || !event) return
|
|
590
|
+
if (typeof event.type === 'string' && event.type.startsWith('compaction/')) {
|
|
591
|
+
sessions.visible.ensure(sessionId).dirty = true
|
|
592
|
+
return
|
|
593
|
+
}
|
|
599
594
|
if (event.type === 'user/message') {
|
|
600
595
|
const data = event.data || {}
|
|
601
596
|
const source = data.source
|
|
602
|
-
//
|
|
603
|
-
|
|
604
|
-
|
|
597
|
+
// 自注入块不是人话:登记可见性后返回,避免下一步拿注入正文再检索(自激)。
|
|
598
|
+
if (isOwnInjection(source)) {
|
|
599
|
+
onSessionEvent(sessions.visible.ensure(sessionId), event)
|
|
600
|
+
return
|
|
601
|
+
}
|
|
605
602
|
const kind = source && source.kind
|
|
606
603
|
// 通知 / relay / job / 时间快照都不是人说的;无 source 的老宿主按人话处理(与 lastUserText 同口径)。
|
|
607
604
|
if (kind && kind !== 'user') return
|
|
@@ -671,12 +668,23 @@ function warnUnsafeSessionRoot(root, rejection) {
|
|
|
671
668
|
* 返回 null 表示本步无事可做(交回原决策)。
|
|
672
669
|
*/
|
|
673
670
|
async function injectForStep({ payload, decision, config, cfg, audit, shadow, sessions }) {
|
|
671
|
+
// 宿主已 abort 的请求不要再做注入/记账:pre-step 之后宿主还有 abort 检查,消息可能根本不会 append。
|
|
672
|
+
if (payload?.signal?.aborted) return null
|
|
674
673
|
const session = payload && payload.agent && payload.agent.session
|
|
675
674
|
// 与工具侧同一口径的「当前工作目录」:0.2.1+ 走 workingDirectory 投影(cd 后会变),老宿主回退
|
|
676
675
|
// header.cwd。少了这一步,cd 之后审计与懒索引会落在两个不同的 store 里。
|
|
677
676
|
const cwd = sessionWorkingDir(session, { agent: payload?.agent })
|
|
678
677
|
const sessionId = session && session.id
|
|
679
678
|
if (!cwd || !sessionId) return null
|
|
679
|
+
const visibleState = sessions.visible.ensure(sessionId)
|
|
680
|
+
const surfaceReady = ensureVisible(session, visibleState)
|
|
681
|
+
const reconcile = {
|
|
682
|
+
source: surfaceReady ? 'surface' : 'cache',
|
|
683
|
+
visibleItems: visibleState.items.size,
|
|
684
|
+
visibleBlocks: visibleState.blocks.size,
|
|
685
|
+
degraded: visibleState.degraded,
|
|
686
|
+
genSupported: visibleState.genSupported,
|
|
687
|
+
}
|
|
680
688
|
// 会话 cwd 命中内置名单 / roots.deny / roots.exclude 时整条链路停在这里:不读 store(历史遗留的
|
|
681
689
|
// 超大 store 光是 load() 就能 OOM),也不写审计——`appendShadowAudit` 里的 mkdirSync 正是把
|
|
682
690
|
// `.dsh-project-memory` 造进家目录、进而触发"目录自标记 → 家目录被锁成项目"的那一步。
|
|
@@ -716,9 +724,46 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
|
|
|
716
724
|
const stepNo = sessions.step.ensure(sessionId) + 1
|
|
717
725
|
sessions.step.set(sessionId, stepNo)
|
|
718
726
|
const quota = sessions.quota.ensure(sessionId)
|
|
719
|
-
|
|
720
|
-
//
|
|
721
|
-
|
|
727
|
+
// 压缩/历史丢失时跳过冷却:否则注入消息刚被替换掉,还要再等 N 步才补回来。
|
|
728
|
+
// 只看“条目是否还可见”,不能把 blocks 也算进来:压缩可能只留下最后一条 card-only
|
|
729
|
+
// 注入(或 root notice),此时一个条目都没了,却因为 blocks.size>0 而永不归零。
|
|
730
|
+
const historyLost = surfaceReady && !visibleState.items.size && !visibleState.legacy.size
|
|
731
|
+
// 压缩把注入消息换掉了:额度也必须跟着归零。只跳过冷却不够——quota 只增不减,打满
|
|
732
|
+
// maxItemsPerSession 的会话压缩后会永久失明(条目通道一直沉默)。
|
|
733
|
+
if (historyLost) {
|
|
734
|
+
quota.items = 0
|
|
735
|
+
quota.chars = 0
|
|
736
|
+
quota.lastStep = null
|
|
737
|
+
}
|
|
738
|
+
reconcile.historyLost = historyLost
|
|
739
|
+
// 条目级去重:surface 可用时看"是否仍在可见上下文里",否则退回进程缓存。
|
|
740
|
+
const seenItems = sessions.items.ensure(sessionId)
|
|
741
|
+
// 上一步的注入没进 surface:先回滚额度/冷却/命中,再算本步的 silence——否则本步会带着
|
|
742
|
+
// 已经打满的旧额度直接沉默(回滚等于没做)。
|
|
743
|
+
const rollback = takeRollback(visibleState)
|
|
744
|
+
if (rollback) {
|
|
745
|
+
quota.items = Math.max(0, quota.items - rollback.ids.length)
|
|
746
|
+
quota.chars = Math.max(0, quota.chars - rollback.chars)
|
|
747
|
+
// 这次注入没发生:冷却的起点也回退,否则下一步会以“冷却中”再次沉默。
|
|
748
|
+
if (quota.lastStep === rollback.step) quota.lastStep = null
|
|
749
|
+
for (const id of rollback.ids) {
|
|
750
|
+
const rec = seenItems.get(id)
|
|
751
|
+
if (rec && rec.step === rollback.step) seenItems.delete(id)
|
|
752
|
+
}
|
|
753
|
+
try {
|
|
754
|
+
const restore = sessions.hitAt.peek(sessionId)
|
|
755
|
+
recordHit({ store, globalStore, ids: rollback.ids, delta: -1, restore })
|
|
756
|
+
sessions.hitAt.delete(sessionId)
|
|
757
|
+
if (store.hasContent) store.save()
|
|
758
|
+
globalStore.commit()
|
|
759
|
+
} catch {
|
|
760
|
+
/* 回滚失败不影响本步注入 */
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
const silence = sessionSilence({ cfg, quota, stepNo, ignoreCooldown: historyLost })
|
|
764
|
+
const skipItem = surfaceReady
|
|
765
|
+
? makeVisibleSkipItem(visibleState, seenItems, stepNo, cfg.reinjectItemsAfter || 0)
|
|
766
|
+
: makeSkipItem(seenItems, stepNo, cfg.reinjectItemsAfter || 0)
|
|
722
767
|
|
|
723
768
|
const built = buildInjection({
|
|
724
769
|
query: query || '',
|
|
@@ -766,6 +811,7 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
|
|
|
766
811
|
scoreQuery: built.scoreQuery,
|
|
767
812
|
dropped: built.dropped,
|
|
768
813
|
silence: silence.reason,
|
|
814
|
+
reconcile,
|
|
769
815
|
}), shadow, root)
|
|
770
816
|
|
|
771
817
|
// 记忆根通告:根是**推定**的(会话工作目录且无任何项目标记)时,第一次注入前告诉模型"记忆存在哪、
|
|
@@ -774,24 +820,30 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
|
|
|
774
820
|
const notice = cfg.maxTokens > 0 ? rootNotice({ root, sessionId, sessions, config }) : null
|
|
775
821
|
|
|
776
822
|
const fp = built.text ? fingerprint(built.dedupeText ?? built.text) : fingerprint(notice || '')
|
|
823
|
+
const entryHash = built.entry ? fingerprint(built.entry) : null
|
|
777
824
|
const injectedText = notice ? (built.text ? `${notice}\n${built.text}` : notice) : built.text
|
|
778
825
|
// 条目级冷却(reinjectItemsAfter>0)与块级指纹必须对齐:条目级已放行、块正文没变时,
|
|
779
826
|
// 块级 fp 会把“该重发”判成“没变化”。宿主外部裁剪历史时,这个开关本来就是为了重发。
|
|
780
|
-
const seen = sessions.items.ensure(sessionId)
|
|
781
827
|
const reinjectDue = cfg.reinjectItemsAfter > 0 && built.reasons.some((r) => {
|
|
782
|
-
const rec =
|
|
828
|
+
const rec = seenItems.get(r.id)
|
|
783
829
|
return rec && Number.isFinite(rec.step) && stepNo - rec.step >= cfg.reinjectItemsAfter
|
|
784
830
|
})
|
|
785
|
-
|
|
831
|
+
const blockSeen = surfaceReady ? isBlockVisible(visibleState, fp) : fp === sessions.lastText.peek(sessionId)
|
|
832
|
+
// 条目全被跳过时正文只剩任务卡:卡本身也要可对账,否则“条目注入的下一步/重启”会重复发一遍卡。
|
|
833
|
+
const cardSeen = surfaceReady && entryHash ? isEntryVisible(visibleState, entryHash) : false
|
|
834
|
+
const seenThisStep = built.reasons.length === 0 && built.entry ? (blockSeen || cardSeen) : blockSeen
|
|
835
|
+
if (!injectedText || (!reinjectDue && seenThisStep)) return null
|
|
786
836
|
sessions.lastText.set(sessionId, fp)
|
|
787
837
|
const itemCount = built.reasons.length
|
|
788
838
|
const summary = itemCount
|
|
789
839
|
? `memory inject: ${itemCount} item(s)${built.entry ? ' + task card' : ''}`
|
|
790
840
|
: built.entry ? 'memory inject: task card' : 'memory root notice'
|
|
791
841
|
|
|
842
|
+
// 构建期间也可能被 abort:在记账/写盘/审计之前再确认一次。
|
|
843
|
+
if (payload?.signal?.aborted) return null
|
|
792
844
|
// 只记真的进了上下文的那几条:dropped 的没被看到,不能记账(否则以后永远不再注入)。
|
|
793
845
|
for (const r of built.reasons) {
|
|
794
|
-
if (r && r.id && r.hash)
|
|
846
|
+
if (r && r.id && r.hash) seenItems.set(r.id, { hash: r.hash, step: stepNo })
|
|
795
847
|
}
|
|
796
848
|
// 会话额度只被"条目"消耗;任务卡不算(否则任务一多就把记忆挤没了)。
|
|
797
849
|
if (built.reasons.length) {
|
|
@@ -804,7 +856,14 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
|
|
|
804
856
|
// save(),只标脏等于进程退出就丢。记账失败绝不影响注入(与审计同约定)。
|
|
805
857
|
if (built.reasons.length) {
|
|
806
858
|
try {
|
|
807
|
-
|
|
859
|
+
const ids = built.reasons.map((r) => r.id)
|
|
860
|
+
const prevHitAt = new Map()
|
|
861
|
+
for (const it of [...store.insightItems(), ...globalStore.items()]) {
|
|
862
|
+
if (it && ids.includes(it.id)) prevHitAt.set(it.id, it.lastHitAt || null)
|
|
863
|
+
}
|
|
864
|
+
if (recordHit({ store, globalStore, ids })) {
|
|
865
|
+
// 若这一步的注入随后被宿主丢弃,回滚要连 lastHitAt 一起恢复到注入前。
|
|
866
|
+
sessions.hitAt.set(sessionId, prevHitAt)
|
|
808
867
|
// 只有这个根里真有东西才落盘。否则一次**全局** insight 的命中就会为一个从没被
|
|
809
868
|
// 索引过的容器目录建出整个 store(`save()` 会 mkdir)。审计侧同样不建,见 audit.js。
|
|
810
869
|
if (store.hasContent) store.save()
|
|
@@ -826,9 +885,12 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
|
|
|
826
885
|
dropped: built.dropped,
|
|
827
886
|
budget: { items: quota.items, chars: quota.chars, lastStep: Number.isFinite(quota.lastStep) ? quota.lastStep : null },
|
|
828
887
|
silence: silence.reason,
|
|
888
|
+
reconcile,
|
|
829
889
|
}), audit, root)
|
|
830
890
|
|
|
831
|
-
|
|
891
|
+
const message = injectionMessage(injectedText, summary, provenanceOf(fp, built.reasons, cfg.maxItemsPerSession, entryHash))
|
|
892
|
+
if (surfaceReady) recordInjected(visibleState, message, { chars: built.itemChars, step: stepNo, reasons: built.reasons })
|
|
893
|
+
return { ...decision, messages: [...decision.messages, message] }
|
|
832
894
|
}
|
|
833
895
|
|
|
834
896
|
/**
|
|
@@ -855,8 +917,8 @@ function rootNotice({ root, sessionId, sessions, config }) {
|
|
|
855
917
|
* 会话级限流:冷却步数 / 条目条数 / 条目字符。三个任一触顶 → 条目通道整体沉默,
|
|
856
918
|
* 但本轮"本该注入什么"仍会进 dropped(不做静默降级)。
|
|
857
919
|
*/
|
|
858
|
-
function sessionSilence({ cfg, quota, stepNo }) {
|
|
859
|
-
const cooling = Number.isFinite(quota.lastStep) && stepNo - quota.lastStep < cfg.gateCooldownSteps
|
|
920
|
+
function sessionSilence({ cfg, quota, stepNo, ignoreCooldown = false }) {
|
|
921
|
+
const cooling = !ignoreCooldown && Number.isFinite(quota.lastStep) && stepNo - quota.lastStep < cfg.gateCooldownSteps
|
|
860
922
|
const itemsLeft = Math.max(0, cfg.maxItemsPerSession - quota.items)
|
|
861
923
|
const charsLeft = Math.max(0, cfg.maxItemCharsPerSession - quota.chars)
|
|
862
924
|
const reason = cooling ? 'cooldown'
|
|
@@ -865,6 +927,32 @@ function sessionSilence({ cfg, quota, stepNo }) {
|
|
|
865
927
|
return { reason, itemsLeft, charsLeft }
|
|
866
928
|
}
|
|
867
929
|
|
|
930
|
+
/**
|
|
931
|
+
* 旧消息(无 provenance)可能的两种整行写法:任务卡的 `- [id] kind: title — body120`
|
|
932
|
+
* 与注入正文的 `- [id] title — fix/solution/choice`。正文变了 → hash 变 → 允许重发。
|
|
933
|
+
*/
|
|
934
|
+
function legacyItemHashes(it) {
|
|
935
|
+
const tail = it.fix || it.solution || it.choice
|
|
936
|
+
const suffixed = tail ? ` — ${tail}` : ''
|
|
937
|
+
return [
|
|
938
|
+
lineHash(`- [${it.id}] ${it.title}${suffixed}`),
|
|
939
|
+
lineHash(`- [${it.id}] ${it.kind || 'lesson'}: ${it.title}${tail ? ` — ${String(tail).slice(0, 120)}` : ''}`),
|
|
940
|
+
]
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
/** surface 可见时的条目去重;cooldown 到期仍允许重发。 */
|
|
944
|
+
function makeVisibleSkipItem(state, seen, stepNo, cooldown) {
|
|
945
|
+
return (it) => {
|
|
946
|
+
const visible = isItemVisible(state, it.id, insightItemHash(it), legacyItemHashes(it))
|
|
947
|
+
// 旧 procedure 正文没有 id:整块文本一致也算仍可见。
|
|
948
|
+
|| (it.kind === 'procedure' && isLegacyBodyVisible(state, insightBody(it)))
|
|
949
|
+
if (!visible) return false
|
|
950
|
+
if (cooldown === 0) return true
|
|
951
|
+
const rec = seen.get(it.id)
|
|
952
|
+
return !rec || stepNo - rec.step < cooldown
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
|
|
868
956
|
/** 条目级去重判据:会话里注入过且正文未变 → 跳过。cooldown=0 永久有效,>0 走步数冷却。 */
|
|
869
957
|
function makeSkipItem(seen, stepNo, cooldown) {
|
|
870
958
|
return (it) => {
|
|
@@ -890,15 +978,13 @@ function recordDropped({ sessions, sessionId, dropped, budgetLog }) {
|
|
|
890
978
|
}
|
|
891
979
|
|
|
892
980
|
/** 追加的注入消息:必须是带 source 的完整消息——裸 {role,content} 会让宿主读 message.source 时崩。 */
|
|
893
|
-
function injectionMessage(text, summary) {
|
|
981
|
+
function injectionMessage(text, summary, memory) {
|
|
982
|
+
const source = { kind: SOURCE_KIND, form: 'notice', summary }
|
|
983
|
+
if (memory) source.memory = memory
|
|
894
984
|
return createUserMessage({
|
|
895
985
|
content: [{ type: 'text', text: `\n\n${INJECT_MARK} ${PLUGIN_NAME} · auto-context\n${text}` }],
|
|
896
986
|
// 宿主对第三方生产者的 `snapshot` 只做追加,不会用后一条替换前一条(只有它自己的 runtime-context
|
|
897
987
|
// 走 replace)。所以这里声明 `notice`:如实表示“这一步注入了什么”,不让 UI 承诺取代先前快照。
|
|
898
|
-
source
|
|
899
|
-
kind: SOURCE_KIND,
|
|
900
|
-
form: 'notice',
|
|
901
|
-
summary,
|
|
902
|
-
},
|
|
988
|
+
source,
|
|
903
989
|
})
|
|
904
990
|
}
|