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,127 @@
|
|
|
1
|
+
// 检索层:把常驻/会话原文按需召回,**返回逐字原文**(不摘要、不重排)。
|
|
2
|
+
//
|
|
3
|
+
// 对齐依据(读 Hermes 源码得到,非猜测):
|
|
4
|
+
// · `hermes_state_common.py:720` 建 `messages_fts USING fts5(...)`;`:840` 另建 `... tokenize='trigram'`
|
|
5
|
+
// · `hermes_state_fts.py:32-37`:**trigram 每个查询词要 ≥3 字符 ⇒ 中文 1–2 字查不到**(CJK 上 session_search 的主要失效面),
|
|
6
|
+
// 所以 Hermes 用自带的可加载 tokenizer `cjk_unicode61`(`native/fts5_cjk/`,约 250 行)——
|
|
7
|
+
// 把**最长的 CJK 连续串重发成重叠字符 bigram**(Lucene CJKAnalyzer 语义),其余交给 unicode61;
|
|
8
|
+
// FTS5 的短语语义把"连续 bigram"变成**精确子串匹配**(下到 2 字)。
|
|
9
|
+
// · `hermes_state_fts.py:112` 明确是**best-effort 加载**:加载不了就退回 trigram(能力缺失要可见,不能假装)。
|
|
10
|
+
//
|
|
11
|
+
// 我们的等价做法:**不引入编译型 tokenizer**(插件里装不了、也不该让宿主去编译),
|
|
12
|
+
// 改成在 **JS 侧做同一套 bigram 变换**,写进一个独立的 `grams` 列,FTS5 用自带的 `unicode61`。
|
|
13
|
+
// 语义与 Hermes 对齐:≥2 字的 CJK 查询走 bigram 精确子串;**1 字** CJK 用 bigram 表达不出来(Hermes 同病),
|
|
14
|
+
// 故显式走子串回退并**如实标注**(见 `search()` 返回行里的 `matchedBy`),不假装是索引命中。
|
|
15
|
+
import fs from "node:fs"
|
|
16
|
+
import path from "node:path"
|
|
17
|
+
|
|
18
|
+
const CJK = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\u3040-\u30ff\uac00-\ud7af]/
|
|
19
|
+
|
|
20
|
+
/** 打开本地 SQLite:宿主是 Bun(`bun:sqlite`),测试跑 Node(`node:sqlite`)。找不到就明确失败。 */
|
|
21
|
+
async function openDb(file) {
|
|
22
|
+
for (const spec of ["bun:sqlite", "node:sqlite"]) {
|
|
23
|
+
try {
|
|
24
|
+
const mod = await import(spec)
|
|
25
|
+
const C = mod.DatabaseSync ?? mod.Database ?? mod.default?.Database ?? mod.default
|
|
26
|
+
if (typeof C === "function") return new C(file)
|
|
27
|
+
} catch { /* 换下一个运行时 */ }
|
|
28
|
+
}
|
|
29
|
+
throw new Error("找不到可用的本地 SQLite(试过 bun:sqlite 与 node:sqlite)")
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** CJK 连续串 ⇒ 重叠 bigram;其余(拉丁词、数字)原样保留。 */
|
|
33
|
+
export function bigrams(text) {
|
|
34
|
+
const out = []
|
|
35
|
+
const runs = String(text ?? "").match(/\S+/g) ?? []
|
|
36
|
+
for (const tok of runs) {
|
|
37
|
+
if (!CJK.test(tok)) { out.push(tok.toLowerCase()); continue }
|
|
38
|
+
// 以 CJK 为单位切段:CJK 段做重叠 bigram,非 CJK 段原样
|
|
39
|
+
let buf = ""
|
|
40
|
+
const flush = () => { if (buf) { out.push(buf.toLowerCase()); buf = "" } }
|
|
41
|
+
const chars = [...tok]
|
|
42
|
+
for (const ch of chars) {
|
|
43
|
+
if (CJK.test(ch)) buf += ch
|
|
44
|
+
else { flush() /* 非 CJK 片段先落 */ }
|
|
45
|
+
}
|
|
46
|
+
flush()
|
|
47
|
+
// 单独对整串做重叠 bigram(混合串也这么做,长度 ≥2 才有 bigram)
|
|
48
|
+
const cjkOnly = chars.filter((c) => CJK.test(c))
|
|
49
|
+
for (let i = 0; i + 1 < cjkOnly.length; i += 1) out.push(cjkOnly[i] + cjkOnly[i + 1])
|
|
50
|
+
}
|
|
51
|
+
return [...new Set(out)]
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 查询变换:与写入同一套;返回 { match, fallback }。 */
|
|
55
|
+
export function queryPlan(query) {
|
|
56
|
+
const q = String(query ?? "").trim()
|
|
57
|
+
const cjkChars = [...q].filter((c) => CJK.test(c))
|
|
58
|
+
// 1 个 CJK 字:bigram 表达不出来 ⇒ 子串回退(Hermes 的 trigram/bigram 同样下不到 1 字)
|
|
59
|
+
if (cjkChars.length === 1 && q.length === 1) return { match: null, fallback: q }
|
|
60
|
+
const grams = bigrams(q)
|
|
61
|
+
if (!grams.length) return { match: null, fallback: q }
|
|
62
|
+
// 用短语(引号)表达"连续"⇒ 精确子串语义(与 Hermes 的 FTS5 短语语义一致)
|
|
63
|
+
return { match: grams.map((g) => `"${g.replace(/"/g, '""')}"`).join(" "), fallback: q }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function createRetriever({ root } = {}) {
|
|
67
|
+
if (!root) throw new Error("createRetriever 需要 root(D 目录)")
|
|
68
|
+
const dir = path.join(root, "index")
|
|
69
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
70
|
+
const db = await openDb(path.join(dir, "retrieve.db"))
|
|
71
|
+
|
|
72
|
+
db.exec(`
|
|
73
|
+
CREATE TABLE IF NOT EXISTS docs (
|
|
74
|
+
id TEXT PRIMARY KEY,
|
|
75
|
+
text TEXT NOT NULL,
|
|
76
|
+
source TEXT,
|
|
77
|
+
indexed_at TEXT NOT NULL
|
|
78
|
+
);
|
|
79
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS docs_fts USING fts5(grams, id UNINDEXED, tokenize='unicode61');
|
|
80
|
+
`)
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
/** 建索引:只存原文(text 逐字保留)+ 由原文派生的 bigram 列。 */
|
|
84
|
+
async index({ id, text, source = null } = {}) {
|
|
85
|
+
if (!id || typeof text !== "string") throw new Error("index 需要 { id, text }")
|
|
86
|
+
const grams = bigrams(text).join(" ")
|
|
87
|
+
db.exec("BEGIN")
|
|
88
|
+
try {
|
|
89
|
+
db.prepare("INSERT INTO docs(id, text, source, indexed_at) VALUES(?,?,?,datetime('now')) " +
|
|
90
|
+
"ON CONFLICT(id) DO UPDATE SET text=excluded.text, source=excluded.source, indexed_at=excluded.indexed_at")
|
|
91
|
+
.run(String(id), text, source)
|
|
92
|
+
db.prepare("DELETE FROM docs_fts WHERE id = ?").run(String(id))
|
|
93
|
+
db.prepare("INSERT INTO docs_fts(grams, id) VALUES(?,?)").run(grams, String(id))
|
|
94
|
+
db.exec("COMMIT")
|
|
95
|
+
} catch (e) { db.exec("ROLLBACK"); throw e }
|
|
96
|
+
return { id: String(id), grams: grams ? grams.split(" ").length : 0 }
|
|
97
|
+
},
|
|
98
|
+
|
|
99
|
+
async remove({ id } = {}) {
|
|
100
|
+
db.prepare("DELETE FROM docs_fts WHERE id = ?").run(String(id))
|
|
101
|
+
return { removed: db.prepare("DELETE FROM docs WHERE id = ?").run(String(id)).changes }
|
|
102
|
+
},
|
|
103
|
+
|
|
104
|
+
/** 检索:命中返回**原文**(`text` 逐字来自 docs.text)。 */
|
|
105
|
+
async search({ query, limit = 5 } = {}) {
|
|
106
|
+
const plan = queryPlan(query)
|
|
107
|
+
const rows = []
|
|
108
|
+
if (plan.match) {
|
|
109
|
+
try {
|
|
110
|
+
const stmt = db.prepare(
|
|
111
|
+
"SELECT d.id, d.text, d.source FROM docs_fts f JOIN docs d ON d.id = f.id " +
|
|
112
|
+
"WHERE docs_fts MATCH ? ORDER BY rank LIMIT ?")
|
|
113
|
+
for (const r of stmt.all(plan.match, Number(limit))) rows.push({ ...r, matchedBy: "fts-bigram" })
|
|
114
|
+
} catch { /* 查询语法异常 ⇒ 落到子串回退,不假装命中 */ }
|
|
115
|
+
}
|
|
116
|
+
if (!rows.length && plan.fallback) {
|
|
117
|
+
const stmt = db.prepare(
|
|
118
|
+
"SELECT id, text, source FROM docs WHERE instr(lower(text), lower(?)) > 0 LIMIT ?")
|
|
119
|
+
for (const r of stmt.all(plan.fallback, Number(limit)))
|
|
120
|
+
rows.push({ ...r, matchedBy: "substring-fallback" })
|
|
121
|
+
}
|
|
122
|
+
return rows
|
|
123
|
+
},
|
|
124
|
+
|
|
125
|
+
async close() { db.close() },
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
// The review/publish protocol (R4 §3.4, on top of §3.2's single commit point).
|
|
2
|
+
//
|
|
3
|
+
// A preview shows a human exactly what would become effective and returns a token that
|
|
4
|
+
// BINDS every fact the decision depended on: the operation, the store, the scope, the
|
|
5
|
+
// candidate's exact bytes, the target's expected revision, the store's policy version,
|
|
6
|
+
// an expiry and a nonce. Confirming re-checks that binding INSIDE the commit lock and
|
|
7
|
+
// executes there, so "what was reviewed" and "what became effective" cannot drift.
|
|
8
|
+
//
|
|
9
|
+
// Two deliberate choices, both required by §3.4:
|
|
10
|
+
//
|
|
11
|
+
// * No whole-store generation CAS. An unrelated publish must not invalidate an
|
|
12
|
+
// outstanding preview, or a busy store would starve review forever. The precondition
|
|
13
|
+
// is the affected read/write set: this candidate's bytes and this target's revision.
|
|
14
|
+
// * A confirmed token REPLAYS its original result instead of erroring or publishing
|
|
15
|
+
// twice. Double-confirm is a normal outcome of a retried UI action, not a mistake.
|
|
16
|
+
//
|
|
17
|
+
// Honest limit, stated where it can be read: this binds CONTENT. It does not prove the
|
|
18
|
+
// operator is a person. `approvedBy` is a protocol requirement recorded in the audit
|
|
19
|
+
// trail — a local signature is not a security boundary (R4 §3.1), and a subagent that can
|
|
20
|
+
// both preview and confirm has not been reviewed by anyone.
|
|
21
|
+
import fs from "node:fs"
|
|
22
|
+
import path from "node:path"
|
|
23
|
+
import { randomUUID } from "node:crypto"
|
|
24
|
+
import { sha256, nowIso, recordId } from "./ids.mjs"
|
|
25
|
+
import { storeHashOf } from "./memories.mjs"
|
|
26
|
+
import { readCandidate, markPublished } from "./candidate.mjs"
|
|
27
|
+
import { withCommitLock } from "./lock.mjs"
|
|
28
|
+
import { publishLocked } from "./writer.mjs"
|
|
29
|
+
import { storeIdFor } from "./paths.mjs"
|
|
30
|
+
|
|
31
|
+
export const DEFAULT_PREVIEW_TTL_MS = 15 * 60 * 1000
|
|
32
|
+
export const DEFAULT_POLICY_VERSION = 1
|
|
33
|
+
|
|
34
|
+
/** The state a human actually reviews. Hashed as-is so the digest is independent of the
|
|
35
|
+
* manifest (a publish does not change what was reviewed) and stable across processes. */
|
|
36
|
+
const REVIEWED_FIELDS = ["kind", "semanticKey", "title", "body", "scope", "supersedes", "evidenceIds"]
|
|
37
|
+
|
|
38
|
+
export function policyVersionFor(L) {
|
|
39
|
+
try {
|
|
40
|
+
const p = JSON.parse(fs.readFileSync(L.policy, "utf8"))
|
|
41
|
+
if (Number.isInteger(p?.version) && p.version > 0) return p.version
|
|
42
|
+
} catch {}
|
|
43
|
+
return DEFAULT_POLICY_VERSION
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function candidateReviewHash(cand) {
|
|
47
|
+
const payload = {}
|
|
48
|
+
for (const f of REVIEWED_FIELDS) payload[f] = cand[f] ?? null
|
|
49
|
+
return sha256(Buffer.from(JSON.stringify(payload)))
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const reviewFile = (L, token) => path.join(L.reviews, `${token}.json`)
|
|
53
|
+
|
|
54
|
+
export function readReview(L, token) {
|
|
55
|
+
try {
|
|
56
|
+
return JSON.parse(fs.readFileSync(reviewFile(L, token), "utf8"))
|
|
57
|
+
} catch {
|
|
58
|
+
return null
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function writeReview(L, rec) {
|
|
63
|
+
fs.mkdirSync(L.reviews, { recursive: true })
|
|
64
|
+
const file = reviewFile(L, rec.token)
|
|
65
|
+
const tmp = `${file}.${process.pid}.tmp`
|
|
66
|
+
fs.writeFileSync(tmp, JSON.stringify(rec, null, 2) + "\n")
|
|
67
|
+
fs.renameSync(tmp, file)
|
|
68
|
+
return rec
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const refuse = (error_code, reason = null, detail = null) => ({ ok: false, error_code, reason, detail })
|
|
72
|
+
|
|
73
|
+
const PUBLISH_REASON_CODES = {
|
|
74
|
+
conflict: "CONFLICT",
|
|
75
|
+
busy: "BUSY",
|
|
76
|
+
lost: "LOCK_LOST",
|
|
77
|
+
"not-validated": "STALE_PREVIEW",
|
|
78
|
+
"not-found": "STALE_PREVIEW",
|
|
79
|
+
"empty-body": "STALE_PREVIEW",
|
|
80
|
+
stale: "STALE_PREVIEW",
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Show the human what would become effective, and bind it.
|
|
85
|
+
* Returns { ok:true, token, recordId, storeId, candidateHash, expectedRevision,
|
|
86
|
+
* policyVersion, expiresAt, operation }.
|
|
87
|
+
*/
|
|
88
|
+
export function previewPublish(L, candidateId, opts = {}) {
|
|
89
|
+
const now = opts.now ?? Date.now()
|
|
90
|
+
const cand = readCandidate(L, candidateId)
|
|
91
|
+
if (!cand) return refuse("CANDIDATE_NOT_FOUND")
|
|
92
|
+
if (cand.status !== "validated") return refuse("CANDIDATE_NOT_VALIDATED", `candidate is ${cand.status}`)
|
|
93
|
+
|
|
94
|
+
const operation = opts.operation ?? "publish"
|
|
95
|
+
const id = recordId(cand.kind, cand.semanticKey)
|
|
96
|
+
// 【B5 步骤 5】原来这里读记录层取 expectedRevision;令牌只绑操作级(§八 (d))⇒ 该读取无用,已删 ✓
|
|
97
|
+
const expectedRevision = null
|
|
98
|
+
const storeId = storeIdFor(L)
|
|
99
|
+
const policyVersion = policyVersionFor(L)
|
|
100
|
+
const candidateHash = candidateReviewHash(cand)
|
|
101
|
+
const expiresAt = now + (opts.ttlMs ?? DEFAULT_PREVIEW_TTL_MS)
|
|
102
|
+
const nonce = randomUUID()
|
|
103
|
+
|
|
104
|
+
// The token IS the digest of the binding, so a token minted for one binding cannot be
|
|
105
|
+
// presented for another even if review records are copied around.
|
|
106
|
+
// 规格 §八((d),与 Hermes 对齐):token 只绑**操作级**内容 —— 不绑目标条目 ✗
|
|
107
|
+
const bound = [operation, storeId, id, candidateHash, String(policyVersion), String(expiresAt), nonce]
|
|
108
|
+
const token = `rv_${sha256(Buffer.from(bound.join("\u0000"))).slice(0, 32)}`
|
|
109
|
+
|
|
110
|
+
writeReview(L, {
|
|
111
|
+
token,
|
|
112
|
+
operation,
|
|
113
|
+
storeId,
|
|
114
|
+
policyVersion,
|
|
115
|
+
nonce,
|
|
116
|
+
candidateId: cand.id,
|
|
117
|
+
recordId: id,
|
|
118
|
+
candidateHash,
|
|
119
|
+
expectedRevision,
|
|
120
|
+
scope: {
|
|
121
|
+
governance: cand.scope.governance,
|
|
122
|
+
ownerId: cand.scope.ownerId ?? null,
|
|
123
|
+
},
|
|
124
|
+
createdAt: nowIso(),
|
|
125
|
+
expiresAt,
|
|
126
|
+
status: "previewed",
|
|
127
|
+
approvedBy: null,
|
|
128
|
+
confirmedAt: null,
|
|
129
|
+
result: null,
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
return { ok: true, token, recordId: id, storeId, candidateHash, expectedRevision, policyVersion, expiresAt, operation }
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* A confirmation that was interrupted between the manifest switch and the record write is
|
|
137
|
+
* already effective. Recover it from the store instead of refusing it as stale, so a crash
|
|
138
|
+
* never turns a completed publish into an error the human has to reason about.
|
|
139
|
+
*/
|
|
140
|
+
function recoverCommitted(L, rec) {
|
|
141
|
+
if (rec.status !== "confirming") return null
|
|
142
|
+
const cand = readCandidate(L, rec.candidateId)
|
|
143
|
+
if (!cand || cand.status !== "published" || cand.publishedRecordId !== rec.recordId) return null
|
|
144
|
+
// B5-β:不再读记录层(manifest.records)✗ —— 重放/恢复的结果只用于**显示**,
|
|
145
|
+
// 内容标识由候选自身的字节 hash 派生 ✓(规格 §八/(d):常驻层是唯一真源 ✓)。
|
|
146
|
+
// 既有断言只依赖 ok / replayed / recordId / recovered ✓(实测 grep ✓),故行为不变 ✓。
|
|
147
|
+
return {
|
|
148
|
+
recordId: rec.recordId,
|
|
149
|
+
contentHash: candidateReviewHash(cand).slice(0, 8),
|
|
150
|
+
generation: storeHashOf(L.root),
|
|
151
|
+
recovered: true,
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Validate the binding and execute, both inside the commit lock (R4 §3.2 step 3).
|
|
157
|
+
* `confirmPublish` is this with operation pinned to "publish"; the generic form exists so
|
|
158
|
+
* the operation binding is testable and so a future `promote` cannot ride a publish token.
|
|
159
|
+
*/
|
|
160
|
+
export function confirmReview(L, token, opts = {}) {
|
|
161
|
+
const now = () => opts.now ?? Date.now()
|
|
162
|
+
const operation = opts.operation ?? "publish"
|
|
163
|
+
const approvedBy = typeof opts.approvedBy === "string" ? opts.approvedBy.trim() : ""
|
|
164
|
+
if (!approvedBy) {
|
|
165
|
+
return refuse("HUMAN_APPROVAL_REQUIRED", "confirmation requires a recorded human approver")
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const rec = readReview(L, token)
|
|
169
|
+
if (!rec) return refuse("UNKNOWN_TOKEN", "no review record for this token")
|
|
170
|
+
if (rec.operation !== operation) {
|
|
171
|
+
return refuse("OPERATION_MISMATCH", `token is bound to operation "${rec.operation}"`)
|
|
172
|
+
}
|
|
173
|
+
if (rec.storeId !== storeIdFor(L)) {
|
|
174
|
+
return refuse("STORE_MISMATCH", "token was minted against a different store")
|
|
175
|
+
}
|
|
176
|
+
if (rec.status === "confirmed") return { ...rec.result, ok: true, replayed: true }
|
|
177
|
+
|
|
178
|
+
const locked = withCommitLock(
|
|
179
|
+
L.lock,
|
|
180
|
+
({ fencing, assertStillOwner }) => {
|
|
181
|
+
// Re-read inside the lock: another process may have confirmed while we waited.
|
|
182
|
+
const fresh = readReview(L, token)
|
|
183
|
+
if (!fresh) return refuse("UNKNOWN_TOKEN", "review record disappeared")
|
|
184
|
+
if (fresh.status === "confirmed") return { ...fresh.result, ok: true, replayed: true }
|
|
185
|
+
|
|
186
|
+
const recovered = recoverCommitted(L, fresh)
|
|
187
|
+
if (recovered) {
|
|
188
|
+
writeReview(L, { ...fresh, status: "confirmed", approvedBy, confirmedAt: nowIso(), result: recovered })
|
|
189
|
+
return { ...recovered, ok: true, replayed: true }
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if (now() > fresh.expiresAt) return refuse("EXPIRED", "the preview is past its expiry")
|
|
193
|
+
if (fresh.policyVersion !== policyVersionFor(L)) {
|
|
194
|
+
return refuse("POLICY_VERSION_MISMATCH", "the store policy changed since the preview", {
|
|
195
|
+
previewed: fresh.policyVersion,
|
|
196
|
+
current: policyVersionFor(L),
|
|
197
|
+
})
|
|
198
|
+
}
|
|
199
|
+
if (storeIdFor(L) !== fresh.storeId) return refuse("STORE_MISMATCH")
|
|
200
|
+
|
|
201
|
+
const cand = readCandidate(L, fresh.candidateId)
|
|
202
|
+
if (!cand) return refuse("STALE_PREVIEW", "the candidate is gone")
|
|
203
|
+
if (cand.status !== "validated") return refuse("STALE_PREVIEW", `candidate is ${cand.status}`)
|
|
204
|
+
if (candidateReviewHash(cand) !== fresh.candidateHash) {
|
|
205
|
+
return refuse("STALE_PREVIEW", "the candidate changed after it was reviewed")
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// The affected read/write set — NOT the whole store. This is what keeps an unrelated
|
|
209
|
+
// publish from invalidating a review (R4 §3.4).
|
|
210
|
+
// 规格 §八((d)):**不**因目标条目变化而失效 ✗ —— "目标已变"由本次锁内重读 + 写时校验兜 ✓,
|
|
211
|
+
// 与 Hermes 同构(前台写入即生效,无"预览失效"概念)。expectedRevision 仅作显示用途保留 ✓。
|
|
212
|
+
|
|
213
|
+
// Record the intent before touching anything, so an interruption is recognisable.
|
|
214
|
+
writeReview(L, { ...fresh, status: "confirming", approvedBy, confirmingAt: nowIso() })
|
|
215
|
+
|
|
216
|
+
const res = publishLocked(L, cand, { fencing, assertStillOwner, approvedBy })
|
|
217
|
+
if (!res.ok) {
|
|
218
|
+
writeReview(L, { ...fresh, status: "previewed" })
|
|
219
|
+
return refuse(PUBLISH_REASON_CODES[res.reason] ?? "PUBLISH_FAILED", res.reason, res.detail ?? null)
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
markPublished(L, cand.id, res.recordId)
|
|
223
|
+
const result = { recordId: res.recordId, contentHash: res.contentHash ?? null, generation: storeHashOf(L.root) }
|
|
224
|
+
writeReview(L, { ...fresh, status: "confirmed", approvedBy, confirmedAt: nowIso(), result })
|
|
225
|
+
return { ...result, ok: true, replayed: false }
|
|
226
|
+
},
|
|
227
|
+
{ waitMs: opts.lockWaitMs },
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
if (!locked.ok) {
|
|
231
|
+
return refuse(locked.reason === "busy" ? "BUSY" : "LOCK_LOST", locked.reason)
|
|
232
|
+
}
|
|
233
|
+
return locked.value
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export function confirmPublish(L, token, opts = {}) {
|
|
237
|
+
return confirmReview(L, token, { ...opts, operation: "publish" })
|
|
238
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { WRITE_PERMISSION_NAME } from "./paths.mjs"
|
|
2
|
+
// 技能读路径(M1-S7)。
|
|
3
|
+
//
|
|
4
|
+
// 目标(GOAL §0 第 6 条):**`skills.paths` 指向 `D/skills/`,宿主原生发现—加载—使用,
|
|
5
|
+
// 且不重复注入索引。**
|
|
6
|
+
//
|
|
7
|
+
// 三条来自宿主实况的硬事实(都不是文档抄的):
|
|
8
|
+
//
|
|
9
|
+
// 1. **宿主原生支持这件事**:`opencode.json` 的 `skills` 是**对象** `{paths, urls}`,
|
|
10
|
+
// `paths` 会被**递归扫 `**/SKILL.md`**。实测(零模型调用,`opencode debug skill`):
|
|
11
|
+
// 不配 `skills.paths` → 我们的技能**不在**清单;配上 → 出现且 `location` 指向我们的
|
|
12
|
+
// `D/skills/<name>/SKILL.md`。源码侧对应 `skill/index.ts:211` 起的那个循环。
|
|
13
|
+
// 2. **格式错了会静默消失**:`name` 必须小写连字符、与文件夹同名;**没有 `description`
|
|
14
|
+
// 的技能会被过滤掉、永不露面**(宿主内置技能正文的原话)。所以格式问题必须**报成错误**,
|
|
15
|
+
// 不能让它静静地什么也不发生。
|
|
16
|
+
// 3. **索引归宿主管**:宿主自己把技能清单注入系统提示(`session/system.ts` 的
|
|
17
|
+
// `SystemPrompt.skills`)。我们的常驻块只装**记忆**——重复注入同一份索引就是白付两次钱。
|
|
18
|
+
// 这条由 `test/skills.test.mjs` 正向对照钉住(块必须非空,才谈得上"不含技能")。
|
|
19
|
+
import fs from "node:fs"
|
|
20
|
+
import path from "node:path"
|
|
21
|
+
|
|
22
|
+
/** 宿主只认这个文件名,逐字一致。 */
|
|
23
|
+
export const SKILL_FILE = "SKILL.md"
|
|
24
|
+
|
|
25
|
+
/** 技能名规则(照宿主内置技能正文):小写、连字符分隔、≤64 字符。 */
|
|
26
|
+
const NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
|
27
|
+
const NAME_MAX = 64
|
|
28
|
+
|
|
29
|
+
/** `D/skills/` 的**绝对**路径。相对根会被解析成绝对——宿主的相对 `paths` 是相对**会话目录**的,
|
|
30
|
+
* 那会让同一个 D 在不同项目下指向不同地方。 */
|
|
31
|
+
export function skillsDir(root) {
|
|
32
|
+
if (!root) throw new Error("skillsDir 需要 root(D 目录)")
|
|
33
|
+
return path.join(path.resolve(String(root)), "skills")
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 极简 frontmatter:只要 `---` 包起来的 `key: value`。不引 YAML 依赖(宿主自己也是窄解析)。 */
|
|
37
|
+
function parseFrontmatter(text) {
|
|
38
|
+
const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(String(text))
|
|
39
|
+
if (!m) return null
|
|
40
|
+
const out = {}
|
|
41
|
+
for (const line of m[1].split(/\r?\n/)) {
|
|
42
|
+
const hit = /^([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/.exec(line)
|
|
43
|
+
if (hit) out[hit[1]] = hit[2].trim().replace(/^["']|["']$/g, "")
|
|
44
|
+
}
|
|
45
|
+
return out
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 检查一个技能目录是否符合宿主的形状。**不合规要报错**——宿主对不合规是静默的
|
|
50
|
+
* (尤其没有 description 的那种,永远不会被列给模型),静默失败最难查。
|
|
51
|
+
*/
|
|
52
|
+
export function checkSkillLayout(dir) {
|
|
53
|
+
const folder = path.basename(path.resolve(String(dir)))
|
|
54
|
+
const file = path.join(dir, SKILL_FILE)
|
|
55
|
+
if (!fs.existsSync(file)) return { ok: false, error: `目录里没有 ${SKILL_FILE}:${file}` }
|
|
56
|
+
|
|
57
|
+
const fm = parseFrontmatter(fs.readFileSync(file, "utf8"))
|
|
58
|
+
if (!fm) return { ok: false, error: `${SKILL_FILE} 缺少 frontmatter(要以 --- 开头包一段)` }
|
|
59
|
+
|
|
60
|
+
const name = fm.name
|
|
61
|
+
if (!name) return { ok: false, error: "frontmatter 缺 name" }
|
|
62
|
+
if (name !== folder) {
|
|
63
|
+
return { ok: false, error: `name(${name})与文件夹名(${folder})不一致——宿主按文件夹定位技能` }
|
|
64
|
+
}
|
|
65
|
+
if (!NAME_RE.test(name) || name.length > NAME_MAX) {
|
|
66
|
+
return { ok: false, error: `name 必须小写连字符分隔、≤${NAME_MAX} 字符:${name}` }
|
|
67
|
+
}
|
|
68
|
+
if (!fm.description) {
|
|
69
|
+
return { ok: false, error: "缺 description:宿主会把没有 description 的技能**静默过滤**,模型永远看不到它" }
|
|
70
|
+
}
|
|
71
|
+
return { ok: true, name }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 把 `D/skills/` 并进宿主的 `opencode.json`(返回**新对象**,不就地改)。
|
|
76
|
+
*
|
|
77
|
+
* 三条要求:① 用户已有的字段一个都不能丢;② 幂等(跑两次不长出两条);
|
|
78
|
+
* ③ 兼容宿主自己那层 v2 换算——`skills` 曾经可以是**字符串数组**(`v2-compat.ts:155-160`
|
|
79
|
+
* 把它换算成 `{paths, urls}`),我们按同一语义处理,免得写出一份宿主读不懂的配置。
|
|
80
|
+
*/
|
|
81
|
+
export function hostConfigFor({ root, existing = {} } = {}) {
|
|
82
|
+
const ours = skillsDir(root)
|
|
83
|
+
const prev = existing && typeof existing === "object" ? existing : {}
|
|
84
|
+
const rawSkills = prev.skills
|
|
85
|
+
|
|
86
|
+
let paths = []
|
|
87
|
+
// 必须给初值:两条分支都可能不进(配置里根本没有 skills 段),
|
|
88
|
+
// 否则下面 `urls.length` 就是读 undefined 的属性(第一次跑就是这么红的)。
|
|
89
|
+
let urls = []
|
|
90
|
+
if (Array.isArray(rawSkills)) {
|
|
91
|
+
paths = rawSkills.filter((v) => typeof v === "string" && !/^https?:\/\//i.test(v))
|
|
92
|
+
urls = rawSkills.filter((v) => typeof v === "string" && /^https?:\/\//i.test(v))
|
|
93
|
+
} else if (rawSkills && typeof rawSkills === "object") {
|
|
94
|
+
paths = Array.isArray(rawSkills.paths) ? rawSkills.paths.filter((v) => typeof v === "string") : []
|
|
95
|
+
urls = Array.isArray(rawSkills.urls) ? rawSkills.urls.filter((v) => typeof v === "string") : []
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const merged = paths.includes(ours) ? paths.slice() : [...paths, ours]
|
|
99
|
+
const skills = { ...(urls.length ? { urls } : {}), paths: merged }
|
|
100
|
+
|
|
101
|
+
// §0 第 5 条接线(C42):让宿主对**我们的写入权限**要求询问。
|
|
102
|
+
// 键必须与插件 `ask()` 发出的名字同源(WRITE_PERMISSION_NAME),否则策略从不匹配 ⇒ 静默放行。
|
|
103
|
+
// 不覆盖用户已设过的值:用户显式 allow/deny 是他的决定,只补**缺失**的那一项。
|
|
104
|
+
const rawPerm = prev.permission
|
|
105
|
+
const permission =
|
|
106
|
+
rawPerm && typeof rawPerm === "object" && !Array.isArray(rawPerm) ? { ...rawPerm } : {}
|
|
107
|
+
if (permission[WRITE_PERMISSION_NAME] === undefined) permission[WRITE_PERMISSION_NAME] = "ask"
|
|
108
|
+
|
|
109
|
+
return { ...prev, skills, permission }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ── 技能来源(对齐 Hermes `skills.external_dirs`) ─────────────────────
|
|
113
|
+
// 规则照 Hermes:①本地在前、外部在后(发现顺序)②同名**输给本地** ③外部目录**只读**
|
|
114
|
+
// ④冲突要在 doctor 里**显式报告**(不许悄悄压住)。
|
|
115
|
+
// 不做的那条轴:Hermes 还有 `trusted_project_dirs`(仓库级技能 + 白名单)。宿主 OpenCode
|
|
116
|
+
// 没有"进某仓库自动加载该仓库技能"这一层,我们只是宿主里的插件 ⇒ 该风险面在宿主里不存在,
|
|
117
|
+
// 故**不做**(记账见 30-decision-log D59)。
|
|
118
|
+
export function listSkillsIn(dir) {
|
|
119
|
+
try {
|
|
120
|
+
return fs
|
|
121
|
+
.readdirSync(dir, { withFileTypes: true })
|
|
122
|
+
.filter((e) => e.isDirectory() && fs.existsSync(path.join(dir, e.name, SKILL_FILE)))
|
|
123
|
+
.map((e) => e.name)
|
|
124
|
+
.sort()
|
|
125
|
+
} catch {
|
|
126
|
+
return null
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function resolveSkillSources({ localDir = null, externalDirs = [] } = {}) {
|
|
131
|
+
const skills = []
|
|
132
|
+
const conflicts = []
|
|
133
|
+
const missing = []
|
|
134
|
+
const seen = new Map()
|
|
135
|
+
const take = (dir, source) => {
|
|
136
|
+
const names = listSkillsIn(dir)
|
|
137
|
+
if (names === null) {
|
|
138
|
+
// 本地目录不存在 = 还没放技能(正常);**外部**目录不存在 = 配置写错了(要报)。
|
|
139
|
+
if (source !== "local") missing.push(dir)
|
|
140
|
+
return
|
|
141
|
+
}
|
|
142
|
+
for (const name of names) {
|
|
143
|
+
if (seen.has(name)) {
|
|
144
|
+
conflicts.push({ name, winner: seen.get(name), loser: { name, location: path.join(dir, name), source } })
|
|
145
|
+
continue
|
|
146
|
+
}
|
|
147
|
+
const entry = { name, location: path.join(dir, name), source }
|
|
148
|
+
seen.set(name, entry)
|
|
149
|
+
skills.push(entry)
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (localDir) take(localDir, "local")
|
|
153
|
+
for (const d of externalDirs) if (d) take(d, "external")
|
|
154
|
+
return { skills, conflicts, missing }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// doctor 用的一行报告:谁赢了、谁被压住,说清楚。
|
|
158
|
+
export function describeConflicts({ conflicts = [] } = {}) {
|
|
159
|
+
if (!conflicts.length) return null
|
|
160
|
+
const parts = conflicts.map((c) => c.name + "(本地赢:" + c.winner.location + ";外部被压住:" + c.loser.location + ")")
|
|
161
|
+
return "技能命名冲突 " + conflicts.length + " 处:" + parts.join(";")
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// doctor 的技能节:让 `doctor` 一句话说清「本地/外部各几份、谁被压住、哪个外部目录根本不存在」。
|
|
165
|
+
export function doctorSkillsSection({ localDir = null, externalDirs = [] } = {}) {
|
|
166
|
+
const r = resolveSkillSources({ localDir, externalDirs })
|
|
167
|
+
return {
|
|
168
|
+
localDir,
|
|
169
|
+
externalDirs,
|
|
170
|
+
skillCount: r.skills.length,
|
|
171
|
+
conflictCount: r.conflicts.length,
|
|
172
|
+
conflicts: describeConflicts(r),
|
|
173
|
+
missing: r.missing,
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// 外部技能目录来自**我们自己的** `D/config.json`(键 `skills.external_dirs`,与 Hermes 同名同义),
|
|
178
|
+
// 不去动宿主的 `opencode.json`(那是宿主的配置面,我们只往里写必需的那一条 skills.paths)。
|
|
179
|
+
// 读不到 / 坏 JSON / 类型不对 ⇒ 一律空数组(fail closed:没配就是没配,不猜)。
|
|
180
|
+
export function readExternalDirs(root) {
|
|
181
|
+
if (!root) return []
|
|
182
|
+
let cfg = null
|
|
183
|
+
try {
|
|
184
|
+
cfg = JSON.parse(fs.readFileSync(path.join(root, "config.json"), "utf8"))
|
|
185
|
+
} catch {
|
|
186
|
+
return []
|
|
187
|
+
}
|
|
188
|
+
const raw = cfg?.skills?.external_dirs
|
|
189
|
+
if (!Array.isArray(raw)) return []
|
|
190
|
+
return raw.filter((v) => typeof v === "string" && v.trim()).map((v) => v.trim())
|
|
191
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// 冻结块(M1-S4)。
|
|
2
|
+
//
|
|
3
|
+
// 它回答一个问题:**这次会话该看到的那段常驻内容是什么**——而且答案在同一次会话里**不再变**。
|
|
4
|
+
//
|
|
5
|
+
// 为什么必须冻结(不是因为好看):
|
|
6
|
+
// · Hermes 在会话加载时把记忆冻结一次,理由是"**prefix cache 稳定**"——每轮重算是每轮一次 cache miss。
|
|
7
|
+
// · 还有一条更隐蔽的:不冻结的话,**模型能在同一回合里给自己写指令,下一步就被它自己写的指令影响**。
|
|
8
|
+
// · 实测 OpenCode **不冻结**(会话中途改全局指令立刻生效,去重粒度是 MessageID 而不是会话),
|
|
9
|
+
// 所以这件事得我们自己实现:首次有效 sessionID 建一份快照,此后逐字复用。
|
|
10
|
+
//
|
|
11
|
+
// 块内**不许有动态字段**(时间、用量、修订号、epoch)——写进去等于每轮都破一次 cache,
|
|
12
|
+
// 而且会让"冻结"这件事看起来还在、其实已经失效(extra#6)。
|
|
13
|
+
//
|
|
14
|
+
// 与旧读路径的关系:这一块**取代**了 G1 的 `context.mjs` + `render.mjs` 在注入上的职责。
|
|
15
|
+
// 那两件仍留在 src/ 里(CLI 与旧测试还用),但**不再出现在活跃注入路径上**(S4 的"旧读路径退出")。
|
|
16
|
+
import fs from "node:fs"
|
|
17
|
+
import path from "node:path"
|
|
18
|
+
|
|
19
|
+
import { createMemoryStore, ENTRY_DELIMITER, DEFAULT_LIMITS } from "./memories.mjs"
|
|
20
|
+
import { scanForThreats, blockedPlaceholder } from "./threats.mjs"
|
|
21
|
+
|
|
22
|
+
/** 块的版本号。它进快照(用于识别陈旧快照),但**不进块文本**。 */
|
|
23
|
+
// 版本号进快照用于识别陈旧快照。**加消毒(⑥ 注入安全)时必须升它**——
|
|
24
|
+
// 否则修复前冻结的旧快照会因为版本仍相等而被逐字复用,恶意原文照样进提示词(审计 A147)。
|
|
25
|
+
export const BLOCK_VERSION = 2
|
|
26
|
+
|
|
27
|
+
/** 稳定标识:适配器靠它做幂等判断(hook 每次 run 触发三次)。 */
|
|
28
|
+
export const BLOCK_MARKER = "<ocg-resident"
|
|
29
|
+
|
|
30
|
+
const SECTIONS = [
|
|
31
|
+
["memory", "## 记忆(长期事实)"],
|
|
32
|
+
["user", "## 画像(关于用户本人)"],
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
const snapshotPath = (root, sessionID) => path.join(root, "snapshots", `${sessionID}.json`)
|
|
36
|
+
|
|
37
|
+
/** 原子写:写同目录临时文件再 rename(要么旧、要么完整新,不会半截)。 */
|
|
38
|
+
function atomicWrite(file, text) {
|
|
39
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
40
|
+
const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`
|
|
41
|
+
fs.writeFileSync(tmp, text)
|
|
42
|
+
fs.renameSync(tmp, file)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const FILE_FOR_KIND = { memory: "MEMORY.md", user: "USER.md" }
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 注入前的消毒(照 Hermes `memory_tool_store.load_from_disk`):命中威胁模式 ⇒ **只在快照里**
|
|
49
|
+
* 换成 `[BLOCKED: …]`,**磁盘原文不动**——悄悄删掉会把攻击藏起来,用户就看不到也删不掉。
|
|
50
|
+
*/
|
|
51
|
+
function sanitizeForInjection(entry, kind) {
|
|
52
|
+
const ids = scanForThreats(entry, { scope: "strict" })
|
|
53
|
+
if (!ids.length) return entry
|
|
54
|
+
return blockedPlaceholder({ file: FILE_FOR_KIND[kind] ?? "MEMORY.md", ids })
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 块文本**只由常驻内容决定**:同一份内容 ⇒ 同一份字节(与 sessionID 无关)。 */
|
|
58
|
+
function buildBlock(entries) {
|
|
59
|
+
const sections = []
|
|
60
|
+
for (const [kind, heading] of SECTIONS) {
|
|
61
|
+
const list = (entries[kind] ?? []).map((e) => sanitizeForInjection(e, kind))
|
|
62
|
+
if (list.length) sections.push(`${heading}\n${list.join(ENTRY_DELIMITER)}`)
|
|
63
|
+
}
|
|
64
|
+
if (!sections.length) return null
|
|
65
|
+
return `${BLOCK_MARKER} v${BLOCK_VERSION}>\n\n${sections.join("\n\n")}\n\n</ocg-resident>`
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function readSnapshot(file) {
|
|
69
|
+
try {
|
|
70
|
+
const snap = JSON.parse(fs.readFileSync(file, "utf8"))
|
|
71
|
+
// 版本不符或形状不对 ⇒ 当作没有(重建),绝不让坏字节进提示词。
|
|
72
|
+
if (snap?.version === BLOCK_VERSION && typeof snap.block === "string" && snap.block) return snap
|
|
73
|
+
} catch {
|
|
74
|
+
/* 读不到/坏 JSON 都走重建 */
|
|
75
|
+
}
|
|
76
|
+
return null
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 取本次会话该注入的冻结块。
|
|
81
|
+
*
|
|
82
|
+
* @returns {{ text: string|null, version: number, created: boolean, sessionID: string }}
|
|
83
|
+
* `text === null` 表示"没有任何常驻内容可注入"——这时**不建快照**(空快照会让下次误以为已冻结)。
|
|
84
|
+
*/
|
|
85
|
+
export async function frozenBlockFor({ root, sessionID, store = null, enabled = {}, limits = {} } = {}) {
|
|
86
|
+
if (!root) throw new Error("frozenBlockFor 需要 root(即 D 目录)")
|
|
87
|
+
if (!sessionID) throw new Error("frozenBlockFor 需要 sessionID(冻结的粒度就是它)")
|
|
88
|
+
|
|
89
|
+
const file = snapshotPath(root, sessionID)
|
|
90
|
+
|
|
91
|
+
// ① 已经有快照 → 逐字复用(哪怕常驻文件后来被改过:这就是冻结)。
|
|
92
|
+
const existing = readSnapshot(file)
|
|
93
|
+
if (existing) return { text: existing.block, version: BLOCK_VERSION, created: false, sessionID }
|
|
94
|
+
|
|
95
|
+
// ② 没有 → 从常驻两库构建。内容决定字节,所以并发首注入也会得到同一份。
|
|
96
|
+
const s = store ?? createMemoryStore({ root, enabled, limits })
|
|
97
|
+
const entries = Object.fromEntries(SECTIONS.map(([kind]) => [kind, s.read({ kind })]))
|
|
98
|
+
const block = buildBlock(entries)
|
|
99
|
+
if (!block) return { text: null, version: BLOCK_VERSION, created: false, sessionID }
|
|
100
|
+
|
|
101
|
+
atomicWrite(
|
|
102
|
+
file,
|
|
103
|
+
JSON.stringify(
|
|
104
|
+
{ sessionID, version: BLOCK_VERSION, block, frozenAt: new Date().toISOString() },
|
|
105
|
+
null,
|
|
106
|
+
2,
|
|
107
|
+
) + "\n",
|
|
108
|
+
)
|
|
109
|
+
return { text: block, version: BLOCK_VERSION, created: true, sessionID }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 快照元信息(诊断用;不参与注入)。 */
|
|
113
|
+
export function snapshotInfo({ root, sessionID }) {
|
|
114
|
+
const snap = readSnapshot(snapshotPath(root, sessionID))
|
|
115
|
+
if (!snap) return null
|
|
116
|
+
return { sessionID: snap.sessionID, version: snap.version, frozenAt: snap.frozenAt, bytes: snap.block.length }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export { DEFAULT_LIMITS }
|