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.
- package/LICENSE +202 -0
- package/README.md +52 -0
- package/bin/oc-grow.mjs +14 -0
- package/package.json +35 -0
- package/src/adapter-opencode/index.mjs +300 -0
- package/src/adapter-opencode/install.mjs +387 -0
- package/src/adapter-opencode/memory-tool.mjs +170 -0
- package/src/adapter-opencode/review-runner.mjs +369 -0
- package/src/cli/commands.mjs +421 -0
- package/src/cli/envelope.mjs +64 -0
- package/src/cli/main.mjs +245 -0
- package/src/core/audit.mjs +40 -0
- package/src/core/background-review.mjs +261 -0
- package/src/core/budget.mjs +64 -0
- package/src/core/candidate.mjs +96 -0
- package/src/core/home.mjs +61 -0
- package/src/core/identity.mjs +100 -0
- package/src/core/ids.mjs +22 -0
- package/src/core/lock.mjs +107 -0
- package/src/core/memories.mjs +306 -0
- package/src/core/memory-actions.mjs +222 -0
- package/src/core/paths.mjs +81 -0
- package/src/core/retrieve.mjs +127 -0
- package/src/core/review.mjs +238 -0
- package/src/core/skills.mjs +191 -0
- package/src/core/snapshot.mjs +119 -0
- package/src/core/threats.mjs +50 -0
- package/src/core/write-approval.mjs +74 -0
- package/src/core/writer.mjs +168 -0
- package/src/index.mjs +31 -0
- package/src/learn/consume.mjs +152 -0
- package/src/learn/headless.mjs +364 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// 威胁模式扫描(对齐 Hermes `tools/threat_patterns.py`,第一版逐条照抄)。
|
|
2
|
+
// 语义照抄:scope "strict" = 全部 "all" 模式 + strict 专属模式;"context" 只跑 "all"。
|
|
3
|
+
// 用途两处(也照 Hermes):①写入命中**即拒** ②加载命中**只在注入快照内**替换为 [BLOCKED: …],
|
|
4
|
+
// **磁盘原文不动**(悄悄删掉会把攻击藏起来,用户就看不到、也就删不掉)。
|
|
5
|
+
export const MAX_SCAN_CHARS = 65536
|
|
6
|
+
|
|
7
|
+
const FILLER = "(?:\\w+\\s+){0,8}"
|
|
8
|
+
const SECRET_VAR = "\\$\\{?\\w*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)S?\\b"
|
|
9
|
+
const MODIFY = "(update|modify|edit|write|change|append|add\\s+to)\\s+[^\\n]{0,2048}"
|
|
10
|
+
|
|
11
|
+
// [正则, id, scope];scope ∈ {"all","strict"};与 Hermes 的清单一一对应。
|
|
12
|
+
const RAW = [
|
|
13
|
+
[`ignore\\s+${FILLER}(previous|all|above|prior)\\s+${FILLER}instructions`, "prompt_injection", "all"],
|
|
14
|
+
["system\\s+prompt\\s+override", "sys_prompt_override", "all"],
|
|
15
|
+
[`disregard\\s+${FILLER}(your|all|any)\\s+${FILLER}(instructions|rules|guidelines)`, "disregard_rules", "all"],
|
|
16
|
+
[`act\\s+as\\s+(if|though)\\s+${FILLER}you\\s+${FILLER}(have\\s+no|don't\\s+have)\\s+${FILLER}(restrictions|limits|rules)`, "bypass_restrictions", "all"],
|
|
17
|
+
["<!--[^>]{0,512}(?:ignore|override|system|secret|hidden)[^>]{0,512}-->", "html_comment_injection", "all"],
|
|
18
|
+
["<\\s*div\\s+style\\s*=\\s*[\"'][^>]{0,2048}display\\s*:\\s*none", "hidden_div", "all"],
|
|
19
|
+
[`do\\s+not\\s+${FILLER}tell\\s+${FILLER}the\\s+user`, "deception_hide", "all"],
|
|
20
|
+
[`curl\\s+[^\\n]{0,2048}${SECRET_VAR}`, "exfil_curl", "all"],
|
|
21
|
+
[`wget\\s+[^\\n]{0,2048}${SECRET_VAR}`, "exfil_wget", "all"],
|
|
22
|
+
["cat\\s+[^\\n]{0,2048}(\\.env|credentials|\\.netrc|\\.pgpass|\\.npmrc|\\.pypirc)", "read_secrets", "all"],
|
|
23
|
+
["(send|post|upload|transmit)\\s+[^\\n]{0,2048}\\s+(to|at)\\s+https?://", "send_to_url", "strict"],
|
|
24
|
+
[`(include|output|print|share)\\s+${FILLER}(conversation|chat\\s+history|previous\\s+messages|full\\s+context|entire\\s+context)`, "context_exfil", "strict"],
|
|
25
|
+
["authorized_keys", "ssh_backdoor", "strict"],
|
|
26
|
+
["\\$HOME/\\.hermes/\\.env|~/\\.hermes/\\.env", "hermes_env", "strict"],
|
|
27
|
+
[`${MODIFY}(?:AGENTS\\.md|CLAUDE\\.md|\\.cursorrules|\\.clinerules)`, "agent_config_mod", "strict"],
|
|
28
|
+
[`${MODIFY}\\.hermes/(config\\.yaml|SOUL\\.md)`, "hermes_config_mod", "strict"],
|
|
29
|
+
["(?:api[_-]?key|token|secret|password)\\s*[=:]\\s*[\"'][A-Za-z0-9+/=_-]{20,}", "hardcoded_secret", "strict"],
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
export const THREAT_PATTERNS = RAW.map(([source, id, scope]) => ({ id, scope, re: new RegExp(source, "i") }))
|
|
33
|
+
|
|
34
|
+
/** 命中就返回模式名数组(空数组=干净)。空/非字符串/已挡的都直通(照 Hermes)。 */
|
|
35
|
+
export function scanForThreats(text, { scope = "strict" } = {}) {
|
|
36
|
+
if (typeof text !== "string" || !text) return []
|
|
37
|
+
if (text.startsWith("[BLOCKED:")) return []
|
|
38
|
+
const body = text.slice(0, MAX_SCAN_CHARS)
|
|
39
|
+
const ids = []
|
|
40
|
+
for (const p of THREAT_PATTERNS) {
|
|
41
|
+
if (scope !== "strict" && p.scope !== "all") continue
|
|
42
|
+
if (p.re.test(body)) ids.push(p.id)
|
|
43
|
+
}
|
|
44
|
+
return ids
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 注入快照里用来**替换**命中条目的占位符(措辞照 Hermes)。磁盘原文不动。 */
|
|
48
|
+
export function blockedPlaceholder({ file = "MEMORY.md", ids = [] } = {}) {
|
|
49
|
+
return `[BLOCKED: ${file} entry contained threat pattern(s): ${ids.join(", ")}. Removed from system prompt; use memory(action=remove) to delete the original.]`
|
|
50
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// 写入闸门(照 Hermes):`<subsystem>.write_approval`,子系统 memory / skills。
|
|
2
|
+
//
|
|
3
|
+
// 对齐依据(读 Hermes 源码得到,非猜测):
|
|
4
|
+
// · `tools/write_approval.py:37` CONFIG_KEY="write_approval"、`:43 write_approval_enabled(subsystem)`
|
|
5
|
+
// · `:44` 注释原文 "any unset/invalid value means gate off";`:49` `cfg_get(..., default=False)`
|
|
6
|
+
// · `:38 _TRUTHY_STRINGS = frozenset({"on","true","yes","1","approve","enabled"})`
|
|
7
|
+
// · `:54-59 _normalize_enabled`:bool 直采;字符串查白名单;**其余(含数值 1)一律 False=关**
|
|
8
|
+
// · `:45-46` 未知子系统直接 False;`:48-51` 读配置抛异常也 False
|
|
9
|
+
//
|
|
10
|
+
// 语义:**关=写入直接生效;开=进待批**(待批记录带 origin、后台来源标 [auto],见后续切片)。
|
|
11
|
+
// 落点:`D/config.json`,形状与 Hermes 同:{"memory":{"write_approval":<value>},"skills":{...}}。
|
|
12
|
+
// 为什么用我们自己的配置文件:宿主配置只承载 `skills.paths` 与 permission 条目(那是宿主机制),
|
|
13
|
+
// 闸门是**我们子系统的行为开关**,与 Hermes 把 `write_approval` 放在 agent 自己的 config 里同形。
|
|
14
|
+
import fs from "node:fs"
|
|
15
|
+
import path from "node:path"
|
|
16
|
+
|
|
17
|
+
export const SUBSYSTEMS = ["memory", "skills"]
|
|
18
|
+
export const CONFIG_KEY = "write_approval"
|
|
19
|
+
const TRUTHY_STRINGS = new Set(["on", "true", "yes", "1", "approve", "enabled"])
|
|
20
|
+
|
|
21
|
+
/** Hermes `_normalize_enabled` 的等价实现:bool 直采;字符串查白名单;其余一律关。 */
|
|
22
|
+
export function normalizeEnabled(value) {
|
|
23
|
+
if (typeof value === "boolean") return value
|
|
24
|
+
return typeof value === "string" && TRUTHY_STRINGS.has(value.trim().toLowerCase())
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function readConfig(root) {
|
|
28
|
+
try {
|
|
29
|
+
return JSON.parse(fs.readFileSync(path.join(root, "config.json"), "utf8"))
|
|
30
|
+
} catch {
|
|
31
|
+
return null // 缺失/损坏 ⇒ 与 Hermes 一致:当关(fail 到"直接生效"这一侧,因为关=直写)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 闸门是否开启(开=进待批)。读不到/非法/未知子系统 ⇒ false。 */
|
|
36
|
+
export function writeApprovalEnabled({ root, subsystem } = {}) {
|
|
37
|
+
if (!root) throw new Error("writeApprovalEnabled 需要 root(即 D 目录)")
|
|
38
|
+
if (!SUBSYSTEMS.includes(subsystem)) return false
|
|
39
|
+
const cfg = readConfig(root)
|
|
40
|
+
const raw = cfg && typeof cfg === "object" && !Array.isArray(cfg) ? cfg?.[subsystem]?.[CONFIG_KEY] : undefined
|
|
41
|
+
return normalizeEnabled(raw)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 写入来源:启动器/插件登记的前台、后台复习、或身份不明(fail-closed)。 */
|
|
45
|
+
export const ORIGINS = ["foreground", "background", "unknown"]
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 写入门控判定(照 Hermes):
|
|
49
|
+
* · 闸门关(默认)⇒ `apply`(直接生效)
|
|
50
|
+
* · 闸门开 + 后台 **add**(非破坏性)⇒ `apply`(Hermes:后台 add 直写)
|
|
51
|
+
* · 闸门开 + 前台 + 有交互通道 ⇒ `ask`(内联问:批准即写、拒绝不写)
|
|
52
|
+
* · 其余(后台破坏性 / 无通道 / 身份不明)⇒ `stage`(进待批,带 origin、后台标 [auto])
|
|
53
|
+
* 依据:`tools/write_approval.py:43-59,166`;`agent/background_review.py:1062`(无人值守的 fork 拿不到记忆工具)。
|
|
54
|
+
*/
|
|
55
|
+
export function decideWrite({ root, subsystem, origin = "unknown", destructive = false, interactive = false, hostPermission = null } = {}) {
|
|
56
|
+
if (!root) throw new Error("decideWrite 需要 root(即 D 目录)")
|
|
57
|
+
// 【硬不变量,与闸门无关】后台的破坏性操作(改/删)**永远只提案**:
|
|
58
|
+
// Hermes 依据 `agent/background_review.py:1062`——无人值守的 fork 拿不到记忆工具,
|
|
59
|
+
// 不能去删"没人复核过"的条目。这条不受 write_approval 开关影响。
|
|
60
|
+
// 【A127 · 两闸优先级】宿主权限闸说不行 ⇒ 直接 deny:
|
|
61
|
+
// 这一条压过其余所有规则(闸关、后台 add、有没有通道都不改变它)。
|
|
62
|
+
// 优先级链:**宿主 deny > 后台破坏性 stage > 身份不明 stage > 闸关 apply / 闸开 ask|stage**。
|
|
63
|
+
if (hostPermission === "deny") return "deny"
|
|
64
|
+
if (origin === "background" && destructive) return "stage"
|
|
65
|
+
// 【A132 · fail-closed】"闸关=写入直接生效"这条**只对已登记来源成立**。
|
|
66
|
+
// 身份不明的人(启动器没登记 / 登记值不认识)不能靠"就当你是前台"混进直写这条路——
|
|
67
|
+
// 那正是"把 unknown 改写成 foreground"的漏洞。身份不明一律进待批,让人看一眼。
|
|
68
|
+
if (origin === "unknown") return "stage"
|
|
69
|
+
if (!writeApprovalEnabled({ root, subsystem })) return "apply"
|
|
70
|
+
// 照 Hermes `evaluate_gate`:闸开时 skills(任何来源)与后台来源一律进待批
|
|
71
|
+
if (subsystem === "skills" || origin === "background") return "stage"
|
|
72
|
+
if (origin === "foreground" && interactive) return "ask"
|
|
73
|
+
return "stage"
|
|
74
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// Knowledge Writer: the single side-effect surface for effective changes (R4 §3.1–§3.2).
|
|
2
|
+
//
|
|
3
|
+
// Everything else (plugin, CLI, review session) may only *propose*. Only publish()/forget()
|
|
4
|
+
// change what is in effect, and both do it under the commit lock with a generation CAS.
|
|
5
|
+
import fs from "node:fs"
|
|
6
|
+
import path from "node:path"
|
|
7
|
+
import { recordId, sha256, nowIso, txId } from "./ids.mjs"
|
|
8
|
+
import { withCommitLock } from "./lock.mjs"
|
|
9
|
+
import { appendAudit } from "./audit.mjs"
|
|
10
|
+
import { readCandidate, markPublished } from "./candidate.mjs"
|
|
11
|
+
import { createMemoryStore, fileForTarget, storeHashOf } from "./memories.mjs"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
function prepareTx(L, tx) {
|
|
15
|
+
fs.mkdirSync(L.tx, { recursive: true })
|
|
16
|
+
fs.writeFileSync(path.join(L.tx, `${tx.id}.json`), JSON.stringify(tx, null, 2) + "\n")
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function clearTx(L, id) {
|
|
20
|
+
try { fs.rmSync(path.join(L.tx, `${id}.json`), { force: true }) } catch {}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Publish a validated candidate. Returns one of:
|
|
25
|
+
* { ok:true, recordId, generation, revision }
|
|
26
|
+
* { ok:false, reason:"not-found"|"not-validated"|"busy"|"stale"|"conflict"|"lost" , detail? }
|
|
27
|
+
*
|
|
28
|
+
* Takes the commit lock itself. Callers that must validate first and execute in the SAME
|
|
29
|
+
* critical section (the review protocol, R4 §3.2 step 3) take the lock and call
|
|
30
|
+
* `publishLocked` directly instead.
|
|
31
|
+
*/
|
|
32
|
+
export function publish(L, candidateIdArg, opts = {}) {
|
|
33
|
+
const cand = readCandidate(L, candidateIdArg)
|
|
34
|
+
if (!cand) return { ok: false, reason: "not-found" }
|
|
35
|
+
if (cand.status !== "validated") return { ok: false, reason: "not-validated", detail: cand.status }
|
|
36
|
+
|
|
37
|
+
// expectedGeneration may be supplied by the caller (review tooling previews against a
|
|
38
|
+
// known generation). Otherwise we read it here and CAS against it inside the lock.
|
|
39
|
+
// 令牌 = **锁内整库快照 hash**(规格 §三);参数名保留 expectedGeneration 只改含义。
|
|
40
|
+
const expectedGeneration = opts.expectedGeneration ?? storeHashOf(L.root)
|
|
41
|
+
const tx = {
|
|
42
|
+
id: txId(),
|
|
43
|
+
candidateId: cand.id,
|
|
44
|
+
recordId: recordId(cand.kind, cand.semanticKey),
|
|
45
|
+
expectedGeneration,
|
|
46
|
+
startedAt: nowIso(),
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const locked = withCommitLock(
|
|
50
|
+
L.lock,
|
|
51
|
+
({ fencing, assertStillOwner }) => publishLocked(L, cand, { fencing, assertStillOwner, tx, target: opts.target ?? null }),
|
|
52
|
+
opts,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
if (locked.ok) {
|
|
56
|
+
clearTx(L, tx.id)
|
|
57
|
+
if (locked.value.ok) markPublished(L, cand.id, locked.value.recordId)
|
|
58
|
+
return locked.value
|
|
59
|
+
}
|
|
60
|
+
return { ok: false, reason: locked.reason }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The body of a publish, with the commit lock ALREADY HELD.
|
|
65
|
+
*
|
|
66
|
+
* `tx` (optional) carries the generation this publish was prepared against; passing it turns
|
|
67
|
+
* on the whole-store CAS. The review protocol deliberately omits it — R4 §3.4 requires that
|
|
68
|
+
* unrelated additions not invalidate an outstanding preview, so it states its own narrower
|
|
69
|
+
* precondition via `precondition({ manifest })` instead, which returns a failure object or null.
|
|
70
|
+
*/
|
|
71
|
+
export function publishLocked(L, cand, { fencing, assertStillOwner, tx = null, precondition = null, approvedBy = null, target = null } = {}) {
|
|
72
|
+
const id = recordId(cand.kind, cand.semanticKey)
|
|
73
|
+
const body = String(cand.body ?? "").trim()
|
|
74
|
+
if (!body) return { ok: false, reason: "empty-body" }
|
|
75
|
+
|
|
76
|
+
if (tx && storeHashOf(L.root) !== tx.expectedGeneration) {
|
|
77
|
+
return { ok: false, reason: "stale", detail: { expectedGeneration: tx.expectedGeneration, actual: storeHashOf(L.root) } }
|
|
78
|
+
}
|
|
79
|
+
if (precondition) {
|
|
80
|
+
const failed = precondition({ recordId: id, candidate: cand })
|
|
81
|
+
if (failed) return failed
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const draftEntry = {
|
|
85
|
+
id,
|
|
86
|
+
kind: cand.kind,
|
|
87
|
+
governance: cand.scope.governance,
|
|
88
|
+
ownerId: cand.scope.ownerId,
|
|
89
|
+
status: "published",
|
|
90
|
+
createdAt: nowIso(),
|
|
91
|
+
evidenceIds: cand.evidenceIds ?? [],
|
|
92
|
+
supersedes: [...new Set(cand.supersedes ?? [])],
|
|
93
|
+
source: cand.source ?? null,
|
|
94
|
+
fence: fencing,
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const content = String(body ?? "").trim() // 常驻层=纯文本块(§ 分隔、无元数据)
|
|
98
|
+
const contentHash = sha256(Buffer.from(content))
|
|
99
|
+
draftEntry.contentHash = contentHash
|
|
100
|
+
|
|
101
|
+
if (tx) prepareTx(L, { ...tx, phase: "prepared", contentHash })
|
|
102
|
+
|
|
103
|
+
// 1) content first: until the manifest switch, readers see new bytes vs old hash and
|
|
104
|
+
// quarantine the record. That failure mode is safe (never injects unverified text).
|
|
105
|
+
|
|
106
|
+
// 规格 §七 第三层:受信任调用直接落常驻层(personal → USER.md / project → MEMORY.md,
|
|
107
|
+
// 单一真源=显式 target)。仍走 store 的 mutate(锁内重读-改-写 + 限额 + 原子替换)。
|
|
108
|
+
createMemoryStore({ root: L.root }).writeTrusted({
|
|
109
|
+
kind: fileForTarget(target ?? "memory"),
|
|
110
|
+
text: content,
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
// 2) manifest switch = the single effective point.
|
|
114
|
+
if (!assertStillOwner()) return { ok: false, reason: "lost" }
|
|
115
|
+
appendAudit(L, {
|
|
116
|
+
event: "publish",
|
|
117
|
+
txId: tx?.id ?? null,
|
|
118
|
+
recordId: id,
|
|
119
|
+
candidateId: cand.id,
|
|
120
|
+
contentHash,
|
|
121
|
+
generation: storeHashOf(L.root),
|
|
122
|
+
origin: cand.origin,
|
|
123
|
+
// Who approved it becoming effective. A publish that went through the review protocol
|
|
124
|
+
// records the human here, so "confirmation required a person" is auditable and not
|
|
125
|
+
// merely enforced at the call site (R4 §3.4).
|
|
126
|
+
approvedBy,
|
|
127
|
+
})
|
|
128
|
+
return { ok: true, recordId: id, generation: storeHashOf(L.root), contentHash: sha256(content).slice(0, 8) }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Withdraw a record from recall. Never a physical delete; the audit trail stays. */
|
|
132
|
+
export function forget(L, { kind, match } = {}, reason = null) {
|
|
133
|
+
// 【B5 步骤 2】签名由 (L, id) 改为 (L, {kind, match}):常驻层只有子串寻址 ✓。
|
|
134
|
+
// 记录层的墓碑/撤回纪元随该层退役(docs/b5-retirement-runbook.md 步骤 2–3)✓。
|
|
135
|
+
const expectedGeneration = storeHashOf(L.root)
|
|
136
|
+
const locked = withCommitLock(L.lock, ({ fencing }) => {
|
|
137
|
+
if (storeHashOf(L.root) !== expectedGeneration) return { ok: false, reason: "stale" }
|
|
138
|
+
|
|
139
|
+
try {
|
|
140
|
+
createMemoryStore({ root: L.root }).removeTrusted({ kind, match })
|
|
141
|
+
} catch (err) {
|
|
142
|
+
const msg = String((err && err.message) || "")
|
|
143
|
+
// 【A80 · 2026-09-20】零命中**不得**报成功:零命中既可能是「本来就不在」,也可能是
|
|
144
|
+
// 「match 串写错」——后者会让内容**仍然留在注入面**却报 alreadyWithdrawn ✗(谎报成功)。
|
|
145
|
+
// 按 Hermes 的形态:删除匹配不到 ⇒ 明确失败,让调用方自己核对子串。
|
|
146
|
+
if (msg.includes("未命中")) return { ok: false, reason: "not-found", hint: "零命中:请核对 match 子串是否与库中原文逐字一致" }
|
|
147
|
+
if (msg.includes("歧义")) return { ok: false, reason: "ambiguous" }
|
|
148
|
+
return { ok: false, reason: "not-found" }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
appendAudit(L, { event: "forget", kind, match, reason, generation: storeHashOf(L.root), fence: fencing })
|
|
152
|
+
return { ok: true, kind, match }
|
|
153
|
+
})
|
|
154
|
+
return locked.ok ? locked.value : { ok: false, reason: locked.reason }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Report records whose bytes no longer match the manifest (R4: drift is surfaced, never
|
|
158
|
+
* silently re-published). */
|
|
159
|
+
// 【退役 2026-09-20|B5】detectDrift():只读记录层(manifest.records + 记录文件的内容 hash)。
|
|
160
|
+
// 记录层按判据「废」退役(docs/reuse-matrix.md / docs/b5-scope.md)⇒ 不迁移:常驻层是自由文本,
|
|
161
|
+
// 没有 ID、没有内容 hash、没有"漂移"概念(规格 §八/(d):常驻层是唯一真源,改动即内容本身)。
|
|
162
|
+
|
|
163
|
+
/** Crash recovery (R4 §3.2 step 4): leftover transaction files mean a publish was
|
|
164
|
+
* interrupted. The manifest is the authority, so both outcomes are safe; we only need to
|
|
165
|
+
* close the bookkeeping and record that we did. */
|
|
166
|
+
// 【退役 2026-09-20|B5】recover():只处理记录层的 tx 簿记(manifest.records[tx.recordId])✓;
|
|
167
|
+
// 记录层按判据「废」退役(docs/reuse-matrix.md · docs/b5-scope.md)⇒ 常驻层无 tx/无 recordId,不迁移 ✓。
|
|
168
|
+
// 接守者:常驻层的崩溃安全由「锁内重读-改-写 + 临时文件 rename 原子替换」承担(memories.mjs::mutate)✓。
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Public entry point. Deliberately small: the kit is a library first, surfaces later.
|
|
2
|
+
export { layout, ensureDirs, KINDS, GOVERNANCE, VISIBILITY, SCHEMA_VERSION } from "./core/paths.mjs"
|
|
3
|
+
export { storeIdFor } from "./core/paths.mjs"
|
|
4
|
+
// (S3 收口)旧的清单权威 `./core/manifest.mjs` 已从公开入口撤下:
|
|
5
|
+
// 它判「废」,active-boundary 要求它不在活跃入口的 import 闭包里。旧职责由 memories 承接。
|
|
6
|
+
// (可见性判定退役)`visibilityVerdict` / `isVisibleTo` 已从公开面撤下:Hermes 的记忆层没有「按条目
|
|
7
|
+
// 作用域判定该不该注入」这根轴(隔离靠 store/home 边界),本项目不保留,也不提供伪兼容替身。
|
|
8
|
+
// 项目轴退役(⑤ 隔离):`makeScope` 也随之下公开面——隔离靠 store/home 边界,
|
|
9
|
+
// 条目本身不带项目字段;需要解析落点时仍保留 `resolveProject` / `findRepoRoot`。
|
|
10
|
+
export { resolveProject, findRepoRoot } from "./core/identity.mjs"
|
|
11
|
+
export {
|
|
12
|
+
createCandidate,
|
|
13
|
+
readCandidate,
|
|
14
|
+
listCandidates,
|
|
15
|
+
validateCandidate,
|
|
16
|
+
rejectCandidate,
|
|
17
|
+
} from "./core/candidate.mjs"
|
|
18
|
+
export { publish, publishLocked, forget } from "./core/writer.mjs"
|
|
19
|
+
export {
|
|
20
|
+
previewPublish,
|
|
21
|
+
confirmPublish,
|
|
22
|
+
confirmReview,
|
|
23
|
+
readReview,
|
|
24
|
+
policyVersionFor,
|
|
25
|
+
candidateReviewHash,
|
|
26
|
+
DEFAULT_PREVIEW_TTL_MS,
|
|
27
|
+
DEFAULT_POLICY_VERSION,
|
|
28
|
+
} from "./core/review.mjs"
|
|
29
|
+
export { DEFAULT_BUDGET, normalizeBudget, estimateTokens } from "./core/budget.mjs"
|
|
30
|
+
export { appendAudit, readAudit } from "./core/audit.mjs"
|
|
31
|
+
export { withCommitLock, lockInfo } from "./core/lock.mjs"
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// S7: the queue consumer — the link between "a correction was captured" and "a candidate exists
|
|
2
|
+
// to review".
|
|
3
|
+
//
|
|
4
|
+
// The adapter stops at enqueue on purpose: a child session created inside an event callback is
|
|
5
|
+
// killed when the parent run ends (measured, spike-003), so distilling has to happen outside the
|
|
6
|
+
// session, driven by an external scheduler. This module is what that scheduler calls.
|
|
7
|
+
//
|
|
8
|
+
// Two design choices worth stating:
|
|
9
|
+
//
|
|
10
|
+
// - **progress is an offset beside the queue, not a rewrite of it.** The queue is the raw
|
|
11
|
+
// record of what a user actually said; editing it to mark entries "done" would destroy the
|
|
12
|
+
// evidence that a later distillation was faithful.
|
|
13
|
+
// - **a reported failure still advances the offset.** Retrying a wedged entry forever wedges
|
|
14
|
+
// every entry behind it. The failure is reported, counted, and left in the queue file for a
|
|
15
|
+
// human to look at — but the line is consumed.
|
|
16
|
+
import fs from "node:fs"
|
|
17
|
+
import path from "node:path"
|
|
18
|
+
|
|
19
|
+
import { runHeadlessLearning } from "./headless.mjs"
|
|
20
|
+
|
|
21
|
+
/** Read the queue. A torn final line (a crash mid-append) is counted and skipped, never fatal. */
|
|
22
|
+
export function readQueue(L) {
|
|
23
|
+
let raw
|
|
24
|
+
try {
|
|
25
|
+
raw = fs.readFileSync(L.learnQueue, "utf8")
|
|
26
|
+
} catch {
|
|
27
|
+
return { entries: [], torn: 0, total: 0 }
|
|
28
|
+
}
|
|
29
|
+
const entries = []
|
|
30
|
+
let torn = 0
|
|
31
|
+
let total = 0
|
|
32
|
+
for (const line of raw.split("\n")) {
|
|
33
|
+
if (!line.trim()) continue
|
|
34
|
+
total += 1
|
|
35
|
+
try {
|
|
36
|
+
entries.push({ ...JSON.parse(line), line: total })
|
|
37
|
+
} catch {
|
|
38
|
+
torn += 1
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return { entries, torn, total }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** How many physical queue lines a consumer has already handled. */
|
|
45
|
+
export function queueOffset(L) {
|
|
46
|
+
try {
|
|
47
|
+
const n = Number.parseInt(fs.readFileSync(L.learnOffset, "utf8").trim(), 10)
|
|
48
|
+
return Number.isFinite(n) && n >= 0 ? n : 0
|
|
49
|
+
} catch {
|
|
50
|
+
return 0
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function setQueueOffset(L, n) {
|
|
55
|
+
fs.mkdirSync(path.dirname(L.learnOffset), { recursive: true })
|
|
56
|
+
const tmp = `${L.learnOffset}.${process.pid}.tmp`
|
|
57
|
+
fs.writeFileSync(tmp, `${n}\n`)
|
|
58
|
+
fs.renameSync(tmp, L.learnOffset)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Distil whatever has been captured since the last pass.
|
|
63
|
+
*
|
|
64
|
+
* `runner` is injectable so the contract can be tested without spawning a model, and so a caller
|
|
65
|
+
* can supply a recorded transcript for a deterministic end-to-end run.
|
|
66
|
+
*/
|
|
67
|
+
export async function consumeQueue(L, opts = {}) {
|
|
68
|
+
const {
|
|
69
|
+
projectDir = L.root,
|
|
70
|
+
limit = Infinity,
|
|
71
|
+
runner = runHeadlessLearning,
|
|
72
|
+
dryRun = false,
|
|
73
|
+
opencodeBin,
|
|
74
|
+
timeoutMs,
|
|
75
|
+
env,
|
|
76
|
+
} = opts
|
|
77
|
+
|
|
78
|
+
const { entries, torn, total } = readQueue(L)
|
|
79
|
+
const offset = queueOffset(L)
|
|
80
|
+
const pending = entries.filter((e) => e.line > offset)
|
|
81
|
+
|
|
82
|
+
if (dryRun) {
|
|
83
|
+
return { ok: true, dryRun: true, processed: 0, succeeded: 0, failed: 0, skipped: 0, pending: pending.length, torn, entries: [] }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const outcomes = []
|
|
87
|
+
let processed = 0
|
|
88
|
+
let succeeded = 0
|
|
89
|
+
let failed = 0
|
|
90
|
+
let skipped = 0
|
|
91
|
+
|
|
92
|
+
for (const entry of pending) {
|
|
93
|
+
if (processed >= limit) break
|
|
94
|
+
|
|
95
|
+
// An entry with nothing to distil is still consumed: it must not sit at the head of the
|
|
96
|
+
// queue blocking everything behind it.
|
|
97
|
+
if (!String(entry.excerpt ?? "").trim()) {
|
|
98
|
+
skipped += 1
|
|
99
|
+
processed += 1
|
|
100
|
+
setQueueOffset(L, entry.line)
|
|
101
|
+
outcomes.push({ line: entry.line, sessionId: entry.sessionId ?? null, state: "skipped", reason: "no excerpt", candidates: [] })
|
|
102
|
+
continue
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
let res
|
|
106
|
+
try {
|
|
107
|
+
res = await runner({
|
|
108
|
+
store: L,
|
|
109
|
+
projectDir,
|
|
110
|
+
correction: entry,
|
|
111
|
+
opencodeBin,
|
|
112
|
+
timeoutMs,
|
|
113
|
+
env,
|
|
114
|
+
})
|
|
115
|
+
} catch (e) {
|
|
116
|
+
res = { ok: false, candidates: [], reason: String(e?.message ?? e) }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
processed += 1
|
|
120
|
+
setQueueOffset(L, entry.line)
|
|
121
|
+
|
|
122
|
+
if (res?.ok && (res.candidates ?? []).length > 0) succeeded += 1
|
|
123
|
+
else if (res?.ok) skipped += 1
|
|
124
|
+
else failed += 1
|
|
125
|
+
|
|
126
|
+
outcomes.push({
|
|
127
|
+
line: entry.line,
|
|
128
|
+
sessionId: entry.sessionId ?? null,
|
|
129
|
+
projectId: entry.projectId ?? null,
|
|
130
|
+
state: res?.ok ? ((res.candidates ?? []).length > 0 ? "candidates" : "no-candidates") : "failed",
|
|
131
|
+
candidates: (res?.candidates ?? []).map((c) => c.id ?? c),
|
|
132
|
+
reason: res?.reason ?? null,
|
|
133
|
+
})
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// If everything readable has been handled, the offset also clears any torn tail line — a crash
|
|
137
|
+
// fragment must not wedge the queue forever.
|
|
138
|
+
const lastLine = entries.length ? entries[entries.length - 1].line : 0
|
|
139
|
+
if (offset >= lastLine && total > Math.max(offset, lastLine)) setQueueOffset(L, total)
|
|
140
|
+
|
|
141
|
+
return {
|
|
142
|
+
ok: failed === 0,
|
|
143
|
+
dryRun: false,
|
|
144
|
+
processed,
|
|
145
|
+
succeeded,
|
|
146
|
+
failed,
|
|
147
|
+
skipped,
|
|
148
|
+
pending: Math.max(0, pending.length - processed),
|
|
149
|
+
torn,
|
|
150
|
+
entries: outcomes,
|
|
151
|
+
}
|
|
152
|
+
}
|