opencode-growth 0.1.2 → 0.1.59

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.
Files changed (44) hide show
  1. package/README.md +2 -1
  2. package/package.json +1 -1
  3. package/src/adapter-opencode/curator-runner.mjs +254 -0
  4. package/src/adapter-opencode/index.mjs +305 -19
  5. package/src/adapter-opencode/install.mjs +63 -12
  6. package/src/adapter-opencode/journey-tool.mjs +57 -0
  7. package/src/adapter-opencode/memory-tool.mjs +57 -5
  8. package/src/adapter-opencode/provider-tools.mjs +237 -0
  9. package/src/adapter-opencode/review-runner.mjs +75 -21
  10. package/src/adapter-opencode/session-search-tool.mjs +66 -0
  11. package/src/adapter-opencode/skill-tool.mjs +221 -0
  12. package/src/cli/commands.mjs +74 -1
  13. package/src/cli/curator-cmd.mjs +147 -0
  14. package/src/cli/journey-cmd.mjs +61 -0
  15. package/src/cli/journey-view.mjs +174 -0
  16. package/src/cli/main.mjs +172 -25
  17. package/src/cli/memory-cmd.mjs +165 -0
  18. package/src/cli/session-index-cmd.mjs +74 -0
  19. package/src/cli/skill-cmd.mjs +192 -0
  20. package/src/core/approve.mjs +155 -0
  21. package/src/core/audit.mjs +51 -0
  22. package/src/core/background-review.mjs +88 -1
  23. package/src/core/home.mjs +56 -21
  24. package/src/core/journey.mjs +298 -0
  25. package/src/core/lock.mjs +6 -0
  26. package/src/core/memories.mjs +186 -9
  27. package/src/core/memory-actions.mjs +73 -18
  28. package/src/core/session-freshness.mjs +201 -0
  29. package/src/core/session-index.mjs +467 -0
  30. package/src/core/session-query.mjs +161 -0
  31. package/src/core/session-source.mjs +202 -0
  32. package/src/core/session-tool.mjs +181 -0
  33. package/src/core/skill-actions.mjs +372 -0
  34. package/src/core/skill-backup.mjs +95 -0
  35. package/src/core/skill-lifecycle.mjs +265 -0
  36. package/src/core/skill-usage.mjs +119 -0
  37. package/src/core/skills.mjs +28 -2
  38. package/src/core/sqlite-runtime.mjs +35 -0
  39. package/src/core/write-approval.mjs +13 -9
  40. package/src/host/rest-client.mjs +70 -0
  41. package/src/provider/config.mjs +187 -0
  42. package/src/provider/openviking-rest.mjs +742 -0
  43. package/src/provider/runtime.mjs +417 -0
  44. package/src/provider/wiring.mjs +164 -0
