@yolk_vat-y/dsh-project-memory 0.6.5 → 0.6.7
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 +194 -0
- package/README.md +24 -21
- package/README.zh-CN.md +25 -23
- package/package.json +6 -4
- package/scripts/bench-edits.mjs +87 -0
- package/skills/project-memory/SKILL.md +72 -0
- package/skills/project-memory/scripts/pm-digest.mjs +138 -0
- package/src/audit.js +35 -62
- package/src/auto-inject.js +171 -220
- package/src/chunker.js +1 -1
- package/src/client/paging.js +22 -50
- package/src/client/slash.ts +12 -48
- package/src/doc-index.js +7 -5
- package/src/doc-pipeline.js +2 -0
- package/src/enhancer.js +45 -92
- package/src/index-pipeline.js +14 -10
- package/src/index.js +51 -73
- package/src/insight-store.js +132 -129
- package/src/ops.js +290 -54
- package/src/project-profile.js +20 -15
- package/src/readiness.js +153 -106
- package/src/recall.js +55 -134
- package/src/skill.js +86 -0
- package/src/store.js +311 -214
- package/src/tools/index-doc.js +5 -1
- package/src/tools/index-repo.js +2 -1
- package/src/tools/lesson-tools.js +2 -2
- package/src/util/flush.js +62 -0
- package/src/util/fs.js +346 -191
- package/src/util/path-token.js +8 -3
- package/src/util/persist.js +27 -0
- package/src/util/ru.js +202 -0
- package/src/util/search.js +33 -1
- package/src/vector-index.js +104 -104
- package/src/watch.js +74 -61
package/package.json
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yolk_vat-y/dsh-project-memory",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.7",
|
|
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",
|
|
7
7
|
"main": "src/index.js",
|
|
8
8
|
"files": [
|
|
9
9
|
"src",
|
|
10
|
+
"skills",
|
|
10
11
|
"client",
|
|
11
12
|
"scripts",
|
|
12
13
|
"cordis.patch.yml",
|
|
@@ -19,7 +20,7 @@
|
|
|
19
20
|
"url": "https://github.com/00080000/dsh-project-memory.git"
|
|
20
21
|
},
|
|
21
22
|
"scripts": {
|
|
22
|
-
"test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.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/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/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/tool-schema-size.test.mjs && node test/enhancer.test.mjs",
|
|
23
|
+
"test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.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/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",
|
|
23
24
|
"eval:injection": "node test/injection-scenarios.test.mjs",
|
|
24
25
|
"typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.client.json",
|
|
25
26
|
"selfcheck:triggers": "node test/injection-scenarios.test.mjs --selfcheck",
|
|
@@ -28,7 +29,8 @@
|
|
|
28
29
|
"bench:peak": "node --expose-gc scripts/file-peak.mjs",
|
|
29
30
|
"bench:store": "node scripts/bench-store.mjs",
|
|
30
31
|
"schema:size": "node scripts/tool-schema-size.mjs",
|
|
31
|
-
"build:client": "tsdown"
|
|
32
|
+
"build:client": "tsdown",
|
|
33
|
+
"bench:edits": "node scripts/bench-edits.mjs"
|
|
32
34
|
},
|
|
33
35
|
"keywords": [
|
|
34
36
|
"dsh",
|
|
@@ -111,6 +113,6 @@
|
|
|
111
113
|
"./cordis.patch.yml": "./cordis.patch.yml"
|
|
112
114
|
},
|
|
113
115
|
"optionalDependencies": {
|
|
114
|
-
"leanvec": "^0.
|
|
116
|
+
"leanvec": "^0.2.0"
|
|
115
117
|
}
|
|
116
118
|
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 大量小文件的性能基准(不需要 dsh、不联网、不碰你自己的 store)。
|
|
3
|
+
//
|
|
4
|
+
// node scripts/bench-edits.mjs [--files 400] [--edits 30] [--dir <空目录>] [--keep]
|
|
5
|
+
//
|
|
6
|
+
// 量两件事:
|
|
7
|
+
// 1. 首次索引 N 个小文件(每个文件写一个分片);
|
|
8
|
+
// 2. 之后 M 次"单文件修改 → 懒索引"(每次一个 save:锁 + 分片 + 目录元数据)。
|
|
9
|
+
//
|
|
10
|
+
// 为什么单独有这个脚本:Windows/NTFS 上每次文件操作都要过过滤驱动,单文件更新的成本
|
|
11
|
+
// 由**文件操作次数**决定,而不是 CPU。Linux 上 p50 1ms 的路径到 NTFS 上可以是几十毫秒;
|
|
12
|
+
// 这个脚本用同一份代码量出差异,也用来守住"别在每次 save 里加 O(N) 扫描"。
|
|
13
|
+
//
|
|
14
|
+
// 用法示例(Windows 原生 / WSL 挂载盘):
|
|
15
|
+
// node scripts/bench-edits.mjs --dir C:\\Temp\\pm-bench
|
|
16
|
+
// node scripts/bench-edits.mjs --dir /mnt/c/Users/Public/pm-bench --files 400
|
|
17
|
+
import { mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
18
|
+
import { tmpdir } from 'node:os'
|
|
19
|
+
import path from 'node:path'
|
|
20
|
+
import { indexRepository } from '../src/tools/index-repo.js'
|
|
21
|
+
import { indexFile } from '../src/lazy.js'
|
|
22
|
+
|
|
23
|
+
const arg = (name, fallback) => {
|
|
24
|
+
const i = process.argv.indexOf(`--${name}`)
|
|
25
|
+
return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback
|
|
26
|
+
}
|
|
27
|
+
const files = Number(arg('files', 400))
|
|
28
|
+
const edits = Number(arg('edits', 30))
|
|
29
|
+
const keep = process.argv.includes('--keep')
|
|
30
|
+
const parent = arg('dir', null)
|
|
31
|
+
const base = parent ? path.resolve(parent) : mkdtempSync(path.join(tmpdir(), 'pm-bench-'))
|
|
32
|
+
const root = path.join(base, `many-small-${Date.now().toString(36)}`)
|
|
33
|
+
if (parent) mkdirSync(base, { recursive: true })
|
|
34
|
+
|
|
35
|
+
const config = {
|
|
36
|
+
memoryDir: '.dsh-project-memory',
|
|
37
|
+
chunkChars: 3000,
|
|
38
|
+
maxChunksPerFile: 40,
|
|
39
|
+
maxFileSizeMb: 10,
|
|
40
|
+
maxPdfPages: 1000,
|
|
41
|
+
enableTypeScript: false,
|
|
42
|
+
}
|
|
43
|
+
const mb = (bytes) => (bytes / 1048576).toFixed(1)
|
|
44
|
+
|
|
45
|
+
mkdirSync(root, { recursive: true })
|
|
46
|
+
for (let i = 0; i < files; i++) {
|
|
47
|
+
writeFileSync(path.join(root, `m${i}.js`), `export function f${i}(a) {\n return a + ${i}\n}\n\nexport const v${i} = ${i}\n`)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const t0 = Date.now()
|
|
51
|
+
await indexRepository(null, config, root, {})
|
|
52
|
+
const indexMs = Date.now() - t0
|
|
53
|
+
|
|
54
|
+
const storeDir = path.join(root, config.memoryDir)
|
|
55
|
+
const shards = readdirSync(path.join(storeDir, 'shards'))
|
|
56
|
+
let contentBytes = 0
|
|
57
|
+
for (const name of readdirSync(storeDir)) {
|
|
58
|
+
const p = path.join(storeDir, name)
|
|
59
|
+
try {
|
|
60
|
+
const st = statSync(p)
|
|
61
|
+
if (st.isFile()) contentBytes += st.size
|
|
62
|
+
} catch {
|
|
63
|
+
/* 统计期间消失的临时文件 */
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const samples = []
|
|
68
|
+
for (let i = 0; i < edits; i++) {
|
|
69
|
+
const file = path.join(root, `m${i % files}.js`)
|
|
70
|
+
writeFileSync(file, `export function f${i % files}(a) {\n return a + ${i} // edit ${i}\n}\n`)
|
|
71
|
+
const started = Date.now()
|
|
72
|
+
await indexFile(null, config, file, null, root)
|
|
73
|
+
samples.push(Date.now() - started)
|
|
74
|
+
}
|
|
75
|
+
samples.sort((a, b) => a - b)
|
|
76
|
+
const pick = (r) => samples[Math.min(samples.length - 1, Math.floor(r * samples.length))]
|
|
77
|
+
|
|
78
|
+
console.log(JSON.stringify({
|
|
79
|
+
files,
|
|
80
|
+
edits,
|
|
81
|
+
root: keep ? root : '(deleted)',
|
|
82
|
+
index: { ms: indexMs, perFileMs: Number((indexMs / files).toFixed(2)), shards: shards.length, contentKB: Number((contentBytes / 1024).toFixed(1)) },
|
|
83
|
+
singleFileEditMs: { p50: pick(0.5), p90: pick(0.9), max: samples.at(-1) },
|
|
84
|
+
peakRssMB: Number(mb(process.resourceUsage().maxRSS * 1024)),
|
|
85
|
+
}, null, 2))
|
|
86
|
+
|
|
87
|
+
if (!keep) rmSync(root, { recursive: true, force: true })
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: project-memory
|
|
3
|
+
description: Recall and maintain this project's long-term memory — indexed docs and code symbols, lessons, decisions, procedures, and cross-session tasks. Use it before re-deriving project context or repeating a past mistake.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Project memory
|
|
7
|
+
|
|
8
|
+
This repository keeps a memory store at `.dsh-project-memory/` (path configurable). It holds three
|
|
9
|
+
kinds of things:
|
|
10
|
+
|
|
11
|
+
1. **Indexed corpus** — documents (Markdown / PDF / text) and code symbols, with `path:line`
|
|
12
|
+
citations.
|
|
13
|
+
2. **Insights** — lessons (`problem → fix`), decisions (`choice + reason`), procedures (steps), and
|
|
14
|
+
experience notes. These are written by agents, across sessions.
|
|
15
|
+
3. **Tasks** — cross-session work records with steps and hot files. A session can be bound to one.
|
|
16
|
+
|
|
17
|
+
Query it before re-deriving; write to it only after something has been verified.
|
|
18
|
+
|
|
19
|
+
## When to query
|
|
20
|
+
|
|
21
|
+
- Before asking the human to re-explain the project, a past decision, or "what were we doing".
|
|
22
|
+
- Before changing a subsystem: there may be a lesson about its failure modes.
|
|
23
|
+
- Before an irreversible action (commit / publish / release / push / deploy / migrate): the store may
|
|
24
|
+
know a prerequisite you would otherwise miss.
|
|
25
|
+
- When resuming: call `list_tasks`, then `select_task` if one matches the current work.
|
|
26
|
+
|
|
27
|
+
## Workflow
|
|
28
|
+
|
|
29
|
+
1. **Locate context**
|
|
30
|
+
- `query_memory` with `query` = what you actually need ("how are shards written", "why store
|
|
31
|
+
scope", "where is X implemented").
|
|
32
|
+
- `type`: `all` (default) / `doc` / `symbol` / `experience` / `insight` / `task`.
|
|
33
|
+
- Results carry ids and citations. Treat them as evidence: read the cited file when the answer
|
|
34
|
+
matters.
|
|
35
|
+
2. **Refresh the index if it looks empty or stale**
|
|
36
|
+
- `index_repo root:"<project>"` — incremental; unchanged files are skipped.
|
|
37
|
+
- `index_doc file_path:"…"` — one document, even outside the corpus.
|
|
38
|
+
- `memory_stats` — counts, last index time, per-file list.
|
|
39
|
+
3. **Write back what will still be true next session**
|
|
40
|
+
- `save_lesson` — one insight. Give `kind` (`lesson` / `decision` / `procedure`), a one-line
|
|
41
|
+
`title`, and the body: `pattern` + `fix`, or `choice` + `reason`, or `steps`.
|
|
42
|
+
- `remember problem solution` — shorthand for `kind: experience`.
|
|
43
|
+
- `files`: project-relative paths the conclusion is about.
|
|
44
|
+
- `trigger.when`: when this should be recalled. `ops` (action), `writes` (file about to change),
|
|
45
|
+
`intents` (words the human would use). `guard` only narrows; `prevents` records what breaks
|
|
46
|
+
without it. Do **not** write a trigger you have not seen fire.
|
|
47
|
+
- `scope`: `task` (needs a bound task), `project` (default), `global` (rarely).
|
|
48
|
+
4. **Correct or delete**
|
|
49
|
+
- Same `id` + new fields = in-place update (old value kept in `prev`).
|
|
50
|
+
- `forget id_or_query` is a real delete, no undo. Prefer ids; keyword deletes refuse when too many
|
|
51
|
+
entries match.
|
|
52
|
+
|
|
53
|
+
## Rules
|
|
54
|
+
|
|
55
|
+
- Memory is evidence, not authority. Re-check the file before acting on a citation.
|
|
56
|
+
- Do not save: progress narration, temporary state, secrets/credentials, anything derivable from the
|
|
57
|
+
code in one read.
|
|
58
|
+
- One durable entry beats five observations. Merge by updating the existing id.
|
|
59
|
+
- Write in the same language the project uses; keep titles short and searchable.
|
|
60
|
+
- The store self-ignores in git; do not commit it unless the human explicitly wants memory in the repo.
|
|
61
|
+
|
|
62
|
+
## Diagnostics
|
|
63
|
+
|
|
64
|
+
Run from a shell (no dsh required):
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
node <this-skill-dir>/scripts/pm-digest.mjs <project-root>
|
|
68
|
+
node <this-skill-dir>/scripts/pm-digest.mjs <project-root> --json
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
It prints store size, insight/task counts, trigger coverage, and staleness. Use it when memory looks
|
|
72
|
+
empty, suspiciously large, or when you need to explain what is stored.
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 项目记忆的体检脚本(零依赖、不调模型、不写盘)。
|
|
3
|
+
//
|
|
4
|
+
// node pm-digest.mjs [项目根] [--json]
|
|
5
|
+
//
|
|
6
|
+
// 面向模型与人类各一半:模型拿它替代"先读三个 JSON 再数数"的多次工具往返;
|
|
7
|
+
// 人拿它看 store 是否异常增长、trigger 覆盖多少、任务是不是全归档了。
|
|
8
|
+
// 只输出计数与少量标题,不打印正文——避免把记忆内容再塞回上下文。
|
|
9
|
+
import { readFileSync, readdirSync, statSync } from 'node:fs'
|
|
10
|
+
import { homedir } from 'node:os'
|
|
11
|
+
import path from 'node:path'
|
|
12
|
+
|
|
13
|
+
const args = process.argv.slice(2)
|
|
14
|
+
const json = args.includes('--json')
|
|
15
|
+
const root = path.resolve(args.find((a) => !a.startsWith('--')) || process.cwd())
|
|
16
|
+
const memoryDir = path.join(root, '.dsh-project-memory')
|
|
17
|
+
|
|
18
|
+
const readJson = (file, fallback) => {
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(readFileSync(file, 'utf8'))
|
|
21
|
+
} catch {
|
|
22
|
+
return fallback
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const days = (iso) => {
|
|
26
|
+
const t = Date.parse(iso || '')
|
|
27
|
+
return Number.isFinite(t) ? Math.max(0, Math.round((Date.now() - t) / 86_400_000)) : null
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function shardStats(dir) {
|
|
31
|
+
try {
|
|
32
|
+
let files = 0
|
|
33
|
+
let bytes = 0
|
|
34
|
+
for (const name of readdirSync(dir)) {
|
|
35
|
+
if (!name.endsWith('.json')) continue
|
|
36
|
+
try {
|
|
37
|
+
const st = statSync(path.join(dir, name))
|
|
38
|
+
if (!st.isFile()) continue
|
|
39
|
+
files++
|
|
40
|
+
bytes += st.size
|
|
41
|
+
} catch {
|
|
42
|
+
/* 分片在统计途中消失:跳过 */
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return { files, bytes }
|
|
46
|
+
} catch {
|
|
47
|
+
return { files: 0, bytes: 0 }
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function insightStats(items) {
|
|
52
|
+
const kinds = {}
|
|
53
|
+
const scopes = {}
|
|
54
|
+
let archived = 0
|
|
55
|
+
let withTrigger = 0
|
|
56
|
+
let withFiles = 0
|
|
57
|
+
let stale90 = 0
|
|
58
|
+
let lastAt = null
|
|
59
|
+
for (const it of items) {
|
|
60
|
+
if (!it || typeof it !== 'object') continue
|
|
61
|
+
kinds[it.kind || '?'] = (kinds[it.kind || '?'] || 0) + 1
|
|
62
|
+
scopes[it.scope || '?'] = (scopes[it.scope || '?'] || 0) + 1
|
|
63
|
+
if (it.archived) archived++
|
|
64
|
+
if (it.trigger && it.trigger.when) withTrigger++
|
|
65
|
+
if (Array.isArray(it.files) && it.files.length) withFiles++
|
|
66
|
+
const age = days(it.updatedAt || it.createdAt)
|
|
67
|
+
if (age !== null && age > 90) stale90++
|
|
68
|
+
const at = it.updatedAt || it.createdAt
|
|
69
|
+
if (at && (!lastAt || at > lastAt)) lastAt = at
|
|
70
|
+
}
|
|
71
|
+
return { total: items.length, kinds, scopes, archived, withTrigger, withFiles, stale90, lastAt }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function taskStats(tasks) {
|
|
75
|
+
let archived = 0
|
|
76
|
+
let steps = 0
|
|
77
|
+
let files = 0
|
|
78
|
+
let withInsights = 0
|
|
79
|
+
const active = []
|
|
80
|
+
for (const t of tasks) {
|
|
81
|
+
if (!t || typeof t !== 'object') continue
|
|
82
|
+
if (t.archived) archived++
|
|
83
|
+
else if (t.title) active.push(String(t.title))
|
|
84
|
+
if (Array.isArray(t.steps)) steps += t.steps.length
|
|
85
|
+
if (Array.isArray(t.files)) files += t.files.length
|
|
86
|
+
if (Array.isArray(t.insights) && t.insights.length) withInsights++
|
|
87
|
+
}
|
|
88
|
+
return { total: tasks.length, archived, active: tasks.length - archived, steps, files, withInsights, activeTitles: active.slice(0, 3) }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const insDoc = readJson(path.join(memoryDir, 'insights.json'), null)
|
|
92
|
+
const taskDoc = readJson(path.join(memoryDir, 'tasks.json'), null)
|
|
93
|
+
const binding = readJson(path.join(memoryDir, 'binding.json'), null)
|
|
94
|
+
const globalFile = path.join(homedir(), '.config', 'dsh-project-memory', 'global.json')
|
|
95
|
+
const globalDoc = readJson(globalFile, null)
|
|
96
|
+
|
|
97
|
+
if (!insDoc && !taskDoc) {
|
|
98
|
+
const msg = `no memory store at ${memoryDir} (run index_repo or index_doc first)`
|
|
99
|
+
if (json) process.stdout.write(JSON.stringify({ root, memoryDir, store: false }, null, 2) + '\n')
|
|
100
|
+
else process.stdout.write(msg + '\n')
|
|
101
|
+
process.exit(0)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const shards = shardStats(path.join(memoryDir, 'shards'))
|
|
105
|
+
const insights = insightStats((insDoc && insDoc.items) || [])
|
|
106
|
+
const tasks = taskStats((Array.isArray(taskDoc) ? taskDoc : []) || [])
|
|
107
|
+
const summary = {
|
|
108
|
+
root,
|
|
109
|
+
memoryDir,
|
|
110
|
+
store: true,
|
|
111
|
+
shards,
|
|
112
|
+
insights,
|
|
113
|
+
tasks,
|
|
114
|
+
bindings: binding && typeof binding === 'object' ? Object.keys(binding).length : 0,
|
|
115
|
+
global: { items: globalDoc && Array.isArray(globalDoc.items) ? globalDoc.items.length : 0 },
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (json) {
|
|
119
|
+
process.stdout.write(JSON.stringify(summary, null, 2) + '\n')
|
|
120
|
+
process.exit(0)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const kb = (n) => (n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.round(n / 102.4) / 10} KB`)
|
|
124
|
+
const line = (label, value) => process.stdout.write(`${label.padEnd(12)} ${value}\n`)
|
|
125
|
+
line('project', root)
|
|
126
|
+
line('store', `${shards.files} shards · ${kb(shards.bytes)} · ${insights.total} insights · ${tasks.total} tasks`)
|
|
127
|
+
if (insights.total) {
|
|
128
|
+
const kinds = Object.entries(insights.kinds).map(([k, n]) => `${k} ${n}`).join(' · ')
|
|
129
|
+
line('insights', `${kinds}${insights.archived ? ` · archived ${insights.archived}` : ''}`)
|
|
130
|
+
line('triggers', `${insights.withTrigger}/${insights.total} with when · ${insights.withFiles} with files · ${insights.stale90} older than 90d`)
|
|
131
|
+
}
|
|
132
|
+
if (tasks.total) {
|
|
133
|
+
line('tasks', `${tasks.active} active · ${tasks.archived} archived · ${tasks.steps} steps · ${tasks.files} file links`)
|
|
134
|
+
if (tasks.activeTitles.length) line('active', tasks.activeTitles.join(' | '))
|
|
135
|
+
if (tasks.withInsights === 0) line('task memory', 'none — task-scoped insights are not used here')
|
|
136
|
+
}
|
|
137
|
+
line('bindings', `${summary.bindings} session(s) bound`)
|
|
138
|
+
line('global', `${summary.global.items} entries (~/.config/dsh-project-memory/global.json)`)
|
package/src/audit.js
CHANGED
|
@@ -1,13 +1,6 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// inputTokens),拿不到"这一条记忆值多少"。所以"当时注入了哪几条、因为什么命中、同一轮
|
|
5
|
-
// 哪些被预算挤掉"必须落盘才可离线复盘。缺了它,任何 trigger / 阈值改动都只能靠感觉。
|
|
6
|
-
//
|
|
7
|
-
// 契约(与 auto-inject 同款安全约定):
|
|
8
|
-
// - 只在确有决策(本条真的进了上下文)时写一行:dropped 单独出现不写,否则每步刷屏;
|
|
9
|
-
// - 任何异常(目录不可写、磁盘满、记录序列化失败)一律吞掉,绝不影响宿主请求;
|
|
10
|
-
// - 单文件超限就地轮转一份 `.1`,不引入新的清理线程或后台任务。
|
|
1
|
+
// 注入审计:把每次真实进入上下文的注入决策落成 JSONL,供离线复盘。
|
|
2
|
+
// 契约:只在确有决策时写一行(dropped 单独出现不写);任何异常一律吞掉,
|
|
3
|
+
// 绝不影响宿主请求;单文件超限就地轮转一份 `.1`,不引入后台任务。
|
|
11
4
|
import { appendFileSync, existsSync, mkdirSync, renameSync, statSync } from 'node:fs'
|
|
12
5
|
import path from 'node:path'
|
|
13
6
|
import { hasProjectMarker } from './util/fs.js'
|
|
@@ -15,32 +8,24 @@ import { hasProjectMarker } from './util/fs.js'
|
|
|
15
8
|
export const AUDIT_FILE = 'injection-audit.jsonl'
|
|
16
9
|
const DEFAULT_MAX_BYTES = 256 * 1024
|
|
17
10
|
|
|
18
|
-
//
|
|
19
|
-
// "
|
|
20
|
-
// 带全部候选的特征与判据结果,用来 (a) 离线重放任一阈值、(b) 攒"特征 → 该不该注入"的训练样本。
|
|
11
|
+
// 影子记录与主审计分开文件:主审计只记真的注入步,静默步不落痕;影子每步都写,
|
|
12
|
+
// 带全部候选与判据,用于离线重放阈值、攒"特征 → 该不该注入"的样本。
|
|
21
13
|
export const SHADOW_FILE = 'admission-shadow.jsonl'
|
|
22
|
-
// 512KB
|
|
23
|
-
//
|
|
24
|
-
// 实测本插件自己的 store 里 3.1M/4.2M 是日志)。512KB 下上限降到 ≈1.5MB,
|
|
25
|
-
// 而按每行 ~1.5KB 算仍有 ~680 步的历史窗口 —— 远超"离线重放最近的历史"所需。
|
|
14
|
+
// 512KB 而非 2MB:只保留 `.1` 一代,硬上限是 2×shadow + 2×audit ≈1.5MB(此前 4.6MB,
|
|
15
|
+
// 实测本插件 store 里 3.1M/4.2M 是日志);每行 ~1.5KB 仍有 ~680 步窗口。
|
|
26
16
|
const DEFAULT_SHADOW_MAX_BYTES = 512 * 1024
|
|
27
17
|
|
|
28
18
|
/**
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
* (相对阈值就是分数比),所以「**全部 cand + 按排名补足**」既保住离线重放最需要的那批,
|
|
34
|
-
* 又砍掉远处必然被 coverage/relative 拦掉的尾巴。截断量记在 `candidatesTotal`,不静默。
|
|
19
|
+
* 一行影子记录最多保留的候选数:90.6% 的体积是 `candidates`(实测 210 行 / 965KB,
|
|
20
|
+
* 候选占 875KB),真实 store 单步 40~60 条(中位 42)。候选按分数降序、`cand` 必在最前,
|
|
21
|
+
* 所以保留全部 cand + 按排名补足,砍掉远处必被 coverage/relative 拦掉的尾巴;
|
|
22
|
+
* 截断量记在 `candidatesTotal`。
|
|
35
23
|
*/
|
|
36
24
|
const SHADOW_MAX_CANDIDATES = 16
|
|
37
25
|
|
|
38
26
|
/**
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
* 另一边忘了。语义刻意选择:
|
|
42
|
-
* - `!== false` 而不是 `=== true`:未配置 = 开(观测是这个插件唯一的仪表盘);
|
|
43
|
-
* - `> 0` 而不是 `!= null`:0 / 负数 / NaN 都视为「没配」,退回默认上限,而不是禁用。
|
|
27
|
+
* 两份旁路日志共用的配置归一,差别只有开关名 / 上限键 / 默认值。
|
|
28
|
+
* `!== false`:未配置 = 开;`> 0`:0 / 负数 / NaN 都视为没配,退回默认上限而不是禁用。
|
|
44
29
|
*/
|
|
45
30
|
function cfgSideLog(config, { enabledKey, maxKey, defaultMaxBytes }) {
|
|
46
31
|
const c = (config && config.autoContext) || {}
|
|
@@ -69,18 +54,15 @@ export function shadowFileFor(memoryDir) {
|
|
|
69
54
|
}
|
|
70
55
|
|
|
71
56
|
/**
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
* - 带**全部候选**的判据特征(cov/matched/support/relative)与场景(query/ops/writes),
|
|
75
|
-
* 所以能离线回答"阈值换成 0.40 会注入什么"、并攒出"特征 → 该不该注入"的样本。
|
|
57
|
+
* 一步的影子记录(纯函数,可单测):每步都写(含零注入步),并带全部候选的
|
|
58
|
+
* 判据特征与场景,才能离线回答"换个阈值会注入什么"、攒出训练样本。
|
|
76
59
|
* @param {object} input { sessionId, root, step, query, scoreQuery, ops, writes, reasons, dropped, candidates, silence }
|
|
77
60
|
*/
|
|
78
61
|
export function shadowRecordFrom(input) {
|
|
79
62
|
const reasons = Array.isArray(input.reasons) ? input.reasons : []
|
|
80
63
|
const candidates = Array.isArray(input.candidates) ? input.candidates : []
|
|
81
64
|
const dropped = Array.isArray(input.dropped) ? input.dropped : []
|
|
82
|
-
// `support` / `terms`
|
|
83
|
-
// 逐条恒定(实测 139/139 步)。把它们从每条候选提到行级:单候选省 ~25 B,整行省 ~23%。
|
|
65
|
+
// `support` / `terms` 是查询级量,半步内逐条恒定(实测 139/139 步),提到行级省 ~23%。
|
|
84
66
|
const first = candidates[0]
|
|
85
67
|
const slim = candidates.map((c) => ({
|
|
86
68
|
id: c.id,
|
|
@@ -108,19 +90,22 @@ export function shadowRecordFrom(input) {
|
|
|
108
90
|
step: typeof input.step === 'number' ? input.step : null,
|
|
109
91
|
// 人类消息截断保存:没有它就判不了"这次注入该不该"——标签要能回放到当时的场景。
|
|
110
92
|
query: typeof input.query === 'string' ? input.query.slice(0, 300) : '',
|
|
111
|
-
// **实际用于评分**的查询文本(intent +
|
|
112
|
-
// 写目标驱动的那些步 `query` 是空的、候选却非空。少了这一栏,判据无法离线重放。
|
|
93
|
+
// **实际用于评分**的查询文本(intent + 写目标拼合),与 `query` 不同:写目标驱动的步 query 为空、候选非空;缺它无法离线重放判据。
|
|
113
94
|
scoreQuery: typeof input.scoreQuery === 'string' ? input.scoreQuery.slice(0, 300) : '',
|
|
95
|
+
// query 来源:本步 delta / 会话缓存的最后一条真人消息 / 无——复盘要先分清"本来没意图"与"来源取错"。
|
|
96
|
+
querySource: ['delta', 'session'].includes(input.querySource) ? input.querySource : 'none',
|
|
114
97
|
ops: (Array.isArray(input.ops) ? input.ops : []).slice(0, 12),
|
|
98
|
+
// 人类消息里解析出的全部动作词(含被 `PRE_ACTION_OPS` 过滤掉的),留着才能回答"这条为什么没注入",以及"放回某类动作会发生什么"。
|
|
99
|
+
opsIntent: (Array.isArray(input.opsIntent) ? input.opsIntent : []).slice(0, 12),
|
|
115
100
|
writes: (Array.isArray(input.writes) ? input.writes : []).slice(0, 12),
|
|
116
101
|
injected: reasons.map((r) => ({ id: r.id, channel: r.channel, why: r.why })),
|
|
117
|
-
// 查询级支持度:语料能表示查询里多少个词(`terms`
|
|
102
|
+
// 查询级支持度:语料能表示查询里多少个词(`terms` 是查询词数),通道级沉默判据用的就是它。
|
|
118
103
|
support: typeof first?.support === 'number' ? first.support : null,
|
|
119
104
|
terms: typeof first?.terms === 'number' ? first.terms : null,
|
|
120
|
-
// candidates 的 `decision`
|
|
121
|
-
// (injected / budget / quota / idle / gate / unscheduled
|
|
105
|
+
// candidates 的 `decision` 只说明过没过门槛,进不进上下文看 `outcome`
|
|
106
|
+
// (injected / budget / quota / idle / gate / unscheduled),两者正交。
|
|
122
107
|
candidates: bounded,
|
|
123
|
-
//
|
|
108
|
+
// 截断前的候选总数:读日志的人能看出这一步裁掉了多少。
|
|
124
109
|
candidatesTotal: candidates.length,
|
|
125
110
|
// 触发通道的丢弃不在 candidates 里(候选只收提示通道),单列;有界,避免长候选池撑爆一行。
|
|
126
111
|
dropped: dropped.slice(0, 40),
|
|
@@ -129,19 +114,9 @@ export function shadowRecordFrom(input) {
|
|
|
129
114
|
}
|
|
130
115
|
|
|
131
116
|
/**
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
* `mkdirSync`(`load()` 不建目录,`ensureSelfIgnore()` 也要求目录已存在)。于是任何一次
|
|
136
|
-
* "**在容器目录里**开会话"都会留下一个只装着审计日志的空 store —— 而那个目录随后还会被
|
|
137
|
-
* `resolveProjectMemoryRoot()` 当成项目根。审计是旁路,没有 store 就没有可对照的候选。
|
|
138
|
-
*
|
|
139
|
-
* 两个放行条件:
|
|
140
|
-
* - store 目录已存在 → 真被索引/写过,照旧;
|
|
141
|
-
* - 该根**自身带项目标记**(`hasProjectMarker`)→ 是"声明过的项目",即便还没落过盘,
|
|
142
|
-
* 也该留下第一步的记录(`rootNotice` 用的是同一个判据,两处口径一致)。
|
|
143
|
-
* "根是推定的(无标记)且还没有内容"→ 跳过。这正是容器目录的那种情况。
|
|
144
|
-
*
|
|
117
|
+
* 审计只为"已存在"或"带项目标记"的根建 store 目录:否则在容器目录里开会话会留下
|
|
118
|
+
* 只装审计日志的空 store,并被 `resolveProjectMemoryRoot()` 当成项目根。
|
|
119
|
+
* 标记判据 `hasProjectMarker`,与 `rootNotice` 一致。
|
|
145
120
|
* @param {string} memoryDir `<root>/.dsh-project-memory`
|
|
146
121
|
* @param {string} [root] 项目根;省略时退回 `path.dirname(memoryDir)`
|
|
147
122
|
*/
|
|
@@ -151,9 +126,8 @@ function auditDirReady(memoryDir, root) {
|
|
|
151
126
|
}
|
|
152
127
|
|
|
153
128
|
/**
|
|
154
|
-
* 两份旁路日志共用的追加:目录门禁 / mkdir / 轮转 /
|
|
155
|
-
*
|
|
156
|
-
* (影子记录与主审计的"不建推测根"曾经就是各写一遍)。
|
|
129
|
+
* 两份旁路日志共用的追加:目录门禁 / mkdir / 轮转 / 吞异常只有这一份实现,
|
|
130
|
+
* 调用方只声明文件名与默认上限(分开写会一处补了护栏、另一处漏)。
|
|
157
131
|
* @returns {boolean} 是否写入成功(仅供测试断言)
|
|
158
132
|
*/
|
|
159
133
|
function appendJsonlRecord({ memoryDir, record, cfg, root, fileFor, defaultMaxBytes }) {
|
|
@@ -174,15 +148,15 @@ function appendJsonlRecord({ memoryDir, record, cfg, root, fileFor, defaultMaxBy
|
|
|
174
148
|
}
|
|
175
149
|
|
|
176
150
|
/**
|
|
177
|
-
*
|
|
178
|
-
*
|
|
151
|
+
* 追加一行影子记录。与主审计同约定:任何异常一律吞掉,绝不影响宿主请求。
|
|
152
|
+
* @returns {boolean} 是否写入成功(仅供测试断言)
|
|
179
153
|
*/
|
|
180
154
|
export function appendShadowAudit(memoryDir, record, cfg, root) {
|
|
181
155
|
return appendJsonlRecord({ memoryDir, record, cfg, root, fileFor: shadowFileFor, defaultMaxBytes: DEFAULT_SHADOW_MAX_BYTES })
|
|
182
156
|
}
|
|
183
157
|
|
|
184
158
|
/**
|
|
185
|
-
*
|
|
159
|
+
* 一次注入的审计记录(纯函数,可单测):字段只回答两个问题——
|
|
186
160
|
* 注入了什么(injected)、为什么没注入别的(dropped)。
|
|
187
161
|
* @param {object} input { sessionId, root, step, text, labels, reasons, dropped }
|
|
188
162
|
*/
|
|
@@ -202,9 +176,8 @@ export function auditRecordFrom(input) {
|
|
|
202
176
|
why: r.why,
|
|
203
177
|
chars: typeof r.chars === 'number' ? r.chars : null,
|
|
204
178
|
})),
|
|
205
|
-
// `budget`
|
|
206
|
-
//
|
|
207
|
-
// 只对带数字的条目落键——多数掉落(coverage 等)没有量纲,不该为它们付两个 null。
|
|
179
|
+
// `budget` 掉落带量纲(remaining / need),必须原样落地,否则"细缝可诊断"只活在内存里。
|
|
180
|
+
// 只对带数字的条目落键——多数掉落没有量纲,不该为它们付两个 null。
|
|
208
181
|
dropped: dropped.map((d) => ({
|
|
209
182
|
id: d.id,
|
|
210
183
|
channel: d.channel,
|