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,421 @@
1
+ // The CLI's commands (S4). Each one is a pure function of (options, store) -> envelope.
2
+ //
3
+ // Two rules this file exists to honour:
4
+ // * a refusal is a non-zero exit with a machine-readable code (R4 §3.4);
5
+ // * there is NO command here that publishes without review. `candidates confirm` is the
6
+ // only path to an effective change, it needs a token a human was shown, and it needs a
7
+ // recorded approver. A subagent handed this CLI can preview; it cannot confirm anything
8
+ // a person did not look at.
9
+ import fs from "node:fs"
10
+ import path from "node:path"
11
+
12
+ import { KINDS, SCHEMA_VERSION, MIN_READER } from "../core/paths.mjs"
13
+ import { sha256 } from "../core/ids.mjs"
14
+ import { createMemoryStore, ENTRY_DELIMITER } from "../core/memories.mjs"
15
+ import { listCandidates, readCandidate } from "../core/candidate.mjs"
16
+ import { forget } from "../core/writer.mjs"
17
+ import { storeInitMarker } from "../adapter-opencode/install.mjs"
18
+ import { storeIdFor } from "../core/paths.mjs"
19
+ import { previewPublish, confirmPublish, policyVersionFor } from "../core/review.mjs"
20
+ import { lockInfo } from "../core/lock.mjs"
21
+ import { consumeQueue, queueOffset } from "../learn/consume.mjs"
22
+ import { ok, fail, codeForReason } from "./envelope.mjs"
23
+ import { installAll, resolveInstallPaths, uninstallAll } from "../adapter-opencode/install.mjs"
24
+ import { storeHashOf } from "../core/memories.mjs"
25
+ import { doctorSkillsSection, readExternalDirs, skillsDir } from "../core/skills.mjs"
26
+
27
+ const isDir = (p) => {
28
+ try {
29
+ return fs.statSync(p).isDirectory()
30
+ } catch {
31
+ return false
32
+ }
33
+ }
34
+
35
+ /** The context a read-path question is asked in. Absent identity is stated, never guessed. */
36
+ function readContext(opts) {
37
+ return {
38
+ sessionId: opts.session ?? null,
39
+ projectId: opts.project ?? null,
40
+ ownerId: opts.owner ?? null,
41
+ environmentId: opts.environment ?? null,
42
+ platform: opts.platform ?? process.platform,
43
+ }
44
+ }
45
+
46
+ // ── doctor ───────────────────────────────────────────────────────────
47
+
48
+ /**
49
+ * Report whether this store can actually do its job. A missing capability is DEGRADED and a
50
+ * non-zero exit: a doctor that passes green on a store missing half its layout is a trap.
51
+ */
52
+ function doctorChecks(opts, ctx) {
53
+ const { L } = ctx
54
+ const checks = []
55
+ const add = (name, status, detail) => checks.push({ name, status, detail: detail ?? null })
56
+
57
+ add("store root exists", isDir(L.root) ? "ok" : "failed", L.root)
58
+
59
+ // 本世代的**权威回执**是安装器写的 `install-manifest.json`(含 storeSource:这个 D 怎么来的)。
60
+ // 旧世代的 `state/manifest.json` 只在**它还在场**时顺带解析一次——不在场不是错误。
61
+ let legacyManifest = null
62
+ const installManifestPath = path.join(L.root, "install-manifest.json")
63
+ try {
64
+ const im = JSON.parse(fs.readFileSync(installManifestPath, "utf8"))
65
+ add("install manifest parses", "ok",
66
+ `tool ${im.tool ?? "?"} · version ${im.version ?? "?"} · store 来源 ${im.storeSource ?? "?"} · storeHash ${storeHashOf(L.root)}`)
67
+ } catch (e) {
68
+ add("install manifest parses", "failed", `${installManifestPath}: ${e.message}`)
69
+ }
70
+ const legacyPath = path.join(L.root, "state", "manifest.json")
71
+ if (fs.existsSync(legacyPath)) {
72
+ try {
73
+ legacyManifest = JSON.parse(fs.readFileSync(legacyPath, "utf8"))
74
+ add("legacy state/manifest.json parses", "ok", legacyPath)
75
+ } catch (e) {
76
+ add("legacy state/manifest.json parses", "failed", `${legacyPath}: ${e.message}`)
77
+ }
78
+ } else {
79
+ add("legacy state/manifest.json parses", "ok", "不在场(本世代不再写它)")
80
+ }
81
+
82
+ if (legacyManifest) {
83
+ const v = legacyManifest.schemaVersion
84
+ const compatible = Number.isInteger(v) && v >= MIN_READER && v <= SCHEMA_VERSION
85
+ add("schema within the reader window", compatible ? "ok" : "failed", `store ${v}, reader accepts ${MIN_READER}..${SCHEMA_VERSION}`)
86
+ } else {
87
+ add("schema within the reader window", "ok", "本世代的 store 不带世代号(读取窗口对安装回执不适用)")
88
+ }
89
+
90
+ // 运行时布局 = **安装器创建的那四个目录**(读写路径用的就是它们)。
91
+ // state/ 与 audit/ 是**按需创建**的,所以只报"会被按需创建",不把它们算成缺失能力。
92
+ for (const [name, dir] of [
93
+ ["memories", path.join(L.root, "memories")],
94
+ ["snapshots", path.join(L.root, "snapshots")],
95
+ ["pending", path.join(L.root, "pending")],
96
+ ["skills", path.join(L.root, "skills")],
97
+ ]) {
98
+ add(`${name} directory exists`, isDir(dir) ? "ok" : "failed", dir)
99
+ }
100
+ for (const name of ["state", "audit"]) {
101
+ add(`${name} directory(按需创建)`, "ok", `${path.join(L.root, name)} 不存在时会在首次使用时创建`)
102
+ }
103
+
104
+ const stop = path.join(L.root, "STOP")
105
+ add("no STOP switch present", fs.existsSync(stop) ? "failed" : "ok", stop)
106
+
107
+ // 技能来源(对齐 Hermes `skills.external_dirs`):本地在前、外部只读、同名输给本地;
108
+ // 冲突**必须显式报告**,外部目录不存在也要如实报(否则人看不出配置写错了)。
109
+ {
110
+ const sk = doctorSkillsSection({ localDir: skillsDir(L.root), externalDirs: readExternalDirs(L.root) })
111
+ const bits = [`本地 ${sk.localDir}`, `外部 ${sk.externalDirs.length} 个`, `技能 ${sk.skillCount} 份`]
112
+ if (sk.missing.length) bits.push(`外部目录缺失:${sk.missing.join(", ")}`)
113
+ if (sk.conflicts) bits.push(sk.conflicts)
114
+ add("skills sources resolvable", sk.missing.length ? "failed" : "ok", bits.join(" · "))
115
+ }
116
+
117
+
118
+ // 【片1-④】常驻两库文件:**只提示,不处理**(2026-09-20 拍板)——
119
+ // · 全新 store(无初始化标记、也无任何库文件)⇒ 缺文件是**正常**,记 ok;
120
+ // · 已初始化的 store 上文件缺失 ⇒ 视为**用户的意图** ⇒ 记 `warn`(不是 failed ✓),
121
+ // 说清"不会自动重建",且这里**绝不**创建/恢复文件。
122
+ const libs = ["MEMORY.md", "USER.md"].map((n) => path.join(L.root, "memories", n))
123
+ const initialized = fs.existsSync(storeInitMarker(L)) || libs.some((f) => fs.existsSync(f))
124
+ for (const file of libs) {
125
+ const name = path.basename(file)
126
+ if (fs.existsSync(file)) add(`resident lib ${name}`, "ok", file)
127
+ else if (!initialized) add(`resident lib ${name}`, "ok", `${file} 尚未创建(全新 store,正常)`)
128
+ else add(`resident lib ${name}`, "warn", `${file} 不存在 —— 可能你有意删过;不会自动重建,请自行新建或前台 add 一条`)
129
+ }
130
+
131
+ const held = lockInfo(L.lock)
132
+ const live = held && typeof held.expiresAt === "number" && held.expiresAt > Date.now()
133
+ add("commit lock is free", live ? "degraded" : "ok", live ? `held by pid ${held.pid}` : "free")
134
+
135
+ const broken = checks.filter((c) => c.status !== "ok")
136
+ const data = {
137
+ status: broken.length ? "degraded" : "ok",
138
+ store: L.root,
139
+ storeId: storeIdFor(L),
140
+ policyVersion: policyVersionFor(L),
141
+ node: process.version,
142
+ checks,
143
+ }
144
+ if (broken.length) {
145
+ return fail("doctor", "DEGRADED", `${broken.length} of ${checks.length} checks are not ok: ${broken.map((c) => c.name).join(", ")}`, data)
146
+ }
147
+ return ok("doctor", `all ${checks.length} checks ok`, data)
148
+ }
149
+
150
+ // ── status ───────────────────────────────────────────────────────────
151
+
152
+ export function status(opts, ctx) {
153
+ const { L } = ctx
154
+ // 旧权威(manifest)已退役 ⇒ 只报**常驻存储面**的真实信息(规格 docs/store-token-spec.md 第 5 条)。
155
+ // 路径与分隔符一律取自 memories.mjs(单一真源),不从别处推导——layout() 里没有常驻层的键。
156
+ const store = createMemoryStore({ root: L.root })
157
+ const parts = []
158
+ let entries = 0
159
+ let chars = 0
160
+ for (const kind of ["memory", "user"]) {
161
+ let text = ""
162
+ try {
163
+ text = fs.readFileSync(store.paths.file(kind), "utf8")
164
+ } catch {
165
+ text = ""
166
+ }
167
+ chars += text.length
168
+ entries += text.split(ENTRY_DELIMITER).filter((x) => x.trim() !== "").length
169
+ parts.push(text)
170
+ }
171
+ const pending = store.pending().length
172
+
173
+ const candidates = {}
174
+ for (const c of listCandidates(L)) candidates[c.status] = (candidates[c.status] ?? 0) + 1
175
+
176
+ const data = {
177
+ store: L.root,
178
+ storeId: storeIdFor(L),
179
+ schemaVersion: SCHEMA_VERSION,
180
+ // 世代号的替代:**常驻库内容 hash**(只作"当前快照"标识,不声称单调世代)
181
+ storeHash: sha256(parts.join("\u0000")).slice(0, 16),
182
+ policyVersion: policyVersionFor(L),
183
+ entries,
184
+ chars,
185
+ pending,
186
+ candidates,
187
+ kinds: KINDS,
188
+ }
189
+ return ok("status", `${entries} entrie(s) resident, ${chars} char(s), ${pending} pending`, data)
190
+ }
191
+
192
+ // ── install(S7 part B:安装入口)─────────────────────────────────────────────
193
+
194
+ /**
195
+ * 把适配器装进宿主:D 的目录、宿主的插件文件、宿主的 `skills.paths`。
196
+ *
197
+ * 这个命令存在的理由是一条已经记录在案的事实:`install.mjs` 判「留」却**从任何入口都够不到**,
198
+ * 于是"宿主插件的安装入口不存在"——用户装不上。装不上就没有闭环。
199
+ *
200
+ * 它**不碰** D 里的记忆与快照:只建目录、写宿主侧的两个文件。
201
+ */
202
+ export function installCmd(opts, ctx) {
203
+ const { L } = ctx
204
+ try {
205
+ const out = installAll({
206
+ store: L.root,
207
+ configDir: opts.config ? String(opts.config) : null,
208
+ queuePath: opts.queue ? String(opts.queue) : null,
209
+ dryRun: Boolean(opts["dry-run"]),
210
+ })
211
+ return ok(
212
+ "install",
213
+ opts["dry-run"] ? "dry-run:只是计划,一个字节都没写" : `装好了:${out.shim}`,
214
+ {
215
+ store: out.store,
216
+ configDir: out.configDir,
217
+ shim: out.shim,
218
+ pluginDir: out.pluginDir,
219
+ configFile: out.configFile,
220
+ skillsPath: out.skillsPath,
221
+ configCreated: out.created,
222
+ dryRun: Boolean(opts["dry-run"]),
223
+ plan: out.report,
224
+ },
225
+ )
226
+ } catch (err) {
227
+ return fail("install", "INSTALL_FAILED", err?.message ?? String(err))
228
+ }
229
+ }
230
+
231
+ // ── candidates ───────────────────────────────────────────────────────
232
+
233
+ export function candidatesList(opts, ctx) {
234
+ const { L } = ctx
235
+ const rows = listCandidates(L, opts.state ? { status: opts.state } : {}).map((c) => ({
236
+ id: c.id,
237
+ kind: c.kind,
238
+ semanticKey: c.semanticKey,
239
+ status: c.status,
240
+ origin: c.origin,
241
+ createdAt: c.createdAt,
242
+ }))
243
+ return ok("candidates.list", `${rows.length} candidate(s)`, { candidates: rows, state: opts.state ?? null })
244
+ }
245
+
246
+ export function candidatesPreview(opts, ctx) {
247
+ const { L } = ctx
248
+ const id = opts._[0]
249
+ if (!id) return fail("candidates.preview", "USAGE", "candidates preview <candidateId>")
250
+ const r = previewPublish(L, id, {})
251
+ if (!r.ok) return fail("candidates.preview", r.error_code, r.reason ?? r.error_code, null)
252
+
253
+ // Show the reviewer what they are approving (audit A14). Binding the bytes with a hash is not
254
+ // the same as a person having read them: a preview that returns only a token and a digest asks
255
+ // someone to sign a document they cannot see. The payload below is exactly the bytes the token
256
+ // binds, read back from the candidate the hash was taken over.
257
+ const cand = readCandidate(L, id)
258
+ return ok("candidates.preview", `review token for ${r.recordId} (expires ${new Date(r.expiresAt).toISOString()})`, {
259
+ token: r.token,
260
+ operation: r.operation,
261
+ recordId: r.recordId,
262
+ candidateId: id,
263
+ candidateHash: r.candidateHash,
264
+ expectedRevision: r.expectedRevision,
265
+ policyVersion: r.policyVersion,
266
+ expiresAt: r.expiresAt,
267
+ storeId: r.storeId,
268
+ candidate: {
269
+ id: cand.id,
270
+ kind: cand.kind,
271
+ semanticKey: cand.semanticKey,
272
+ title: cand.title,
273
+ body: cand.body,
274
+ status: cand.status,
275
+ scope: {
276
+ governance: cand.scope?.governance ?? null,
277
+ visibility: cand.scope?.visibility ?? null,
278
+ // The record's own field names, not tidier ones: a reviewer should be reading the same
279
+ // shape that will be written, not a paraphrase of it.
280
+ scopeProjectIds: cand.scope?.scopeProjectIds ?? [],
281
+ originProjectId: cand.scope?.originProjectId ?? null,
282
+ ownerId: cand.scope?.ownerId ?? null,
283
+ appliesWhen: cand.scope?.appliesWhen ?? null,
284
+ },
285
+ evidence: cand.evidenceIds ?? [],
286
+ origin: cand.origin ?? null,
287
+ contentHash: r.expectedContentHash ?? null,
288
+ },
289
+ })
290
+ }
291
+
292
+ export function candidatesConfirm(opts, ctx) {
293
+ const { L } = ctx
294
+ const token = opts._[0]
295
+ if (!token) return fail("candidates.confirm", "USAGE", "candidates confirm <token> --as <who>")
296
+ if (!opts.as || !String(opts.as).trim()) {
297
+ return fail(
298
+ "candidates.confirm",
299
+ "HUMAN_APPROVAL_REQUIRED",
300
+ "confirmation needs --as <who> identifying the person who reviewed the preview",
301
+ null,
302
+ )
303
+ }
304
+ const wait = Number.parseInt(process.env.OCG_LOCK_WAIT_MS ?? "", 10)
305
+ const r = confirmPublish(L, token, {
306
+ approvedBy: String(opts.as),
307
+ ...(Number.isFinite(wait) ? { lockWaitMs: wait } : {}),
308
+ })
309
+ if (!r.ok) return fail("candidates.confirm", r.error_code, r.reason ?? r.error_code, r.detail ?? null)
310
+ return ok("candidates.confirm", r.replayed ? "already confirmed — returning the original result" : `published ${r.recordId}`, {
311
+ recordId: r.recordId,
312
+ contentHash: r.contentHash ?? null,
313
+ generation: r.generation,
314
+ replayed: Boolean(r.replayed),
315
+ approvedBy: String(opts.as),
316
+ })
317
+ }
318
+
319
+ // ── memory ───────────────────────────────────────────────────────────
320
+
321
+
322
+ export function memoryForget(opts, ctx) {
323
+ const { L } = ctx
324
+ const match = opts._[0]
325
+ if (!match) return fail("memory.forget", "USAGE", "memory forget <match> [--kind memory|user] [--reason <text>]")
326
+ const r = forget(L, { kind: opts.kind ?? "memory", match }, opts.reason ?? null)
327
+ if (!r.ok) return fail("memory.forget", codeForReason(r.reason), `cannot withdraw 「${match}」: ${r.reason}`)
328
+ return ok("memory.forget", r.alreadyWithdrawn ? `「${match}」 was already withdrawn` : `「${match}」 withdrawn`, {
329
+ match,
330
+ kind: r.kind ?? (opts.kind ?? "memory"),
331
+ withdrawn: true,
332
+ alreadyWithdrawn: Boolean(r.alreadyWithdrawn),
333
+ })
334
+ }
335
+
336
+ // ── learn ────────────────────────────────────────────────────────────
337
+
338
+ /**
339
+ * Distil the corrections captured since the last pass into candidates.
340
+ *
341
+ * This is the link S6 deliberately left out: capturing a correction inside an OpenCode session
342
+ * writes a queue line, and something outside the session has to turn it into a candidate. It is
343
+ * a scheduling command, so it is idempotent — running it twice distils nothing the second time.
344
+ *
345
+ * It does NOT publish. Learning produces candidates; a person still has to confirm them.
346
+ */
347
+ export async function learnRun(opts, ctx) {
348
+ const { L } = ctx
349
+ const limit = opts.limit === undefined ? Infinity : Number(opts.limit)
350
+ if (Number.isNaN(limit) || limit < 0) {
351
+ return fail("learn.run", "USAGE", "--limit must be a non-negative number")
352
+ }
353
+
354
+ const before = queueOffset(L)
355
+ const res = await consumeQueue(L, {
356
+ projectDir: opts.project ?? L.root,
357
+ limit,
358
+ dryRun: Boolean(opts["dry-run"]),
359
+ })
360
+
361
+ if (res.dryRun) {
362
+ return ok("learn.run", `${res.pending} correction(s) waiting (dry run: nothing was learned)`, {
363
+ dryRun: true,
364
+ pending: res.pending,
365
+ torn: res.torn,
366
+ offset: before,
367
+ })
368
+ }
369
+
370
+ const summary = res.processed === 0
371
+ ? "nothing new to learn"
372
+ : `${res.processed} correction(s): ${res.succeeded} produced candidates, ${res.failed} failed, ${res.skipped} skipped`
373
+ return ok("learn.run", summary, {
374
+ dryRun: false,
375
+ processed: res.processed,
376
+ succeeded: res.succeeded,
377
+ failed: res.failed,
378
+ skipped: res.skipped,
379
+ pending: res.pending,
380
+ torn: res.torn,
381
+ offsetBefore: before,
382
+ offsetAfter: queueOffset(L),
383
+ entries: res.entries,
384
+ })
385
+ }
386
+
387
+ // ── context ──────────────────────────────────────────────────────────
388
+
389
+
390
+ /** Read one candidate without going through the CLI — used by `doctor --deep` later. */
391
+ export function candidateOrNull(L, id) {
392
+ return readCandidate(L, id)
393
+ }
394
+
395
+ /**
396
+ * doctor 外面包一层:把**安装路径解析**也报出来 —— 让「它认为该往哪写」可见,
397
+ * 而不是只报 store 内部健康度。解析失败不影响 doctor 本体。
398
+ */
399
+ export function doctor(opts, ctx) {
400
+ const envOut = doctorChecks(opts, ctx)
401
+ try {
402
+ const resolved = resolveInstallPaths({ store: ctx?.L?.root ?? null, configDir: opts?.config ? String(opts.config) : null })
403
+ // handler 返回的是 {envelope, exit} 包装(不是信封本身),且 data 是冻结的 ⇒ 造新对象返回
404
+ const env = envOut?.envelope
405
+ if (env && env.data) return { ...envOut, envelope: { ...env, data: { ...env.data, resolved } } }
406
+ } catch { /* 解析不出就不报,不因此让 doctor 挂掉 */ }
407
+ return envOut
408
+ }
409
+
410
+ /** uninstall:只撤我们写的东西(回执 + shim + 我们追加的那条 skills path),幂等。 */
411
+ export function uninstallCmd(opts, ctx) {
412
+ const { L } = ctx
413
+ try {
414
+ const out = uninstallAll({ store: L.root, configDir: opts.config ? String(opts.config) : null })
415
+ return ok("uninstall",
416
+ out.removed.length ? `撤掉了 ${out.removed.length} 项` : "没有需要撤的东西(幂等)",
417
+ { ...out })
418
+ } catch (e) {
419
+ return fail("uninstall", "REFUSED", e?.message ?? String(e))
420
+ }
421
+ }
@@ -0,0 +1,64 @@
1
+ // The CLI's return envelope and its exit-code policy (S4).
2
+ //
3
+ // Every command answers with the SAME shape, success or failure, so a caller never has to
4
+ // guess: { ok, command, error_code, message, data }. `error_code` is the machine-readable
5
+ // half and is what maps to an exit code — R4 §3.4 requires STALE_PREVIEW to be non-zero, and
6
+ // a refusal that exits 0 is worse than no CLI at all.
7
+ //
8
+ // 0 OK the command did what it said
9
+ // 1 REFUSED a policy or staleness refusal: the request was understood and denied
10
+ // 2 USAGE the caller asked for something that does not exist
11
+ // 3 BUSY retryable contention (another writer holds the commit lock)
12
+ // 4 NOT_FOUND the named thing is not in the store
13
+ // 5 DEGRADED a capability is missing; never a green pass (GOAL §1, S4)
14
+ export const EXIT = {
15
+ OK: 0,
16
+ REFUSED: 1,
17
+ USAGE: 2,
18
+ BUSY: 3,
19
+ NOT_FOUND: 4,
20
+ DEGRADED: 5,
21
+ }
22
+
23
+ const EXIT_FOR_CODE = {
24
+ USAGE: EXIT.USAGE,
25
+ NOT_FOUND: EXIT.NOT_FOUND,
26
+ CANDIDATE_NOT_FOUND: EXIT.NOT_FOUND,
27
+ BUSY: EXIT.BUSY,
28
+ LOCK_LOST: EXIT.BUSY,
29
+ DEGRADED: EXIT.DEGRADED,
30
+ }
31
+
32
+ /** Unknown codes are refusals, not successes — the default must fail closed. */
33
+ export function exitFor(error_code) {
34
+ if (!error_code) return EXIT.OK
35
+ return EXIT_FOR_CODE[error_code] ?? EXIT.REFUSED
36
+ }
37
+
38
+ export function ok(command, message, data = null) {
39
+ return {
40
+ envelope: { ok: true, command, error_code: null, message, data },
41
+ exit: EXIT.OK,
42
+ }
43
+ }
44
+
45
+ export function fail(command, error_code, message, data = null) {
46
+ return {
47
+ envelope: { ok: false, command, error_code, message, data },
48
+ exit: exitFor(error_code),
49
+ }
50
+ }
51
+
52
+ /** Map a library reason string onto this surface's error codes. */
53
+ export function codeForReason(reason, fallback = "REFUSED") {
54
+ const table = {
55
+ "not-found": "NOT_FOUND",
56
+ "not-validated": "CANDIDATE_NOT_VALIDATED",
57
+ busy: "BUSY",
58
+ lost: "LOCK_LOST",
59
+ stale: "STALE_PREVIEW",
60
+ conflict: "CONFLICT",
61
+ "empty-body": "CANDIDATE_NOT_VALIDATED",
62
+ }
63
+ return table[reason] ?? fallback
64
+ }