@@ -0,0 +1,202 @@
1
+ // 会话原文只读来源(G4 S1a):形状探测适配器 + 逐 part 抽取。
2
+ //
3
+ // 方向 A′(GOAL-会话索引与检索.md):只读宿主 opencode.db 全库,
4
+ // `part JOIN message JOIN session` 逐 part 抽取原话——part(type=text) 是正文承载层,
5
+ // 索引单位=part、阅读单位=message;三重 ID(part.id/message.id/session.id)+ role + 顺序全还原。
6
+ // 只读口径(D88):运行时原生 readOnly + `PRAGMA query_only=1`,**不用 `immutable=1`**;
7
+ // 主库与 -wal 零字节写痕是硬约束(宿主库只读红线)。
8
+ // 失败语义:认不出 ⇒ `unsupported-schema` 可见(六种事实各有其码),坏 JSON 计数跳过不吞空,
9
+ // 未识别 part 类型只计数不伪装。绝不把异常吞成 []。
10
+ import fs from "node:fs"
11
+ import { openDb } from "./sqlite-runtime.mjs"
12
+
13
+ const REQUIRED = {
14
+ session: ["id", "project_id", "directory", "title", "time_created"],
15
+ message: ["id", "session_id", "time_created", "data"],
16
+ part: ["id", "message_id", "time_created", "data"],
17
+ }
18
+ const KNOWN_TABLES = new Set([
19
+ ...Object.keys(REQUIRED),
20
+ "session_v2", "session_input", "session_message", "session_context_epoch", "session_share",
21
+ "workspace", "project", "project_directory", "migration", "account", "account_state",
22
+ "control_account", "credential", "data_migration", "event", "event_sequence", "permission",
23
+ "todo",
24
+ ])
25
+
26
+ const norm = (s) => String(s).toLowerCase().replace(/_/g, "")
27
+
28
+ /** 打开宿主库的只读句柄。缺失/权限/不可用是三种不同事实,各有其码。 */
29
+ export async function openSource(file) {
30
+ try {
31
+ fs.accessSync(file, fs.constants.R_OK)
32
+ } catch (e) {
33
+ const err = new Error(e.code === "ENOENT"
34
+ ? `宿主库不存在:${file}`
35
+ : `宿主库不可读:${file}`)
36
+ err.code = e.code === "ENOENT" ? "source-missing" : "permission-denied"
37
+ throw err
38
+ }
39
+ let db
40
+ try {
41
+ db = await openDb(file, { readOnly: true })
42
+ } catch (e) {
43
+ const err = new Error(`宿主库打不开:${file}(${e.message})`)
44
+ err.code = /permission|authorization|EACCES|access/i.test(e.message)
45
+ ? "permission-denied"
46
+ : "source-unavailable"
47
+ throw err
48
+ }
49
+ db.exec("PRAGMA query_only=1")
50
+ return {
51
+ db,
52
+ file,
53
+ async close() { try { db.close() } catch { /* 已关 */ } },
54
+ }
55
+ }
56
+
57
+ /** 形状探测:认得出的两代(9-15/9-25)与认不出的 `unsupported-schema` 必须可辨。 */
58
+ export function probeShape(src) {
59
+ const db = src.db ?? src
60
+ const facts = []
61
+ const rows = db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all()
62
+ const tables = new Set(rows.map((r) => r.name))
63
+
64
+ for (const [table, cols] of Object.entries(REQUIRED)) {
65
+ if (!tables.has(table)) {
66
+ facts.push({ code: "missing-table", detail: table })
67
+ continue
68
+ }
69
+ const have = db.prepare(`PRAGMA table_info(${table})`).all().map((r) => r.name)
70
+ const haveSet = new Set(have)
71
+ for (const col of cols) {
72
+ if (haveSet.has(col)) continue
73
+ const renamed = have.find((h) => norm(h) === norm(col))
74
+ if (renamed) {
75
+ facts.push({ code: "renamed-column", detail: `${table}.${col}~${renamed}` })
76
+ } else {
77
+ facts.push({ code: "missing-column", detail: `${table}.${col}` })
78
+ }
79
+ }
80
+ }
81
+
82
+ const generation = tables.has("session_v2")
83
+ ? "oc-9-15"
84
+ : (tables.has("session_input") || tables.has("session_message") ? "oc-9-25" : "core-only")
85
+ const unknown_tables = [...tables].filter((t) => !KNOWN_TABLES.has(t) && !t.startsWith("sqlite_")).sort()
86
+ return {
87
+ ok: facts.length === 0,
88
+ state: facts.length === 0 ? "ok" : "unsupported-schema",
89
+ generation,
90
+ facts,
91
+ unknown_tables,
92
+ }
93
+ }
94
+
95
+ /**
96
+ * 逐 part 抽取:索引单位=part、阅读单位=message;多 text part 分列展示不拼接。
97
+ * 字符串 tool output 默认不进正文(includeToolOutput 显式启用后单列 kind='tool-output');
98
+ * 未识别 part 类型只计数报告;坏 JSON 计数跳过但绝不吞空好行。
99
+ */
100
+ export function extractParts(src, { includeToolOutput = false, session_id = null } = {}) {
101
+ const db = src.db ?? src
102
+ const probe = probeShape(src)
103
+ if (!probe.ok) {
104
+ return {
105
+ ok: false,
106
+ state: probe.state,
107
+ parts: [],
108
+ counts: {},
109
+ unrecognized: {},
110
+ bad_json: 0,
111
+ inconsistent_session_id: 0,
112
+ empty: false,
113
+ facts: probe.facts,
114
+ }
115
+ }
116
+
117
+ const rows = db.prepare(`
118
+ SELECT p.id AS part_id, p.message_id AS message_id,
119
+ p.session_id AS part_session_id, p.time_created AS part_time, p.data AS part_data,
120
+ m.session_id AS m_session, m.time_created AS m_time, m.data AS m_data,
121
+ s.project_id AS project_id, s.directory AS directory, s.title AS title
122
+ FROM part p
123
+ JOIN message m ON m.id = p.message_id
124
+ JOIN session s ON s.id = m.session_id
125
+ ${session_id ? "WHERE m.session_id = ?" : ""}
126
+ ORDER BY p.time_created, p.id
127
+ `).all(...(session_id ? [session_id] : []))
128
+
129
+ const parts = []
130
+ const counts = { text: 0, tool: 0, tool_output: 0, reasoning: 0 }
131
+ const unrecognized = {}
132
+ const facts = []
133
+ let badJson = 0
134
+ let inconsistent = 0
135
+
136
+ for (const row of rows) {
137
+ let data
138
+ try {
139
+ data = JSON.parse(row.part_data)
140
+ } catch {
141
+ badJson += 1
142
+ if (facts.length < 5) facts.push({ code: "bad-json", detail: `part:${row.part_id}` })
143
+ continue
144
+ }
145
+ let msg = null
146
+ try {
147
+ msg = JSON.parse(row.m_data)
148
+ } catch {
149
+ badJson += 1
150
+ if (facts.length < 5) facts.push({ code: "bad-json", detail: `message:${row.message_id}` })
151
+ }
152
+ const role = msg && typeof msg.role === "string" ? msg.role : null
153
+ if (row.part_session_id && row.part_session_id !== row.m_session) inconsistent += 1
154
+
155
+ const type = data && typeof data.type === "string" ? data.type : null
156
+ if (type === "text" && typeof data.text === "string") {
157
+ counts.text += 1
158
+ parts.push({
159
+ part_id: row.part_id, message_id: row.message_id, session_id: row.m_session,
160
+ role, kind: "text", text: data.text, time_created: row.part_time, message_time: row.m_time,
161
+ project_id: row.project_id, directory: row.directory, title: row.title,
162
+ })
163
+ continue
164
+ }
165
+ if (type === "tool") {
166
+ counts.tool += 1
167
+ const out = data.state && typeof data.state.output === "string" ? data.state.output : null
168
+ if (includeToolOutput && out) {
169
+ counts.tool_output += 1
170
+ parts.push({
171
+ part_id: row.part_id, message_id: row.message_id, session_id: row.m_session,
172
+ role, kind: "tool-output", text: out, time_created: row.part_time, message_time: row.m_time,
173
+ project_id: row.project_id, directory: row.directory, title: row.title,
174
+ })
175
+ }
176
+ continue
177
+ }
178
+ if (type === "reasoning") {
179
+ counts.reasoning += 1
180
+ continue
181
+ }
182
+ const key = type ?? "<missing-type>"
183
+ unrecognized[key] = (unrecognized[key] ?? 0) + 1
184
+ }
185
+
186
+ const tally = db.prepare(`
187
+ SELECT (SELECT COUNT(*) FROM session) AS sessions,
188
+ (SELECT COUNT(*) FROM message) AS messages,
189
+ (SELECT COUNT(*) FROM part) AS parts
190
+ `).get()
191
+ return {
192
+ ok: true,
193
+ state: probe.state,
194
+ parts,
195
+ counts,
196
+ unrecognized,
197
+ bad_json: badJson,
198
+ inconsistent_session_id: inconsistent,
199
+ empty: tally.sessions === 0 && tally.messages === 0 && tally.parts === 0,
200
+ facts,
201
+ }
202
+ }
@@ -0,0 +1,181 @@
1
+ // S3b(G4):同款工具面——四形状 discovery/scroll/read/browse。
2
+ //
3
+ // 信封={success,mode,state,coverage,as_of,results|messages,error?,repair_hint?}(判据冻结的核心键);
4
+ // 失效标记(stale/incomplete/index_corrupt)为诚实性附加键(D89)——绝不静默吞掉。
5
+ // Hermes 无来源字段(lineage/profile/compacted)**不做伪字段**(对检差异记 71 校准记录)。
6
+ // 查询核心/状态/过滤与 CLI 共用(src/core/session-index.mjs)——两面不各造一套。
7
+ import { createHash } from "node:crypto"
8
+
9
+ import { openStore, readStore, searchStore, statusStore } from "./session-index.mjs"
10
+ import { boundedRefresh } from "./session-freshness.mjs"
11
+
12
+ /** 大 part 分块读的块长(字符);工具输出预算独立——budget.mjs 不参与,不丢原文。 */
13
+ export const CHUNK_CHARS = 1500
14
+
15
+ const fingerprintOf = (text) => createHash("sha256").update(text, "utf8").digest("hex").slice(0, 16)
16
+
17
+ function coreOf(root, partial = null) {
18
+ const base = statusStore({ root })
19
+ return {
20
+ state: partial?.state ?? base.state,
21
+ coverage: partial?.coverage ?? base.coverage,
22
+ as_of: partial?.as_of ?? base.as_of,
23
+ }
24
+ }
25
+
26
+ function envelope(mode, core, extra = {}) {
27
+ return {
28
+ success: true,
29
+ mode,
30
+ state: core.state,
31
+ coverage: core.coverage,
32
+ as_of: core.as_of,
33
+ ...extra,
34
+ }
35
+ }
36
+
37
+ function failure(mode, core, error, repair_hint = null) {
38
+ return {
39
+ success: false,
40
+ mode,
41
+ state: core.state,
42
+ coverage: core.coverage,
43
+ as_of: core.as_of,
44
+ error,
45
+ ...(repair_hint ? { repair_hint } : {}),
46
+ }
47
+ }
48
+
49
+ /**
50
+ * 四形状工具面。root=派生库根(与 CLI 的 --store 同一个 D)。
51
+ * discovery 命中 11 项身份字段;scroll 用真实字符串 message ID + match_part_id 锚点;
52
+ * read 支持头尾窗口与大 part 分块(part_id+part_offset+指纹,不符报 stale-anchor 不暗跳字);
53
+ * browse 给最近会话与计数。
54
+ */
55
+ export function createSessionTool({ root, sourcePath = null } = {}) {
56
+ if (!root) throw new Error("createSessionTool 需要 root")
57
+ const resolvedSource = () => sourcePath ?? statusStore({ root }).source_path ?? null
58
+
59
+ function discover({ query, limit = 3, session_id = null, role = null, since = null, until = null, includeToolOutput = false, noRelax = false, dedupe = "session" } = {}) {
60
+ const r = searchStore({
61
+ root,
62
+ query,
63
+ limit: 60,
64
+ session_id,
65
+ role,
66
+ since,
67
+ until,
68
+ includeToolOutput,
69
+ noRelax,
70
+ })
71
+ if (!r.ok) return failure("discover", coreOf(root, r), r.error_code ?? "usage", r.message ?? null)
72
+ const core = coreOf(root, r)
73
+ let rows = r.results
74
+ if (dedupe === "session") {
75
+ const seen = new Set()
76
+ rows = rows.filter((h) => (seen.has(h.session_id) ? false : (seen.add(h.session_id), true)))
77
+ }
78
+ rows = rows.slice(0, Number(limit) > 0 ? Number(limit) : 3)
79
+ const extra = { results: rows }
80
+ if (!rows.length && r.message) extra.repair_hint = r.message
81
+ if (r.stale) extra.stale = r.stale
82
+ if (r.incomplete) extra.incomplete = true
83
+ if (r.index_corrupt) extra.index_corrupt = true
84
+ return envelope("discover", core, extra)
85
+ }
86
+
87
+ function scroll({ session_id, match_part_id = null, around_message_id = null, window = 5 } = {}) {
88
+ const r = readStore({ root, session_id, message_id: around_message_id ?? null, part_id: match_part_id ?? null, window })
89
+ const core = coreOf(root, r)
90
+ if (!r.ok) return failure("scroll", core, r.error_code ?? "not-found", r.error ?? null)
91
+ const anchorId = match_part_id
92
+ ? (r.messages.find((m) => m.parts.some((p) => p.part_id === match_part_id))?.message_id ?? null)
93
+ : (around_message_id ?? null)
94
+ const messages = r.messages.map((m) => (m.message_id === anchorId ? { ...m, anchor: true } : m))
95
+ return envelope("scroll", core, { messages })
96
+ }
97
+
98
+ function read({ session_id, position = "tail", window = 5, part_id = null, part_offset = null, part_fingerprint = null } = {}) {
99
+ const core = coreOf(root)
100
+ if (part_id) {
101
+ // 大 part 分块读:part_id + part_offset + 指纹;指纹不符 ⇒ stale-anchor,绝不暗跳字。
102
+ const store = openStore(root)
103
+ try {
104
+ const row = store.db.prepare("SELECT text FROM parts WHERE part_id = ? AND session_id = ?").get(part_id, session_id)
105
+ if (!row) return failure("read", core, "not-found", `没有这个 part:${part_id}`)
106
+ const fp = fingerprintOf(row.text)
107
+ if (part_fingerprint != null && part_fingerprint !== fp) {
108
+ return failure("read", core, "stale-anchor", "内容已变(指纹不符)——先重新 discover 拿新锚点,再按新偏移读")
109
+ }
110
+ const offset = Number.isFinite(Number(part_offset)) && part_offset != null ? Number(part_offset) : 0
111
+ const chunk_text = row.text.slice(offset, offset + CHUNK_CHARS)
112
+ const end = offset + chunk_text.length
113
+ return envelope("read", core, {
114
+ results: [{
115
+ part_id,
116
+ part_offset: offset,
117
+ chunk_text,
118
+ next_offset: end < row.text.length ? end : null,
119
+ part_fingerprint: fp,
120
+ total_length: row.text.length,
121
+ }],
122
+ })
123
+ } finally {
124
+ store.close()
125
+ }
126
+ }
127
+ const r = readStore({ root, session_id, window, position })
128
+ if (!r.ok) return failure("read", coreOf(root, r), r.error_code ?? "not-found", r.error ?? null)
129
+ return envelope("read", coreOf(root, r), { messages: r.messages })
130
+ }
131
+
132
+ function browse({ limit = 3 } = {}) {
133
+ const core = coreOf(root)
134
+ const store = openStore(root)
135
+ try {
136
+ const rows = store.db.prepare(`
137
+ SELECT session_id, title, directory, project_id,
138
+ MAX(time_created) AS last_at,
139
+ COUNT(*) AS part_count,
140
+ COUNT(DISTINCT message_id) AS message_count
141
+ FROM parts
142
+ GROUP BY session_id
143
+ ORDER BY last_at DESC
144
+ LIMIT ?
145
+ `).all(Number(limit) > 0 ? Number(limit) : 3)
146
+ return envelope("browse", core, {
147
+ results: rows.map((r) => ({
148
+ session_id: r.session_id,
149
+ title: r.title,
150
+ directory: r.directory,
151
+ project_id: r.project_id,
152
+ when: r.last_at != null ? new Date(r.last_at).toISOString() : null,
153
+ message_count: r.message_count,
154
+ part_count: r.part_count,
155
+ })),
156
+ })
157
+ } finally {
158
+ store.close()
159
+ }
160
+ }
161
+
162
+ /**
163
+ * 带「搜索前有界快刷预算」的 discover(S4):
164
+ * refreshBudgetMs>0 ⇒ 预刷,超时带 stale 返回不卡调用;显式 0/负数 ⇒ 不刷并如实标 stale;
165
+ * 不传 ⇒ 纯快照查询(信封 state/as_of 自述新鲜度)。
166
+ */
167
+ async function discoverAsync(args = {}) {
168
+ const { refreshBudgetMs, ...rest } = args
169
+ let timeoutStale = false
170
+ if (refreshBudgetMs !== undefined) {
171
+ // 预算闸只在 boundedRefresh 一处(0/负数=没核对;超时=没核对),这里不重复判
172
+ const r = await boundedRefresh({ root, sourcePath: resolvedSource(), budgetMs: refreshBudgetMs })
173
+ timeoutStale = Boolean(r.timedOut)
174
+ }
175
+ const env = discover(rest)
176
+ if (timeoutStale) env.stale = { since: env.as_of, reason: "refresh-timeout" }
177
+ return env
178
+ }
179
+
180
+ return { discover, discoverAsync, scroll, read, browse }
181
+ }