opencode-growth 0.1.2 → 0.1.74
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/README.md +72 -13
- package/package.json +1 -1
- package/src/adapter-opencode/curator-runner.mjs +257 -0
- package/src/adapter-opencode/index.mjs +309 -19
- package/src/adapter-opencode/install.mjs +329 -52
- package/src/adapter-opencode/journey-tool.mjs +57 -0
- package/src/adapter-opencode/memory-tool.mjs +57 -5
- package/src/adapter-opencode/provider-tools.mjs +237 -0
- package/src/adapter-opencode/review-runner.mjs +180 -37
- package/src/adapter-opencode/session-search-tool.mjs +66 -0
- package/src/adapter-opencode/skill-tool.mjs +221 -0
- package/src/cli/commands.mjs +98 -5
- package/src/cli/curator-cmd.mjs +149 -0
- package/src/cli/journey-cmd.mjs +61 -0
- package/src/cli/journey-view.mjs +174 -0
- package/src/cli/main.mjs +173 -26
- package/src/cli/memory-cmd.mjs +165 -0
- package/src/cli/session-index-cmd.mjs +87 -0
- package/src/cli/skill-cmd.mjs +194 -0
- package/src/core/approve.mjs +295 -0
- package/src/core/audit.mjs +51 -0
- package/src/core/background-review.mjs +114 -2
- package/src/core/home.mjs +56 -21
- package/src/core/journey.mjs +298 -0
- package/src/core/lock.mjs +6 -0
- package/src/core/memories.mjs +215 -10
- package/src/core/memory-actions.mjs +73 -18
- package/src/core/paths.mjs +0 -1
- package/src/core/session-freshness.mjs +201 -0
- package/src/core/session-index.mjs +508 -0
- package/src/core/session-query.mjs +161 -0
- package/src/core/session-source.mjs +209 -0
- package/src/core/session-tool.mjs +189 -0
- package/src/core/skill-actions.mjs +391 -0
- package/src/core/skill-backup.mjs +95 -0
- package/src/core/skill-lifecycle.mjs +277 -0
- package/src/core/skill-usage.mjs +119 -0
- package/src/core/skills.mjs +30 -3
- package/src/core/sqlite-runtime.mjs +35 -0
- package/src/core/write-approval.mjs +13 -9
- package/src/host/rest-client.mjs +70 -0
- package/src/index.mjs +0 -1
- package/src/provider/config.mjs +187 -0
- package/src/provider/openviking-rest.mjs +742 -0
- package/src/provider/runtime.mjs +417 -0
- package/src/provider/wiring.mjs +164 -0
- package/src/core/budget.mjs +0 -64
- package/src/core/retrieve.mjs +0 -127
package/src/cli/main.mjs
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
1
|
// CLI entry logic (S4): parse argv, resolve the store, dispatch, render.
|
|
2
2
|
//
|
|
3
|
-
// The store
|
|
4
|
-
//
|
|
3
|
+
// The store comes from ONE rule shared with the installer and the plugin (`src/core/home.mjs`):
|
|
4
|
+
// `--store` (explicit) > `$OCG_STORE` (compat override) > `$OCG_HOME` > platform default.
|
|
5
|
+
// The resolution's provenance travels with the request (`store_source`/`store_via`/`store_conflicts`)
|
|
6
|
+
// so a lower-priority variable that was set to a *different* path is visible rather than silently
|
|
7
|
+
// outvoted — the failure mode this rule exists to prevent is "ran against the wrong store".
|
|
8
|
+
// Resolution itself never moves data: whatever root is picked is the root that gets written.
|
|
5
9
|
import process from "node:process"
|
|
10
|
+
import { homedir } from "node:os"
|
|
6
11
|
|
|
7
12
|
import { layout } from "../core/paths.mjs"
|
|
13
|
+
import { resolveStoreRoot } from "../core/home.mjs"
|
|
8
14
|
import { EXIT, fail } from "./envelope.mjs"
|
|
9
15
|
import {
|
|
10
16
|
doctor,
|
|
@@ -13,14 +19,21 @@ import {
|
|
|
13
19
|
candidatesPreview,
|
|
14
20
|
candidatesConfirm,
|
|
15
21
|
memoryForget,
|
|
22
|
+
memoryPendingCmd,
|
|
23
|
+
memoryApproveCmd,
|
|
16
24
|
learnRun,
|
|
17
25
|
installCmd,
|
|
18
26
|
uninstallCmd,
|
|
19
27
|
} from "./commands.mjs"
|
|
28
|
+
import { journeyCmd, journeyListCmd } from "./journey-cmd.mjs"
|
|
29
|
+
import { memorySetup, memoryStatus, memoryOff } from "./memory-cmd.mjs"
|
|
30
|
+
import { sessionIndexRebuildCmd, sessionIndexReadCmd, sessionIndexSearchCmd, sessionIndexStatusCmd, sessionIndexSyncCmd } from "./session-index-cmd.mjs"
|
|
31
|
+
import { curatorPruneCmd, curatorRunCmd, curatorLedgerCmd } from "./curator-cmd.mjs"
|
|
32
|
+
import { skillCreateCmd, skillPatchCmd, skillListCmd, skillViewCmd, skillUsageCmd, skillArchiveCmd, skillRestoreCmd, skillPinCmd, skillUnpinCmd, skillLifecycleCmd, skillRollbackCmd, skillAdoptCmd, skillUnmanagedCmd } from "./skill-cmd.mjs"
|
|
20
33
|
|
|
21
34
|
const USAGE = `oc-grow — memory, candidates and the review protocol for OpenCode
|
|
22
35
|
|
|
23
|
-
Usage: oc-grow --store <dir> [--json] <command> [args]
|
|
36
|
+
Usage: oc-grow [--store <dir>] [--json] <command> [args]
|
|
24
37
|
|
|
25
38
|
doctor can this store do its job? (never a green pass when not)
|
|
26
39
|
status what is in effect, what is pending
|
|
@@ -32,16 +45,56 @@ Usage: oc-grow --store <dir> [--json] <command> [args]
|
|
|
32
45
|
memory forget <recordId> [--reason <text>]
|
|
33
46
|
withdraw it; takes effect immediately
|
|
34
47
|
what this session was actually given, and every eviction
|
|
48
|
+
memory pending list staged proposals (what is waiting for a person)
|
|
49
|
+
memory approve <ref> --as <who> apply one staged proposal to the resident layer; needs a
|
|
50
|
+
recorded approver. Rejecting needs no command: delete the
|
|
51
|
+
file. A ref that matches zero or several is never guessed
|
|
35
52
|
install [--config <dir>] [--dry-run]
|
|
36
|
-
uninstall [--config <dir>]
|
|
53
|
+
uninstall [--config <dir>] [--from <manifest>]
|
|
37
54
|
write the host plugin file + register D/skills/;
|
|
38
55
|
changes nothing inside D
|
|
39
56
|
learn run [--limit <n>] [--dry-run]
|
|
40
57
|
distil corrections captured since the last pass into
|
|
41
58
|
candidates; never publishes anything
|
|
59
|
+
journey [--since <dur>] [--kind <k>] [--state <s>] [--reveal 0..1]
|
|
60
|
+
[--play] [--fps <n>] [--json]
|
|
61
|
+
what has been learned: a timeline graph (default full
|
|
62
|
+
range; --since filters and says so)
|
|
63
|
+
journey list [--since <dur>] [--kind <k>] [--state <s>] [--json]
|
|
64
|
+
the rows behind the graph: time · symbol+kind ·
|
|
65
|
+
action/state · title · source + actionable hint
|
|
66
|
+
|
|
67
|
+
skill create <name> --description "Use when ..." (--content <md> | --content-file <path>)
|
|
68
|
+
form a new skill at D/skills/<name>/SKILL.md; the
|
|
69
|
+
receipt names the skill and its location (host ack)
|
|
70
|
+
skill patch <name> --old-string <s> --new-string <s>
|
|
71
|
+
grow an existing skill in the SAME file (old text must
|
|
72
|
+
match exactly once)
|
|
73
|
+
skill list skills with their trigger line and location
|
|
74
|
+
|
|
75
|
+
session-index sync --source <db> full read-only snapshot of the host opencode.db into the
|
|
76
|
+
store's own index (idempotent upsert + mark-and-sweep)
|
|
77
|
+
session-index rebuild --source <db> wipe the derived index and re-snapshot (recovery / rebind)
|
|
78
|
+
session-index search <query> verbatim substring scan over the snapshot; hits carry
|
|
79
|
+
[--limit <n>] part/message/session/project identity + as_of
|
|
80
|
+
[--session <id>] [--role <r>]
|
|
81
|
+
session-index status coverage + state: capability gaps are named, never
|
|
82
|
+
disguised as "no matches" (exit 5 when degraded)
|
|
83
|
+
session-index read --session <id> re-read the original text at a hit point (windowed)
|
|
84
|
+
[--message <id>] [--part <id>] [--window <n>]
|
|
85
|
+
|
|
86
|
+
memory setup [<provider>] [--no-input] [--set k=v ...] [--secret-env VAR ...] [--dry-run]
|
|
87
|
+
configure an optional external memory provider (additive;
|
|
88
|
+
credentials only as environment variable names)
|
|
89
|
+
memory status [--probe] what is configured (read-only; no network unless --probe)
|
|
90
|
+
memory off explicitly turn the external provider off (config & .env kept; reload to apply)
|
|
91
|
+
provider <setup|status|off> alias of the memory group — same service, same output
|
|
42
92
|
|
|
43
93
|
Options:
|
|
44
|
-
--store <dir> the store to operate on
|
|
94
|
+
--store <dir> the store to operate on. Lowest..highest precedence is shared with the plugin
|
|
95
|
+
and the installer: --store > $OCG_STORE > $OCG_HOME > ~/.opencode-growth
|
|
96
|
+
(Windows: %LOCALAPPDATA%\\opencode-growth). Whichever root is picked is the one
|
|
97
|
+
that gets written — nothing is migrated between roots.
|
|
45
98
|
--json machine-readable output; every answer uses one envelope
|
|
46
99
|
--help this text
|
|
47
100
|
|
|
@@ -52,7 +105,7 @@ should not read "ok" into it. There is no command that publishes without review.
|
|
|
52
105
|
`
|
|
53
106
|
|
|
54
107
|
/** Grouped commands need two words; everything else is one. */
|
|
55
|
-
const GROUPS = new Set(["candidates", "memory", "context", "learn"])
|
|
108
|
+
const GROUPS = new Set(["candidates", "memory", "context", "learn", "journey", "provider", "skill", "session-index", "curator"])
|
|
56
109
|
|
|
57
110
|
const COMMANDS = {
|
|
58
111
|
doctor,
|
|
@@ -61,12 +114,50 @@ const COMMANDS = {
|
|
|
61
114
|
"candidates preview": candidatesPreview,
|
|
62
115
|
"candidates confirm": candidatesConfirm,
|
|
63
116
|
"memory forget": memoryForget,
|
|
117
|
+
"memory pending": memoryPendingCmd,
|
|
118
|
+
"memory approve": memoryApproveCmd,
|
|
64
119
|
"learn run": learnRun,
|
|
120
|
+
"memory setup": memorySetup,
|
|
121
|
+
"memory status": memoryStatus,
|
|
122
|
+
"memory off": memoryOff,
|
|
123
|
+
"provider setup": memorySetup,
|
|
124
|
+
"provider status": memoryStatus,
|
|
125
|
+
"provider off": memoryOff,
|
|
126
|
+
journey: journeyCmd,
|
|
127
|
+
"journey list": journeyListCmd,
|
|
128
|
+
"skill create": skillCreateCmd,
|
|
129
|
+
"skill patch": skillPatchCmd,
|
|
130
|
+
"skill list": skillListCmd,
|
|
131
|
+
"skill view": skillViewCmd,
|
|
132
|
+
"skill usage": skillUsageCmd,
|
|
133
|
+
"skill archive": skillArchiveCmd,
|
|
134
|
+
"skill restore": skillRestoreCmd,
|
|
135
|
+
"skill pin": skillPinCmd,
|
|
136
|
+
"skill unpin": skillUnpinCmd,
|
|
137
|
+
"skill lifecycle": skillLifecycleCmd,
|
|
138
|
+
"skill rollback": skillRollbackCmd,
|
|
139
|
+
"skill adopt": skillAdoptCmd,
|
|
140
|
+
"skill unmanaged": skillUnmanagedCmd,
|
|
65
141
|
install: installCmd,
|
|
66
142
|
uninstall: uninstallCmd,
|
|
143
|
+
"curator prune": curatorPruneCmd,
|
|
144
|
+
"curator run": curatorRunCmd,
|
|
145
|
+
"curator ledger": curatorLedgerCmd,
|
|
146
|
+
"session-index sync": sessionIndexSyncCmd,
|
|
147
|
+
"session-index rebuild": sessionIndexRebuildCmd,
|
|
148
|
+
"session-index search": sessionIndexSearchCmd,
|
|
149
|
+
"session-index status": sessionIndexStatusCmd,
|
|
150
|
+
"session-index read": sessionIndexReadCmd,
|
|
67
151
|
}
|
|
68
152
|
|
|
69
|
-
const BOOLEAN_FLAGS = new Set(["json", "help", "dry-run"])
|
|
153
|
+
const BOOLEAN_FLAGS = new Set(["json", "help", "dry-run", "play", "no-color", "probe"])
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* 命令面的自洽校验用(M4):`install` 写进宿主命令面的文案里提到的命令,必须真的在这里。
|
|
157
|
+
* 装在文档里、跑起来不存在的命令,是比没有文档更坏的东西(实测撞过一次:`/ocg-approve`
|
|
158
|
+
* 指向 `oc-grow memory approve`,而那条命令当时根本不存在)。
|
|
159
|
+
*/
|
|
160
|
+
export const KNOWN_COMMANDS = Object.freeze(Object.keys(COMMANDS))
|
|
70
161
|
|
|
71
162
|
/** `--x v` becomes {x: "v"}; a valueless or boolean flag becomes true. */
|
|
72
163
|
export function parseArgv(argv) {
|
|
@@ -87,7 +178,8 @@ export function parseArgv(argv) {
|
|
|
87
178
|
if (BOOLEAN_FLAGS.has(name) || next === undefined || next.startsWith("--")) {
|
|
88
179
|
options[name] = true
|
|
89
180
|
} else {
|
|
90
|
-
|
|
181
|
+
// 重复旗标(--set k=v 可多次)升为数组;单次保持标量,既有命令不受影响
|
|
182
|
+
options[name] = name in options ? [].concat(options[name], next) : next
|
|
91
183
|
i += 1
|
|
92
184
|
}
|
|
93
185
|
}
|
|
@@ -99,7 +191,7 @@ export function resolveCommand(positionals) {
|
|
|
99
191
|
if (!positionals.length) return { key: null, rest: [] }
|
|
100
192
|
const [first, second, ...tail] = positionals
|
|
101
193
|
if (GROUPS.has(first)) {
|
|
102
|
-
if (!second) return { key:
|
|
194
|
+
if (!second) return { key: first, rest: [] } // 单词入口(journey)合法;查不到时按 unknown command 报 USAGE
|
|
103
195
|
return { key: `${first} ${second}`, rest: tail }
|
|
104
196
|
}
|
|
105
197
|
return { key: first, rest: [second, ...tail].filter((x) => x !== undefined) }
|
|
@@ -115,6 +207,43 @@ function render(command, env) {
|
|
|
115
207
|
if (bad.length) lines.push(` → ${env.message}`)
|
|
116
208
|
return lines.join("\n")
|
|
117
209
|
}
|
|
210
|
+
case "memory.setup":
|
|
211
|
+
return env.message
|
|
212
|
+
case "memory.status": {
|
|
213
|
+
// 报告形状照 H `cmd_status`(hermes_cli/memory_setup.py:352-400):内建面 + Provider 行
|
|
214
|
+
// + 配置明细(秘密 `(set)`)+ Status 行。**缺席五分在报告面必须一眼可辨**(S2 判据):
|
|
215
|
+
// 第五态「服务故障」只在 `--probe` 时才可能观测到,且要写清它需要网络。
|
|
216
|
+
const built = d.builtin ?? {}
|
|
217
|
+
const lines = [
|
|
218
|
+
"Memory status",
|
|
219
|
+
"─".repeat(40),
|
|
220
|
+
" Built-in (① 常驻记忆 / ② 会话检索):",
|
|
221
|
+
` memory dir: ${built.memory ? "✓" : "✗"} (always on — provider 缺席时照旧)`,
|
|
222
|
+
` Provider: ${d.provider ?? "(none — built-in only)"}`,
|
|
223
|
+
]
|
|
224
|
+
if (d.config && Object.keys(d.config).length) {
|
|
225
|
+
lines.push(" config:")
|
|
226
|
+
for (const [k, v] of Object.entries(d.config)) lines.push(` ${String(k).padEnd(19)} ${v}`)
|
|
227
|
+
}
|
|
228
|
+
if (d.recall && Object.keys(d.recall).length) {
|
|
229
|
+
// 召回九键的**生效值**(照 H `:91-98` 的键名):改配置要能在这里看见效果
|
|
230
|
+
lines.push(" recall:")
|
|
231
|
+
for (const [k, v] of Object.entries(d.recall)) lines.push(` ${String(k).padEnd(21)} ${v}`)
|
|
232
|
+
}
|
|
233
|
+
const tail = d.state === "available" ? "available ✓" : `not available ✗ [${d.code ?? "?"}]`
|
|
234
|
+
lines.push(` Status: ${tail}`)
|
|
235
|
+
if (d.reason) lines.push(` ${d.reason}`)
|
|
236
|
+
if (d.probed) {
|
|
237
|
+
lines.push(d.probe?.ok
|
|
238
|
+
? ` Probe: ok ✓ (user ${d.probe.user ?? "?"}${d.probe.initialized === null ? "" : `, initialized ${d.probe.initialized}`})`
|
|
239
|
+
: ` Probe: FAILED ✗ 服务故障:${d.probe?.error ?? ""}`)
|
|
240
|
+
} else if (d.provider && d.state === "available") {
|
|
241
|
+
lines.push(" Probe: (not run — 只读状态不发网络请求;要探活用 memory status --probe)")
|
|
242
|
+
}
|
|
243
|
+
return lines.join("\n")
|
|
244
|
+
}
|
|
245
|
+
case "memory.off":
|
|
246
|
+
return env.message
|
|
118
247
|
case "uninstall":
|
|
119
248
|
return [
|
|
120
249
|
`store ${d.store}`,
|
|
@@ -130,11 +259,26 @@ function render(command, env) {
|
|
|
130
259
|
...(d.plan ?? []).map((l) => ` · ${l}`),
|
|
131
260
|
].join("\n")
|
|
132
261
|
case "status":
|
|
262
|
+
// 人读面必须说**人话**:字段名跟着 status() 的 data 走,不跟着记忆里的旧形状走
|
|
263
|
+
// (曾经这里读 d.records/d.generation/d.retractionEpoch,而 status() 给的是
|
|
264
|
+
// entries/chars/pending/storeHash/policyVersion ⇒ 人第一眼看到的是 undefined)。
|
|
133
265
|
return [
|
|
134
266
|
`store ${d.store}`,
|
|
135
|
-
`records ${d.
|
|
267
|
+
`records ${d.entries} in effect (${d.chars} char(s), storeHash ${d.storeHash}, policyVersion ${d.policyVersion})`,
|
|
268
|
+
`pending ${d.pending}${d.pending ? " (a person must approve them: oc-grow memory pending)" : ""}`,
|
|
136
269
|
`candidates ${Object.entries(d.candidates ?? {}).map(([k, v]) => `${k}=${v}`).join(" ") || "none"}`,
|
|
137
270
|
].join("\n")
|
|
271
|
+
case "memory.pending": {
|
|
272
|
+
if (!d.pending?.length) return "no staged proposals"
|
|
273
|
+
return d.pending
|
|
274
|
+
.map((p) => {
|
|
275
|
+
const what = String(p.text ?? p.match ?? "").split("\n")[0]
|
|
276
|
+
return ` ${p.file} ${p.op ?? "?"} ${p.kind ?? "?"}${p.label ? ` ${p.label}` : ""} ${what}`
|
|
277
|
+
})
|
|
278
|
+
.join("\n")
|
|
279
|
+
}
|
|
280
|
+
case "memory.approve":
|
|
281
|
+
return `${d.op} applied (${d.file}) approved by ${d.approvedBy} · ${d.pending} staged proposal(s) left`
|
|
138
282
|
case "candidates.list": {
|
|
139
283
|
if (!d.candidates?.length) return "no candidates"
|
|
140
284
|
return d.candidates.map((c) => ` ${c.status.padEnd(9)} ${c.id} ${c.kind}/${c.semanticKey}`).join("\n")
|
|
@@ -166,13 +310,20 @@ function render(command, env) {
|
|
|
166
310
|
}
|
|
167
311
|
case "candidates.confirm":
|
|
168
312
|
return `published ${d.recordId} @${d.contentHash ?? "?"} (approved by ${d.approvedBy})${d.replayed ? " — replay" : ""}`
|
|
169
|
-
case "memory.
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
return `${d.recordId} withdrawn (retraction epoch ${d.retractionEpoch})`
|
|
313
|
+
case "memory.forget": {
|
|
314
|
+
// 撤回纪元随记录层一起退役(B5),人读面只说**做了什么**:撤了哪一条、是不是本来就不在。
|
|
315
|
+
const what = `「${d.match}」 (${d.kind})`
|
|
316
|
+
return d.alreadyWithdrawn ? `was already withdrawn: ${what}` : `withdrawn: ${what}`
|
|
317
|
+
}
|
|
175
318
|
case "learn.run": {
|
|
319
|
+
// 干跑与真跑是**两种形状**:干跑没有 processed/succeeded/failed/skipped
|
|
320
|
+
// (曾经人读面按真跑的形状读,干跑就打印一排 undefined)。
|
|
321
|
+
if (d.dryRun) {
|
|
322
|
+
return [
|
|
323
|
+
`dry run — nothing was learned`,
|
|
324
|
+
`pending ${d.pending} torn ${d.torn} offset ${d.offset}`,
|
|
325
|
+
].join("\n")
|
|
326
|
+
}
|
|
176
327
|
const lines = [
|
|
177
328
|
`processed ${d.processed} ok ${d.succeeded} failed ${d.failed} skipped ${d.skipped}`,
|
|
178
329
|
`queue offset ${d.offsetBefore ?? d.offset} -> ${d.offsetAfter ?? d.offset} pending ${d.pending ?? 0} torn ${d.torn ?? 0}`,
|
|
@@ -182,13 +333,6 @@ function render(command, env) {
|
|
|
182
333
|
}
|
|
183
334
|
return lines.join("\n")
|
|
184
335
|
}
|
|
185
|
-
case "context.show":
|
|
186
|
-
return [
|
|
187
|
-
`session ${d.sessionId} state=${d.state}`,
|
|
188
|
-
`injected ${d.injectedHash ?? "(nothing yet)"} ${d.chars} chars / ~${d.tokens} tokens`,
|
|
189
|
-
`admitted ${d.admitted.length} evicted ${d.rejected.length}`,
|
|
190
|
-
...(d.rejected ?? []).map((r) => ` evicted ${r.id}: ${r.reason}`),
|
|
191
|
-
].join("\n")
|
|
192
336
|
default:
|
|
193
337
|
return env.message
|
|
194
338
|
}
|
|
@@ -202,7 +346,9 @@ export async function run(argv, env = process.env) {
|
|
|
202
346
|
return EXIT.OK
|
|
203
347
|
}
|
|
204
348
|
|
|
205
|
-
const
|
|
349
|
+
const safeHomedir = () => { try { return homedir() || null } catch { return null } }
|
|
350
|
+
const resolved = resolveStoreRoot({ override: options.store ?? null, env, homeDir: safeHomedir() })
|
|
351
|
+
const store = resolved.store
|
|
206
352
|
const commandWanted = resolveCommand(positionals)
|
|
207
353
|
|
|
208
354
|
if (!commandWanted.key) {
|
|
@@ -219,7 +365,8 @@ export async function run(argv, env = process.env) {
|
|
|
219
365
|
}
|
|
220
366
|
|
|
221
367
|
if (!store) {
|
|
222
|
-
const result = fail(commandWanted.key, "USAGE",
|
|
368
|
+
const result = fail(commandWanted.key, "USAGE",
|
|
369
|
+
"no store: pass --store <dir>, or set $OCG_STORE / $OCG_HOME (no unique root could be resolved)")
|
|
223
370
|
emit(result, Boolean(options.json))
|
|
224
371
|
return result.exit
|
|
225
372
|
}
|
|
@@ -229,7 +376,7 @@ export async function run(argv, env = process.env) {
|
|
|
229
376
|
// green on the store it just repaired. The write paths create what they need themselves.
|
|
230
377
|
const L = layout(store)
|
|
231
378
|
|
|
232
|
-
const result = await handler({ ...options, _: commandWanted.rest }, { L })
|
|
379
|
+
const result = await handler({ ...options, _: commandWanted.rest }, { L, storeResolution: resolved })
|
|
233
380
|
emit(result, Boolean(options.json))
|
|
234
381
|
return result.exit
|
|
235
382
|
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// W5 · memory setup|status|off(provider 组是同一服务的别名)。
|
|
2
|
+
// 只读 status 不联网;off 幂等、保留配置与后端内容;错误路径不猜、不覆盖。
|
|
3
|
+
import fs from "node:fs"
|
|
4
|
+
|
|
5
|
+
import { ok, fail } from "./envelope.mjs"
|
|
6
|
+
import {
|
|
7
|
+
PROVIDERS, homeFor, validate, loadConfig, saveConfig, saveSecretEnv, requireEnv, secretValues, redact,
|
|
8
|
+
} from "../provider/config.mjs"
|
|
9
|
+
import { buildProviderRuntime, readSecretEnv } from "../provider/wiring.mjs"
|
|
10
|
+
|
|
11
|
+
const NAMES = () => Object.keys(PROVIDERS).join(" / ")
|
|
12
|
+
|
|
13
|
+
function usage(cmd) {
|
|
14
|
+
return fail(cmd, "USAGE",
|
|
15
|
+
`usage: oc-grow memory setup [<provider>] [--no-input] [--set k=v ...] [--secret-env VAR ...] [--dry-run]` +
|
|
16
|
+
` · provider 名单:${NAMES()} · 凭据只接受环境变量名(--secret-env VAR)`)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const list = (v) => (v === undefined ? [] : Array.isArray(v) ? v : [v])
|
|
20
|
+
|
|
21
|
+
function parseSets(ctx) {
|
|
22
|
+
const rest = ctx._ ?? []
|
|
23
|
+
if (rest.length > 1) return { error: `unexpected argument '${rest[1]}'` }
|
|
24
|
+
const provider = rest[0] ?? null
|
|
25
|
+
const values = {}
|
|
26
|
+
for (const kv of list(ctx.set)) {
|
|
27
|
+
const s = String(kv)
|
|
28
|
+
const j = s.indexOf("=")
|
|
29
|
+
if (j <= 0) return { error: `--set expects k=v, got '${s}'` }
|
|
30
|
+
values[s.slice(0, j)] = s.slice(j + 1)
|
|
31
|
+
}
|
|
32
|
+
const secretEnvs = []
|
|
33
|
+
for (const v of list(ctx["secret-env"])) {
|
|
34
|
+
if (!v || String(v).includes("=")) return { error: `--secret-env expects an environment VARIABLE NAME (never a value), got '${v ?? ""}'` }
|
|
35
|
+
secretEnvs.push(v)
|
|
36
|
+
}
|
|
37
|
+
return { provider, values, secretEnvs, dryRun: !!ctx["dry-run"], noInput: !!ctx["no-input"] }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function memorySetup(ctx, { L }) {
|
|
41
|
+
const cmd = "memory.setup"
|
|
42
|
+
const home = homeFor()
|
|
43
|
+
const parsed = parseSets(ctx)
|
|
44
|
+
if (parsed.error) return fail(cmd, "USAGE", parsed.error)
|
|
45
|
+
const { provider, values, secretEnvs, dryRun } = parsed
|
|
46
|
+
if (!provider) return usage(cmd)
|
|
47
|
+
if (!(provider in PROVIDERS)) {
|
|
48
|
+
return fail(cmd, "USAGE", `unknown provider '${provider}' · provider 名单:${NAMES()}`)
|
|
49
|
+
}
|
|
50
|
+
// 共享同一验证(--dry-run 与正式执行同一条路)
|
|
51
|
+
const v = validate(provider, values)
|
|
52
|
+
if (!v.ok) return fail(cmd, "USAGE", v.error)
|
|
53
|
+
// 凭据只收环境变量名;名字必须真有值(fail closed)
|
|
54
|
+
for (const varName of secretEnvs) {
|
|
55
|
+
try { requireEnv(varName) } catch (e) { return fail(cmd, "REFUSED", e.message) }
|
|
56
|
+
}
|
|
57
|
+
const secrets = secretEnvs.map((n) => process.env[n]).filter(Boolean)
|
|
58
|
+
const plan = {
|
|
59
|
+
provider,
|
|
60
|
+
config: v.fields,
|
|
61
|
+
secretEnvs,
|
|
62
|
+
home,
|
|
63
|
+
note: dryRun
|
|
64
|
+
? "dry run — nothing was written(凭据只以变量名出现,值不进任何输出)"
|
|
65
|
+
: "已保存;凭据落 $OCG_HOME/.env(0600);现有实例需重载后生效",
|
|
66
|
+
}
|
|
67
|
+
const say = redact(JSON.stringify(plan, null, 2), secrets.concat(secretValues(home)))
|
|
68
|
+
if (dryRun) return ok(cmd, say, { dryRun: true, provider, config: v.fields, secretEnvs })
|
|
69
|
+
let cfg
|
|
70
|
+
try { cfg = loadConfig(L.root) } catch (e) {
|
|
71
|
+
return fail(cmd, "REFUSED", `provider config is unreadable — refusing to overwrite: ${e.message}`)
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
for (const varName of secretEnvs) saveSecretEnv(home, varName)
|
|
75
|
+
} catch (e) {
|
|
76
|
+
return fail(cmd, "REFUSED", e.message)
|
|
77
|
+
}
|
|
78
|
+
cfg.providers = cfg.providers ?? {}
|
|
79
|
+
cfg.providers[provider] = v.fields
|
|
80
|
+
cfg.secretEnvs = cfg.secretEnvs ?? {}
|
|
81
|
+
cfg.secretEnvs[provider] = Array.from(new Set([...(cfg.secretEnvs[provider] ?? []), ...secretEnvs]))
|
|
82
|
+
cfg.active = provider
|
|
83
|
+
saveConfig(L.root, cfg)
|
|
84
|
+
return ok(cmd, redact(plan.note, secretValues(home)), { provider, config: v.fields, secretEnvs })
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function memoryStatus(ctx, { L }) {
|
|
88
|
+
const cmd = "memory.status"
|
|
89
|
+
const home = homeFor()
|
|
90
|
+
const wantProbe = Boolean(ctx?.probe)
|
|
91
|
+
// 诊断面必须**诚实失败**:配置损坏时不许把 status 收敛成"ok",也不许猜 provider
|
|
92
|
+
// (W5 判据⑦⑩;corrupt 在会话侧是「缺席回落」,在诊断侧是「看得见的失败」——两处口径不同是有意的)。
|
|
93
|
+
try {
|
|
94
|
+
loadConfig(L.root)
|
|
95
|
+
} catch (e) {
|
|
96
|
+
if (e?.corrupt) return fail(cmd, "REFUSED", `provider config is unreadable (corrupt): ${e.message}`)
|
|
97
|
+
return fail(cmd, "REFUSED", `provider config is unreadable: ${e.message}`)
|
|
98
|
+
}
|
|
99
|
+
// 状态报告与运行时**同源**:直接用 wiring 的构造面拿 code,报告面不许另写一套判据
|
|
100
|
+
// (否则「status 说好的、runtime 却说没配」这类漂移迟早发生)。
|
|
101
|
+
const built = buildProviderRuntime({ store: L.root, home })
|
|
102
|
+
const builtin = { memory: fs.existsSync(L.memory) }
|
|
103
|
+
if (!built.runtime) {
|
|
104
|
+
const state = "unavailable"
|
|
105
|
+
const data = {
|
|
106
|
+
builtin,
|
|
107
|
+
provider: null,
|
|
108
|
+
code: built.reasonCode,
|
|
109
|
+
state,
|
|
110
|
+
reason: built.reason,
|
|
111
|
+
missing: [],
|
|
112
|
+
config: null,
|
|
113
|
+
probe: null,
|
|
114
|
+
// S3:缺席时也如实交代「哪一面归谁」(能力面与场景标签跟 runtime 同源)
|
|
115
|
+
capabilities: built.capabilities ?? null,
|
|
116
|
+
scenario: built.scenario ?? null,
|
|
117
|
+
}
|
|
118
|
+
return ok(cmd, `外部 provider 不可用(${built.reasonCode}):${built.reason}`, data)
|
|
119
|
+
}
|
|
120
|
+
const cfg = loadConfig(L.root)
|
|
121
|
+
const fields = cfg.providers?.[cfg.active] ?? {}
|
|
122
|
+
const names = list(cfg.secretEnvs?.[cfg.active])
|
|
123
|
+
const missing = names.filter((n) => !readSecretEnv(home, n))
|
|
124
|
+
// 秘密只显示 (set)——照 H `get_status_config` 的脱敏形制(绝不回显值)
|
|
125
|
+
const config = { ...fields, [names[0] ?? "token"]: missing.length ? "(missing)" : "(set)" }
|
|
126
|
+
let probe = null
|
|
127
|
+
let code = null
|
|
128
|
+
let state = "available"
|
|
129
|
+
if (wantProbe) {
|
|
130
|
+
probe = await built.provider.probe()
|
|
131
|
+
if (!probe.ok) {
|
|
132
|
+
code = "unreachable"
|
|
133
|
+
state = "unavailable"
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
// 生效的召回九键(读 provider 自己的归一结果 ⇒ 报告面与运行时同源,不另写一套默认值)
|
|
137
|
+
let recall = null
|
|
138
|
+
try { recall = built.provider.diagnostics?.().recall ?? null } catch { recall = null }
|
|
139
|
+
const data = { builtin, provider: cfg.active, code, state, reason: null, missing, config, probe, probed: wantProbe, recall, capabilities: built.capabilities ?? null, scenario: built.scenario ?? null }
|
|
140
|
+
// 人读面也要看得见分工(否则用户只能靠 JSON 才知道工具面/自动面归谁)。
|
|
141
|
+
const capText = built.capabilities ? `自动面 ${built.capabilities.auto ? "OCG" : "外让"} · 工具面 ${built.capabilities.tools ? "OCG" : "外让"}` : "能力面未定"
|
|
142
|
+
const scenarioText = built.scenario ? `场景 ${built.scenario}` : "场景未定"
|
|
143
|
+
return ok(cmd, state === "available"
|
|
144
|
+
? `provider '${cfg.active}' 已配置${wantProbe ? "(探活通过)" : "(只读状态,不发网络请求)"} · ${capText} · ${scenarioText}`
|
|
145
|
+
: `provider '${cfg.active}' 探活失败(服务故障):${probe?.error ?? ""} · ${capText} · ${scenarioText}`, data)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export async function memoryOff(ctx, { L }) {
|
|
149
|
+
const cmd = "memory.off"
|
|
150
|
+
let cfg
|
|
151
|
+
try { cfg = loadConfig(L.root) } catch (e) {
|
|
152
|
+
return fail(cmd, "REFUSED", `provider config is unreadable — refusing to overwrite: ${e.message}`)
|
|
153
|
+
}
|
|
154
|
+
// 显式关闭落盘成 "off"(而不是清成 null):这样「显式关闭」与「从未配置」在报告面
|
|
155
|
+
// 分得开(S2「缺席五分可辨」;D96 的执行面)。幂等。
|
|
156
|
+
const was = cfg.active
|
|
157
|
+
cfg.active = "off"
|
|
158
|
+
saveConfig(L.root, cfg)
|
|
159
|
+
return ok(cmd, "已显式关闭外部 provider(配置与后端内容保留);现有实例需重载后生效", {
|
|
160
|
+
provider: null,
|
|
161
|
+
active: "off",
|
|
162
|
+
previously: was ?? null,
|
|
163
|
+
})
|
|
164
|
+
}
|
|
165
|
+
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// `oc-grow session-index …`(G4 S3a):sync / search / status / read / rebuild 的命令面。
|
|
2
|
+
// 与工具面共用查询核心(src/core/session-index.mjs);信封与退码走 envelope.mjs 统一口径。
|
|
3
|
+
// 能力缺失(源形状认不出/源不可用)一律退码 5 DEGRADED——绝不绿着说「无匹配」。
|
|
4
|
+
import { fail, ok } from "./envelope.mjs"
|
|
5
|
+
import { readStore, rebindStore, repairHintFor, searchStore, statusStore, syncStore } from "../core/session-index.mjs"
|
|
6
|
+
|
|
7
|
+
const CAP_STATES = new Set([
|
|
8
|
+
"not-configured",
|
|
9
|
+
"unsupported-schema",
|
|
10
|
+
"source-missing",
|
|
11
|
+
"source-unavailable",
|
|
12
|
+
"permission-denied",
|
|
13
|
+
])
|
|
14
|
+
|
|
15
|
+
function syncEnvelope(command, r) {
|
|
16
|
+
if (r.ok) {
|
|
17
|
+
return ok(command, `sync ok · parts ${r.counts.parts} · sessions ${r.counts.sessions} · +${r.added} ~${r.updated} -${r.removed}`, r)
|
|
18
|
+
}
|
|
19
|
+
if (CAP_STATES.has(r.state)) {
|
|
20
|
+
return fail(command, "DEGRADED", r.error ?? `能力缺失:${r.state}`, r)
|
|
21
|
+
}
|
|
22
|
+
if (r.error_code === "source-mismatch") {
|
|
23
|
+
return fail(command, "SOURCE_MISMATCH", r.error, r)
|
|
24
|
+
}
|
|
25
|
+
return fail(command, "SYNC_FAILED", r.error ?? `sync 失败:${r.state}`, r)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function sessionIndexSyncCmd(options) {
|
|
29
|
+
const source = options.source
|
|
30
|
+
if (!source) return fail("session-index sync", "USAGE", "需要 --source <opencode.db 路径>")
|
|
31
|
+
return syncEnvelope("session-index sync", await syncStore({ root: options.store, sourcePath: source }))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function sessionIndexRebuildCmd(options) {
|
|
35
|
+
const source = options.source
|
|
36
|
+
if (!source) return fail("session-index rebuild", "USAGE", "需要 --source <opencode.db 路径>")
|
|
37
|
+
// rebuild=显式全量重建:清派生库并按同一套 mark-and-sweep 重新落(恢复/换源后的口径)。
|
|
38
|
+
rebindStore({ root: options.store, sourcePath: source })
|
|
39
|
+
return syncEnvelope("session-index rebuild", await syncStore({ root: options.store, sourcePath: source }))
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function sessionIndexSearchCmd(options) {
|
|
43
|
+
const query = String(options._?.[0] ?? "").trim()
|
|
44
|
+
if (!query) return fail("session-index search", "USAGE", "需要查询词")
|
|
45
|
+
const r = searchStore({
|
|
46
|
+
root: options.store,
|
|
47
|
+
query,
|
|
48
|
+
limit: options.limit ? Number(options.limit) : 20,
|
|
49
|
+
session_id: options.session ?? null,
|
|
50
|
+
role: options.role ?? null,
|
|
51
|
+
since: options.since != null ? Number(options.since) : null,
|
|
52
|
+
until: options.until != null ? Number(options.until) : null,
|
|
53
|
+
})
|
|
54
|
+
// 能力缺失/未配置:没有缓存命中时**不得**报成功零结果(那与「有效源无命中」不可分)。
|
|
55
|
+
if (repairHintFor(r.state) && !r.count) {
|
|
56
|
+
return fail("session-index search", "DEGRADED", `历史索引不可用(state ${r.state})`, {
|
|
57
|
+
...r, repair_hint: repairHintFor(r.state),
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
const prefix = r.stale ? `历史索引降级(state ${r.state},as_of ${r.as_of ?? "未知"})· ` : ""
|
|
61
|
+
return ok("session-index search", `${prefix}${r.message ?? `${r.count} 命中`}`, r)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function sessionIndexStatusCmd(options) {
|
|
65
|
+
const st = statusStore({ root: options.store })
|
|
66
|
+
if (st.state === "ok") return ok("session-index status", `state ok · parts ${st.counts.parts ?? 0}`, st)
|
|
67
|
+
// 能力缺失/未完成对账:退码 5,信封里 state/facts 说清缺什么。
|
|
68
|
+
const facts = st.facts?.length ? ` · ${st.facts.map((f) => `${f.code}:${f.detail}`).join(";")}` : ""
|
|
69
|
+
const hint = repairHintFor(st.state)
|
|
70
|
+
const label = st.state === "not-configured" ? " · 历史来源尚未绑定" : ""
|
|
71
|
+
return fail("session-index status", "DEGRADED", `state ${st.state}${facts}${label}${hint ? ` · ${hint}` : ""}`, {
|
|
72
|
+
...st, repair_hint: hint,
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function sessionIndexReadCmd(options) {
|
|
77
|
+
const r = readStore({
|
|
78
|
+
root: options.store,
|
|
79
|
+
session_id: options.session ?? null,
|
|
80
|
+
message_id: options.message ?? null,
|
|
81
|
+
part_id: options.part ?? null,
|
|
82
|
+
window: options.window != null ? Number(options.window) : 5,
|
|
83
|
+
})
|
|
84
|
+
if (r.ok) return ok("session-index read", `messages ${r.messages.length}`, r)
|
|
85
|
+
if (r.error_code === "not-found") return fail("session-index read", "NOT_FOUND", r.error, r)
|
|
86
|
+
return fail("session-index read", "USAGE", r.error, r)
|
|
87
|
+
}
|