@modusensus/dsh-mneme 0.8.16 → 0.9.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.
Files changed (73) hide show
  1. package/README.md +16 -3
  2. package/assets/icon.svg +2 -2
  3. package/docs/CONFIGURATION.md +2 -1
  4. package/docs/CONTINUITY.md +18 -3
  5. package/docs/WORKFLOWS.md +299 -0
  6. package/lib/api.js +124 -8
  7. package/lib/candidates.js +454 -0
  8. package/lib/capabilities.js +819 -0
  9. package/lib/client.js +1703 -182
  10. package/lib/config.js +31 -5
  11. package/lib/continuity.js +35 -6
  12. package/lib/dream/decisions.js +17 -1
  13. package/lib/dream/sleep.js +10 -2
  14. package/lib/dream.js +5 -1
  15. package/lib/entities/extractor.js +4 -0
  16. package/lib/index.js +49 -12
  17. package/lib/inject.js +6 -1
  18. package/lib/pipeline.js +534 -0
  19. package/lib/scope.js +16 -4
  20. package/lib/serve.js +1 -1
  21. package/lib/service.js +59 -18
  22. package/lib/session-usage.js +350 -0
  23. package/lib/settings.js +7 -1
  24. package/lib/store.js +55 -3
  25. package/lib/summarize.js +31 -0
  26. package/lib/tools.js +11 -2
  27. package/package.json +1 -1
  28. package/scripts/publish-gate.mjs +197 -0
  29. package/src/api.js +124 -8
  30. package/src/candidates.js +454 -0
  31. package/src/capabilities.js +819 -0
  32. package/src/config.js +31 -5
  33. package/src/continuity.js +35 -6
  34. package/src/dream/decisions.js +17 -1
  35. package/src/dream/sleep.js +10 -2
  36. package/src/dream.js +5 -1
  37. package/src/entities/extractor.js +4 -0
  38. package/src/index.js +49 -12
  39. package/src/inject.js +6 -1
  40. package/src/pipeline.js +534 -0
  41. package/src/scope.js +16 -4
  42. package/src/serve.js +1 -1
  43. package/src/service.js +59 -18
  44. package/src/session-usage.js +350 -0
  45. package/src/settings.js +7 -1
  46. package/src/store.js +55 -3
  47. package/src/summarize.js +31 -0
  48. package/src/tools.js +11 -2
  49. package/test/api.test.js +147 -7
  50. package/test/candidates.test.js +345 -0
  51. package/test/capabilities.test.js +577 -0
  52. package/test/client.test.js +361 -2
  53. package/test/continuity.test.js +84 -0
  54. package/test/embed-ready-poll.test.js +94 -0
  55. package/test/entities.test.js +13 -2
  56. package/test/failure-query.test.js +147 -0
  57. package/test/failure-retention.test.js +105 -0
  58. package/test/graph-api.test.js +36 -2
  59. package/test/inject-recall.test.js +32 -4
  60. package/test/llm-audit.test.js +92 -1
  61. package/test/mint-source.test.js +202 -0
  62. package/test/pipeline.test.js +505 -0
  63. package/test/placement.test.js +1 -1
  64. package/test/publish-gate.test.js +272 -0
  65. package/test/recall-retention.test.js +128 -0
  66. package/test/release-workflow.test.js +77 -0
  67. package/test/scope-distill-stamp.test.js +135 -0
  68. package/test/serve.test.js +1 -1
  69. package/test/session-usage.test.js +308 -0
  70. package/test/store-write-path-columns.test.js +191 -0
  71. package/test/summarize.test.js +176 -0
  72. package/test/supersede-state-tracking.test.js +4 -4
  73. package/test/tools.test.js +16 -1
