dsh-memorytree-rule 0.0.0-stage → 1.0.2

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/lib/ingest.mjs ADDED
@@ -0,0 +1,279 @@
1
+ // lib/ingest.mjs — 把 AGENTS.md(主干正本)解析成 trunk 枝条目。
2
+ //
3
+ // 原则:
4
+ // - 文件永远是正本;插件只做「可检索的索引副本」,每条都带 source=AGENTS.md#Lx-Ly 与逐字证据。
5
+ // - 文件里删掉/改写的规则:改写→原位更新(uid 不变,保留引用);删除→归档(不硬删)。
6
+ // - 这里只解析 §1 主干(其他枝的内容属于 memories.db 的职责,不是文件里的规则)。
7
+ import fs from "node:fs";
8
+ import { checksum, truncate } from "./text.mjs";
9
+ import { setMeta, getMeta, bumpIndexVersion, tx } from "./db.mjs";
10
+
11
+ const RULE_RE = /^\s*[-*]\s+\*\*(§[\d\-–]+)[\s\u3000]+([^*]+?)\*\*\s*[::;]\s*(.*)$/;
12
+ const HEADING_RE = /^(#{2,4})\s+(.+?)\s*$/;
13
+
14
+ /**
15
+ * 纯函数解析,方便单测。
16
+ * @returns {{trunk:string, rules:Array<{uid:string,num:string,title:string,text:string,section:string,group:string,startLine:number,endLine:number}>, headings:string[]}}
17
+ */
18
+ export function parseAgents(text) {
19
+ const src = String(text ?? "").replace(/\r\n?/g, "\n");
20
+ const lines = src.split("\n");
21
+ const rules = [];
22
+ const unparsed = [];
23
+ const stack = []; // {level, title}
24
+ let trunkTitle = null;
25
+ let trunkName = null;
26
+ let trunkFound = false;
27
+ let cur = null;
28
+
29
+ const headingPath = () => stack.map((s) => s.title).filter(Boolean).join(" / ");
30
+ const groupOf = () => {
31
+ for (let i = stack.length - 1; i >= 0; i -= 1) {
32
+ const t = stack[i].title;
33
+ if (/^§1-\d+/.test(t)) return t.replace(/^§[\d\-–]+\s*/, "").trim();
34
+ }
35
+ const h1 = stack.find((s) => /^§1[\s\u3000]/.test(s.title));
36
+ return h1 ? h1.title.replace(/^§1[\s\u3000]*/, "").replace(/(.*$/, "").trim() : "主干";
37
+ };
38
+
39
+ const flush = () => {
40
+ if (!cur) return;
41
+ const body = cur.lines.join("\n").trim();
42
+ if (body.length > 0) {
43
+ rules.push({
44
+ uid: "trunk:" + cur.num,
45
+ num: cur.num,
46
+ title: cur.title,
47
+ text: cur.title + ":" + body,
48
+ section: cur.section,
49
+ group: cur.group,
50
+ startLine: cur.startLine,
51
+ endLine: cur.endLine,
52
+ });
53
+ } else {
54
+ unparsed.push({ line: cur.startLine, text: "规则正文为空:" + cur.title });
55
+ }
56
+ cur = null;
57
+ };
58
+
59
+ for (let i = 0; i < lines.length; i += 1) {
60
+ const line = lines[i];
61
+ const h = HEADING_RE.exec(line);
62
+ if (h) {
63
+ flush();
64
+ const level = h[1].length;
65
+ const title = h[2].trim();
66
+ while (stack.length && stack[stack.length - 1].level >= level) stack.pop();
67
+ stack.push({ level, title });
68
+ if (level === 2 && /^§1[\s\u3000]/.test(title)) {
69
+ trunkTitle = title;
70
+ trunkName = title;
71
+ trunkFound = true;
72
+ }
73
+ if (level === 2 && /^§[2-5][\s\u3000]/.test(title)) trunkTitle = null;
74
+ continue;
75
+ }
76
+ // 只收 §1 下的规则
77
+ if (!trunkTitle) {
78
+ if (cur) flush();
79
+ continue;
80
+ }
81
+ const m = RULE_RE.exec(line);
82
+ if (m) {
83
+ if (!/^§1-/.test(m[1].replace(/[–]/g, "-"))) {
84
+ unparsed.push({ line: i + 1, text: "§1 下出现了非 §1 编号:" + line.trim().slice(0, 160) });
85
+ if (cur) flush();
86
+ continue;
87
+ }
88
+ flush();
89
+ cur = {
90
+ num: m[1].replace(/[–]/g, "-"),
91
+ title: m[2].trim(),
92
+ lines: [m[3].trim()],
93
+ startLine: i + 1,
94
+ endLine: i + 1,
95
+ section: headingPath(),
96
+ group: groupOf(),
97
+ };
98
+ continue;
99
+ }
100
+ // 形似 §1 规则但格式没解析出来:记下来让同步拒绝,避免它被当成「文件里已删除」而归档。
101
+ if (/^\s*[-*]\s+\*\*\s*§1-\d+/.test(line)) {
102
+ unparsed.push({ line: i + 1, text: line.trim().slice(0, 160) });
103
+ continue;
104
+ }
105
+ if (cur) {
106
+ if (line.trim() === "") {
107
+ cur.lines.push("");
108
+ cur.endLine = i + 1;
109
+ continue;
110
+ }
111
+ // 顶格的新列表/普通段落=规则结束;缩进或嵌套列表属于本条规则
112
+ if (/^\S/.test(line) && !/^\s/.test(line)) {
113
+ flush();
114
+ continue;
115
+ }
116
+ cur.lines.push(line);
117
+ cur.endLine = i + 1;
118
+ }
119
+ }
120
+ flush();
121
+ return { trunk: trunkFound ? trunkName || "§1 主干" : null, rules, unparsed, headings: stack.map((s) => s.title) };
122
+ }
123
+
124
+ /** 把解析结果同步进库,返回变更统计。 */
125
+ export function syncTrunk(store, agentsPath, opts = {}) {
126
+ let raw;
127
+ try {
128
+ raw = fs.readFileSync(agentsPath, "utf8");
129
+ } catch (err) {
130
+ return { ok: false, reason: "读不到主干文件:" + (err && err.message ? err.message : String(err)), path: agentsPath };
131
+ }
132
+ const parsed = parseAgents(raw);
133
+ if (!parsed.trunk) {
134
+ return { ok: false, reason: "文件里没有找到 §1 主干章节,未同步(避免把别的文件内容当规则)", path: agentsPath, ruleCount: parsed.rules.length };
135
+ }
136
+ if (parsed.unparsed && parsed.unparsed.length > 0) {
137
+ const first = parsed.unparsed[0];
138
+ return {
139
+ ok: false,
140
+ reason: "AGENTS.md 第 " + first.line + " 行像 §1 规则但格式无法解析(" + first.text + "),已拒绝同步;" +
141
+ "格式应为 `- **§1-x-x 标题**:正文`。",
142
+ path: agentsPath,
143
+ ruleCount: parsed.rules.length,
144
+ unparsed: parsed.unparsed.slice(0, 10),
145
+ };
146
+ }
147
+ const fileChecksum = checksum(raw);
148
+ const prevChecksum = getMeta(store.db, "agents_checksum", null);
149
+ if (parsed.rules.length === 0 && opts.allowEmpty !== true) {
150
+ // 文件格式全坏 / §1 被清空时,继续同步会把库里所有 active 主干规则静默归档。
151
+ // 只有显式 allowEmpty 才允许这么做(目前没有调用方传)。
152
+ return {
153
+ ok: false,
154
+ reason: prevChecksum
155
+ ? "AGENTS.md 里解析到 0 条 §1 规则,已拒绝同步以保护现有主干索引;请检查文件格式。"
156
+ : "§1 主干下没有解析到规则条目(格式应为 `- **§1-x-x 标题**:正文`)",
157
+ path: agentsPath,
158
+ ruleCount: 0,
159
+ };
160
+ }
161
+
162
+ const scope = opts.scope ?? "user";
163
+ let added = 0;
164
+ let updated = 0;
165
+ let unchanged = 0;
166
+ let restored = 0;
167
+ const seen = new Set();
168
+ let archived = 0;
169
+
170
+ const seenUids = new Set();
171
+ for (const r of parsed.rules) {
172
+ if (seenUids.has(r.uid)) {
173
+ return { ok: false, path: agentsPath, checksum: fileChecksum, rules: parsed.rules.length, error: "AGENTS.md 里编号重复:" + r.uid };
174
+ }
175
+ seenUids.add(r.uid);
176
+ }
177
+
178
+ tx(store.db, () => {
179
+ for (const r of parsed.rules) {
180
+ seen.add(r.uid);
181
+ const existing = store.get(r.uid);
182
+ if (existing && (existing.layer !== "trunk" || existing.scope !== scope)) {
183
+ throw new Error("编号 " + r.uid + " 已被非主干条目占用,拒绝同步");
184
+ }
185
+ const source = "AGENTS.md#L" + r.startLine + "-L" + r.endLine;
186
+ const tags = ["主干", r.group];
187
+ if (existing) {
188
+ if (existing.checksum === checksum(r.text)) {
189
+ unchanged += 1;
190
+ // 文件里仍在的规则就是 active;如果副本被归档/取代,按文件恢复,
191
+ // 避免「看板显示已归档、DSH 每轮还在执行这条规则」的不一致。
192
+ if (existing.status !== "active") {
193
+ store.db
194
+ .prepare("UPDATE node SET status='active', superseded_by=NULL, updated_at=? WHERE id=?")
195
+ .run(store.now(), existing.id);
196
+ store.revision("trunk:restored", existing.id, existing.uid, { source });
197
+ bumpIndexVersion(store.db);
198
+ restored += 1;
199
+ }
200
+ // 行号可能变了,顺手修正 source(不产生新版本)
201
+ if (existing.source !== source || existing.subject !== r.group) {
202
+ store.db.prepare("UPDATE node SET source=?, subject=?, updated_at=? WHERE id=?").run(source, r.group, store.now(), existing.id);
203
+ }
204
+ continue;
205
+ }
206
+ store.update(
207
+ existing.id,
208
+ {
209
+ text: r.text,
210
+ title: truncate(r.title, 80),
211
+ subject: r.group,
212
+ tags,
213
+ source,
214
+ evidence: r.text,
215
+ status: "active",
216
+ importance: 0.9,
217
+ trust: 100,
218
+ },
219
+ { allowActiveTrunk: true, skipRedact: true },
220
+ );
221
+ updated += 1;
222
+ continue;
223
+ }
224
+ store.add({
225
+ uid: r.uid,
226
+ scope,
227
+ layer: "trunk",
228
+ kind: "rule",
229
+ status: "active",
230
+ subject: r.group,
231
+ title: truncate(r.title, 80),
232
+ text: r.text,
233
+ tags,
234
+ source,
235
+ evidence: r.text,
236
+ importance: 0.9,
237
+ trust: 100,
238
+ halfLifeDays: 0,
239
+ skipRedact: true,
240
+ });
241
+ added += 1;
242
+ }
243
+
244
+ // 文件里已不存在的旧规则 → 归档(不硬删,保留可追溯)
245
+ const stale = store.db.prepare("SELECT id,uid,source FROM node WHERE layer='trunk' AND status='active' AND scope=?").all(scope);
246
+ for (const n of stale) {
247
+ if (!String(n.source || "").startsWith("AGENTS.md")) continue;
248
+ if (seen.has(n.uid)) continue;
249
+ store.db.prepare("UPDATE node SET status='archived', updated_at=? WHERE id=?").run(store.now(), n.id);
250
+ store.db.prepare("DELETE FROM trunk_bucket WHERE uid=?").run(n.uid);
251
+ store.revision("trunk:removed", n.id, n.uid, { source: n.source });
252
+ archived += 1;
253
+ }
254
+
255
+ setMeta(store.db, "agents_checksum", fileChecksum);
256
+ setMeta(store.db, "agents_sync_at", String(store.now()));
257
+ setMeta(store.db, "agents_path", agentsPath);
258
+ setMeta(store.db, "agents_rules", String(parsed.rules.length));
259
+ store.audit("ingest", {
260
+ scope,
261
+ query: agentsPath,
262
+ hits: parsed.rules.length,
263
+ detail: { added, updated, unchanged, restored, archived, changed: prevChecksum !== fileChecksum },
264
+ });
265
+ });
266
+ return {
267
+ ok: true,
268
+ path: agentsPath,
269
+ checksum: fileChecksum,
270
+ changed: prevChecksum !== fileChecksum,
271
+ rules: parsed.rules.length,
272
+ added,
273
+ updated,
274
+ unchanged,
275
+ restored,
276
+ archived,
277
+ groups: Array.from(new Set(parsed.rules.map((r) => r.group))),
278
+ };
279
+ }
package/lib/levels.mjs ADDED
@@ -0,0 +1,40 @@
1
+ // lib/levels.mjs — 信任程度的六档中文名与数值映射。
2
+ //
3
+ // 界面只显示中文;数字只存在于库里,用来排序与提升候选。
4
+ // 「待定修复」「忽略删除」是标记,不会自动删除任何条目。
5
+
6
+ export const TRUST_LEVELS = [
7
+ { key: "core", label: "信任核心", trust: 100 },
8
+ { key: "high", label: "高等信任", trust: 90 },
9
+ { key: "mid", label: "中等信任", trust: 80 },
10
+ { key: "low", label: "低等信任", trust: 60 },
11
+ { key: "pending", label: "待定修复", trust: 40 },
12
+ { key: "ignore", label: "忽略删除", trust: 10 },
13
+ ];
14
+
15
+ function nearest(list, value, field) {
16
+ let best = list[0];
17
+ let gap = Infinity;
18
+ for (const level of list) {
19
+ const d = Math.abs(Number(level[field]) - Number(value));
20
+ if (d < gap) {
21
+ gap = d;
22
+ best = level;
23
+ }
24
+ }
25
+ return best;
26
+ }
27
+
28
+ export function trustLevel(value) {
29
+ return nearest(TRUST_LEVELS, Number(value ?? 0), "trust");
30
+ }
31
+
32
+ export function trustByKey(key) {
33
+ return TRUST_LEVELS.find((l) => l.key === String(key)) || null;
34
+ }
35
+
36
+ /** 候选条目:信任选到「中等信任」或更高,自动转正式。 */
37
+ export function shouldPromoteByTrust(key) {
38
+ const i = TRUST_LEVELS.findIndex((l) => l.key === String(key));
39
+ return i >= 0 && i <= 2;
40
+ }
package/lib/paths.mjs ADDED
@@ -0,0 +1,85 @@
1
+ // lib/paths.mjs — 路径解析:全部跨平台,不写死 D:\ 或 C:\。
2
+ //
3
+ // 设计取舍:
4
+ // - 数据默认放 <DSH_HOME>/memory-tree,而不是插件目录(插件目录更新会被替换)。
5
+ // - 备份脚本会把 memories.db 备份走;新库放在同一棵 DSH_HOME 下,用户加一条备份规则即可。
6
+ // - 任何路径都允许被行 config / config.json 覆盖,方便测试与多实例。
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+
10
+ export function dshHome(env = process.env) {
11
+ const v = env.DSH_HOME;
12
+ return v !== undefined && String(v).trim() !== "" ? String(v).trim() : path.join(os.homedir(), ".dsh");
13
+ }
14
+
15
+ /** 展开 ~ 与 %VAR%(Windows)/$VAR;不展开不存在的变量,原样保留。 */
16
+ export function expandPath(p, env = process.env) {
17
+ let s = String(p ?? "").trim();
18
+ if (s === "") return "";
19
+ if (s === "~") return os.homedir();
20
+ if (s.startsWith("~/") || s.startsWith("~\\")) s = path.join(os.homedir(), s.slice(2));
21
+ s = s.replace(/%([A-Za-z_][A-Za-z0-9_]*)%/g, (m, name) => (env[name] !== undefined ? String(env[name]) : m));
22
+ s = s.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (m, a, b) => {
23
+ const name = a ?? b;
24
+ return env[name] !== undefined ? String(env[name]) : m;
25
+ });
26
+ return s;
27
+ }
28
+
29
+ /**
30
+ * 解析插件用到的全部路径。
31
+ * config 优先级(由调用方合并):行 config > <dataDir>/config.json > 默认。
32
+ */
33
+ export function resolvePaths(config = {}, env = process.env) {
34
+ const home = dshHome(env);
35
+ const dataDirRaw = expandPath(config.dataDir, env);
36
+ const dataDir = path.resolve(dataDirRaw !== "" ? dataDirRaw : path.join(home, "memory-tree"));
37
+ const dbFile = path.resolve(expandPath(config.dbFile, env) || path.join(dataDir, "memory.db"));
38
+ const agentsRaw = expandPath(config.agentsPath, env);
39
+ const agentsPath = path.resolve(agentsRaw !== "" ? agentsRaw : path.join(home, "AGENTS.md"));
40
+ const legacyRaw = expandPath(config.legacyDb, env);
41
+ const legacyDb = path.resolve(legacyRaw !== "" ? legacyRaw : path.join(home, "remembers-data", "memories.db"));
42
+ const backupRaw = expandPath(config.backupDir, env);
43
+ const backupDir = path.resolve(backupRaw !== "" ? backupRaw : path.join(dataDir, "backups"));
44
+ const rootArchive = expandPath(config.rootArchive, env);
45
+ const rootCold = expandPath(config.rootCold, env);
46
+ const boardCwdRaw = expandPath(config.boardCwd, env);
47
+ const boardCwd = boardCwdRaw !== "" ? path.resolve(boardCwdRaw) : "";
48
+ return {
49
+ home,
50
+ dataDir,
51
+ dbFile,
52
+ agentsPath,
53
+ legacyDb,
54
+ backupDir,
55
+ boardCwd,
56
+ rootArchive,
57
+ rootCold,
58
+ configFile: path.join(dataDir, "config.json"),
59
+ exportDir: path.join(dataDir, "exports"),
60
+ reportFile: path.join(dataDir, "report.html"),
61
+ };
62
+ }
63
+
64
+ /** scope 的稳定名字:workspace 用 cwd 的短哈希,避免路径里的用户名/盘符进入字符串比较。 */
65
+ import { createHash } from "node:crypto";
66
+
67
+ export function workspaceScope(cwd) {
68
+ const p = String(cwd ?? "").trim();
69
+ if (p === "") return "workspace:unknown";
70
+ const base = p.replace(/\\/g, "/").replace(/\/+$/, "");
71
+ // Windows / macOS 默认大小写不敏感,统一小写避免同一目录两个 scope;Linux 保留大小写。
72
+ const norm = process.platform === "win32" || process.platform === "darwin" ? base.toLowerCase() : base;
73
+ const h = createHash("sha1").update(norm).digest("hex").slice(0, 10);
74
+ return "workspace:" + h;
75
+ }
76
+
77
+ export function scopeLabel(scope, cwdMap = {}) {
78
+ const s = String(scope ?? "");
79
+ if (s === "user") return "user(全局)";
80
+ if (s.startsWith("workspace:")) {
81
+ const name = cwdMap[s];
82
+ return name ? "workspace(" + name + ")" : s;
83
+ }
84
+ return s;
85
+ }