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/commands.mjs
CHANGED
|
@@ -11,7 +11,7 @@ import path from "node:path"
|
|
|
11
11
|
|
|
12
12
|
import { KINDS, SCHEMA_VERSION, MIN_READER } from "../core/paths.mjs"
|
|
13
13
|
import { sha256 } from "../core/ids.mjs"
|
|
14
|
-
import { createMemoryStore, ENTRY_DELIMITER } from "../core/memories.mjs"
|
|
14
|
+
import { createMemoryStore, resolveMemoryLimits, ENTRY_DELIMITER } from "../core/memories.mjs"
|
|
15
15
|
import { listCandidates, readCandidate } from "../core/candidate.mjs"
|
|
16
16
|
import { forget } from "../core/writer.mjs"
|
|
17
17
|
import { storeInitMarker } from "../adapter-opencode/install.mjs"
|
|
@@ -22,6 +22,7 @@ import { consumeQueue, queueOffset } from "../learn/consume.mjs"
|
|
|
22
22
|
import { ok, fail, codeForReason } from "./envelope.mjs"
|
|
23
23
|
import { installAll, resolveInstallPaths, uninstallAll } from "../adapter-opencode/install.mjs"
|
|
24
24
|
import { storeHashOf } from "../core/memories.mjs"
|
|
25
|
+
import { listPending, approvePending } from "../core/approve.mjs"
|
|
25
26
|
import { doctorSkillsSection, readExternalDirs, skillsDir } from "../core/skills.mjs"
|
|
26
27
|
|
|
27
28
|
const isDir = (p) => {
|
|
@@ -173,8 +174,11 @@ export function status(opts, ctx) {
|
|
|
173
174
|
const candidates = {}
|
|
174
175
|
for (const c of listCandidates(L)) candidates[c.status] = (candidates[c.status] ?? 0) + 1
|
|
175
176
|
|
|
177
|
+
const limits = resolveMemoryLimits(L.root)
|
|
176
178
|
const data = {
|
|
177
179
|
store: L.root,
|
|
180
|
+
// 生效上限(与写入/批准/批量同一口径):诊断要能回答"现在到底卡在多少"
|
|
181
|
+
limits,
|
|
178
182
|
storeId: storeIdFor(L),
|
|
179
183
|
schemaVersion: SCHEMA_VERSION,
|
|
180
184
|
// 世代号的替代:**常驻库内容 hash**(只作"当前快照"标识,不声称单调世代)
|
|
@@ -186,7 +190,7 @@ export function status(opts, ctx) {
|
|
|
186
190
|
candidates,
|
|
187
191
|
kinds: KINDS,
|
|
188
192
|
}
|
|
189
|
-
return ok("status", `${entries} entrie(s) resident, ${chars} char(s), ${pending} pending
|
|
193
|
+
return ok("status", `${entries} entrie(s) resident, ${chars} char(s), ${pending} pending · limits ${limits.memory}/${limits.user}(改 config.json 后下一次动作生效)`, data)
|
|
190
194
|
}
|
|
191
195
|
|
|
192
196
|
// ── install(S7 part B:安装入口)─────────────────────────────────────────────
|
|
@@ -213,12 +217,16 @@ export function installCmd(opts, ctx) {
|
|
|
213
217
|
opts["dry-run"] ? "dry-run:只是计划,一个字节都没写" : `装好了:${out.shim}`,
|
|
214
218
|
{
|
|
215
219
|
store: out.store,
|
|
220
|
+
...storeProvenance(ctx),
|
|
216
221
|
configDir: out.configDir,
|
|
217
222
|
shim: out.shim,
|
|
218
223
|
pluginDir: out.pluginDir,
|
|
219
224
|
configFile: out.configFile,
|
|
220
225
|
skillsPath: out.skillsPath,
|
|
221
226
|
configCreated: out.created,
|
|
227
|
+
configWouldCreate: out.wouldCreate,
|
|
228
|
+
storeConfig: out.storeConfig,
|
|
229
|
+
resident: out.resident,
|
|
222
230
|
dryRun: Boolean(opts["dry-run"]),
|
|
223
231
|
plan: out.report,
|
|
224
232
|
},
|
|
@@ -333,6 +341,66 @@ export function memoryForget(opts, ctx) {
|
|
|
333
341
|
})
|
|
334
342
|
}
|
|
335
343
|
|
|
344
|
+
// 待批的处置面(C8 的第三件:`pending|approve|reject` 三件齐全)。
|
|
345
|
+
// reject 不需要命令:**删掉待批文件即拒绝**(语义已由文件面钉住);这里补齐另外两件——
|
|
346
|
+
// 列出来(人得先看见才能处置)与批准(**必须署名**:没署名不算批准)。
|
|
347
|
+
export function memoryPendingCmd(opts, ctx) {
|
|
348
|
+
const { L } = ctx
|
|
349
|
+
const pending = listPending(L)
|
|
350
|
+
return ok("memory.pending", `${pending.length} staged proposal(s)`, {
|
|
351
|
+
store: L.root,
|
|
352
|
+
pending,
|
|
353
|
+
hint: pending.length ? `approve one: oc-grow --store ${L.root} memory approve <file> --as <who-you-are>` : null,
|
|
354
|
+
})
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
export async function memoryApproveCmd(opts, ctx) {
|
|
358
|
+
const { L } = ctx
|
|
359
|
+
const ref = opts._[0]
|
|
360
|
+
if (!ref) return fail("memory.approve", "USAGE", "memory approve <pendingFile|ref> --as <who-you-are>")
|
|
361
|
+
const who = opts.as ?? null
|
|
362
|
+
const r = await approvePending(L, String(ref), { approvedBy: who })
|
|
363
|
+
if (r.ok) {
|
|
364
|
+
return ok("memory.approve", `${r.op} applied — approved by ${r.approvedBy}`, {
|
|
365
|
+
file: r.file,
|
|
366
|
+
op: r.op,
|
|
367
|
+
kind: r.kind,
|
|
368
|
+
origin: r.origin,
|
|
369
|
+
approvedBy: r.approvedBy,
|
|
370
|
+
pending: r.pending,
|
|
371
|
+
})
|
|
372
|
+
}
|
|
373
|
+
const codes = {
|
|
374
|
+
usage: "USAGE",
|
|
375
|
+
"not-found": "NOT_FOUND",
|
|
376
|
+
ambiguous: "AMBIGUOUS_PROPOSAL",
|
|
377
|
+
invalid: "INVALID_PROPOSAL",
|
|
378
|
+
"human-approval-required": "HUMAN_APPROVAL_REQUIRED",
|
|
379
|
+
"apply-failed": "APPLY_FAILED",
|
|
380
|
+
stale: "STALE_PROPOSAL",
|
|
381
|
+
"snapshot-failed": "SNAPSHOT_FAILED",
|
|
382
|
+
busy: "BUSY",
|
|
383
|
+
lost: "LOCK_LOST",
|
|
384
|
+
}
|
|
385
|
+
const said = {
|
|
386
|
+
"not-found": `没有这条待批提案:${ref}`,
|
|
387
|
+
ambiguous: `「${ref}」命中多条待批提案,请写得更具体:${(r.hits ?? []).join(" / ")}`,
|
|
388
|
+
invalid: `这条提案不完整、不能批准:${r.detail ?? ""}`,
|
|
389
|
+
"human-approval-required": "批准需要署名:--as <who-you-are>(没有署名的批准不算批准)",
|
|
390
|
+
"apply-failed": `应用失败、待批文件已保留:${r.detail ?? ""}`,
|
|
391
|
+
stale: `提案已过期、未应用(也没有覆盖新内容):${r.detail ?? ""}`,
|
|
392
|
+
"snapshot-failed": `写入前快照失败,未应用:${r.detail ?? ""}`,
|
|
393
|
+
busy: "提交锁被占用,稍后重试",
|
|
394
|
+
lost: "提交锁在写入期间易主,本次未生效",
|
|
395
|
+
}
|
|
396
|
+
return fail("memory.approve", codes[r.reason] ?? "REFUSED", said[r.reason] ?? `无法批准:${r.reason}`, {
|
|
397
|
+
file: r.file ?? null,
|
|
398
|
+
files: r.files ?? null,
|
|
399
|
+
hits: r.hits ?? null,
|
|
400
|
+
reason: r.reason,
|
|
401
|
+
})
|
|
402
|
+
}
|
|
403
|
+
|
|
336
404
|
// ── learn ────────────────────────────────────────────────────────────
|
|
337
405
|
|
|
338
406
|
/**
|
|
@@ -402,18 +470,43 @@ export function doctor(opts, ctx) {
|
|
|
402
470
|
const resolved = resolveInstallPaths({ store: ctx?.L?.root ?? null, configDir: opts?.config ? String(opts.config) : null })
|
|
403
471
|
// handler 返回的是 {envelope, exit} 包装(不是信封本身),且 data 是冻结的 ⇒ 造新对象返回
|
|
404
472
|
const env = envOut?.envelope
|
|
405
|
-
|
|
473
|
+
const provenance = storeProvenance(ctx)
|
|
474
|
+
if (env && env.data) return { ...envOut, envelope: { ...env, data: { ...env.data, resolved, ...provenance } } }
|
|
406
475
|
} catch { /* 解析不出就不报,不因此让 doctor 挂掉 */ }
|
|
407
476
|
return envOut
|
|
408
477
|
}
|
|
409
478
|
|
|
479
|
+
/**
|
|
480
|
+
* 「这个 store 是怎么被挑出来的」——三个入口共用一条规则,于是**来源必须跟着回执走**:
|
|
481
|
+
* 否则被压过的那个变量(指向另一个库)谁也看不见,下次就会有人对着错的库排障。
|
|
482
|
+
*/
|
|
483
|
+
function storeProvenance(ctx) {
|
|
484
|
+
const r = ctx?.storeResolution
|
|
485
|
+
if (!r) return {}
|
|
486
|
+
return {
|
|
487
|
+
store_source: r.source ?? null,
|
|
488
|
+
store_via: r.via ?? null,
|
|
489
|
+
store_conflicts: r.conflicts ?? [],
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
410
493
|
/** uninstall:只撤我们写的东西(回执 + shim + 我们追加的那条 skills path),幂等。 */
|
|
411
494
|
export function uninstallCmd(opts, ctx) {
|
|
495
|
+
const allowed = new Set(["_", "store", "config", "from", "json", "no-color"])
|
|
496
|
+
for (const key of Object.keys(opts)) {
|
|
497
|
+
if (!allowed.has(key)) return fail("uninstall", "USAGE", `uninstall 不支持选项 --${key};恢复回执使用 --from <manifest>`)
|
|
498
|
+
}
|
|
499
|
+
for (const key of ["store", "config", "from"]) {
|
|
500
|
+
if (opts[key] !== undefined && (typeof opts[key] !== "string" || !opts[key].trim())) {
|
|
501
|
+
return fail("uninstall", "USAGE", `--${key} 需要且只接受一个非空值,未做任何改动`)
|
|
502
|
+
}
|
|
503
|
+
}
|
|
412
504
|
const { L } = ctx
|
|
413
505
|
try {
|
|
414
|
-
const out = uninstallAll({ store: L.root, configDir: opts.config
|
|
506
|
+
const out = uninstallAll({ store: L.root, configDir: opts.config ?? null, from: opts.from ?? null })
|
|
415
507
|
return ok("uninstall",
|
|
416
|
-
out.
|
|
508
|
+
out.retained.length ? `撤掉了 ${out.removed.length} 项,保留 ${out.retained.length} 项`
|
|
509
|
+
: out.removed.length ? `撤掉了 ${out.removed.length} 项` : "没有需要撤的东西(幂等)",
|
|
417
510
|
{ ...out })
|
|
418
511
|
} catch (e) {
|
|
419
512
|
return fail("uninstall", "REFUSED", e?.message ?? String(e))
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// S4 · G2 独立 curator CLI 的三个动词(`curator prune|run|ledger`)。
|
|
2
|
+
//
|
|
3
|
+
// 判据来源=GOAL §S4「G2:curator 可独立跑(run/prune/ledger),产物与内建 curator 同形」
|
|
4
|
+
// + Extra criterion 5「独立=不依赖交互会话事件触发(机械 prune/ledger 直跑;需模型的整理
|
|
5
|
+
// 允许连 OpenCode 服务——不另造 agent 运行时)」。
|
|
6
|
+
//
|
|
7
|
+
// 动词面(与 Hermes `hermes curator` 对齐的收束记 D117;D114 是初版三动词的对照):
|
|
8
|
+
// · `run`(无 `--consolidate`)=**机械迁移**(老化/归档),核心=
|
|
9
|
+
// `core/skill-lifecycle.applyLifecycleTransitions` —— 与内建 pass 同一个函数,
|
|
10
|
+
// 零宿主零模型即可跑。这与 Hermes 的 `hermes curator run` 同名同义(机械 pass)。
|
|
11
|
+
// · `run --consolidate --host <url>` =带模型的整理 pass,核心=
|
|
12
|
+
// `adapter-opencode/curator-runner.runCuratorPass` —— 与内建触发(会话事件)走同一执行体;
|
|
13
|
+
// 独立跑时**连宿主服务**,不自行起 agent 运行时。对应 Hermes 的 `run --consolidate`。
|
|
14
|
+
// · `prune` =`run`(机械)的**兼容别名**,保留一版并提示迁移(H 无此动词)。
|
|
15
|
+
// · `ledger` =账本读/归档(`core/audit`),产物与内建 pass 写进的是**同一份账本**。
|
|
16
|
+
import { ok, fail } from "./envelope.mjs"
|
|
17
|
+
import { readAudit, compactAudit } from "../core/audit.mjs"
|
|
18
|
+
import { applyLifecycleTransitions } from "../core/skill-lifecycle.mjs"
|
|
19
|
+
import { listCuratorCandidates, runCuratorPass, curatorConsolidateEnabled } from "../adapter-opencode/curator-runner.mjs"
|
|
20
|
+
import { normalizeMessages } from "../adapter-opencode/review-runner.mjs"
|
|
21
|
+
import { createRestClient } from "../host/rest-client.mjs"
|
|
22
|
+
|
|
23
|
+
/** 账本里属于「技能变更」的事件(照 Hermes skill ledger:技能的 create/patch/archive/…)。 */
|
|
24
|
+
const SKILL_EVENT_RE = /^skill[-_]/i
|
|
25
|
+
const DEFAULT_LEDGER_LIMIT = 20
|
|
26
|
+
|
|
27
|
+
const usage = (cmd) =>
|
|
28
|
+
fail(
|
|
29
|
+
cmd,
|
|
30
|
+
"USAGE",
|
|
31
|
+
[
|
|
32
|
+
"usage: oc-grow curator run [--dry-run]",
|
|
33
|
+
" oc-grow curator run --consolidate --host <http://127.0.0.1:PORT> [--session <sid>] [--dry-run]",
|
|
34
|
+
" oc-grow curator prune [--dry-run] (兼容别名,等价于 curator run;建议改用 run)",
|
|
35
|
+
" oc-grow curator ledger [--limit <n>] [--skill <name>] | [--compact --older-than-days <n>]",
|
|
36
|
+
].join(" · "),
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
/** 机械面:老化迁移。零宿主、零模型,产物=库变化 + 时钟 + 审计(三者都走内建同一函数)。 */
|
|
40
|
+
function mechanicalPass(cmd, label, flags, ctx) {
|
|
41
|
+
const dryRun = Boolean(flags["dry-run"])
|
|
42
|
+
const r = applyLifecycleTransitions({ root: ctx.L.root, dryRun, origin: "foreground" })
|
|
43
|
+
if (!r.ok) return fail(cmd, "DEGRADED", `机械维护失败:${r.error ?? "未知原因"}`)
|
|
44
|
+
const pinned = r.skipped_pinned ?? []
|
|
45
|
+
const msg =
|
|
46
|
+
`${label}${dryRun ? "(dry-run:库/快照/时钟/审计全不动)" : ""}:检查 ${r.checked} · 锚时钟 ${r.seeded} · ` +
|
|
47
|
+
`stale ${r.marked_stale} · 归档 ${r.archived} · 提案 ${r.staged} · 复活 ${r.reactivated}` +
|
|
48
|
+
(pinned.length ? ` · 跳过 pinned ${pinned.length}(${pinned.map((x) => x.name).join("、")})` : "")
|
|
49
|
+
return ok(cmd, msg, r)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* `curator prune` —— `curator run`(机械)的兼容别名:H 没有 `prune` 动词,多一个同名异义的命令面
|
|
54
|
+
* 会让「同名触发不同副作用」,所以机械路径的规范入口是 `run`;这里只保留一版并提示迁移(D117)。
|
|
55
|
+
*/
|
|
56
|
+
export async function curatorPruneCmd(flags, ctx) {
|
|
57
|
+
const r = mechanicalPass("curator.prune", "curator prune", flags, ctx)
|
|
58
|
+
// 兼容别名:产物与 `run` 逐字相同,只多一句迁移提示(信封的 message 在 envelope 下)
|
|
59
|
+
r.envelope.message = `${r.envelope.message} · 提示:curator prune 是兼容别名,规范入口是 oc-grow curator run`
|
|
60
|
+
return r
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* `curator run` —— 与 Hermes 同名同义:**不带 `--consolidate` 就是机械 pass**(零宿主零模型);
|
|
65
|
+
* 带 `--consolidate` 才进模型整理,这时必须给 `--host`(连正在跑的 OpenCode 服务,不自行起 agent 运行时)。
|
|
66
|
+
* `--host` 单独给也算 `--consolidate`(只有模型 pass 需要宿主),避免「给了宿主却什么都没发生」。
|
|
67
|
+
*/
|
|
68
|
+
export async function curatorRunCmd(flags, ctx) {
|
|
69
|
+
const cmd = "curator.run"
|
|
70
|
+
const host = flags.host ?? flags.url ?? null
|
|
71
|
+
const consolidate = Boolean(flags.consolidate) || Boolean(host) || curatorConsolidateEnabled(ctx.L.root)
|
|
72
|
+
if (!consolidate) return mechanicalPass(cmd, "curator run(机械迁移)", flags, ctx)
|
|
73
|
+
if (!host) {
|
|
74
|
+
return fail(
|
|
75
|
+
cmd,
|
|
76
|
+
"USAGE",
|
|
77
|
+
"curator run --consolidate 需要 --host <http://127.0.0.1:PORT> —— 连正在跑的 OpenCode 服务;本命令不自行起 agent 运行时",
|
|
78
|
+
)
|
|
79
|
+
}
|
|
80
|
+
const dryRun = Boolean(flags["dry-run"])
|
|
81
|
+
const client = createRestClient({ baseUrl: String(host) })
|
|
82
|
+
try {
|
|
83
|
+
let sessionId = flags.session ? String(flags.session) : null
|
|
84
|
+
if (!sessionId) {
|
|
85
|
+
// 独立跑=不需要人在某个交互会话里:自己建一个根会话当父(子会话挂它下面,产物仍落在宿主会话体系里)。
|
|
86
|
+
const created = await client.session.create({ body: {} })
|
|
87
|
+
sessionId = created?.data?.id ?? created?.id ?? null
|
|
88
|
+
if (!sessionId) return fail(cmd, "DEGRADED", "宿主没给出会话 id(POST /session 的返回里没有 id)")
|
|
89
|
+
}
|
|
90
|
+
const skills = listCuratorCandidates(ctx.L.root)
|
|
91
|
+
const r = await runCuratorPass({ client, sessionId, root: ctx.L.root, skills, dryRun })
|
|
92
|
+
if (!r?.ok) return fail(cmd, "DEGRADED", `整理 pass 没跑成:${r?.error ?? "未知原因"}`)
|
|
93
|
+
const messages = normalizeMessages(r.messages)
|
|
94
|
+
const report = [].concat(messages ?? [])
|
|
95
|
+
.filter((m) => (m?.role ?? m?.info?.role) === "assistant")
|
|
96
|
+
.map((m) => {
|
|
97
|
+
if (typeof m?.text === "string" && m.text.trim()) return m.text
|
|
98
|
+
const parts = m?.parts ?? m?.info?.parts ?? []
|
|
99
|
+
return (Array.isArray(parts) ? parts : []).filter((p) => p?.type === "text").map((p) => String(p.text ?? "")).join("\n")
|
|
100
|
+
})
|
|
101
|
+
.filter((t) => t && t.trim())
|
|
102
|
+
.join("\n")
|
|
103
|
+
.trim()
|
|
104
|
+
return ok(
|
|
105
|
+
cmd,
|
|
106
|
+
`curator run --consolidate${dryRun ? "(dry-run)" : ""}:父会话 ${sessionId} · 子会话 ${r.childId} · ` +
|
|
107
|
+
`候选 ${skills.length} 个 · ${report ? "已取回报告" : "未取回文本(子会话没产出 assistant 文本)"}`,
|
|
108
|
+
{ sessionId, childId: r.childId, candidates: skills.length, report: report || null, restriction: r.restriction ?? null },
|
|
109
|
+
)
|
|
110
|
+
} catch (e) {
|
|
111
|
+
return fail(cmd, "DEGRADED", `连宿主失败:${String(e?.message ?? e)}`)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 账本面:读(newest-first、可按技能过滤、可限量)或按龄归档。 */
|
|
116
|
+
export async function curatorLedgerCmd(flags, ctx) {
|
|
117
|
+
const cmd = "curator.ledger"
|
|
118
|
+
if (flags.compact) {
|
|
119
|
+
const days = flags["older-than-days"] === undefined ? 30 : Number(flags["older-than-days"])
|
|
120
|
+
if (!Number.isFinite(days) || days <= 0) return fail(cmd, "USAGE", "--older-than-days 必须是正数")
|
|
121
|
+
const r = compactAudit(ctx.L, { olderThanDays: days })
|
|
122
|
+
if (!r.ok) return fail(cmd, "USAGE", r.error)
|
|
123
|
+
return ok(
|
|
124
|
+
cmd,
|
|
125
|
+
`curator ledger 按龄归档:搬走 ${r.moved} 条(${r.files} 个文件)· 留 ${r.kept} 条${r.archived ? ` · 归档目录 ${r.archived}` : ""}`,
|
|
126
|
+
r,
|
|
127
|
+
)
|
|
128
|
+
}
|
|
129
|
+
const limitRaw = flags.limit === undefined ? DEFAULT_LEDGER_LIMIT : Number(flags.limit)
|
|
130
|
+
if (!Number.isFinite(limitRaw) || limitRaw < 0) return fail(cmd, "USAGE", "--limit 必须是非负数")
|
|
131
|
+
const { events, skipped } = readAudit(ctx.L, 5000)
|
|
132
|
+
let rows = events.filter((e) => SKILL_EVENT_RE.test(String(e?.event ?? "")))
|
|
133
|
+
if (flags.skill) rows = rows.filter((e) => String(e?.name ?? "") === String(flags.skill))
|
|
134
|
+
rows = rows
|
|
135
|
+
.map((e, i) => ({ e, i }))
|
|
136
|
+
.sort((a, b) => {
|
|
137
|
+
const ta = Date.parse(a.e?.ts ?? "")
|
|
138
|
+
const tb = Date.parse(b.e?.ts ?? "")
|
|
139
|
+
if (Number.isFinite(ta) && Number.isFinite(tb) && ta !== tb) return tb - ta
|
|
140
|
+
return b.i - a.i // 同时刻(或坏 ts)按写入倒序
|
|
141
|
+
})
|
|
142
|
+
.slice(0, limitRaw)
|
|
143
|
+
.map(({ e }) => e)
|
|
144
|
+
if (!rows.length) {
|
|
145
|
+
const scope = flags.skill ? `技能「${flags.skill}」` : "任何技能"
|
|
146
|
+
return ok(cmd, `curator ledger 是空的:账本里没有${scope}的变更条目(跑过 curator prune 或 skill create|patch|archive 才会有)`, { entries: [], skipped })
|
|
147
|
+
}
|
|
148
|
+
return ok(cmd, `curator ledger:${rows.length} 条(newest-first · 读 ${events.length} 条 · 坏行 ${skipped})`, { entries: rows, skipped })
|
|
149
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// 片 3 命令层:journey / journey list —— 全程只读(§5.5-③/⑤)。
|
|
2
|
+
// 人读帧在 message 里(render 走 default 分支吐 message);--json 时 message 是一行摘要,
|
|
3
|
+
// data 是 §5.3 的机读 payload(信封命令面一致优先)。
|
|
4
|
+
import process from "node:process"
|
|
5
|
+
|
|
6
|
+
import { ok, fail } from "./envelope.mjs"
|
|
7
|
+
import { buildJourney } from "../core/journey.mjs"
|
|
8
|
+
import { parseSince, parseReveal, applyFilters, collectRows, renderFrame, renderRowLines, KINDS, STATES } from "./journey-view.mjs"
|
|
9
|
+
|
|
10
|
+
const ALL_STATES = new Set(Object.values(STATES).flat())
|
|
11
|
+
|
|
12
|
+
function build(flags, { L }, argv) {
|
|
13
|
+
const now = Math.floor(Date.now() / 1000)
|
|
14
|
+
let sinceInfo = null
|
|
15
|
+
if (flags.since !== undefined) {
|
|
16
|
+
if (flags.since === true) return { bad: fail(argv[0], "USAGE", "--since 需要值(7d / 24h / ISO 时间)") }
|
|
17
|
+
sinceInfo = parseSince(flags.since, now)
|
|
18
|
+
if (!sinceInfo) return { bad: fail(argv[0], "USAGE", `--since 只接 7d / 24h / ISO 时间,拿到:${flags.since}`) }
|
|
19
|
+
}
|
|
20
|
+
if (flags.kind !== undefined && (flags.kind === true || !KINDS.includes(flags.kind))) {
|
|
21
|
+
return { bad: fail(argv[0], "USAGE", `--kind 只接 ${KINDS.join(" / ")},拿到:${flags.kind}`) }
|
|
22
|
+
}
|
|
23
|
+
if (flags.state !== undefined && (flags.state === true || !ALL_STATES.has(flags.state))) {
|
|
24
|
+
return { bad: fail(argv[0], "USAGE", `--state 只接 ${[...ALL_STATES].join(" / ")},拿到:${flags.state}`) }
|
|
25
|
+
}
|
|
26
|
+
let reveal = 1
|
|
27
|
+
if (flags.reveal !== undefined) {
|
|
28
|
+
reveal = parseReveal(String(flags.reveal))
|
|
29
|
+
if (reveal === null) return { bad: fail(argv[0], "USAGE", `--reveal 只接 0..1,拿到:${flags.reveal}`) }
|
|
30
|
+
}
|
|
31
|
+
const run = { clock: now, args: argv.slice(), identity: "ocg-cli" }
|
|
32
|
+
const payload0 = buildJourney(L, { since: sinceInfo?.since ?? null, sinceLabel: sinceInfo?.label ?? null, now, run })
|
|
33
|
+
const payload = applyFilters(payload0, { kind: flags.kind ?? null, state: flags.state ?? null })
|
|
34
|
+
return { payload, sinceInfo, reveal, now }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function journeyCmd(flags, ctx) {
|
|
38
|
+
const argv = ["journey", ...(flags._ ?? [])]
|
|
39
|
+
const b = build(flags, ctx, argv)
|
|
40
|
+
if (b.bad) return b.bad
|
|
41
|
+
const frame = renderFrame(b.payload, { since: b.sinceInfo, reveal: b.reveal })
|
|
42
|
+
if (flags.play && !process.stdout.isTTY) process.stderr.write("play: degraded - no live terminal\n")
|
|
43
|
+
// --json 输出数据不输出帧:message 只给一行摘要(动画帧不许污染 JSON)
|
|
44
|
+
const total = (b.payload.nodes ?? []).length + (b.payload.ocg?.candidates ?? []).length + (b.payload.ocg?.events ?? []).length
|
|
45
|
+
const message = flags.json
|
|
46
|
+
? `journey: ${total} objects · window ${b.payload.ocg.window}`
|
|
47
|
+
: frame
|
|
48
|
+
return ok("journey", message, b.payload)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function journeyListCmd(flags, ctx) {
|
|
52
|
+
const argv = ["journey", "list", ...(flags._ ?? [])]
|
|
53
|
+
const b = build(flags, ctx, argv)
|
|
54
|
+
if (b.bad) return b.bad
|
|
55
|
+
const rows = collectRows(b.payload)
|
|
56
|
+
return ok("journey.list", renderRowLines(rows), {
|
|
57
|
+
rows,
|
|
58
|
+
filter: b.payload.ocg.filter,
|
|
59
|
+
window: b.payload.ocg.window,
|
|
60
|
+
})
|
|
61
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// 片 3 视图层(§5.1 参数语义 + §5.2 人读帧 + journey list 行)——纯变换,不碰磁盘。
|
|
2
|
+
// §5.2 骨架=图例 + 分类图例 + 日期分桶 + 无时间锚点单列 + 轴 + 累计轨迹 + 揭示进度 + 摘要。
|
|
3
|
+
// 符号照 Hermes:◆ memory / ● skill(H/hermes_cli/journey.py:270);◇ candidate、▪ event 是 ocg 扩展。
|
|
4
|
+
export const KINDS = ["memory", "skill", "candidate"]
|
|
5
|
+
export const STATES = {
|
|
6
|
+
memory: ["published", "withdrawn"],
|
|
7
|
+
skill: ["active"],
|
|
8
|
+
candidate: ["proposed", "validated", "published", "rejected"], // published 是候选协议里的真实状态(USAGE 四态),v2 表漏列
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const DAY = 86400
|
|
12
|
+
const LEVELS = ["▁", "▂", "▃", "▅", "▇", "█"]
|
|
13
|
+
const levelChar = (n) => (n <= 0 ? " " : LEVELS[Math.min(5, Math.ceil(Math.log2(n + 1)) - 1 < 0 ? 0 : Math.ceil(Math.log2(n + 1)) - 1)])
|
|
14
|
+
|
|
15
|
+
/** `7d` / `24h` / ISO 时间 ⇒ {since, label};解析不了返回 null(调用方转 USAGE)。 */
|
|
16
|
+
export function parseSince(v, now) {
|
|
17
|
+
const m = /^(\d+)([dh])$/.exec(String(v))
|
|
18
|
+
if (m) return { since: now - Number(m[1]) * (m[2] === "d" ? DAY : 3600), label: String(v) }
|
|
19
|
+
const t = Date.parse(String(v))
|
|
20
|
+
if (Number.isFinite(t)) return { since: Math.floor(t / 1000), label: String(v) }
|
|
21
|
+
return null
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** `--reveal 0..1`;0 就是 0(不复制 Hermes journey.py:231 的 `or 1.0` 瑕疵)。 */
|
|
25
|
+
export function parseReveal(v) {
|
|
26
|
+
const n = Number(v)
|
|
27
|
+
return Number.isFinite(n) && n >= 0 && n <= 1 ? n : null
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function itemCategory(item) {
|
|
31
|
+
return item.kind === "memory" || item.kind === "skill" ? item.kind : "candidate"
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const symbolOf = (cat) => ({ memory: "◆", skill: "●", candidate: "◇", event: "▪" })[cat] ?? "?"
|
|
35
|
+
|
|
36
|
+
/** 一行 = 一个对象/事件:{timestamp, symbol, kind, action, title, source, hint}(对象 + 事件合流,时间升序、无时间锚点在最后单列)。 */
|
|
37
|
+
export function collectRows(payload) {
|
|
38
|
+
const rows = []
|
|
39
|
+
for (const n of payload.nodes ?? []) {
|
|
40
|
+
rows.push({
|
|
41
|
+
timestamp: n.timestamp, symbol: symbolOf(n.kind), kind: n.kind, action: n.state, title: n.label,
|
|
42
|
+
source: n.source, id: n.id,
|
|
43
|
+
hint: n.kind === "memory"
|
|
44
|
+
? `oc-grow memory forget "${n.label}"`
|
|
45
|
+
: "本版无可执行写命令(只读定位)",
|
|
46
|
+
})
|
|
47
|
+
}
|
|
48
|
+
for (const c of payload.ocg?.candidates ?? []) {
|
|
49
|
+
rows.push({
|
|
50
|
+
timestamp: c.createdAt, symbol: "◇", kind: "candidate", action: c.status, title: c.id,
|
|
51
|
+
source: c.source, id: c.id,
|
|
52
|
+
hint: `oc-grow candidates preview ${c.id}`,
|
|
53
|
+
})
|
|
54
|
+
}
|
|
55
|
+
for (const e of payload.ocg?.events ?? []) {
|
|
56
|
+
rows.push({
|
|
57
|
+
timestamp: e.timestamp, symbol: "▪", kind: "event", action: e.type,
|
|
58
|
+
title: e.subjectRef ? `${e.type} → ${e.subjectRef.id}` : e.type,
|
|
59
|
+
source: e.source, id: e.id,
|
|
60
|
+
hint: "审计/冻结事件(只读)",
|
|
61
|
+
})
|
|
62
|
+
}
|
|
63
|
+
rows.sort((a, b) => (a.timestamp ?? Number.MAX_SAFE_INTEGER) - (b.timestamp ?? Number.MAX_SAFE_INTEGER))
|
|
64
|
+
return rows
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* --kind / --state 筛选(journey 图形与 journey list 共用这一份数据):
|
|
69
|
+
* 对象按类别/状态筛;事件行随其 subject 走,绑不上的事件在给了筛选时隐藏。
|
|
70
|
+
*/
|
|
71
|
+
export function applyFilters(payload, { kind = null, state = null } = {}) {
|
|
72
|
+
if (!kind && !state) return payload
|
|
73
|
+
const rows = collectRows(payload)
|
|
74
|
+
const keptRows = rows.filter((r) =>
|
|
75
|
+
(kind ? r.kind === kind || (r.kind === "event" && false) : true) &&
|
|
76
|
+
(state ? r.action === state : true) && r.kind !== "event")
|
|
77
|
+
const keptIds = new Set(keptRows.map((r) => r.id))
|
|
78
|
+
const keptEvents = (payload.ocg?.events ?? []).filter((e) => e.subjectRef && keptIds.has(e.subjectRef.id))
|
|
79
|
+
const nodes = (payload.nodes ?? []).filter((n) => keptIds.has(n.id))
|
|
80
|
+
const candidates = (payload.ocg?.candidates ?? []).filter((c) => keptIds.has(c.id))
|
|
81
|
+
const memory = (payload.memory ?? []).filter((c) => nodes.some((n) => n.label === c.title))
|
|
82
|
+
const edges = (payload.edges ?? []).filter((e) => keptIds.has(e.source) && keptIds.has(e.target))
|
|
83
|
+
const skillCount = nodes.filter((n) => n.kind === "skill").length
|
|
84
|
+
const clustersMap = new Map()
|
|
85
|
+
for (const n of nodes) clustersMap.set(n.category, (clustersMap.get(n.category) ?? 0) + 1)
|
|
86
|
+
return {
|
|
87
|
+
...payload,
|
|
88
|
+
nodes, edges, memory,
|
|
89
|
+
clusters: [...clustersMap].map(([category, count]) => ({ category, count })),
|
|
90
|
+
stats: {
|
|
91
|
+
...payload.stats,
|
|
92
|
+
nodes: skillCount,
|
|
93
|
+
memory_nodes: nodes.filter((n) => n.kind === "memory").length,
|
|
94
|
+
memory_skill_edges: edges.length,
|
|
95
|
+
learned_skills: skillCount,
|
|
96
|
+
categories: [...new Set(nodes.filter((n) => n.kind === "skill").map((n) => n.category))],
|
|
97
|
+
},
|
|
98
|
+
ocg: { ...payload.ocg, candidates, events: keptEvents },
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** §5.2 人读帧(默认视图=图形,不是日志表)。items = 对象 + 事件;reveal 从最旧开始揭示。 */
|
|
103
|
+
export function renderFrame(payload, { since = null, reveal = 1 } = {}) {
|
|
104
|
+
const rows = collectRows(payload)
|
|
105
|
+
const total = rows.length
|
|
106
|
+
const revealed = Math.ceil(total * reveal)
|
|
107
|
+
const lines = []
|
|
108
|
+
lines.push("legend ◆ memory · ● skill · ◇ candidate")
|
|
109
|
+
const byCat = { memory: 0, skill: 0, candidate: 0 }
|
|
110
|
+
for (const r of rows) if (r.kind !== "event") byCat[itemCategory({ kind: r.kind })] += 1
|
|
111
|
+
lines.push(`categories memory ${byCat.memory} · skill ${byCat.skill} · candidate ${byCat.candidate}`)
|
|
112
|
+
if (total === 0) lines.push("empty 还没有学到任何东西(对象、事件都没有)")
|
|
113
|
+
|
|
114
|
+
// 日期分桶(一行 = 一个日期桶)+ 无时间锚点单列
|
|
115
|
+
const buckets = new Map()
|
|
116
|
+
const undated = []
|
|
117
|
+
rows.forEach((r, i) => {
|
|
118
|
+
const shown = i < revealed
|
|
119
|
+
if (r.timestamp == null) { undated.push({ r, shown }); return }
|
|
120
|
+
const d = new Date(r.timestamp * 1000).toISOString().slice(0, 10)
|
|
121
|
+
if (!buckets.has(d)) buckets.set(d, [])
|
|
122
|
+
buckets.get(d).push({ r, shown })
|
|
123
|
+
})
|
|
124
|
+
const dayKeys = [...buckets.keys()].sort() // 旧在上、新在下(照 Hermes)
|
|
125
|
+
for (const d of dayKeys) {
|
|
126
|
+
const items = buckets.get(d)
|
|
127
|
+
const syms = items.map((x) => (x.shown ? x.r.symbol : "·")).join("")
|
|
128
|
+
const first = items.find((x) => x.shown)
|
|
129
|
+
lines.push(`${d} ${levelChar(items.length)}${syms}${first ? ` ${String(first.r.title).slice(0, 24)}` : ""}`)
|
|
130
|
+
}
|
|
131
|
+
for (const u of undated) {
|
|
132
|
+
lines.push(`undated ${u.shown ? u.r.symbol : "·"} ${u.shown ? String(u.r.title).slice(0, 24) : "……"} (无时间锚点)`)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// 轴 + 累计轨迹 + 揭示进度 + 摘要
|
|
136
|
+
lines.push(dayKeys.length
|
|
137
|
+
? `date axis ${dayKeys[0]} ──── ${dayKeys[dayKeys.length - 1]}`
|
|
138
|
+
: "date axis (没有有时间锚点的项)")
|
|
139
|
+
const cum = []
|
|
140
|
+
for (let i = 1; i <= 6; i += 1) cum.push(levelChar(Math.floor((total * i) / 6)))
|
|
141
|
+
lines.push(`cumulative ${total ? cum.join("") : ""} (${total} objects)`.replace(/\s+/, " "))
|
|
142
|
+
const pct = total ? Math.round((revealed / total) * 100) : 100
|
|
143
|
+
const window = payload.ocg?.window === "all" ? "全量" : payload.ocg?.window
|
|
144
|
+
lines.push(`reveal ${revealed}/${total} (${pct}%) · 窗口:${window} · 来源:memories/MEMORY.md + audit/ + candidates/`)
|
|
145
|
+
const pub = (payload.nodes ?? []).filter((n) => n.kind === "memory" && n.state === "published").length
|
|
146
|
+
const wd = (payload.nodes ?? []).filter((n) => n.kind === "memory" && n.state === "withdrawn").length
|
|
147
|
+
const skills = (payload.nodes ?? []).filter((n) => n.kind === "skill").length
|
|
148
|
+
lines.push(`summary ${pub} published · ${payload.ocg?.pending ?? 0} pending · ${wd} withdrawn · ${skills} skill`)
|
|
149
|
+
|
|
150
|
+
lines.push(...filterHintLines(payload, since))
|
|
151
|
+
return lines.join("\n")
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** 过滤提示(§5.1:显式给 --since 才过滤,且必须提示已过滤 + 看全量入口)。
|
|
155
|
+
* CLI 人读帧与会话内工具**同用这一处**——「同一份 payload」的语义侧同源。 */
|
|
156
|
+
export function filterHintLines(payload, since) {
|
|
157
|
+
if (!since) return []
|
|
158
|
+
const hidden = payload.ocg?.filter?.hidden ?? 0
|
|
159
|
+
const unknown = payload.ocg?.coverage?.unknownTime ?? 0
|
|
160
|
+
return [
|
|
161
|
+
`since=${since.label} · 已过滤:隐藏 ${hidden} 项 · 无时间锚点 ${unknown} 项单列(不计入隐藏)`,
|
|
162
|
+
"去掉 --since 重跑看全量",
|
|
163
|
+
]
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** journey list 的人读行(五段:时间 · 符号+kind · 动作/状态 · 标题 · 来源 + 可执行提示)。 */
|
|
167
|
+
export function renderRowLines(rows) {
|
|
168
|
+
if (!rows.length) return "no rows"
|
|
169
|
+
return rows.map((r) => {
|
|
170
|
+
const t = r.timestamp == null ? "(无时间)" : new Date(r.timestamp * 1000).toISOString().slice(0, 10)
|
|
171
|
+
const src = `${r.source?.file ?? "?"}${r.source?.line ? `:${r.source.line}` : ""}`
|
|
172
|
+
return ` ${t} ${r.symbol}${r.kind} ${r.action} ${String(r.title).slice(0, 32)} [${src}]\n → ${r.hint}`
|
|
173
|
+
}).join("\n")
|
|
174
|
+
}
|