@@ -0,0 +1,454 @@
1
+ /**
2
+ * M.O. 候选层(candidates):图上没有的路走过之后,先落在这里。
3
+ *
4
+ * 为什么要有这一层(设计约定,见 docs/WORKFLOWS.md 与本地形状草稿):
5
+ * 一张只会被照着走的图,会让 agent 失去自主性——它要么沉默地服从,要么沉默地偏离。
6
+ * 所以图上必须留一个**合法的出口**:agent 可以判断「这条路这次可能不对」,
7
+ * 按风险档选择记账先走(R0/R1)或停下问人(R2/R3)。
8
+ * 走出来的那段路**不直接进仓库**,而是先变成这里的候选。
9
+ *
10
+ * 三层的关系,一句话:
11
+ * 绕行 → 候选(本文件,住本地) → 定稿(<项目>/.mneme/pipelines/,进仓库)
12
+ * 候选是定稿的**唯一入口**,而定稿只放人亲手批过的东西。
13
+ *
14
+ * 为什么候选不进仓库:
15
+ * 它是草稿,一天可能长十条、死掉九条;进仓库就是垃圾,也会被当成规程引用。
16
+ * 它的生命周期(没被再走到就归档)和记忆条目(留痕)本来就不同。
17
+ *
18
+ * 为什么候选的校验比定稿松:
19
+ * 草稿本来就该是松的。定稿那边的 validatePipeline 要求 id/name/project/version/status/
20
+ * done/trigger 与每一步的 phase/when/do/done/why 一个不缺——那是「要跑的东西」的标准。
21
+ * 候选只有「一段走通了的路 + 为什么」,缺的字段在**升格那一刻**才补齐,
22
+ * 并且补齐后照样要过 validatePipeline 那一关(见 promoteCandidate)。
23
+ */
24
+ import { readFileSync, readdirSync, existsSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
25
+ import { createHash } from "node:crypto";
26
+ import { dirname, join } from "node:path";
27
+ import { homedir } from "node:os";
28
+ import { validatePipeline, RISK_LEVELS } from "./pipeline.js";
29
+
30
+ /** 候选的状态机。`collecting` 还在攒次数,`proposed` 够格了在等人点头。 */
31
+ export const CANDIDATE_STATUSES = ["collecting", "proposed", "promoted", "dropped"];
32
+
33
+ /** 升格门槛:走过两次才算「不是偶然」——这条来自「复用第二次才算类型,第一次只是实例」。 */
34
+ export const PROMOTE_MIN_SEEN = 2;
35
+
36
+ /** 只走过一次、且这么久没再被走到 → 归档。归档不删文件,留着当负清单的邻居。 */
37
+ export const STALE_AFTER_DAYS = 30;
38
+
39
+ /**
40
+ * 风险档的来源。自报是必须的,但**不能只靠自报**:
41
+ * 「模型在自己上下文里给自己打分,会漏掉自己绝大多数错误」——
42
+ * 所以除风险档之外还有一份机械的、可按字节审计的兜底清单(见 IRREVERSIBLE_PATTERNS)。
43
+ */
44
+ export const RISK_SOURCES = ["self", "blacklist"];
45
+
46
+ /**
47
+ * 不可逆/对外动作的**机械兜底清单**:绕行动作里只要命中任何一条,
48
+ * 一律按最高档(R2)处理、停下问人,**不看它自报了什么风险档**。
49
+ *
50
+ * 为什么是清单而不是「让模型再判一次」:
51
+ * 清单可以审计、可以 diff、可以事后追责;再判一次只是把同一个错误问两遍。
52
+ * 判定只看**命令/工具调用的原文**(大小写与多余空白归一后做子串匹配),
53
+ * 这是一条纯函数,不依赖任何模型判断。
54
+ *
55
+ * ⚠️ 两个坑,都在第一次冒烟里现形过:
56
+ *
57
+ * **其一,必须看子命令,不能只看工具名。** `gh pr` 既可能是 `view` / `list` / `checks`
58
+ * (只读,随便跑),也可能是 `create` / `merge` / `close`(对外,必须拦)——差一个子命令,
59
+ * 性质完全相反。第一版把 `gh pr` 整条写成 `requires`,结果「看一眼 PR」也被拦下了。
60
+ * 所以条目拆成三层:`commands`(工具名)、`requires`(要求出现的子命令)、
61
+ * `forbids`(出现就排除,用于兜住 `view`/`list` 这类只读子命令)。
62
+ *
63
+ * **其二,宁可漏报也不误报。** 误报会把只读绕行也推给人,直接毁掉「自主性住在 R0/R1」。
64
+ * 所以每条只认准自己那个动作的词形,不做宽泛匹配。
65
+ *
66
+ * 这份清单是**准入判据**的一部分,改动要走 PR:加条目容易,删条目要能说清为什么。
67
+ */
68
+ export const IRREVERSIBLE_PATTERNS = [
69
+ // ── 推送与远端分支 ──────────────────────────────────────────────
70
+ { id: "git-push", commands: ["git push"], why: "推到远端即离开本机(含 --tags / --force)" },
71
+ // 轻量 tag 也是写(`git tag v1.0` 不带任何参数)——所以用 forbids 列**只读**特征,
72
+ // 默认拦。第一版写成 requires:["-a","-s","-d","-f","-m"],结果 `git tag v1.0.0` 漏过去了。
73
+ { id: "git-tag-write", commands: ["git tag"], forbids: ["-l", "--list", "-n ", "-v ", "--verify"], why: "打 tag 是发布链的入口" },
74
+ // ── GitHub ─────────────────────────────────────────────────────
75
+ // 只读子命令明确排除;其余按写处理(`gh pr` 后面接的不是已知只读词,就当它要写)。
76
+ { id: "gh-pr-write", commands: ["gh pr"], forbids: ["view", "list", "checks", "diff", "status"], why: "开/改/合 PR 是对外动作" },
77
+ { id: "gh-release-write", commands: ["gh release"], forbids: ["view", "list"], why: "发 Release 是对外发布" },
78
+ { id: "gh-issue-write", commands: ["gh issue"], forbids: ["view", "list", "status"], why: "提/改 issue 是对外说话" },
79
+ // `gh api` 的默认是 GET(只读)——**不写方法就放行**,所以这条必须用 requires:
80
+ // 只有显式写出写方法才拦。用 forbids 表达不了「默认安全」这件事(不写方法时两个特征
81
+ // 都不出现,forbids 不成立、规则照样命中,于是只读调用被误拦)。
82
+ // 教训:**requires 表达「必须出现才算数」,forbids 表达「出现就排除」——
83
+ // 对「默认安全、显式才危险」的动作只能用 requires。**
84
+ { id: "gh-api-write", commands: ["gh api"], requires: ["-x post", "-x put", "-x patch", "-x delete", "-f ", "--field", "--input", "-x post"], why: "gh api 默认 GET 只读,显式写方法与字段才算写" },
85
+ { id: "gh-workflow-run", commands: ["gh workflow run"], why: "触发工作流(可能发布)" },
86
+ { id: "gh-repo-write", commands: ["gh repo"], forbids: ["view", "list"], why: "改仓库设置" },
87
+ // ── 发布 ───────────────────────────────────────────────────────
88
+ { id: "npm-publish", commands: ["npm publish"], why: "registry 不允许覆盖已发布版本" },
89
+ { id: "yarn-publish", commands: ["yarn publish"], why: "同上" },
90
+ { id: "pnpm-publish", commands: ["pnpm publish"], why: "同上" },
91
+ // ── 对外写请求 ─────────────────────────────────────────────────
92
+ { id: "curl-write", commands: ["curl"], requires: ["-x post", "-x put", "-x patch", "-x delete", "--request post", "--request put", "--request patch", "--request delete", "--data", "-d "], why: "对外写请求" },
93
+ { id: "wget-post", commands: ["wget"], requires: ["--post-data", "--post-file"], why: "对外写请求" },
94
+ // ── 凭据与权限 ─────────────────────────────────────────────────
95
+ { id: "gh-secret", commands: ["gh secret"], why: "改凭据" },
96
+ { id: "gh-auth-write", commands: ["gh auth"], forbids: ["status", "token"], why: "改鉴权身份(status/token 是只读)" },
97
+ // ── 破坏性删除 ─────────────────────────────────────────────────
98
+ { id: "rm-rf", commands: ["rm -rf", "rm -fr"], why: "不可逆删除" },
99
+ { id: "rmdir-recursive", commands: ["rmdir /s"], why: "Windows 递归删除" },
100
+ { id: "remove-item-recurse", commands: ["remove-item"], requires: ["-recurse"], why: "PowerShell 递归删除" },
101
+ { id: "drop-table", commands: ["drop table"], why: "删数据" }
102
+ ];
103
+
104
+ function normCommand(text) {
105
+ return String(text == null ? "" : text).replace(/\s+/g, " ").trim().toLowerCase();
106
+ }
107
+
108
+ /** 单条规则是否命中:工具名要出现,`requires` 至少一个要出现,`forbids` 一个都不许出现。 */
109
+ function matchesPattern(text, entry) {
110
+ const commands = Array.isArray(entry.commands) ? entry.commands : [entry.commands];
111
+ if (!commands.some((c) => text.includes(normCommand(c)))) return false;
112
+ if (Array.isArray(entry.forbids) && entry.forbids.some((f) => text.includes(normCommand(f)))) return false;
113
+ if (Array.isArray(entry.requires) && !entry.requires.some((r) => text.includes(normCommand(r)))) return false;
114
+ return true;
115
+ }
116
+
117
+ /**
118
+ * 扫一段绕行动作里有没有不可逆/对外的信号。
119
+ * @returns {{hit: boolean, matches: Array<{id: string, why: string}>}}
120
+ */
121
+ export function scanIrreversible(actions) {
122
+ const list = Array.isArray(actions) ? actions : [actions];
123
+ const matches = [];
124
+ for (const raw of list) {
125
+ const text = normCommand(typeof raw === "string" ? raw : raw && (raw.command || raw.tool));
126
+ if (!text) continue;
127
+ for (const entry of IRREVERSIBLE_PATTERNS) {
128
+ if (matchesPattern(text, entry) && !matches.some((m) => m.id === entry.id)) {
129
+ matches.push({ id: entry.id, why: entry.why });
130
+ }
131
+ }
132
+ }
133
+ return { hit: matches.length > 0, matches };
134
+ }
135
+
136
+ const RISK_ORDER = { R0: 0, R1: 1, R2: 2, R3: 3 };
137
+ const maxRisk = (a, b) => (RISK_ORDER[a] >= RISK_ORDER[b] ? a : b);
138
+
139
+ /**
140
+ * 绕行的分档判定——**这一刀的核心规则**(2026-10-16 定档:B 档)。
141
+ *
142
+ * 自报风险档 ∈ {R0, R1} 且 不跨闸门 且 兜底清单没命中
143
+ * → "model":记账先走(自主性住在这里)
144
+ * 否则
145
+ * → "human":停下等点头(刚性只住在这里)
146
+ *
147
+ * 三条各自独立、都要过:
148
+ * 1. **风险档**:这是自报的,单靠它不够。
149
+ * 2. **兜底清单**:机械匹配,不看自报——自报说 R0 但命令里有 `git push`,照样拦。
150
+ * 这正是「模型给自己打分不可靠」的直接应用,不是不信任,是不给单点。
151
+ * 3. **闸门保护**:这条绕行如果走下去,图上某个 gate 会不会永远不被经过?
152
+ * 会 → 拦住。**与风险档无关**:闸门本来就放在「错了很难撤」的地方,
153
+ * 绕开它等于把安全阀绕掉,哪怕这条绕行本身全是只读动作。
154
+ */
155
+ export function decideDetour({ risk = "R0", actions = [], crossesGate = false } = {}) {
156
+ const selfRisk = RISK_LEVELS.includes(risk) ? risk : "R2"; // 自报非法 → 按最保守的档
157
+ const scan = scanIrreversible(actions);
158
+ const blockedByBlacklist = scan.hit;
159
+ const blockedByGate = crossesGate === true;
160
+ const blockedByRisk = RISK_ORDER[selfRisk] >= RISK_ORDER.R2;
161
+
162
+ const reasons = [];
163
+ if (blockedByRisk) reasons.push(`自报风险档 ${selfRisk}`);
164
+ if (blockedByBlacklist) reasons.push(`兜底清单命中:${scan.matches.map((m) => m.id).join(" / ")}`);
165
+ if (blockedByGate) reasons.push("会让图上的闸门永远不被经过");
166
+
167
+ if (!reasons.length) {
168
+ return {
169
+ decidedBy: "model",
170
+ risk: selfRisk,
171
+ reason: "R0/R1 且不跨闸门、兜底清单未命中:记账先走",
172
+ scan
173
+ };
174
+ }
175
+ // 停下问人时,风险档按「自报与命中项的较高者」记,便于结算卡上看得准。
176
+ const effective = blockedByBlacklist || blockedByGate ? maxRisk(selfRisk, "R2") : selfRisk;
177
+ return { decidedBy: "human", risk: effective, reason: reasons.join(";"), scan };
178
+ }
179
+
180
+ /**
181
+ * 项目根 → 稳定的短键。**不把绝对路径写进文件名**(那里面是本机用户名),
182
+ * 但又要同一个项目每次算到同一个键,所以取「目录名 + 路径哈希前 8 位」。
183
+ */
184
+ export function projectKey(projectRoot) {
185
+ const root = String(projectRoot || "").trim();
186
+ if (root === "") return null;
187
+ const hash = createHash("sha256").update(root).digest("hex").slice(0, 8);
188
+ // 两种分隔符都要认,**不能借 path.basename()**:它跟着运行平台走,posix 上
189
+ // `\` 不是分隔符,一条 Windows 路径会被整条当成文件名——清洗后用户名的残片
190
+ // 就进了目录名(Linux CI 实抓:C--Users-someone-Desktop-dsh-mne)。
191
+ // Windows 腿对这条**结构性看不见**(win32.basename 两种分隔符都认),所以回归锁
192
+ // 只在 ubuntu 矩阵腿上有杀伤力,别因为它在 Windows 上绿就以为它没用。
193
+ const name = (root.split(/[\\/]/).filter((s) => s !== "").pop() || "project")
194
+ .replace(/[^A-Za-z0-9._-]/g, "-")
195
+ .slice(0, 32);
196
+ return `${name}-${hash}`;
197
+ }
198
+
199
+ /** 展开 `~`;候选层跟 `memoryDir` 一样是本地状态,不是仓库内容。 */
200
+ function expandHome(p) {
201
+ const s = String(p || "");
202
+ if (s === "~") return homedir();
203
+ if (s.startsWith("~/") || s.startsWith("~\\")) return join(homedir(), s.slice(2));
204
+ return s;
205
+ }
206
+
207
+ /** 候选层的家:`<memoryDir>/candidates/<项目键>/`。memoryDir 为空时退回默认。 */
208
+ export function candidateDir({ memoryDir, projectRoot } = {}) {
209
+ const base = expandHome(memoryDir && memoryDir.trim() ? memoryDir : "~/.dsh/memory");
210
+ const key = projectKey(projectRoot);
211
+ if (!key) return null;
212
+ return join(base, "candidates", key);
213
+ }
214
+
215
+ /**
216
+ * 候选的形状校验——比定稿松,但**有几个字段一个都不能少**:
217
+ * 没有 reason 的绕行不叫绕行,叫乱走;没有 outcome 的记录没法参与任何判断。
218
+ */
219
+ export function validateCandidate(raw, file = "<candidate>") {
220
+ const problems = [];
221
+ const bad = (msg) => problems.push(msg);
222
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
223
+ return { ok: false, problems: ["顶层必须是一个对象"] };
224
+ }
225
+ if (typeof raw.id !== "string" || !/^cand-[a-z0-9-]{4,64}$/.test(raw.id)) {
226
+ bad("id 必须是 cand- 开头的小写 kebab");
227
+ }
228
+ if (typeof raw.origin !== "string" || !["detour", "manual"].includes(raw.origin)) {
229
+ bad("origin 必须是 detour / manual");
230
+ }
231
+ if (typeof raw.reason !== "string" || raw.reason.trim() === "") {
232
+ // 这条是**硬要求**:写不出「为什么觉得这条路可能不对」,就不是绕行。
233
+ bad("reason 必填——写不出理由就不许绕");
234
+ }
235
+ if (!Array.isArray(raw.steps) || raw.steps.length === 0) {
236
+ bad("steps 至少要有一步");
237
+ } else {
238
+ raw.steps.forEach((s, i) => {
239
+ if (!s || typeof s !== "object") return bad(`steps[${i}] 必须是对象`);
240
+ for (const key of ["title", "when", "do", "done"]) {
241
+ if (typeof s[key] !== "string" || s[key].trim() === "") bad(`steps[${i}].${key} 必须是非空字符串`);
242
+ }
243
+ if (!RISK_LEVELS.includes(s.risk)) bad(`steps[${i}].risk 必须是 ${RISK_LEVELS.join(" / ")}`);
244
+ });
245
+ }
246
+ if (!Array.isArray(raw.seen)) bad("seen 必须是数组(可以为空)");
247
+ if (!CANDIDATE_STATUSES.includes(raw.status)) {
248
+ bad(`status 必须是 ${CANDIDATE_STATUSES.join(" / ")}`);
249
+ }
250
+ return { ok: problems.length === 0, problems, file };
251
+ }
252
+
253
+ /** 一条候选的 id:按「项目 + 步骤形状」定,所以同一段路走两次会落到同一条候选上。 */
254
+ export function candidateId(steps) {
255
+ const shape = (Array.isArray(steps) ? steps : [])
256
+ .map((s) => `${s && s.title ? String(s.title).trim() : ""}`)
257
+ .join(" → ");
258
+ return `cand-${createHash("sha256").update(shape).digest("hex").slice(0, 12)}`;
259
+ }
260
+
261
+ /** 读一个项目下的全部候选;坏文件不静默跳过(与定稿同一纪律)。 */
262
+ export function loadCandidates(dir) {
263
+ if (!dir || !existsSync(dir)) return [];
264
+ const out = [];
265
+ for (const file of readdirSync(dir).filter((f) => f.endsWith(".json")).sort()) {
266
+ let raw;
267
+ try {
268
+ raw = JSON.parse(readFileSync(join(dir, file), "utf8"));
269
+ } catch (error) {
270
+ throw new Error(`${file}: JSON 解析失败:${error.message}`);
271
+ }
272
+ const v = validateCandidate(raw, file);
273
+ if (!v.ok) throw new Error(`${file}: ${v.problems.join("; ")}`);
274
+ out.push(raw);
275
+ }
276
+ return out;
277
+ }
278
+
279
+ /** 写一条候选(幂等:同 id 覆盖,但 seen 会合并去重)。 */
280
+ export function saveCandidate(dir, candidate) {
281
+ if (!dir) throw new Error("candidateDir 为空:拿不到项目根或 memoryDir");
282
+ const v = validateCandidate(candidate);
283
+ if (!v.ok) throw new Error(v.problems.join("; "));
284
+ mkdirSync(dir, { recursive: true });
285
+ writeFileSync(join(dir, `${candidate.id}.json`), JSON.stringify(candidate, null, 2), "utf8");
286
+ return candidate;
287
+ }
288
+
289
+ /**
290
+ * 记一次绕行。两次走同一段路会并进同一条候选——这正是「复用第二次才算类型」的落点。
291
+ * 返回 `{ candidate, created, promotedNow }`。
292
+ */
293
+ export function recordDetour(dir, { steps, reason, outcome = "unknown", evidence = [], runId = null, sessionId = null, now = Date.now() } = {}) {
294
+ const id = candidateId(steps);
295
+ const existing = loadCandidates(dir).find((c) => c.id === id) || null;
296
+ const at = new Date(now).toISOString();
297
+ const entry = { runId, sessionId, at, outcome, evidence: Array.isArray(evidence) ? evidence.slice() : [] };
298
+
299
+ if (!existing) {
300
+ const candidate = {
301
+ id,
302
+ origin: "detour",
303
+ steps: (steps || []).map((s) => ({
304
+ title: s.title, when: s.when, do: s.do, done: s.done, risk: s.risk
305
+ })),
306
+ reason,
307
+ counterfactual: null,
308
+ seen: [entry],
309
+ status: "collecting",
310
+ createdAt: at
311
+ };
312
+ saveCandidate(dir, candidate);
313
+ return { candidate, created: true, promotedNow: false };
314
+ }
315
+
316
+ existing.seen = Array.isArray(existing.seen) ? existing.seen : [];
317
+ existing.seen.push(entry);
318
+ if (!existing.reason && reason) existing.reason = reason;
319
+ const promotedNow = maybePropose(existing);
320
+ saveCandidate(dir, existing);
321
+ return { candidate: existing, created: false, promotedNow };
322
+ }
323
+
324
+ /**
325
+ * 够格就翻成 `proposed`——**只是「够格被提议」,不是「自动进图」**。
326
+ * 两条都要满足:走过两次(且至少一次 worked)、且写得出反事实。
327
+ * 第二条不由代码判断(它是人话),所以这里只翻状态、把缺口标出来,由提议时补齐。
328
+ */
329
+ export function maybePropose(candidate) {
330
+ if (!candidate || candidate.status !== "collecting") return false;
331
+ const seen = Array.isArray(candidate.seen) ? candidate.seen : [];
332
+ const worked = seen.filter((s) => s && s.outcome === "worked").length;
333
+ if (seen.length >= PROMOTE_MIN_SEEN && worked >= 1) {
334
+ candidate.status = "proposed";
335
+ candidate.proposedAt = new Date().toISOString();
336
+ return true;
337
+ }
338
+ return false;
339
+ }
340
+
341
+ /** 长期没被再走到 → 归档。归档**不删文件**(留着当负清单的邻居),只换状态。 */
342
+ export function archiveStale(dir, { now = Date.now(), staleAfterDays = STALE_AFTER_DAYS } = {}) {
343
+ const archived = [];
344
+ for (const c of loadCandidates(dir)) {
345
+ if (c.status !== "collecting") continue;
346
+ const seen = Array.isArray(c.seen) ? c.seen : [];
347
+ if (seen.length >= PROMOTE_MIN_SEEN) continue;
348
+ const last = seen.length ? Date.parse(seen[seen.length - 1].at) : Date.parse(c.createdAt || "");
349
+ if (!Number.isFinite(last)) continue;
350
+ if ((now - last) / 86400000 > staleAfterDays) {
351
+ c.status = "dropped";
352
+ c.droppedReason = `只走过 ${seen.length} 次,${staleAfterDays} 天内没再被走到`;
353
+ saveCandidate(dir, c);
354
+ archived.push(c.id);
355
+ }
356
+ }
357
+ return archived;
358
+ }
359
+
360
+ /**
361
+ * 升格:把候选补成一份**合法的定稿**,但**只返回内容,不写盘**。
362
+ *
363
+ * 为什么不直接写进仓库:提交是 R1、推送是 R2,分开两档,人始终握着一道。
364
+ * 调用方拿到 `{ ok, pipeline, problems }` 之后自己决定怎么落(写文件 + 请人 review + commit)。
365
+ * 补出来的东西照样要过 validatePipeline——**升格不是降低标准,是补齐标准**。
366
+ */
367
+ export function promoteCandidate(candidate, { name, project, done = "", trigger = [], steps = null } = {}) {
368
+ const raw = {
369
+ id: candidate.id.replace(/^cand-/, ""),
370
+ name: name || candidate.reason || candidate.id,
371
+ project: project || "",
372
+ version: 0,
373
+ status: "active",
374
+ done: done || `${candidate.steps.length} 步全部有归属,且每一步的完成判据都被满足`,
375
+ trigger: trigger.length ? trigger : [{ kind: "phrase", value: "走这条路" }],
376
+ steps: (steps || candidate.steps).map((s, i) => ({
377
+ id: s.id || `S${i + 1}`,
378
+ phase: s.phase || "流程",
379
+ title: s.title,
380
+ when: s.when,
381
+ do: s.do,
382
+ who: s.who || "main",
383
+ tool: s.tool || "",
384
+ done: s.done,
385
+ risk: s.risk,
386
+ needs: Array.isArray(s.needs) ? s.needs : (i === 0 ? [] : [`S${i}`]),
387
+ why: s.why || candidate.reason || "",
388
+ // 反事实对照:候选上如果记了就用它——它是**准入判据**,不是备注。
389
+ evidence: s.evidence || (candidate.counterfactual ? [candidate.counterfactual] : []),
390
+ gate: s.gate === true
391
+ }))
392
+ };
393
+ try {
394
+ return { ok: true, pipeline: validatePipeline(raw, candidate.id), problems: [] };
395
+ } catch (error) {
396
+ return { ok: false, pipeline: null, problems: error.problems || [String(error && error.message)] };
397
+ }
398
+ }
399
+
400
+ /** 候选的清单行(面板与 agent 共用的投影,与定稿的 available[] 对齐)。 */
401
+ export function summarizeCandidate(candidate) {
402
+ const seen = Array.isArray(candidate.seen) ? candidate.seen : [];
403
+ const worked = seen.filter((s) => s && s.outcome === "worked").length;
404
+ const failed = seen.filter((s) => s && s.outcome === "failed").length;
405
+ return {
406
+ id: candidate.id,
407
+ title: candidate.steps && candidate.steps[0] ? candidate.steps[0].title : candidate.id,
408
+ origin: candidate.origin,
409
+ reason: candidate.reason,
410
+ status: candidate.status,
411
+ steps: (candidate.steps || []).length,
412
+ // 风险档取这条路上最高的那一档:整段路的「最坏情况」才是它该被看待的档位。
413
+ risk: (candidate.steps || []).reduce((acc, s) => maxRisk(acc, s.risk || "R0"), "R0"),
414
+ seen: seen.length,
415
+ worked,
416
+ failed,
417
+ lastSeenAt: seen.length ? seen[seen.length - 1].at : null,
418
+ counterfactual: candidate.counterfactual || null
419
+ };
420
+ }
421
+
422
+ /** 面板与 agent 的公共入口:一个项目下的候选清单 + 各自的可用动作。 */
423
+ export function readCandidateDoc({ memoryDir, projectRoot, now = Date.now() } = {}) {
424
+ const dir = candidateDir({ memoryDir, projectRoot });
425
+ const items = dir ? loadCandidates(dir).map(summarizeCandidate) : [];
426
+ return {
427
+ contract: "mneme.candidates/v1",
428
+ dir,
429
+ projectKey: projectKey(projectRoot),
430
+ counts: {
431
+ collecting: items.filter((i) => i.status === "collecting").length,
432
+ proposed: items.filter((i) => i.status === "proposed").length,
433
+ promoted: items.filter((i) => i.status === "promoted").length,
434
+ dropped: items.filter((i) => i.status === "dropped").length
435
+ },
436
+ available: items,
437
+ // 「这一刀不做的事」也写进契约里,免得以后有人以为忘了做。
438
+ boundaries: {
439
+ autoPromote: false,
440
+ autoApprove: false,
441
+ injectIntoMemory: false
442
+ }
443
+ };
444
+ }
445
+
446
+ /** 删一条候选:只在人明确要求时用。 */
447
+ export function removeCandidate(dir, id) {
448
+ const p = join(dir, `${id}.json`);
449
+ if (!existsSync(p)) return false;
450
+ rmSync(p, { force: true });
451
+ return true;
452
+ }
453
+
454
+ export { dirname as _dirname };