opencode-growth 0.1.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.
@@ -0,0 +1,245 @@
1
+ // CLI entry logic (S4): parse argv, resolve the store, dispatch, render.
2
+ //
3
+ // The store is REQUIRED (`--store <dir>` or `$OCG_STORE`). There is deliberately no default:
4
+ // a tool that silently picks a store is a tool that will one day publish into the wrong one.
5
+ import process from "node:process"
6
+
7
+ import { layout } from "../core/paths.mjs"
8
+ import { EXIT, fail } from "./envelope.mjs"
9
+ import {
10
+ doctor,
11
+ status,
12
+ candidatesList,
13
+ candidatesPreview,
14
+ candidatesConfirm,
15
+ memoryForget,
16
+ learnRun,
17
+ installCmd,
18
+ uninstallCmd,
19
+ } from "./commands.mjs"
20
+
21
+ const USAGE = `oc-grow — memory, candidates and the review protocol for OpenCode
22
+
23
+ Usage: oc-grow --store <dir> [--json] <command> [args]
24
+
25
+ doctor can this store do its job? (never a green pass when not)
26
+ status what is in effect, what is pending
27
+ candidates list [--state <s>] proposed | validated | published | rejected
28
+ candidates preview <candidateId> show what would become effective; returns a token
29
+ candidates confirm <token> --as <who>
30
+ publish it — requires the token AND a recorded approver
31
+ [--project <id>] [--owner <id>] [--platform <p>]
32
+ memory forget <recordId> [--reason <text>]
33
+ withdraw it; takes effect immediately
34
+ what this session was actually given, and every eviction
35
+ install [--config <dir>] [--dry-run]
36
+ uninstall [--config <dir>]
37
+ write the host plugin file + register D/skills/;
38
+ changes nothing inside D
39
+ learn run [--limit <n>] [--dry-run]
40
+ distil corrections captured since the last pass into
41
+ candidates; never publishes anything
42
+
43
+ Options:
44
+ --store <dir> the store to operate on (or set $OCG_STORE). Required.
45
+ --json machine-readable output; every answer uses one envelope
46
+ --help this text
47
+
48
+ Exit codes: 0 ok · 1 refused · 2 usage · 3 busy · 4 not found · 5 degraded
49
+
50
+ Exit 5 is not a failure of the command but of the store: a capability is missing, and you
51
+ should not read "ok" into it. There is no command that publishes without review.
52
+ `
53
+
54
+ /** Grouped commands need two words; everything else is one. */
55
+ const GROUPS = new Set(["candidates", "memory", "context", "learn"])
56
+
57
+ const COMMANDS = {
58
+ doctor,
59
+ status,
60
+ "candidates list": candidatesList,
61
+ "candidates preview": candidatesPreview,
62
+ "candidates confirm": candidatesConfirm,
63
+ "memory forget": memoryForget,
64
+ "learn run": learnRun,
65
+ install: installCmd,
66
+ uninstall: uninstallCmd,
67
+ }
68
+
69
+ const BOOLEAN_FLAGS = new Set(["json", "help", "dry-run"])
70
+
71
+ /** `--x v` becomes {x: "v"}; a valueless or boolean flag becomes true. */
72
+ export function parseArgv(argv) {
73
+ const positionals = []
74
+ const options = {}
75
+ for (let i = 0; i < argv.length; i += 1) {
76
+ const arg = argv[i]
77
+ if (arg === "--") {
78
+ positionals.push(...argv.slice(i + 1))
79
+ break
80
+ }
81
+ if (!arg.startsWith("--")) {
82
+ positionals.push(arg)
83
+ continue
84
+ }
85
+ const name = arg.slice(2)
86
+ const next = argv[i + 1]
87
+ if (BOOLEAN_FLAGS.has(name) || next === undefined || next.startsWith("--")) {
88
+ options[name] = true
89
+ } else {
90
+ options[name] = next
91
+ i += 1
92
+ }
93
+ }
94
+ return { positionals, options }
95
+ }
96
+
97
+ /** Resolve `candidates preview` from ["candidates", "preview", "cand_1"]. */
98
+ export function resolveCommand(positionals) {
99
+ if (!positionals.length) return { key: null, rest: [] }
100
+ const [first, second, ...tail] = positionals
101
+ if (GROUPS.has(first)) {
102
+ if (!second) return { key: null, rest: [] }
103
+ return { key: `${first} ${second}`, rest: tail }
104
+ }
105
+ return { key: first, rest: [second, ...tail].filter((x) => x !== undefined) }
106
+ }
107
+
108
+ function render(command, env) {
109
+ const d = env.data ?? {}
110
+ switch (command) {
111
+ case "doctor": {
112
+ const bad = (d.checks ?? []).filter((c) => c.status !== "ok")
113
+ const lines = [`doctor: ${d.status} (${d.checks?.length ?? 0} checks, node ${d.node})`]
114
+ for (const c of d.checks ?? []) lines.push(` ${c.status === "ok" ? "ok " : c.status === "degraded" ? "degr" : "FAIL"} ${c.name}`)
115
+ if (bad.length) lines.push(` → ${env.message}`)
116
+ return lines.join("\n")
117
+ }
118
+ case "uninstall":
119
+ return [
120
+ `store ${d.store}`,
121
+ `plugin ${d.pluginDir}`,
122
+ ...(d.report ?? []),
123
+ ].join("\n")
124
+ case "install":
125
+ return [
126
+ `store ${d.store}`,
127
+ `plugin ${d.shim}`,
128
+ `config ${d.configFile}`,
129
+ `skills ${d.skillsPath}`,
130
+ ...(d.plan ?? []).map((l) => ` · ${l}`),
131
+ ].join("\n")
132
+ case "status":
133
+ return [
134
+ `store ${d.store}`,
135
+ `records ${d.records} in effect (generation ${d.generation}, retraction epoch ${d.retractionEpoch})`,
136
+ `candidates ${Object.entries(d.candidates ?? {}).map(([k, v]) => `${k}=${v}`).join(" ") || "none"}`,
137
+ ].join("\n")
138
+ case "candidates.list": {
139
+ if (!d.candidates?.length) return "no candidates"
140
+ return d.candidates.map((c) => ` ${c.status.padEnd(9)} ${c.id} ${c.kind}/${c.semanticKey}`).join("\n")
141
+ }
142
+ case "candidates.preview": {
143
+ // The point of a preview is that a person reads it before typing confirm, so the human
144
+ // output leads with the content and only then mentions the token (audit A14). A preview
145
+ // that shows a digest and asks for a signature asks someone to approve what they cannot see.
146
+ const c = d.candidate ?? {}
147
+ const aw = c.scope?.appliesWhen ?? {}
148
+ const when = Object.values(aw).some((v) => v !== null && v !== undefined)
149
+ ? [` applies when ${JSON.stringify(aw)}`]
150
+ : []
151
+ const projects = c.scope?.scopeProjectIds ?? []
152
+ return [
153
+ `${c.kind ?? "?"} ${c.semanticKey ?? "?"} -> ${d.recordId}${d.expectedContentHash ? ` (content ${String(d.expectedContentHash).slice(0, 8)})` : " (new)"}`,
154
+ ` title: ${c.title ?? ""}`,
155
+ ...String(c.body ?? "").split("\n").map((l) => ` | ${l}`),
156
+ ` scope: governance=${c.scope?.governance ?? "?"}${c.scope?.ownerId ? ` owner=${c.scope.ownerId}` : ""}`,
157
+ ...when,
158
+ ` evidence: ${(c.evidence ?? []).length}`,
159
+ "",
160
+ ` hash ${d.candidateHash}`,
161
+ ` token ${d.token}`,
162
+ ` expires ${new Date(d.expiresAt).toISOString()}`,
163
+ "",
164
+ `to accept: oc-grow candidates confirm ${d.token} --as <who-you-are>`,
165
+ ].join("\n")
166
+ }
167
+ case "candidates.confirm":
168
+ return `published ${d.recordId} @${d.contentHash ?? "?"} (approved by ${d.approvedBy})${d.replayed ? " — replay" : ""}`
169
+ case "memory.explain":
170
+ return d.recalled
171
+ ? `${d.recordId} IS recalled here (${d.kind}, ${d.visibility}, content ${d.contentHash ?? "?"})`
172
+ : `${d.recordId} is NOT recalled here — ${d.reason}`
173
+ case "memory.forget":
174
+ return `${d.recordId} withdrawn (retraction epoch ${d.retractionEpoch})`
175
+ case "learn.run": {
176
+ const lines = [
177
+ `processed ${d.processed} ok ${d.succeeded} failed ${d.failed} skipped ${d.skipped}`,
178
+ `queue offset ${d.offsetBefore ?? d.offset} -> ${d.offsetAfter ?? d.offset} pending ${d.pending ?? 0} torn ${d.torn ?? 0}`,
179
+ ]
180
+ for (const e of d.entries ?? []) {
181
+ lines.push(` ${e.state} ${e.sessionId ?? "(no session)"} ${(e.candidates ?? []).join(",") || "-"}${e.reason ? ` (${e.reason})` : ""}`)
182
+ }
183
+ return lines.join("\n")
184
+ }
185
+ case "context.show":
186
+ return [
187
+ `session ${d.sessionId} state=${d.state}`,
188
+ `injected ${d.injectedHash ?? "(nothing yet)"} ${d.chars} chars / ~${d.tokens} tokens`,
189
+ `admitted ${d.admitted.length} evicted ${d.rejected.length}`,
190
+ ...(d.rejected ?? []).map((r) => ` evicted ${r.id}: ${r.reason}`),
191
+ ].join("\n")
192
+ default:
193
+ return env.message
194
+ }
195
+ }
196
+
197
+ export async function run(argv, env = process.env) {
198
+ const { positionals, options } = parseArgv(argv)
199
+
200
+ if (options.help || positionals.includes("help")) {
201
+ process.stdout.write(USAGE)
202
+ return EXIT.OK
203
+ }
204
+
205
+ const store = options.store ?? (env.OCG_STORE && String(env.OCG_STORE).trim()) ?? null
206
+ const commandWanted = resolveCommand(positionals)
207
+
208
+ if (!commandWanted.key) {
209
+ const result = fail(commandWanted.key ?? "", "USAGE", "no command given — see --help")
210
+ emit(result, Boolean(options.json))
211
+ return result.exit
212
+ }
213
+
214
+ const handler = COMMANDS[commandWanted.key]
215
+ if (!handler) {
216
+ const result = fail(commandWanted.key, "USAGE", `unknown command: ${positionals.join(" ")} — see --help`)
217
+ emit(result, Boolean(options.json))
218
+ return result.exit
219
+ }
220
+
221
+ if (!store) {
222
+ const result = fail(commandWanted.key, "USAGE", "no store: pass --store <dir> or set $OCG_STORE")
223
+ emit(result, Boolean(options.json))
224
+ return result.exit
225
+ }
226
+
227
+ // Deliberately NOT ensureDirs() here. Recreating the layout on every command masks exactly
228
+ // the damage `doctor` exists to report: it would rebuild a missing directory and then pass
229
+ // green on the store it just repaired. The write paths create what they need themselves.
230
+ const L = layout(store)
231
+
232
+ const result = await handler({ ...options, _: commandWanted.rest }, { L })
233
+ emit(result, Boolean(options.json))
234
+ return result.exit
235
+ }
236
+
237
+ function emit(result, asJson) {
238
+ if (asJson) {
239
+ process.stdout.write(JSON.stringify(result.envelope, null, 2) + "\n")
240
+ return
241
+ }
242
+ const body = result.envelope.ok ? render(result.envelope.command, result.envelope) : `${result.envelope.error_code}: ${result.envelope.message}`
243
+ const stream = result.envelope.ok ? process.stdout : process.stderr
244
+ stream.write((body ?? result.envelope.message) + "\n")
245
+ }
@@ -0,0 +1,40 @@
1
+ // Append-only audit (R4 §3.2 step 4). Serialised through the commit lock by callers;
2
+ // this module only guarantees line integrity and crash-tolerant reads.
3
+ import fs from "node:fs"
4
+ import path from "node:path"
5
+ import { nowIso } from "./ids.mjs"
6
+
7
+ function monthFile(L, when = new Date()) {
8
+ const ym = `${when.getUTCFullYear()}-${String(when.getUTCMonth() + 1).padStart(2, "0")}`
9
+ return path.join(L.audit, `${ym}.jsonl`)
10
+ }
11
+
12
+ export function appendAudit(L, event) {
13
+ fs.mkdirSync(L.audit, { recursive: true })
14
+ const line = JSON.stringify({ ts: nowIso(), ...event }) + "\n"
15
+ fs.appendFileSync(monthFile(L), line)
16
+ }
17
+
18
+ /** Tolerates a torn final line (process killed mid-append) by skipping unparsable rows
19
+ * instead of throwing, and reporting how many were skipped. */
20
+ export function readAudit(L, limit = 200) {
21
+ const out = []
22
+ let skipped = 0
23
+ let files = []
24
+ try {
25
+ files = fs.readdirSync(L.audit).filter((f) => f.endsWith(".jsonl")).sort()
26
+ } catch {
27
+ return { events: [], skipped: 0 }
28
+ }
29
+ for (const f of files) {
30
+ for (const line of fs.readFileSync(path.join(L.audit, f), "utf8").split("\n")) {
31
+ if (!line.trim()) continue
32
+ try {
33
+ out.push(JSON.parse(line))
34
+ } catch {
35
+ skipped += 1
36
+ }
37
+ }
38
+ }
39
+ return { events: out.slice(-limit), skipped }
40
+ }
@@ -0,0 +1,261 @@
1
+ import fs from "node:fs"
2
+ import path from "node:path"
3
+
4
+ // 后台复习的调度与有界(照 Hermes agent/background_review.py 的口径)
5
+ // 机制:回合结束触发一次「要不要复习」的检查 → 达阈值才派发 → 一次一个 → 新回合可取消(握手 ≤2s)
6
+ // 判定的三条(机制/触发/判定)都对齐 Hermes,第一版不加自造物。
7
+
8
+ // 有界:迭代上限、输入预算=上下文 75%、封顶 600k、未知窗口 120k、取消握手 2.0s
9
+ export const REVIEW_LIMITS = Object.freeze({
10
+ maxIterations: 16,
11
+ inputContextFraction: 0.75,
12
+ inputCap: 600000,
13
+ unknownWindow: 120000,
14
+ cancelTimeoutMs: 2000,
15
+ })
16
+
17
+ // 阈值:memory 按**用户回合**计数、skills 按**迭代**计数,默认各 10
18
+ export const REVIEW_THRESHOLDS = Object.freeze({ memory: 10, skills: 10 })
19
+
20
+ // 输入预算(照 Hermes `_context_derived_review_input_budget`):
21
+ // · 有窗口 ⇒ min(600k, max(1, floor(window × 75%)))
22
+ // · 窗口未知 ⇒ **直接退回 120k 常量**,不再乘 0.75(Hermes 就是这么返回的)
23
+ export function reviewInputBudget(windowTokens) {
24
+ const known = Number.isFinite(windowTokens) && windowTokens > 0
25
+ if (!known) return REVIEW_LIMITS.unknownWindow
26
+ return Math.min(Math.max(1, Math.floor(windowTokens * REVIEW_LIMITS.inputContextFraction)), REVIEW_LIMITS.inputCap)
27
+ }
28
+
29
+ // 输入面:同模型路径吃**整份回合会话**;只有换模型才退化为「最近 24 条 + 更早折叠」,且必须标注
30
+ export function planReviewInput({ messages = [], isSameModel = true } = {}) {
31
+ const all = Array.isArray(messages) ? messages.slice() : []
32
+ if (isSameModel) return { messages: all, degraded: false, collapsed: 0, note: null }
33
+ const tail = all.slice(-24)
34
+ const collapsed = Math.max(0, all.length - tail.length)
35
+ return {
36
+ messages: tail,
37
+ degraded: true,
38
+ collapsed,
39
+ note: collapsed > 0 ? "换了模型:只喂最近 24 条,更早的 " + collapsed + " 条已折叠(降级)" : "换了模型:只喂最近 24 条(降级)",
40
+ }
41
+ }
42
+
43
+ export function createReviewScheduler({
44
+ dispatch,
45
+ interrupt = null,
46
+ thresholds = REVIEW_THRESHOLDS,
47
+ now = () => Date.now(),
48
+ // C③:**工具可用性前置**(照 Hermes)。mem 记 memory 工具、skills 记宿主 skill 工具;
49
+ // 值只认 true(可用)/ false(明确不可用)/ null(未知 —— 也当不可用,fail-closed)。
50
+ //
51
+ // 默认给 true 的理由(写清楚,免得后人当疏漏):Hermes 那边 `valid_tool_names` 在运行期
52
+ // **总是**有值(`turn_context.py:675` 直接成员测试);"未知"这个态只在我们这边出现。
53
+ // 生产路径上,适配器**必须显式传**它从宿主工具表读到的值(`review-runner` 负责),
54
+ // 这条由 C③ 检查器断言;默认值只是让库在不传时不至于把功能整个关掉。
55
+ toolsAvailable = { memory: true, skills: true },
56
+ } = {}) {
57
+ if (typeof dispatch !== "function") throw new TypeError("createReviewScheduler 需要 dispatch 函数")
58
+ let userTurns = 0
59
+ let iterations = 0
60
+ let inFlight = null
61
+ let inflightKind = null
62
+ const available = (what) => (what === true)
63
+
64
+ // 阈值判定同样带前置(照 `turn_finalizer.py:629` 那三行)。
65
+ const pick = () => {
66
+ if (available(toolsAvailable.memory) && thresholds.memory > 0 && userTurns >= thresholds.memory) return { kind: "memory" }
67
+ if (available(toolsAvailable.skills) && thresholds.skills > 0 && iterations >= thresholds.skills) return { kind: "skills" }
68
+ return null
69
+ }
70
+
71
+ return {
72
+ // 照 `turn_context.py:675 _tick_memory_nudge`:只在 interval>0 且**对应工具在可用名单里**时前进。
73
+ noteUserTurn({ memoryTool = toolsAvailable.memory } = {}) {
74
+ if (!(thresholds.memory > 0)) return userTurns
75
+ if (!available(memoryTool)) return userTurns
76
+ userTurns += 1
77
+ return userTurns
78
+ },
79
+ // 照 `turn_iteration_prep.py:121`:只在 skill 工具可用时按**工具调用迭代**前进;
80
+ // 且**用过 skill 就重置**(Hermes 注释原文:"resets whenever skill_manage is used")。
81
+ noteIteration({ skillTool = toolsAvailable.skills, skillUsed = false } = {}) {
82
+ if (!(thresholds.skills > 0)) return iterations
83
+ if (skillUsed) { iterations = 0; return iterations }
84
+ if (!available(skillTool)) return iterations
85
+ iterations += 1
86
+ return iterations
87
+ },
88
+ counters() { return { userTurns, iterations } },
89
+ busy() { return inFlight !== null },
90
+ // 回合结束时的检查点:达阈值且不在跑 ⇒ 派发;否则如实说为什么没派发
91
+ async maybeDispatch() {
92
+ if (inFlight !== null) return { dispatched: false, reason: "busy" }
93
+ const job = pick()
94
+ if (!job) return { dispatched: false, reason: "below-threshold" }
95
+ if (job.kind === "memory") userTurns = 0
96
+ else iterations = 0
97
+ inflightKind = job.kind
98
+ inFlight = Promise.resolve()
99
+ .then(() => dispatch({ kind: job.kind }))
100
+ .finally(() => { inFlight = null; inflightKind = null })
101
+ // 把在跑的作业一并交出去:调用方(回合结束/测试)可以选择等它落地
102
+ return { dispatched: true, kind: job.kind, pending: inFlight }
103
+ },
104
+ // 取消握手:新回合来时而有的动作。等 ≤2s;没等到就放弃(等它自己跑完),并如实返回
105
+ async cancel(reason = "foreground-turn") {
106
+ if (inFlight === null) return { cancelled: false, reason: "idle", waitedMs: 0, kind: null, interrupted: false }
107
+ // 照 Hermes:取消是**真中断**(run.cancel()),不是干等它跑完;中断后仍握手 ≤2s
108
+ let interrupted = false
109
+ if (typeof interrupt === "function") {
110
+ try { interrupt(); interrupted = true } catch { interrupted = false }
111
+ }
112
+ const t0 = now()
113
+ const kind = inflightKind
114
+ const timedOut = Symbol("timeout")
115
+ let timer
116
+ const timeout = new Promise((res) => { timer = setTimeout(() => res(timedOut), REVIEW_LIMITS.cancelTimeoutMs) })
117
+ const settled = await Promise.race([inFlight.then(() => "done").catch(() => "done"), timeout])
118
+ clearTimeout(timer)
119
+ const waitedMs = now() - t0
120
+ if (settled === timedOut) return { cancelled: false, reason: "timeout", waitedMs, kind, interrupted }
121
+ return { cancelled: true, reason, waitedMs, kind, interrupted }
122
+ },
123
+ }
124
+ }
125
+
126
+ // 硬不变量(照 Hermes background_review.py:647-649 proposal_staged):
127
+ // 后台复习里,**破坏性**操作(改/删既有条目)永不直写,一律进提案;**新增**直接写。
128
+ // 而且提案**必须浮出**到人眼前(一行可读提示),不许悄悄堆在磁盘上。
129
+ export const DESTRUCTIVE_OPS = Object.freeze(["remove", "update"])
130
+ // A137:动作是**闭集**——只有我们提示词里定下的三类。闭集外的一律"没看懂",
131
+ // 既不直写也不当提案(`delete:` 这种拼写变体不许变成一次写入)。
132
+ export const REVIEW_OPS = Object.freeze(["add", "update", "remove"])
133
+ export const PROPOSAL_ORIGIN = "background"
134
+
135
+ // A137:改造/删除必须能**唯一定位**目标条目(照 `memories.mjs` 的命中口径:唯一/未命中/歧义)。
136
+ // 提案带着它,人才知道"这条提案要动的是哪一条"。
137
+ export function matchEntry({ entries = [], needle = "" } = {}) {
138
+ const n = String(needle ?? "").trim()
139
+ if (!n) return { status: "none", reason: "empty-match", candidates: [] }
140
+ const hits = entries.filter((e) => String(e).includes(n))
141
+ if (hits.length === 1) return { status: "unique", entry: hits[0], candidates: hits }
142
+ if (hits.length === 0) return { status: "none", candidates: [] }
143
+ return { status: "ambiguous", candidates: hits }
144
+ }
145
+
146
+ export function classifyReviewOutcome({ actions = [], entries = null } = {}) {
147
+ const direct = []
148
+ const proposals = []
149
+ const ignored = []
150
+ for (const a of actions) {
151
+ if (!a || typeof a.op !== "string") continue
152
+ if (!REVIEW_OPS.includes(a.op)) {
153
+ ignored.push({ op: a.op, text: a.text, reason: "unknown-op" })
154
+ continue
155
+ }
156
+ if (DESTRUCTIVE_OPS.includes(a.op)) {
157
+ // 提案必须能定位目标:entries 没给就如实标 unknown(不许假装定位过)
158
+ const match = entries ? matchEntry({ entries, needle: a.text }) : { status: "unknown", reason: "no-entries" }
159
+ proposals.push({ op: a.op, kind: a.kind, text: a.text, match, origin: PROPOSAL_ORIGIN, label: "[auto]" })
160
+ } else {
161
+ direct.push({ op: a.op, kind: a.kind, text: a.text })
162
+ }
163
+ }
164
+ return { direct, proposals, ignored, mustSurface: proposals.length > 0 }
165
+ }
166
+
167
+ // 浮出行:人扫一眼就知道"后台替你攒了几条待批、它们不是你自己提的"
168
+ export function surfaceLine({ proposals = [], ignored = [] } = {}) {
169
+ if (!proposals.length && !ignored.length) return null
170
+ const parts = []
171
+ if (proposals.length) {
172
+ const kinds = proposals.map((p) => p.op).join("/")
173
+ parts.push("后台复习:攒了 " + proposals.length + " 条提案待你处置(" + kinds + ") [auto]")
174
+ }
175
+ if (ignored.length) parts.push("另有 " + ignored.length + " 条未识别的动作已忽略(" + ignored.map((i) => i.op).join("/") + ")")
176
+ return parts.join(";")
177
+ }
178
+
179
+ // 触发源(对齐 Hermes agent/turn_finalizer.py):宿主 `session.idle` = 回合结束。
180
+ // 每次回合结束都做一次「要不要复习」的检查;前台新回合先取消在跑的那次(握手 ≤2s)。
181
+ // 复习本身以**宿主身份**跑在**受限 agent**(只读 plan)里 ⇒ 工具被限定,且发生在宿主会话体系内。
182
+ export const REVIEW_AGENT = "plan"
183
+
184
+ export function createTurnEndHandler({ scheduler, review, sessionId = null } = {}) {
185
+ if (!scheduler || typeof review !== "function") throw new TypeError("createTurnEndHandler 需要 scheduler 与 review")
186
+ let lastResult = null
187
+ let lastKind = null
188
+ return {
189
+ async onIdle() {
190
+ // 时机照 Hermes:取消在**用户回合开始**(onUserTurnStart),回合结束只记账+派发。
191
+ scheduler.noteUserTurn()
192
+ const r = await scheduler.maybeDispatch()
193
+ if (!r.dispatched) return { dispatched: false, reason: r.reason }
194
+ // ⚠️ **真机实测教训(2026-09-21)**:这里**不许 await 作业完成**。
195
+ // 我们是在宿主的 event 回调里被调用的,而复习要经宿主自己的 client 发起——
196
+ // 在回调里等它 ⇒ 回调不返回、宿主的事件循环也就排不到那次调用,直接挂死(实测 onIdle 永不返回)。
197
+ // Hermes 的做法同理:复习跑在后台线程里,不挡前台。想等它的调用方(测试)自己 await `pending`。
198
+ // 结果在作业完成后记下(不阻塞回调):想读结果的调用方先 await pending 再读 lastResult()。
199
+ if (r.pending) {
200
+ r.pending
201
+ .then((out) => { lastResult = out ?? null; lastKind = r.kind })
202
+ .catch(() => { lastResult = null })
203
+ }
204
+ return { dispatched: true, kind: r.kind, pending: r.pending }
205
+ },
206
+ // 用户回合开始:掐掉在跑的后台复习(前台优先),本方法**不派发**任何新复习
207
+ async onUserTurnStart() {
208
+ return scheduler.cancel("user-turn-start")
209
+ },
210
+ lastResult() { return lastResult },
211
+ lastKind() { return lastKind },
212
+ }
213
+ }
214
+
215
+ // ── 产出的解析与落地 ───────────────────────────────────────────────
216
+ // 解析:我们自己在提示词里定了格式,所以像解析**契约**一样严格:只认三类行,其余忽略。
217
+ export function parseReviewActions(text) {
218
+ if (typeof text !== "string" || !text.trim()) return []
219
+ const out = []
220
+ for (const raw of text.split("\n")) {
221
+ const line = raw.trim()
222
+ const m = /^(add|update|remove)\s*:\s*(.+)$/i.exec(line)
223
+ if (!m) continue
224
+ out.push({ op: m[1].toLowerCase(), text: m[2].trim() })
225
+ }
226
+ return out
227
+ }
228
+
229
+ // 待批落盘的形状与 `memories.mjs` 的 stage() 一致(同一份待批面,不分家)。
230
+ function stageProposal(pendingDir, op) {
231
+ fs.mkdirSync(pendingDir, { recursive: true })
232
+ const name = Date.now() + "-" + process.pid + "-" + Math.random().toString(36).slice(2, 8) + ".json"
233
+ const target = path.join(pendingDir, name)
234
+ const tmp = target + ".tmp"
235
+ fs.writeFileSync(tmp, JSON.stringify({ ...op, stagedAt: new Date().toISOString() }, null, 2) + "\n")
236
+ fs.renameSync(tmp, target)
237
+ return name
238
+ }
239
+
240
+ // 落地:新增直接写(受信任写入路径);改造/删除**只提案**(硬不变量)且提案必须浮出。
241
+ export function applyReviewOutcome({ store, actions = [], kind = "memory", gateEnabled = false, entries = null } = {}) {
242
+ const { direct, proposals, ignored, mustSurface } = classifyReviewOutcome({ actions, entries })
243
+ // A139:后台复习的写入**必须过写入闸门**(不再用 writeTrusted 旁路)。
244
+ // 闸开时按 Hermes evaluate_gate:后台来源一律进待批。
245
+ const pending = gateEnabled
246
+ ? [...proposals, ...direct.map((d) => ({ op: d.op, kind: kind ?? d.kind ?? "memory", text: d.text, origin: PROPOSAL_ORIGIN, label: "[auto]" }))]
247
+ : proposals
248
+ let written = 0
249
+ let staged = 0
250
+ for (const d of (gateEnabled ? [] : direct)) {
251
+ if (store?.writeTrusted) {
252
+ store.writeTrusted({ kind: kind ?? d.kind ?? "memory", text: d.text })
253
+ written += 1
254
+ }
255
+ }
256
+ const pendingDir = store?.paths?.pendingDir
257
+ if (pendingDir) for (const p of pending) { stageProposal(pendingDir, p); staged += 1 }
258
+ // 被忽略的动作也要**有人看得见**(不许悄悄吞掉):与提案共用同一条浮出行。
259
+ const surface = (pending.length || ignored.length) ? surfaceLine({ proposals: pending, ignored }) : null
260
+ return { written, staged, ignored, surface, mustSurface: mustSurface || ignored.length > 0 }
261
+ }
@@ -0,0 +1,64 @@
1
+ // Read-path budgets (R2 §2.5, §4): count / per-entry characters / total tokens.
2
+ //
3
+ // Two rules this module exists to make explicit:
4
+ // 1. Over-limit means *dropped whole*. A truncated body can lose "only in staging" or a
5
+ // negation and change the meaning of what was learned, so nothing here ever slices text.
6
+ // 2. The total budget is measured on the **wrapped** text (envelope + attributes + body),
7
+ // never on bodies alone — otherwise the wrapper silently eats the budget.
8
+
9
+ export const DEFAULT_BUDGET = Object.freeze({
10
+ maxEntries: 12, // how many entries may be injected at once
11
+ maxCharsPerEntry: 1200, // per-entry character ceiling (the rendered entry, envelope-free)
12
+ totalTokens: 3000, // ceiling for the whole injected text, envelope included
13
+ })
14
+
15
+ /** Refuse nonsense instead of clamping it: a silently clamped budget is a silent behaviour change. */
16
+ export function normalizeBudget(input = {}) {
17
+ const out = { ...DEFAULT_BUDGET }
18
+ const unknown = Object.keys(input).filter((k) => !(k in DEFAULT_BUDGET))
19
+ if (unknown.length) throw new Error(`unknown budget key(s): ${unknown.join(", ")}`)
20
+ for (const key of Object.keys(DEFAULT_BUDGET)) {
21
+ const value = input[key]
22
+ if (value === undefined) continue
23
+ if (!Number.isInteger(value) || value < 0) {
24
+ throw new Error(`budget.${key} must be a non-negative integer, got ${JSON.stringify(value)}`)
25
+ }
26
+ out[key] = value
27
+ }
28
+ return out
29
+ }
30
+
31
+ /** Wide ranges: CJK, kana, hangul, full-width punctuation, emoji. */
32
+ function isWide(cp) {
33
+ return (
34
+ (cp >= 0x2e80 && cp <= 0x9fff) ||
35
+ (cp >= 0xac00 && cp <= 0xd7a3) ||
36
+ (cp >= 0xf900 && cp <= 0xfaff) ||
37
+ (cp >= 0xfe30 && cp <= 0xfe4f) ||
38
+ (cp >= 0xff00 && cp <= 0xff60) ||
39
+ (cp >= 0xffe0 && cp <= 0xffe6) ||
40
+ (cp >= 0x1f300 && cp <= 0x1faff)
41
+ )
42
+ }
43
+
44
+ /**
45
+ * Conservative **estimate**, never a measurement.
46
+ *
47
+ * No tokenizer is available offline and the real prompt-cache/token accounting is still an
48
+ * unverified item in the design, so the read path must not pretend to know exact token counts.
49
+ * Wide characters (CJK and friends) are counted at a full token each — character counts are
50
+ * never a valid token count for Chinese; every other run of non-space characters is charged
51
+ * one token per three characters, which over-counts plain ASCII rather than under-counting it.
52
+ */
53
+ export function estimateTokens(text) {
54
+ const source = String(text ?? "")
55
+ let wide = 0
56
+ let narrow = 0
57
+ for (const ch of source) {
58
+ const cp = ch.codePointAt(0)
59
+ if (cp === 0x20 || cp === 0x09 || cp === 0x0a || cp === 0x0d) continue
60
+ if (isWide(cp)) wide += 1
61
+ else narrow += 1
62
+ }
63
+ return wide + Math.ceil(narrow / 3)
64
+ }