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,364 @@
1
+ // The headless learning session (S5): turn a user correction into PROPOSED candidates.
2
+ //
3
+ // Everything here follows from what was measured in spikes/003 rather than assumed:
4
+ //
5
+ // * a headless `opencode run` root session is never torn down by a parent exit, so this can
6
+ // be a plain external process — no in-session fire-and-forget, which was measured to be
7
+ // killed (`MessageAbortedError`, 0 tokens);
8
+ // * PROJECT-level `permission` removes a tool from the schema. AGENT-level `permission`
9
+ // does not — the model keeps bash and write and merely declines by choice. So the
10
+ // restriction is written into the scratch project's opencode.json and never as an agent.
11
+ //
12
+ // And the rule that shapes the whole module: this path may only PROPOSE. It creates
13
+ // candidates; it cannot validate, confirm or publish. A session that could both produce a
14
+ // candidate and confirm it has not been reviewed by anyone (R4 §3.4).
15
+ import fs from "node:fs"
16
+ import os from "node:os"
17
+ import path from "node:path"
18
+ import { spawnSync } from "node:child_process"
19
+
20
+ import { KINDS } from "../core/paths.mjs"
21
+ import { createCandidate, validateCandidate } from "../core/candidate.mjs"
22
+ import { makeScope } from "../core/identity.mjs"
23
+
24
+ export const ORIGIN = "headless-learning"
25
+
26
+ /** Tools the learning session must not hold. `write` is in the list on purpose: denying
27
+ * `edit` alone still leaves a session that can rewrite files it was told to read. */
28
+ export const DENIED_TOOLS = ["bash", "edit", "write"]
29
+
30
+ export const DEFAULT_OPENCODE_BIN = process.env.OCG_OPENCODE_BIN
31
+ ?? path.join(os.homedir(), "opt", "oc-v1", "bin", "opencode")
32
+
33
+ const FENCE = /```(?:json)?\s*([\s\S]*?)```/i
34
+
35
+ /**
36
+ * Write the scratch project the session runs in. Project-level permissions only — an agent
37
+ * definition is the wrong channel and the measured-wrong one.
38
+ */
39
+ export function buildRestrictedProject(dir, opts = {}) {
40
+ fs.mkdirSync(dir, { recursive: true })
41
+ const permission = Object.fromEntries(DENIED_TOOLS.map((t) => [t, "deny"]))
42
+ const config = { $schema: "https://opencode.ai/config.json", permission }
43
+ fs.writeFileSync(path.join(dir, "opencode.json"), JSON.stringify(config, null, 2) + "\n")
44
+ fs.writeFileSync(
45
+ path.join(dir, ".gitignore"),
46
+ ["# scratch project for a restricted learning session — nothing here is meant to persist", ".opencode/", "node_modules/", ""].join("\n"),
47
+ )
48
+ return { dir, permission, denied: [...DENIED_TOOLS] }
49
+ }
50
+
51
+ /**
52
+ * The prompt. It carries the correction verbatim and asks for one strict JSON answer. It
53
+ * deliberately never mentions the review path: confirming is not this session's to do.
54
+ */
55
+ export function buildExtractionPrompt(correction = {}) {
56
+ const excerpt = String(correction.excerpt ?? "").trim()
57
+ return [
58
+ "You are extracting durable knowledge from a correction a user made.",
59
+ "",
60
+ "The user's correction, verbatim:",
61
+ "<<<CORRECTION",
62
+ excerpt,
63
+ "CORRECTION",
64
+ "",
65
+ "Reply with ONE JSON array and nothing else. Each element:",
66
+ ' { "kind": "fact" | "preference" | "episode" | "capability",',
67
+ ' "semanticKey": "<short stable slug>",',
68
+ ' "title": "<one line>",',
69
+ ' "body": "<the durable statement, in the user\'s own terms>" }',
70
+ "",
71
+ "Rules:",
72
+ "- Extract only what the correction actually establishes. Do not generalise beyond it.",
73
+ "- If nothing durable is established, reply with exactly: []",
74
+ "- Do not invent a project, an owner or a visibility: those are decided by the caller.",
75
+ "- Do not run commands. Do not modify files. Answer in text only.",
76
+ ].join("\n")
77
+ }
78
+
79
+ /**
80
+ * Parse the model's answer. Strict by design: a missing field, an unknown kind, or prose
81
+ * instead of JSON yields a rejection with a reason — never a repaired guess, because a
82
+ * fabricated candidate is worse than no candidate.
83
+ */
84
+ export function parseExtraction(raw) {
85
+ const text = String(raw ?? "")
86
+ const fenced = text.match(FENCE)
87
+ const body = fenced ? fenced[1] : text
88
+
89
+ const start = body.indexOf("[")
90
+ const end = body.lastIndexOf("]")
91
+ if (start === -1 || end === -1 || end < start) {
92
+ return { candidates: [], rejected: [], reason: "no json array found in the answer" }
93
+ }
94
+
95
+ let parsed
96
+ try {
97
+ parsed = JSON.parse(body.slice(start, end + 1))
98
+ } catch (e) {
99
+ return { candidates: [], rejected: [], reason: `not json: ${e.message}` }
100
+ }
101
+ if (!Array.isArray(parsed)) {
102
+ return { candidates: [], rejected: [], reason: "not json: the answer was not an array" }
103
+ }
104
+
105
+ const candidates = []
106
+ const rejected = []
107
+ for (const entry of parsed) {
108
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
109
+ rejected.push({ entry, reason: "not an object" })
110
+ continue
111
+ }
112
+
113
+ // A wrong TYPE is not a missing field (audit A15). `String({bad:true})` is "[object Object]"
114
+ // — non-empty, so a check that only asks "is it non-empty after coercion?" accepted a body
115
+ // that is not a sentence. Repairing a wrong type into a plausible-looking string is exactly
116
+ // the "repaired guess" this function exists to refuse, so the type is checked first.
117
+ const wrongType = ["kind", "semanticKey", "title", "body"].find(
118
+ (f) => entry[f] !== undefined && entry[f] !== null && typeof entry[f] !== "string",
119
+ )
120
+ if (wrongType) {
121
+ const got = Array.isArray(entry[wrongType]) ? "array" : typeof entry[wrongType]
122
+ rejected.push({ entry, reason: `${wrongType} must be a string, got ${got}` })
123
+ continue
124
+ }
125
+
126
+ const kind = (entry.kind ?? "").trim()
127
+ const semanticKey = (entry.semanticKey ?? "").trim()
128
+ const bodyText = (entry.body ?? "").trim()
129
+
130
+ if (!kind) { rejected.push({ semanticKey, reason: "missing kind" }); continue }
131
+ if (!KINDS.includes(kind)) { rejected.push({ semanticKey, reason: `unknown kind: ${kind}` }); continue }
132
+ if (!semanticKey) { rejected.push({ entry, reason: "missing semanticKey" }); continue }
133
+ if (!bodyText) { rejected.push({ semanticKey, reason: "missing body" }); continue }
134
+
135
+ candidates.push({
136
+ kind,
137
+ semanticKey,
138
+ title: (entry.title ?? "").trim() || semanticKey,
139
+ body: bodyText,
140
+ })
141
+ }
142
+ return { candidates, rejected, reason: null }
143
+ }
144
+
145
+ /**
146
+ * Read `opencode run --format json`'s event stream: the assistant text, the REAL session id, and
147
+ * the real token usage (audit A16).
148
+ *
149
+ * Returns null when the output is not an event stream, so a plain-text answer — or an older
150
+ * binary, or a test stub — still works through the fallback. Distinguishing the two matters:
151
+ * guessing these values would be worse than recording that they are unknown.
152
+ */
153
+ export function parseEventStream(raw) {
154
+ const lines = String(raw ?? "")
155
+ .split("\n")
156
+ .map((l) => l.trim())
157
+ .filter((l) => l.startsWith("{"))
158
+ if (!lines.length) return null
159
+
160
+ const events = []
161
+ for (const line of lines) {
162
+ try {
163
+ events.push(JSON.parse(line))
164
+ } catch {
165
+ return null // one unparseable "{" line means this is not an event stream
166
+ }
167
+ }
168
+ const withIdentity = events.filter((e) => typeof e?.type === "string" && typeof e?.sessionID === "string")
169
+ if (!withIdentity.length) return null
170
+
171
+ const sessionId = withIdentity[0].sessionID
172
+ const text = events
173
+ .filter((e) => e?.type === "text" && typeof e?.part?.text === "string")
174
+ .map((e) => e.part.text)
175
+ .join("\n")
176
+ const finish = [...events].reverse().find((e) => e?.type === "step_finish" && e?.part?.tokens)
177
+ const tokens = finish?.part?.tokens ?? null
178
+
179
+ return {
180
+ sessionId,
181
+ model: finish?.part?.model ?? null,
182
+ text,
183
+ usage: tokens ? { input: tokens.input, output: tokens.output, cost: finish?.part?.cost } : null,
184
+ }
185
+ }
186
+
187
+ function storeIsUsable(L) {
188
+ const writable = (p) => {
189
+ try {
190
+ return fs.statSync(p).isDirectory()
191
+ } catch {
192
+ return false
193
+ }
194
+ }
195
+ if (!writable(L.candidates) || !writable(L.state)) return "the store layout is missing"
196
+ // 旧权威(manifest)已退役 ⇒ 就绪信号改探**新存储面**:常驻两库存在就必须可读。
197
+ // 只探"存在即可读",不探内容语义 —— 语义由存储层自己的检查负责。
198
+ for (const f of [L.memory, L.user].filter(Boolean)) {
199
+ try {
200
+ if (fs.existsSync(f)) fs.accessSync(f, fs.constants.R_OK)
201
+ } catch (e) {
202
+ return `the resident store is unreadable: ${e.message}`
203
+ }
204
+ }
205
+ return null
206
+ }
207
+
208
+ /** A local gateway that reports cost 0 has no price table; that is not the same as free. */
209
+ function normaliseUsage(usage) {
210
+ const input = Number(usage?.inputTokens ?? usage?.input ?? 0) || 0
211
+ const output = Number(usage?.outputTokens ?? usage?.output ?? 0) || 0
212
+ const cost = Number(usage?.cost ?? 0) || 0
213
+ return { inputTokens: input, outputTokens: output, cost, costKnown: cost > 0 }
214
+ }
215
+
216
+ /**
217
+ * Run one learning pass. With `transcript` supplied it parses that instead of spawning, which
218
+ * is how the behaviour above is tested without an OpenCode install; with `dryRun` it builds
219
+ * the project and the prompt and stops.
220
+ */
221
+ export async function runHeadlessLearning({
222
+ store: L,
223
+ projectDir,
224
+ correction = {},
225
+ transcript = null,
226
+ sessionId = null,
227
+ model = null,
228
+ usage = null,
229
+ dryRun = false,
230
+ opencodeBin = DEFAULT_OPENCODE_BIN,
231
+ timeoutMs = 240_000,
232
+ env = null,
233
+ } = {}) {
234
+ if (!L) return { ok: false, error_code: "USAGE", spawned: false, candidates: [], reason: "no store" }
235
+ const layoutProblem = storeIsUsable(L)
236
+ if (layoutProblem) {
237
+ return { ok: false, error_code: "DEGRADED", spawned: false, candidates: [], reason: layoutProblem }
238
+ }
239
+
240
+ const project = buildRestrictedProject(projectDir, {})
241
+ const prompt = buildExtractionPrompt(correction)
242
+ const base = { ok: true, spawned: false, project: project.dir, prompt, denied: project.denied }
243
+
244
+ if (dryRun) {
245
+ return { ...base, candidates: [], rejected: [], reason: "dry run: nothing was spawned" }
246
+ }
247
+
248
+ let answer = transcript
249
+ // The raw stdout, kept apart from the combined answer: an event stream has to be parsed from
250
+ // stdout alone, because stderr carries logs.
251
+ let streamRaw = transcript
252
+ let actual = { sessionId, model, usage }
253
+
254
+ if (answer === null) {
255
+ if (!fs.existsSync(opencodeBin)) {
256
+ return {
257
+ ok: false,
258
+ error_code: "DEGRADED",
259
+ spawned: false,
260
+ candidates: [],
261
+ reason: `no OpenCode binary at ${opencodeBin}`,
262
+ }
263
+ }
264
+ const res = spawnSync(opencodeBin, ["run", "--format", "json", "--title", `ocg-learn-${Date.now()}`, prompt], {
265
+ cwd: project.dir,
266
+ encoding: "utf8",
267
+ timeout: timeoutMs,
268
+ // Provider credentials are NOT inherited from an opencode config: a config that says
269
+ // `{env:LITELLM_MASTER_KEY}` needs that variable present in the CHILD's environment.
270
+ // The caller supplies what its host needs; this kit stays ignorant of any one gateway.
271
+ env: env ? { ...process.env, ...env } : process.env,
272
+ })
273
+ if (res.error) {
274
+ return { ok: false, error_code: "LEARN_FAILED", spawned: true, candidates: [], reason: String(res.error.message ?? res.error) }
275
+ }
276
+ streamRaw = res.stdout ?? ""
277
+ answer = `${streamRaw}\n${res.stderr ?? ""}`
278
+ actual = { ...actual, exitCode: res.status }
279
+ if (res.status !== 0) {
280
+ return {
281
+ ok: false,
282
+ error_code: "LEARN_FAILED",
283
+ spawned: true,
284
+ candidates: [],
285
+ reason: `opencode run exited ${res.status}`,
286
+ transcript: answer,
287
+ }
288
+ }
289
+ }
290
+
291
+ // `--format json` gives the real session id and the real token usage, which a plain-text run
292
+ // leaves unobservable. Read them when the shape is there; never invent them when it is not
293
+ // (audit A16). The assistant's text comes from the stream too, so extraction runs on the answer
294
+ // rather than on a page of JSON.
295
+ const stream = parseEventStream(streamRaw)
296
+ if (stream) {
297
+ actual = {
298
+ ...actual,
299
+ sessionId: actual.sessionId ?? stream.sessionId,
300
+ model: actual.model ?? stream.model,
301
+ usage: actual.usage ?? stream.usage,
302
+ }
303
+ }
304
+ const parsed = parseExtraction(stream?.text ? stream.text : answer)
305
+ const created = []
306
+ for (const c of parsed.candidates) {
307
+ const scope = makeScope({
308
+ governance: "local",
309
+ kind: c.kind,
310
+ // Scope is the CALLER's, never the model's: "let the extraction model pick the project"
311
+ // was rejected in the design review, and a model that can widen its own scope can leak
312
+ // one project's facts into another.
313
+ appliesWhen: correction.appliesWhen,
314
+ })
315
+ const cand = createCandidate(L, {
316
+ kind: c.kind,
317
+ semanticKey: c.semanticKey,
318
+ title: c.title,
319
+ body: c.body,
320
+ scope,
321
+ evidenceIds: correction.evidenceIds ?? [],
322
+ origin: ORIGIN,
323
+ source: {
324
+ kind: ORIGIN,
325
+ sessionId: actual.sessionId,
326
+ model: actual.model,
327
+ excerpt: String(correction.excerpt ?? "").slice(0, 400),
328
+ // G1 asks for real provenance, and that is two different questions (audit A16): which
329
+ // utterance prompted this, and which session distilled it. Keeping only the second made
330
+ // the first unrecoverable — the candidate could not be traced back to what a person said.
331
+ originMessageId: correction.messageId ?? null,
332
+ originSessionId: correction.originSessionId ?? correction.sessionId ?? null,
333
+ projectId: correction.projectId ?? null,
334
+ learning: {
335
+ sessionId: actual.sessionId ?? null,
336
+ model: actual.model ?? null,
337
+ // Stated, not implied: whether this came from the invocation or was observed in the
338
+ // event stream. A null with no explanation reads like a bug; a false is a fact.
339
+ observedInEventStream: Boolean(stream?.sessionId),
340
+ usage: normaliseUsage(actual.usage),
341
+ },
342
+ },
343
+ })
344
+ // Mark it schema-validated. Note what that word means here: `validated` records that the
345
+ // payload passed the schema — parseExtraction already enforced every field, so the check
346
+ // is a formality this session can settle itself. It is NOT an approval. Approval is the
347
+ // human's, at `confirm`, and it still needs a token and a recorded approver.
348
+ //
349
+ // Doing it here rather than leaving candidates `proposed` is what keeps the chain
350
+ // reachable at all: the review path will only preview a `validated` candidate, so a
351
+ // learning session that stopped at `proposed` would produce work nobody could ever accept.
352
+ validateCandidate(L, cand.id)
353
+ created.push({ id: cand.id, status: "validated", semanticKey: cand.semanticKey, kind: cand.kind })
354
+ }
355
+
356
+ return {
357
+ ...base,
358
+ candidates: created,
359
+ rejected: parsed.rejected,
360
+ reason: parsed.reason,
361
+ usage: normaliseUsage(actual.usage),
362
+ spawned: transcript === null,
363
+ }
364
+ }