opencode-growth 0.1.2 → 0.1.74
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/README.md +72 -13
- package/package.json +1 -1
- package/src/adapter-opencode/curator-runner.mjs +257 -0
- package/src/adapter-opencode/index.mjs +309 -19
- package/src/adapter-opencode/install.mjs +329 -52
- package/src/adapter-opencode/journey-tool.mjs +57 -0
- package/src/adapter-opencode/memory-tool.mjs +57 -5
- package/src/adapter-opencode/provider-tools.mjs +237 -0
- package/src/adapter-opencode/review-runner.mjs +180 -37
- package/src/adapter-opencode/session-search-tool.mjs +66 -0
- package/src/adapter-opencode/skill-tool.mjs +221 -0
- package/src/cli/commands.mjs +98 -5
- package/src/cli/curator-cmd.mjs +149 -0
- package/src/cli/journey-cmd.mjs +61 -0
- package/src/cli/journey-view.mjs +174 -0
- package/src/cli/main.mjs +173 -26
- package/src/cli/memory-cmd.mjs +165 -0
- package/src/cli/session-index-cmd.mjs +87 -0
- package/src/cli/skill-cmd.mjs +194 -0
- package/src/core/approve.mjs +295 -0
- package/src/core/audit.mjs +51 -0
- package/src/core/background-review.mjs +114 -2
- package/src/core/home.mjs +56 -21
- package/src/core/journey.mjs +298 -0
- package/src/core/lock.mjs +6 -0
- package/src/core/memories.mjs +215 -10
- package/src/core/memory-actions.mjs +73 -18
- package/src/core/paths.mjs +0 -1
- package/src/core/session-freshness.mjs +201 -0
- package/src/core/session-index.mjs +508 -0
- package/src/core/session-query.mjs +161 -0
- package/src/core/session-source.mjs +209 -0
- package/src/core/session-tool.mjs +189 -0
- package/src/core/skill-actions.mjs +391 -0
- package/src/core/skill-backup.mjs +95 -0
- package/src/core/skill-lifecycle.mjs +277 -0
- package/src/core/skill-usage.mjs +119 -0
- package/src/core/skills.mjs +30 -3
- package/src/core/sqlite-runtime.mjs +35 -0
- package/src/core/write-approval.mjs +13 -9
- package/src/host/rest-client.mjs +70 -0
- package/src/index.mjs +0 -1
- package/src/provider/config.mjs +187 -0
- package/src/provider/openviking-rest.mjs +742 -0
- package/src/provider/runtime.mjs +417 -0
- package/src/provider/wiring.mjs +164 -0
- package/src/core/budget.mjs +0 -64
- package/src/core/retrieve.mjs +0 -127
package/src/core/memories.mjs
CHANGED
|
@@ -12,13 +12,14 @@ import { scanForThreats } from "./threats.mjs"
|
|
|
12
12
|
// 这条来自 D16/W8 与契约 C03——把人手编辑静默丢弃,人不知道为什么。
|
|
13
13
|
// 3. **origin 由启动器登记的会话身份决定**,调用方自报无效(extra#4):
|
|
14
14
|
// 后台 `add` 直接写(D16 照 Hermes 的 `_background_delete_gate`),改/删强制暂存;
|
|
15
|
-
//
|
|
15
|
+
// **闸关档(默认)不看来源直接生效;闸开档**身份不明 ⇒ 暂存(判定真源=`write-approval.decideWrite`,D73)。
|
|
16
16
|
//
|
|
17
17
|
// 并发与崩溃:**锁内重读-修改-原子替换**(写临时文件 + rename)。
|
|
18
18
|
// 这条不是洁癖:G1 里已实测过"并发消费 → 1 条队列提炼出 2 个候选"。
|
|
19
19
|
import fs from "node:fs"
|
|
20
20
|
import { sha256 } from "./ids.mjs"
|
|
21
21
|
import path from "node:path"
|
|
22
|
+
import { decideWrite } from "./write-approval.mjs"
|
|
22
23
|
|
|
23
24
|
/** 与 Hermes 的 `ENTRY_DELIMITER` 逐字一致。改它等于换磁盘格式,必须先改契约。 */
|
|
24
25
|
export const ENTRY_DELIMITER = "\n§\n"
|
|
@@ -58,6 +59,27 @@ export function fileForTarget(target) {
|
|
|
58
59
|
|
|
59
60
|
export const DEFAULT_LIMITS = { memory: 2200, user: 1375 }
|
|
60
61
|
|
|
62
|
+
/**
|
|
63
|
+
* 生效上限:D/config.json 的 `memory.memory_char_limit` / `memory.user_char_limit`
|
|
64
|
+
* (与 Hermes config_defaults.py 同名同义)。
|
|
65
|
+
* 读不到 / 非法 / 非正数一律回默认——配置坏掉不许把正常写入判成超限(fail 到 Hermes 值)。
|
|
66
|
+
* 这是**唯一**的解析口径:store、批准、批量、CLI 与诊断都从这里取,不在各入口复制默认值。
|
|
67
|
+
*/
|
|
68
|
+
export function resolveMemoryLimits(root) {
|
|
69
|
+
let cfg = null
|
|
70
|
+
try {
|
|
71
|
+
cfg = JSON.parse(fs.readFileSync(path.join(root, "config.json"), "utf8"))
|
|
72
|
+
} catch {
|
|
73
|
+
cfg = null
|
|
74
|
+
}
|
|
75
|
+
const mem = cfg && typeof cfg === "object" ? cfg.memory ?? {} : {}
|
|
76
|
+
const pick = (v, dflt) => {
|
|
77
|
+
const n = Number(v)
|
|
78
|
+
return Number.isFinite(n) && n > 0 ? Math.floor(n) : dflt
|
|
79
|
+
}
|
|
80
|
+
return { memory: pick(mem.memory_char_limit, DEFAULT_LIMITS.memory), user: pick(mem.user_char_limit, DEFAULT_LIMITS.user) }
|
|
81
|
+
}
|
|
82
|
+
|
|
61
83
|
const KINDS = ["memory", "user"]
|
|
62
84
|
const FILES = { memory: "MEMORY.md", user: "USER.md" }
|
|
63
85
|
const ORIGINS = ["foreground", "background", "unknown"]
|
|
@@ -82,6 +104,42 @@ export function findEntryIndex(entries, match) {
|
|
|
82
104
|
return hits[0][1]
|
|
83
105
|
}
|
|
84
106
|
|
|
107
|
+
/** 批量动作枚举(本仓原语名:add/update/remove;Hermes 叫 add/replace/remove)。 */
|
|
108
|
+
export const BATCH_ACTIONS = Object.freeze(["add", "update", "remove"])
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* **整批预扫**(照 Hermes `memory_tool_store.py:414-419` 的 pre-scan):把每一笔的**形态**
|
|
112
|
+
* 与**内容**先看一遍,任一不合格就以「第 N 项」为口径拒掉**整批**——扫描必须发生在任何落盘之前,
|
|
113
|
+
* 包括「暂存」那条路径(先暂存再查=坏内容已经写进待批文件,那也是一次落盘)。
|
|
114
|
+
* 导出它,是因为工具层的门控要先跑同一次扫描,两处必须是**同一个实现**。
|
|
115
|
+
*/
|
|
116
|
+
export function scanBatchOps(operations) {
|
|
117
|
+
const ops = Array.isArray(operations) ? operations : []
|
|
118
|
+
if (!ops.length) throw new Error("operations 不能为空:批量至少要有一项(单条写请用 add/update/remove)")
|
|
119
|
+
ops.forEach((op, i) => {
|
|
120
|
+
const at = `第 ${i + 1} 项`
|
|
121
|
+
const act = op?.action
|
|
122
|
+
if (!BATCH_ACTIONS.includes(act)) throw new Error(`${at}:action 只能是 ${BATCH_ACTIONS.join(" / ")}(收到 ${JSON.stringify(act ?? null)})`)
|
|
123
|
+
// 一批只碰一个库:项里夹带 kind 一律拒(否则「以为写 MEMORY、其实写 USER」)
|
|
124
|
+
if (op?.kind !== undefined) {
|
|
125
|
+
throw new Error(`${at}:不许在项里指定 kind —— 一批只碰一个库,库由整批的 kind 决定`)
|
|
126
|
+
}
|
|
127
|
+
const text = op?.text
|
|
128
|
+
if (act !== "remove" && (typeof text !== "string" || !text.trim())) throw new Error(`${at}(${act}):text 不能为空`)
|
|
129
|
+
if (act !== "add" && (typeof op?.match !== "string" || !op.match.trim())) throw new Error(`${at}(${act}):match(内容子串)不能为空`)
|
|
130
|
+
if (act !== "remove") {
|
|
131
|
+
const hits = scanForThreats(text, { scope: "strict" })
|
|
132
|
+
if (hits.length) {
|
|
133
|
+
const e = new Error(`${at}:内容命中威胁模式 ${hits.join(", ")}(整批已拒,未落盘)`)
|
|
134
|
+
e.code = "THREAT_BLOCKED"
|
|
135
|
+
e.patterns = hits
|
|
136
|
+
throw e
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
})
|
|
140
|
+
return ops
|
|
141
|
+
}
|
|
142
|
+
|
|
85
143
|
/** 解析:按**完整分隔符**切(Hermes 的原话:splits on the FULL delimiter so a bare "§" survives)。 */
|
|
86
144
|
function parse(raw) {
|
|
87
145
|
const text = String(raw).replace(/^\uFEFF/, "")
|
|
@@ -138,7 +196,13 @@ function acquireLock(root, { timeoutMs = LOCK_TIMEOUT_MS } = {}) {
|
|
|
138
196
|
|
|
139
197
|
export function createMemoryStore({ root, identity = null, limits = {}, enabled = {} } = {}) {
|
|
140
198
|
if (!root) throw new Error("createMemoryStore 需要 root(即 D 目录)")
|
|
141
|
-
|
|
199
|
+
// 每次判定都重新解析(配置文件很小):长驻进程(插件)改了配置,下一次动作就生效,
|
|
200
|
+
// 不必重启宿主;显式入参(夹具/嵌入方)仍然优先。
|
|
201
|
+
const limitOf = (kind) => {
|
|
202
|
+
const explicit = Number(limits?.[kind])
|
|
203
|
+
if (Number.isFinite(explicit) && explicit > 0) return Math.floor(explicit)
|
|
204
|
+
return resolveMemoryLimits(root)[kind]
|
|
205
|
+
}
|
|
142
206
|
const enabledOf = (kind) => enabled[kind] !== false
|
|
143
207
|
// 身份**只认登记值**:调用方在每次动作里传的 origin 一律忽略(extra#4)。
|
|
144
208
|
const originOf = () => {
|
|
@@ -146,9 +210,35 @@ export function createMemoryStore({ root, identity = null, limits = {}, enabled
|
|
|
146
210
|
return ORIGINS.includes(o) ? o : "unknown"
|
|
147
211
|
}
|
|
148
212
|
|
|
149
|
-
|
|
213
|
+
/**
|
|
214
|
+
* 严格读(**变更路径**用)。照 `~/.hermes/hermes-agent/tools/memory_tool_store.py:432-447` 的
|
|
215
|
+
* `_read_raw_checked`:非法字节 / 读不到 ⇒ `ok:false`,**绝不把有损视图交出去写回**——
|
|
216
|
+
* 有损解码 + 一次保存 = 用户真实字节被永久替换(Hermes 修过的 #10878 / PR #10888,
|
|
217
|
+
* 正是我们这条 `readRaw → serialize → atomicWrite` 链)。
|
|
218
|
+
* 成功时剥前导 BOM(Hermes 用 `utf-8-sig`):保证"检查过的字节"与"写回的字节"同源。
|
|
219
|
+
*/
|
|
220
|
+
const readRawChecked = (kind) => {
|
|
150
221
|
const p = fileFor(root, kind)
|
|
151
|
-
|
|
222
|
+
if (!fs.existsSync(p)) return { ok: true, text: "" }
|
|
223
|
+
let buf
|
|
224
|
+
try {
|
|
225
|
+
buf = fs.readFileSync(p)
|
|
226
|
+
} catch (e) {
|
|
227
|
+
return { ok: false, why: `读不到 ${p}(${e.code ?? e.message})` }
|
|
228
|
+
}
|
|
229
|
+
let text
|
|
230
|
+
try {
|
|
231
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(buf)
|
|
232
|
+
} catch {
|
|
233
|
+
return { ok: false, why: `${p} 不是合法的 UTF-8` }
|
|
234
|
+
}
|
|
235
|
+
return { ok: true, text: text.replace(/^\uFEFF/, "") }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** 容忍读(**只读路径**用:注入/状态/检索)。照 Hermes:读不回来就当空;它绝不允许参与写回。 */
|
|
239
|
+
const readRaw = (kind) => {
|
|
240
|
+
const r = readRawChecked(kind)
|
|
241
|
+
return r.ok ? r.text : ""
|
|
152
242
|
}
|
|
153
243
|
|
|
154
244
|
const read = ({ kind = "memory" } = {}) => {
|
|
@@ -184,6 +274,7 @@ export function createMemoryStore({ root, identity = null, limits = {}, enabled
|
|
|
184
274
|
const overLimitError = (kind, used, limit) =>
|
|
185
275
|
new Error(
|
|
186
276
|
`写入会超过上限:当前 ${used} / 上限 ${limit} 字符(${kind})。` +
|
|
277
|
+
`这笔文字会一直占用常驻上下文(每次会话都随系统提示带上,按 token 计费)。` +
|
|
187
278
|
`请在当轮整理后再写:合并或删减既有条目,或把详情移到别处。本次写入未落盘。`,
|
|
188
279
|
)
|
|
189
280
|
|
|
@@ -193,7 +284,10 @@ export function createMemoryStore({ root, identity = null, limits = {}, enabled
|
|
|
193
284
|
if (!enabledOf(kind)) throw new Error(`这个库已被关闭(disabled):${kind}`)
|
|
194
285
|
const release = acquireLock(root)
|
|
195
286
|
try {
|
|
196
|
-
|
|
287
|
+
// 变更路径一律走**严格读**:读不回来就拒写,一字不动(Hermes 的 `_read_raw_checked` 口径)。
|
|
288
|
+
const raw = readRawChecked(kind)
|
|
289
|
+
if (!raw.ok) throw new Error(`拒绝写回:${raw.why}——改回可读之前不会覆盖它`)
|
|
290
|
+
const before = parse(raw.text)
|
|
197
291
|
const after = fn(before)
|
|
198
292
|
const next = serialize(after)
|
|
199
293
|
if (next.length > limitOf(kind)) throw overLimitError(kind, next.length, limitOf(kind))
|
|
@@ -259,9 +353,9 @@ export function createMemoryStore({ root, identity = null, limits = {}, enabled
|
|
|
259
353
|
})
|
|
260
354
|
|
|
261
355
|
/**
|
|
262
|
-
*
|
|
263
|
-
*
|
|
264
|
-
*
|
|
356
|
+
* 对外的三个写入口:**先过写入闸门**(判定交 `decideWrite`——只有一处真源),再落到上面三个原语。
|
|
357
|
+
* 闸关档(默认):不看来源,直接生效(D73 照 Hermes `write_approval.py:175`)。
|
|
358
|
+
* 闸开档:后台 / 身份不明 ⇒ 暂存;前台且有交互通道 ⇒ 内联问一次。
|
|
265
359
|
*
|
|
266
360
|
* 一律返回 promise:调用方(工具层/插件)要能统一 `try/catch` 与 `await`,
|
|
267
361
|
* 而不是"有时同步抛、有时拒绝"。**锁内仍然是纯同步的**——`mutate` 里没有任何 `await`,
|
|
@@ -280,11 +374,102 @@ export function createMemoryStore({ root, identity = null, limits = {}, enabled
|
|
|
280
374
|
}
|
|
281
375
|
}
|
|
282
376
|
const origin = originOf()
|
|
283
|
-
|
|
284
|
-
|
|
377
|
+
// **门控只有一处真源**:判定交给 `decideWrite`(照 Hermes 只有一个 `evaluate_gate`)。
|
|
378
|
+
// 这里曾经另写一套「只看 origin」的规则 ⇒ 同一个政策两份实现、口径必然漂移(2026-09-23 合并,D73):
|
|
379
|
+
// · store 面没有交互通道(`interactive:false`)⇒ 闸开时前台也只会 stage,不会 ask;
|
|
380
|
+
// · store 面没有宿主 permission 面(`hostPermission` 不传)⇒ 不会有 `deny`——
|
|
381
|
+
// 宿主的 `permission.ocg_memory_write=deny` 在插件层就被拦掉了,到不了这里;
|
|
382
|
+
// 万一哪天真有 deny 落到这里,下面的分支把它当"不写"处理(进待批,不是静默丢弃)。
|
|
383
|
+
const decision = decideWrite({
|
|
384
|
+
root,
|
|
385
|
+
subsystem: payload?.subsystem === "skills" ? "skills" : "memory",
|
|
386
|
+
origin,
|
|
387
|
+
destructive: op !== "add",
|
|
388
|
+
interactive: false,
|
|
389
|
+
})
|
|
390
|
+
if (decision === "apply") return run()
|
|
285
391
|
return { staged: stage({ op, origin, kind: payload.kind ?? "memory", ...payload }) }
|
|
286
392
|
}
|
|
287
393
|
|
|
394
|
+
/**
|
|
395
|
+
* 批量原子(G3;照 Hermes `apply_batch`/`_batch`,:397-470):
|
|
396
|
+
* ① 空批 ⇒ 拒(`scanBatchOps`);
|
|
397
|
+
* ② **先扫全批**(形态 + 威胁模式),任一坏弹整批拒;
|
|
398
|
+
* ③ 工作副本按序应用,任一项寻址失败 ⇒ 第 N 项点名、整批不写(`mutate` 只在 fn 正常返回后才落盘);
|
|
399
|
+
* ④ 非空库不许被这一批清空(单条 remove 才是有意清空的路);
|
|
400
|
+
* ⑤ 预算只看**最终态**(`mutate` 里那一次检查就是终态;中间态不检);
|
|
401
|
+
* ⑥ `dryRun` ⇒ 同一套检查、不落盘、回每项选中的整条老内容。
|
|
402
|
+
* **一批只碰一个库**(kind 由整批决定,项里不许再带)。
|
|
403
|
+
*/
|
|
404
|
+
const batch = ({ kind = "memory", operations, dryRun = false } = {}) => {
|
|
405
|
+
if (!KINDS.includes(kind)) throw new Error(`未知的库:${kind}`)
|
|
406
|
+
if (!enabledOf(kind)) throw new Error(`这个库已被关闭(disabled):${kind}`)
|
|
407
|
+
const ops = scanBatchOps(operations)
|
|
408
|
+
|
|
409
|
+
/** 在给定条目集上按序应用;失败带「第 N 项」口径。 */
|
|
410
|
+
const apply = (entries) => {
|
|
411
|
+
const working = entries.slice()
|
|
412
|
+
const matched = []
|
|
413
|
+
ops.forEach((op, i) => {
|
|
414
|
+
const act = op.action
|
|
415
|
+
let prev = null
|
|
416
|
+
try {
|
|
417
|
+
if (act === "add") working.push(op.text.trim())
|
|
418
|
+
else {
|
|
419
|
+
const idx = findOne(working, op.match)
|
|
420
|
+
prev = working[idx]
|
|
421
|
+
if (act === "update") working[idx] = op.text.trim()
|
|
422
|
+
else working.splice(idx, 1)
|
|
423
|
+
}
|
|
424
|
+
} catch (e) {
|
|
425
|
+
throw new Error(`第 ${i + 1} 项(${act}):${e?.message ?? e}`)
|
|
426
|
+
}
|
|
427
|
+
matched.push(prev)
|
|
428
|
+
})
|
|
429
|
+
if (entries.length && !working.length) {
|
|
430
|
+
throw new Error(
|
|
431
|
+
`拒绝清空:这一批会把本来非空的 ${FILES[kind]} 删空。整批已拒,一字未写。` +
|
|
432
|
+
`要清空请用单条 remove(那才是有意清空的路),或保留至少一条。`,
|
|
433
|
+
)
|
|
434
|
+
}
|
|
435
|
+
return { working, matched }
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
if (dryRun) {
|
|
439
|
+
const raw = readRawChecked(kind)
|
|
440
|
+
if (!raw.ok) throw new Error(`拒绝解析:${raw.why}`)
|
|
441
|
+
const { working, matched } = apply(parse(raw.text))
|
|
442
|
+
const next = serialize(working)
|
|
443
|
+
if (next.length > limitOf(kind)) throw overLimitError(kind, next.length, limitOf(kind))
|
|
444
|
+
return { ok: true, kind, dryRun: true, applied: ops.length, matchedEntries: matched, used: next.length, limit: limitOf(kind), entries: working.length }
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
let matched = []
|
|
448
|
+
const after = mutate(kind, (entries) => {
|
|
449
|
+
const r = apply(entries)
|
|
450
|
+
matched = r.matched
|
|
451
|
+
return r.working
|
|
452
|
+
})
|
|
453
|
+
const used = serialize(after).length
|
|
454
|
+
return { ok: true, kind, dryRun: false, applied: ops.length, matchedEntries: matched, used, limit: limitOf(kind), entries: after.length }
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** 批量版门控:扫描(同实现)→ `decideWrite` → apply 或**整批**暂存。 */
|
|
458
|
+
const gateBatch = (payload = {}) => {
|
|
459
|
+
const kind = payload?.kind ?? "memory"
|
|
460
|
+
const ops = scanBatchOps(payload?.operations) // ← 先于门控:坏内容不许以「暂存」形式落盘
|
|
461
|
+
const origin = originOf()
|
|
462
|
+
const decision = decideWrite({
|
|
463
|
+
root,
|
|
464
|
+
subsystem: "memory",
|
|
465
|
+
origin,
|
|
466
|
+
destructive: ops.some((o) => o.action !== "add"),
|
|
467
|
+
interactive: false,
|
|
468
|
+
})
|
|
469
|
+
if (decision === "apply") return batch({ ...payload, kind })
|
|
470
|
+
return { staged: stage({ op: "batch", origin, kind, operations: ops, ...(payload?.subsystem ? { subsystem: payload.subsystem } : {}) }) }
|
|
471
|
+
}
|
|
472
|
+
|
|
288
473
|
return {
|
|
289
474
|
root,
|
|
290
475
|
read,
|
|
@@ -298,9 +483,29 @@ export function createMemoryStore({ root, identity = null, limits = {}, enabled
|
|
|
298
483
|
// mutate:锁内重读-改-写 + 限额检查 + 同目录临时文件 + rename 原子替换。
|
|
299
484
|
// ⚠️ 不得暴露到模型动作面(memory-actions 的动作枚举里不许出现它)。
|
|
300
485
|
writeTrusted: (payload = {}) => add(payload), // 与 add 同门:威胁扫描在里面,命中即拒
|
|
486
|
+
// 受信任改写(规格 §七 第三层,对称于上面两条):待批提案被**人批准**后由处置面调用,
|
|
487
|
+
// 与 writeTrusted/removeTrusted 同门(锁内重读-改-写 + 限额 + 原子替换 + 威胁扫描)。
|
|
488
|
+
// ⚠️ 同样不得暴露到模型动作面。
|
|
489
|
+
updateTrusted: (payload = {}) => update(payload),
|
|
301
490
|
// 受信任删除(规格 §七 第三层,对称于 writeTrusted):不经入口门控、仍走 mutate(锁内重读-改-写 + 原子替换)。
|
|
302
491
|
// ⚠️ 同样不得暴露到模型动作面。
|
|
303
492
|
removeTrusted: (payload = {}) => remove(payload),
|
|
304
493
|
paths: { file: (kind) => fileFor(root, kind), pendingDir: pendingDir(root) },
|
|
494
|
+
/**
|
|
495
|
+
* 暂存原语(门控里"暂存"那一半的**单一实现**)。给**已经做完判定**的调用方用(动作层),
|
|
496
|
+
* 也供直接调用方在自己判定为 stage 时使用;落点、文件形状、带 `origin` 的口径与 `gate` 内完全同一条路径。
|
|
497
|
+
* ⚠️ 与 writeTrusted 一族同理:它**只负责落待批**(不碰正文),不得暴露到模型动作面。
|
|
498
|
+
*/
|
|
499
|
+
/**
|
|
500
|
+
* 批量原子(工具面):先过**同一条写入闸门**(判定只有 `decideWrite` 一处真源;
|
|
501
|
+
* 「破坏性」=这批里有非 add 的动作),闸开+后台/无通道 ⇒ 整批**一个**待批文件
|
|
502
|
+
* (半截暂存会让「批」这个语义失效)。扫描在门控之前(`scanBatchOps` 是同一个实现)。
|
|
503
|
+
*/
|
|
504
|
+
batch: (payload = {}) => gateBatch(payload),
|
|
505
|
+
/** 受信任批量(内部:批准待批批量的处置面走它)。⚠️ 与 writeTrusted 一族同理,不得暴露到模型动作面。 */
|
|
506
|
+
batchTrusted: (payload = {}) => batch(payload),
|
|
507
|
+
stageProposal: (payload = {}) =>
|
|
508
|
+
// 多带的字段(如技能提案的 name)原样进待批记录——人要能批,记录就得说清在批什么。
|
|
509
|
+
stage({ ...payload, op: payload.op, origin: payload.origin ?? originOf(), kind: payload.kind ?? "memory", text: payload.text, match: payload.match }),
|
|
305
510
|
}
|
|
306
511
|
}
|
|
@@ -7,7 +7,9 @@ import { WRITE_PERMISSION_NAME } from "./paths.mjs"
|
|
|
7
7
|
// · 前台 + **有**交互通道 → 改/删**内联问一次**,人同意才落盘
|
|
8
8
|
// · 前台 + **没有**交互通道 → 暂存(**不能因为"没人拦"就直写**)
|
|
9
9
|
// · 后台(agent 在名单里)→ add 直写(D16)、改/删暂存
|
|
10
|
-
// · 身份不明 →
|
|
10
|
+
// · 身份不明 → 暂存(fail-closed)
|
|
11
|
+
//
|
|
12
|
+
// 以上四条是**闸开档**的分流;**闸关(默认)不看来源、直接生效**(D73:照 Hermes `write_approval.py:175`)。
|
|
11
13
|
//
|
|
12
14
|
// 三条不许破的线:
|
|
13
15
|
// 1. **模型不能自报身份**:动作参数里没有 origin 这个字段;就算塞进来也不看(extra#4)。
|
|
@@ -67,7 +69,7 @@ export function identityFor({
|
|
|
67
69
|
// 无头 `opencode run` 里 `ctx.ask` 会**立刻返回、没有任何人看过一眼**,
|
|
68
70
|
// 于是"有人批过"的判断完全落空、改删直接落盘。
|
|
69
71
|
// 所以前台直写还要部署方**显式声明**这个会话面是可交互的(`OCG_INTERACTIVE=1`)。
|
|
70
|
-
// 默认不声明 ⇒
|
|
72
|
+
// 默认不声明 ⇒ 判不出前台(闸开档会因身份不明而暂存;闸关档不看来源、直接生效,D73)。
|
|
71
73
|
// A41(astra 实跑复现):**「声明可交互」≠「有人能拦」** —— 只凭 hasAsk+interactive 判定前台,
|
|
72
74
|
// 会让**未登记**的会话身份直接改删落盘(pending=0),违反 extra#4「身份不明时一律暂存」。
|
|
73
75
|
// 现在前台要**两侧都成立**:部署方声明可交互 **且** 这个身份是部署方**登记过**的(对称于 backgroundAgents)。
|
|
@@ -97,11 +99,16 @@ export async function runMemoryAction({
|
|
|
97
99
|
kind = "memory",
|
|
98
100
|
text,
|
|
99
101
|
match,
|
|
102
|
+
operations,
|
|
100
103
|
ask = null,
|
|
101
104
|
limits = {},
|
|
102
105
|
enabled = {},
|
|
103
106
|
} = {}) {
|
|
104
107
|
if (!root) return { ok: false, error: "缺少 root(D 目录)" }
|
|
108
|
+
// G3 批量:给了 `operations` 就走批量面(`action` 忽略——照 Hermes,一个 memory 工具两副参数)。
|
|
109
|
+
if (Array.isArray(operations) && operations.length) {
|
|
110
|
+
return runMemoryBatch({ root, identity, kind, operations, limits, enabled })
|
|
111
|
+
}
|
|
105
112
|
if (!MEMORY_ACTIONS.includes(action)) {
|
|
106
113
|
return { ok: false, error: `未知动作:${String(action)}。可用动作:${MEMORY_ACTIONS.join(" / ")}` }
|
|
107
114
|
}
|
|
@@ -109,8 +116,8 @@ export async function runMemoryAction({
|
|
|
109
116
|
|
|
110
117
|
const hasAsk = typeof ask === "function"
|
|
111
118
|
const declared = identity?.origin
|
|
112
|
-
// **fail-closed**:自称前台但没有交互通道 ⇒ 降级为"身份不明"
|
|
113
|
-
// 这条防的是"通道断了却还在直写"——那正是 extra#4 说的"没人拦"
|
|
119
|
+
// **fail-closed**:自称前台但没有交互通道 ⇒ 降级为"身份不明"(闸开档会因此暂存)。
|
|
120
|
+
// 这条防的是"通道断了却还在直写"——那正是 extra#4 说的"没人拦"的情形;闸关档不看来源(D73)。
|
|
114
121
|
// 需要人批的动作才受"通道断了"的影响:add 不需要(D16),改/删才需要。
|
|
115
122
|
const needsAsk = action === "update" || action === "remove"
|
|
116
123
|
// 【subgoal② · 照 Hermes】闸门判定决定这一笔怎么写:
|
|
@@ -163,19 +170,13 @@ export async function runMemoryAction({
|
|
|
163
170
|
return { ok: true, action, pending: items, ...status() }
|
|
164
171
|
}
|
|
165
172
|
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
kind,
|
|
174
|
-
entries: out.length,
|
|
175
|
-
used: store.status().kinds[kind].used,
|
|
176
|
-
limit: store.status().kinds[kind].limit,
|
|
177
|
-
...status(),
|
|
178
|
-
}
|
|
173
|
+
// 三类动作的执行都**按动作层自己的判定来**(照 Hermes:闸门只判一次,判完就执行)。
|
|
174
|
+
// stage ⇒ 走 store 的暂存原语落一条待批;
|
|
175
|
+
// apply / ask 已获批准 ⇒ 用**受信任原语**落地(`approve.mjs` 的人批准路径同此形状)。
|
|
176
|
+
// 若继续让 store 的受门控家族再判一次,就成了**二次门控**——实测红过:
|
|
177
|
+
// 闸开时刚被人批准的改/删会被 store 重新打进待批(`同意后应当真的删掉`)。
|
|
178
|
+
if (action === "add" && (typeof text !== "string" || !text.trim())) {
|
|
179
|
+
return { ok: false, error: "add 需要非空 text" }
|
|
179
180
|
}
|
|
180
181
|
|
|
181
182
|
// update / remove:**先校验提案,再问,最后才写**。
|
|
@@ -213,10 +214,64 @@ export async function runMemoryAction({
|
|
|
213
214
|
}
|
|
214
215
|
}
|
|
215
216
|
|
|
216
|
-
|
|
217
|
+
// 判定说暂存 ⇒ 落一条待批(不碰正文)
|
|
218
|
+
if (decision === "stage") {
|
|
219
|
+
const file = store.stageProposal({ op: action, kind, text, match })
|
|
220
|
+
return { ok: true, action, staged: true, file, ...status() }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// 否则(`apply`,或闸开时人批准了那个 `ask`)⇒ 用**受信任原语**落地
|
|
224
|
+
if (action === "add") {
|
|
225
|
+
const out = await store.writeTrusted({ kind, text })
|
|
226
|
+
return {
|
|
227
|
+
ok: true,
|
|
228
|
+
action,
|
|
229
|
+
kind,
|
|
230
|
+
entries: out.length,
|
|
231
|
+
used: store.status().kinds[kind].used,
|
|
232
|
+
limit: store.status().kinds[kind].limit,
|
|
233
|
+
...status(),
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
const out = action === "update" ? await store.updateTrusted({ kind, match, text }) : await store.removeTrusted({ kind, match })
|
|
217
237
|
if (out && out.staged) return { ok: true, action, staged: true, file: out.staged, ...status() }
|
|
218
238
|
return { ok: true, action, kind, entries: out.length, ...status() }
|
|
219
239
|
} catch (err) {
|
|
220
240
|
return { ok: false, action, error: err?.message ?? String(err) }
|
|
221
241
|
}
|
|
222
242
|
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* 批量原子(G3):**一个库、一次调用、全成或全败**。
|
|
246
|
+
*
|
|
247
|
+
* 判定与单条面同源:`store.batch` 内部先做「整批预扫」(`scanBatchOps`——与 `memories.mjs`
|
|
248
|
+
* 同一个实现,扫描先于任何落盘),再走**同一条** `decideWrite` 闸门;闸开且这批含非 add 动作
|
|
249
|
+
* (或来源是后台/身份不明)⇒ 整批作为**一个**待批文件暂存,正文一字不动。
|
|
250
|
+
*
|
|
251
|
+
* 与单条面的已知差别(照 Hermes:批量的工具面不做内联问):批量不会 `ask`——store 面没有交互
|
|
252
|
+
* 通道(`interactive:false`),闸开时前台也会落到「暂存」而不是「内联问」。这不是降级,是同一个
|
|
253
|
+
* fail-closed 方向:问不到人就不写。
|
|
254
|
+
*/
|
|
255
|
+
async function runMemoryBatch({ root, identity, kind, operations, limits, enabled }) {
|
|
256
|
+
const action = "batch"
|
|
257
|
+
try {
|
|
258
|
+
const store = createMemoryStore({ root, identity, limits, enabled })
|
|
259
|
+
const out = await store.batch({ kind, operations })
|
|
260
|
+
const st = store.status()
|
|
261
|
+
if (out && out.staged) return { ok: true, action, staged: true, file: out.staged, ...st }
|
|
262
|
+
return {
|
|
263
|
+
ok: true,
|
|
264
|
+
action,
|
|
265
|
+
kind,
|
|
266
|
+
applied: out.applied,
|
|
267
|
+
matchedEntries: out.matchedEntries,
|
|
268
|
+
entries: out.entries,
|
|
269
|
+
used: out.used,
|
|
270
|
+
limit: out.limit,
|
|
271
|
+
...st,
|
|
272
|
+
}
|
|
273
|
+
} catch (err) {
|
|
274
|
+
// 整批拒:正文一字未写;带上点名(「第 N 项」)与威胁模式(若有),让调用方原样转给人看。
|
|
275
|
+
return { ok: false, action, error: err?.message ?? String(err), code: err?.code ?? null, patterns: err?.patterns ?? null }
|
|
276
|
+
}
|
|
277
|
+
}
|
package/src/core/paths.mjs
CHANGED
|
@@ -36,7 +36,6 @@ export function layout(root) {
|
|
|
36
36
|
learnOffset: p("state", "learn-queue.offset"),
|
|
37
37
|
manifest: p("state", "manifest.json"),
|
|
38
38
|
projects: p("state", "projects.json"),
|
|
39
|
-
budget: p("state", "budget.json"),
|
|
40
39
|
watermark: p("state", "watermark.json"),
|
|
41
40
|
policy: p("state", "policy.json"),
|
|
42
41
|
schema: p("state", "schema.json"),
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// S4(G4):自动新鲜度——三路径调**同一幂等 sync**(session-index.syncStore):
|
|
2
|
+
// ① onIdle 定向 session 快刷(scope_session_id:比对该 session 的 part 集合与指纹,撤回删除/编辑)
|
|
3
|
+
// ② fs.watch 盯 库+WAL+父目录 唤醒(消抖、单飞、失败退避、唤醒不丢 pending 位)
|
|
4
|
+
// ③ 低频 timer 完整对账(mark-and-sweep 全库——快刷只作加速,完整对账才是完备边界)
|
|
5
|
+
// watcher 是唤醒源不是持久日志;pending 位持久化进 store meta,status 可见。
|
|
6
|
+
// 搜索前有界快刷预算:超时带 stale 返回,不卡调用(boundedRefresh)。
|
|
7
|
+
import path from "node:path"
|
|
8
|
+
import fs from "node:fs"
|
|
9
|
+
|
|
10
|
+
import { metaSet, openStore, syncStore } from "./session-index.mjs"
|
|
11
|
+
|
|
12
|
+
/** 定向 session 快刷(①):只抽取/撤回该 session 的 part,其余行不动。 */
|
|
13
|
+
export async function fastSync({ root, sourcePath, session_id, includeToolOutput = false, now = null } = {}) {
|
|
14
|
+
return syncStore({ root, sourcePath, includeToolOutput, scope_session_id: session_id, now })
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** 完整对账(③):全库 mark-and-sweep——完备边界。 */
|
|
18
|
+
export async function fullReconcile({ root, sourcePath, includeToolOutput = false, now = null } = {}) {
|
|
19
|
+
return syncStore({ root, sourcePath, includeToolOutput, now })
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* 搜索前有界快刷预算:budgetMs 内没刷完就带 timedOut=true 返回(调用方标 stale),
|
|
24
|
+
* 被赛跑的刷新自身继续跑完(幂等,无害)。budgetMs<=0 ⇒ 不刷、直接如实报「没核对」。
|
|
25
|
+
*/
|
|
26
|
+
export async function boundedRefresh({ root, sourcePath, includeToolOutput = false, budgetMs = 500 } = {}) {
|
|
27
|
+
if (!(budgetMs > 0)) return { refreshed: false, timedOut: true, reason: "no-budget" }
|
|
28
|
+
let timer = null
|
|
29
|
+
const timeout = new Promise((resolve) => {
|
|
30
|
+
timer = setTimeout(() => resolve({ refreshed: false, timedOut: true, reason: "budget-exceeded" }), budgetMs)
|
|
31
|
+
timer.unref?.()
|
|
32
|
+
})
|
|
33
|
+
const run = fullReconcile({ root, sourcePath, includeToolOutput })
|
|
34
|
+
.then((r) => ({ refreshed: Boolean(r.ok), timedOut: false, result: r }))
|
|
35
|
+
.catch((e) => ({ refreshed: false, timedOut: false, error: String(e?.message ?? e) }))
|
|
36
|
+
try {
|
|
37
|
+
return await Promise.race([run, timeout])
|
|
38
|
+
} finally {
|
|
39
|
+
clearTimeout(timer)
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function setPendingMeta(root, v) {
|
|
44
|
+
try {
|
|
45
|
+
const store = openStore(root)
|
|
46
|
+
metaSet(store.db, "pending", v ? "1" : "0")
|
|
47
|
+
store.close()
|
|
48
|
+
} catch { /* 簿记失败不弄挂调度 */ }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 新鲜度调度器。fsImpl/timersImpl/now 可注入(单测用假时钟/假 fs 全确定性驱动)。
|
|
53
|
+
* 串行链保单飞(同一时刻只跑一轮);失败退避 = backoffBaseMs * 2^(failures-1) 封顶 backoffMaxMs,
|
|
54
|
+
* 退避期内的唤醒只挂起 pending(位不丢),退避过后补跑;补跑成功清 pending。
|
|
55
|
+
*/
|
|
56
|
+
export function createFreshnessScheduler({
|
|
57
|
+
root,
|
|
58
|
+
sourcePath,
|
|
59
|
+
includeToolOutput = false,
|
|
60
|
+
debounceMs = 250,
|
|
61
|
+
backoffBaseMs = 1000,
|
|
62
|
+
backoffMaxMs = 60_000,
|
|
63
|
+
intervalMs = 10 * 60 * 1000,
|
|
64
|
+
fsImpl = fs,
|
|
65
|
+
timersImpl = globalThis,
|
|
66
|
+
now = () => Date.now(),
|
|
67
|
+
onEvent = null,
|
|
68
|
+
} = {}) {
|
|
69
|
+
const st = { pending: false, running: false, failures: 0, nextAllowedAt: 0, stopped: false, lastError: null }
|
|
70
|
+
let chain = Promise.resolve()
|
|
71
|
+
let debounceTimer = null
|
|
72
|
+
let retryTimer = null
|
|
73
|
+
let intervalHandle = null
|
|
74
|
+
const watchers = []
|
|
75
|
+
|
|
76
|
+
function setPending(v) {
|
|
77
|
+
st.pending = v
|
|
78
|
+
setPendingMeta(root, v)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function enqueue(task) {
|
|
82
|
+
chain = chain.then(() => task(), () => task())
|
|
83
|
+
return chain
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function runSync(kind, { session_id = null } = {}) {
|
|
87
|
+
if (st.stopped) return { skipped: "stopped" }
|
|
88
|
+
if (now() < st.nextAllowedAt) {
|
|
89
|
+
// 退避期内:只挂起,唤醒不丢 pending 位
|
|
90
|
+
setPending(true)
|
|
91
|
+
onEvent?.({ what: "backed-off", kind, until: st.nextAllowedAt })
|
|
92
|
+
return { backedOff: true, until: st.nextAllowedAt }
|
|
93
|
+
}
|
|
94
|
+
st.running = true
|
|
95
|
+
try {
|
|
96
|
+
const r = session_id
|
|
97
|
+
? await fastSync({ root, sourcePath, session_id, includeToolOutput })
|
|
98
|
+
: await fullReconcile({ root, sourcePath, includeToolOutput })
|
|
99
|
+
if (r.ok) {
|
|
100
|
+
st.failures = 0
|
|
101
|
+
st.nextAllowedAt = 0
|
|
102
|
+
st.lastError = null
|
|
103
|
+
setPending(false)
|
|
104
|
+
onEvent?.({ what: "sync-done", kind, ok: true })
|
|
105
|
+
} else {
|
|
106
|
+
st.failures += 1
|
|
107
|
+
st.lastError = r.error ?? r.error_code ?? "sync-failed"
|
|
108
|
+
st.nextAllowedAt = now() + Math.min(backoffBaseMs * 2 ** (st.failures - 1), backoffMaxMs)
|
|
109
|
+
setPending(true) // 唤醒不丢 pending 位
|
|
110
|
+
onEvent?.({ what: "sync-failed", kind, error: st.lastError, nextAllowedAt: st.nextAllowedAt })
|
|
111
|
+
scheduleRetry()
|
|
112
|
+
}
|
|
113
|
+
return r
|
|
114
|
+
} finally {
|
|
115
|
+
st.running = false
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function scheduleRetry() {
|
|
120
|
+
if (retryTimer != null || st.stopped) return
|
|
121
|
+
const delay = Math.max(0, st.nextAllowedAt - now())
|
|
122
|
+
retryTimer = timersImpl.setTimeout(() => {
|
|
123
|
+
retryTimer = null
|
|
124
|
+
void enqueue(() => runSync("retry"))
|
|
125
|
+
}, delay)
|
|
126
|
+
retryTimer?.unref?.()
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** fs 事件/手动唤醒(②):置 pending + 消抖,窗口内多事件只跑一轮。 */
|
|
130
|
+
function notify() {
|
|
131
|
+
if (st.stopped) return
|
|
132
|
+
setPending(true) // 唤醒不丢 pending 位
|
|
133
|
+
if (debounceTimer != null) timersImpl.clearTimeout(debounceTimer)
|
|
134
|
+
debounceTimer = timersImpl.setTimeout(() => {
|
|
135
|
+
debounceTimer = null
|
|
136
|
+
void enqueue(() => runSync("wake"))
|
|
137
|
+
}, debounceMs)
|
|
138
|
+
debounceTimer?.unref?.()
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** onIdle 定向快刷(①)。 */
|
|
142
|
+
function onIdle(sessionId) {
|
|
143
|
+
return enqueue(() => runSync("idle", { session_id: sessionId }))
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** timer 完整对账(③)。 */
|
|
147
|
+
function tick() {
|
|
148
|
+
return enqueue(() => runSync("timer"))
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function start() {
|
|
152
|
+
const targets = [sourcePath, `${sourcePath}-wal`, path.dirname(sourcePath)]
|
|
153
|
+
for (const t of targets) {
|
|
154
|
+
try {
|
|
155
|
+
const w = fsImpl.watch(t, () => notify())
|
|
156
|
+
w?.unref?.()
|
|
157
|
+
watchers.push({ target: t, w })
|
|
158
|
+
} catch (e) {
|
|
159
|
+
onEvent?.({ what: "watch-failed", target: t, error: String(e?.message ?? e) })
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (intervalMs > 0) {
|
|
163
|
+
intervalHandle = timersImpl.setInterval(() => { void enqueue(() => runSync("timer")) }, intervalMs)
|
|
164
|
+
intervalHandle?.unref?.()
|
|
165
|
+
}
|
|
166
|
+
return { watched: watchers.map((x) => x.target) }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function stop() {
|
|
170
|
+
st.stopped = true
|
|
171
|
+
for (const { w } of watchers) {
|
|
172
|
+
try { w?.close?.() } catch { /* 关不掉就算了 */ }
|
|
173
|
+
}
|
|
174
|
+
watchers.length = 0
|
|
175
|
+
if (debounceTimer != null) timersImpl.clearTimeout(debounceTimer)
|
|
176
|
+
if (retryTimer != null) timersImpl.clearTimeout(retryTimer)
|
|
177
|
+
if (intervalHandle != null) timersImpl.clearInterval(intervalHandle)
|
|
178
|
+
debounceTimer = retryTimer = intervalHandle = null
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function whenIdle() {
|
|
182
|
+
let prev = null
|
|
183
|
+
while (prev !== chain) {
|
|
184
|
+
prev = chain
|
|
185
|
+
await chain.catch(() => {})
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function status() {
|
|
190
|
+
return {
|
|
191
|
+
pending: st.pending,
|
|
192
|
+
running: st.running,
|
|
193
|
+
failures: st.failures,
|
|
194
|
+
nextAllowedAt: st.nextAllowedAt,
|
|
195
|
+
lastError: st.lastError,
|
|
196
|
+
watched: watchers.map((x) => x.target),
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
return { start, stop, notify, onIdle, tick, whenIdle, status }
|
|
201
|
+
}
|