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.
- package/README.md +2 -1
- package/package.json +1 -1
- package/src/adapter-opencode/curator-runner.mjs +254 -0
- package/src/adapter-opencode/index.mjs +305 -19
- package/src/adapter-opencode/install.mjs +63 -12
- 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 +75 -21
- package/src/adapter-opencode/session-search-tool.mjs +66 -0
- package/src/adapter-opencode/skill-tool.mjs +221 -0
- package/src/cli/commands.mjs +74 -1
- package/src/cli/curator-cmd.mjs +147 -0
- package/src/cli/journey-cmd.mjs +61 -0
- package/src/cli/journey-view.mjs +174 -0
- package/src/cli/main.mjs +172 -25
- package/src/cli/memory-cmd.mjs +165 -0
- package/src/cli/session-index-cmd.mjs +74 -0
- package/src/cli/skill-cmd.mjs +192 -0
- package/src/core/approve.mjs +155 -0
- package/src/core/audit.mjs +51 -0
- package/src/core/background-review.mjs +88 -1
- 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 +186 -9
- package/src/core/memory-actions.mjs +73 -18
- package/src/core/session-freshness.mjs +201 -0
- package/src/core/session-index.mjs +467 -0
- package/src/core/session-query.mjs +161 -0
- package/src/core/session-source.mjs +202 -0
- package/src/core/session-tool.mjs +181 -0
- package/src/core/skill-actions.mjs +372 -0
- package/src/core/skill-backup.mjs +95 -0
- package/src/core/skill-lifecycle.mjs +265 -0
- package/src/core/skill-usage.mjs +119 -0
- package/src/core/skills.mjs +28 -2
- 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/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
|
@@ -0,0 +1,74 @@
|
|
|
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, searchStore, statusStore, syncStore } from "../core/session-index.mjs"
|
|
6
|
+
|
|
7
|
+
const CAP_STATES = new Set([
|
|
8
|
+
"unsupported-schema",
|
|
9
|
+
"source-missing",
|
|
10
|
+
"source-unavailable",
|
|
11
|
+
"permission-denied",
|
|
12
|
+
])
|
|
13
|
+
|
|
14
|
+
function syncEnvelope(command, r) {
|
|
15
|
+
if (r.ok) {
|
|
16
|
+
return ok(command, `sync ok · parts ${r.counts.parts} · sessions ${r.counts.sessions} · +${r.added} ~${r.updated} -${r.removed}`, r)
|
|
17
|
+
}
|
|
18
|
+
if (CAP_STATES.has(r.state)) {
|
|
19
|
+
return fail(command, "DEGRADED", r.error ?? `能力缺失:${r.state}`, r)
|
|
20
|
+
}
|
|
21
|
+
if (r.error_code === "source-mismatch") {
|
|
22
|
+
return fail(command, "SOURCE_MISMATCH", r.error, r)
|
|
23
|
+
}
|
|
24
|
+
return fail(command, "SYNC_FAILED", r.error ?? `sync 失败:${r.state}`, r)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function sessionIndexSyncCmd(options) {
|
|
28
|
+
const source = options.source
|
|
29
|
+
if (!source) return fail("session-index sync", "USAGE", "需要 --source <opencode.db 路径>")
|
|
30
|
+
return syncEnvelope("session-index sync", await syncStore({ root: options.store, sourcePath: source }))
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function sessionIndexRebuildCmd(options) {
|
|
34
|
+
const source = options.source
|
|
35
|
+
if (!source) return fail("session-index rebuild", "USAGE", "需要 --source <opencode.db 路径>")
|
|
36
|
+
// rebuild=显式全量重建:清派生库并按同一套 mark-and-sweep 重新落(恢复/换源后的口径)。
|
|
37
|
+
rebindStore({ root: options.store, sourcePath: source })
|
|
38
|
+
return syncEnvelope("session-index rebuild", await syncStore({ root: options.store, sourcePath: source }))
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function sessionIndexSearchCmd(options) {
|
|
42
|
+
const query = String(options._?.[0] ?? "").trim()
|
|
43
|
+
if (!query) return fail("session-index search", "USAGE", "需要查询词")
|
|
44
|
+
const r = searchStore({
|
|
45
|
+
root: options.store,
|
|
46
|
+
query,
|
|
47
|
+
limit: options.limit ? Number(options.limit) : 20,
|
|
48
|
+
session_id: options.session ?? null,
|
|
49
|
+
role: options.role ?? null,
|
|
50
|
+
since: options.since != null ? Number(options.since) : null,
|
|
51
|
+
until: options.until != null ? Number(options.until) : null,
|
|
52
|
+
})
|
|
53
|
+
return ok("session-index search", r.message ?? `${r.count} 命中`, r)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function sessionIndexStatusCmd(options) {
|
|
57
|
+
const st = statusStore({ root: options.store })
|
|
58
|
+
if (st.state === "ok") return ok("session-index status", `state ok · parts ${st.counts.parts ?? 0}`, st)
|
|
59
|
+
// 能力缺失/未完成对账:退码 5,信封里 state/facts 说清缺什么。
|
|
60
|
+
return fail("session-index status", "DEGRADED", `state ${st.state}${st.facts?.length ? ` · ${st.facts.map((f) => `${f.code}:${f.detail}`).join(";")}` : ""}`, st)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function sessionIndexReadCmd(options) {
|
|
64
|
+
const r = readStore({
|
|
65
|
+
root: options.store,
|
|
66
|
+
session_id: options.session ?? null,
|
|
67
|
+
message_id: options.message ?? null,
|
|
68
|
+
part_id: options.part ?? null,
|
|
69
|
+
window: options.window != null ? Number(options.window) : 5,
|
|
70
|
+
})
|
|
71
|
+
if (r.ok) return ok("session-index read", `messages ${r.messages.length}`, r)
|
|
72
|
+
if (r.error_code === "not-found") return fail("session-index read", "NOT_FOUND", r.error, r)
|
|
73
|
+
return fail("session-index read", "USAGE", r.error, r)
|
|
74
|
+
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// S1 形成面 · `oc-grow skill create|patch|list` —— CLI 入口(照 memory-cmd/journey-cmd 信封形制)。
|
|
2
|
+
//
|
|
3
|
+
// 为什么要有它:60- §2 现状行点名的缺口「CLI 无 skill 创建入口」。命令面与工具面共用同一个
|
|
4
|
+
// 动作层(`core/skill-actions.mjs`),所以校验/闸门/认账回执一处不漏——CLI 只做参数取用与
|
|
5
|
+
// 信封/退出码映射(0 OK · 1 REFUSED · 2 USAGE)。
|
|
6
|
+
//
|
|
7
|
+
// 认账闸同样在场:宿主配置(permission.skill.<name>=deny / 目标 agent tools.skill:false)
|
|
8
|
+
// 与 store 的 skills.external_dirs 都要喂给动作层,回执照常三态(已交付/未生效·冲突/待批)。
|
|
9
|
+
// CLI 的目标 agent 固定 `ocg-cli`、身份是前台(=显式指令 ⇒ user-owned)。
|
|
10
|
+
import fs from "node:fs"
|
|
11
|
+
|
|
12
|
+
import { ok, fail } from "./envelope.mjs"
|
|
13
|
+
import { runSkillAction, skillGateFromHostConfig } from "../core/skill-actions.mjs"
|
|
14
|
+
import { readUsage } from "../core/skill-usage.mjs"
|
|
15
|
+
import {
|
|
16
|
+
archiveSkill,
|
|
17
|
+
restoreSkill,
|
|
18
|
+
setPinned,
|
|
19
|
+
applyLifecycleTransitions,
|
|
20
|
+
adoptSkill,
|
|
21
|
+
listUnmanaged,
|
|
22
|
+
} from "../core/skill-lifecycle.mjs"
|
|
23
|
+
import { snapshotSkills, listSnapshots, rollbackSkills } from "../core/skill-backup.mjs"
|
|
24
|
+
import { readExternalDirs } from "../core/skills.mjs"
|
|
25
|
+
import { readHostConfig, renderSkillResult } from "../adapter-opencode/skill-tool.mjs"
|
|
26
|
+
|
|
27
|
+
/** CLI 是人的显式指令面:身份固定前台、agent 名固定(宿主闸按这个名字查 tools.skill)。 */
|
|
28
|
+
const CLI_IDENTITY = Object.freeze({ origin: "foreground", agent: "ocg-cli" })
|
|
29
|
+
|
|
30
|
+
function usage(cmd) {
|
|
31
|
+
return fail(cmd, "USAGE", [
|
|
32
|
+
"usage: oc-grow skill create <name> --description \"Use when <触发>. <一行行为>.\" (--content <md> | --content-file <path>)",
|
|
33
|
+
" oc-grow skill patch <name> --old-string <原文> --new-string <新文>(原文必须唯一命中)",
|
|
34
|
+
" oc-grow skill list",
|
|
35
|
+
].join(" · "))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function act(cmd, action, fields, { L }) {
|
|
39
|
+
const gate = skillGateFromHostConfig({
|
|
40
|
+
hostConfig: readHostConfig(),
|
|
41
|
+
agent: CLI_IDENTITY.agent,
|
|
42
|
+
name: fields.name ?? "",
|
|
43
|
+
})
|
|
44
|
+
const r = await runSkillAction({
|
|
45
|
+
root: L.root,
|
|
46
|
+
identity: CLI_IDENTITY,
|
|
47
|
+
action,
|
|
48
|
+
...fields,
|
|
49
|
+
hostPermission: gate.hostPermission,
|
|
50
|
+
agentSkillEnabled: gate.agentSkillEnabled,
|
|
51
|
+
externalDirs: readExternalDirs(L.root),
|
|
52
|
+
})
|
|
53
|
+
const message = renderSkillResult(r)
|
|
54
|
+
if (r.ok === false) return fail(cmd, "REFUSED", message, { receipt: r.receipt ?? null })
|
|
55
|
+
return ok(cmd, message, {
|
|
56
|
+
receipt: r.receipt ?? null,
|
|
57
|
+
...(r.action === "list" ? { skills: r.skills ?? [] } : {}),
|
|
58
|
+
...(r.action === "view" ? { content: r.content ?? "" } : {}),
|
|
59
|
+
...(r.staged ? { staged: true } : {}),
|
|
60
|
+
})
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function skillCreateCmd(flags, ctx) {
|
|
64
|
+
const cmd = "skill.create"
|
|
65
|
+
const name = flags._?.[0]
|
|
66
|
+
if (!name) return usage(cmd)
|
|
67
|
+
const description = flags.description ?? null
|
|
68
|
+
let content = null
|
|
69
|
+
if (flags["content-file"]) {
|
|
70
|
+
try {
|
|
71
|
+
content = fs.readFileSync(String(flags["content-file"]), "utf8")
|
|
72
|
+
} catch (e) {
|
|
73
|
+
return fail(cmd, "USAGE", `--content-file 读不到:${e?.message ?? e}`)
|
|
74
|
+
}
|
|
75
|
+
} else if (flags.content !== undefined && flags.content !== true) {
|
|
76
|
+
content = String(flags.content)
|
|
77
|
+
}
|
|
78
|
+
if (!description || content === null) return usage(cmd)
|
|
79
|
+
return act(cmd, "create", { name: String(name), description: String(description), content: String(content) }, ctx)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function skillPatchCmd(flags, ctx) {
|
|
83
|
+
const cmd = "skill.patch"
|
|
84
|
+
const name = flags._?.[0]
|
|
85
|
+
const oldString = flags["old-string"]
|
|
86
|
+
const newString = flags["new-string"]
|
|
87
|
+
if (!name || oldString === undefined || oldString === true || newString === undefined || newString === true) return usage(cmd)
|
|
88
|
+
return act(cmd, "patch", { name: String(name), old_string: String(oldString), new_string: String(newString) }, ctx)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function skillListCmd(flags, ctx) {
|
|
92
|
+
return act("skill.list", "list", {}, ctx)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function skillViewCmd(flags, ctx) {
|
|
96
|
+
const cmd = "skill.view"
|
|
97
|
+
const name = flags._?.[0]
|
|
98
|
+
if (!name) return usage(cmd)
|
|
99
|
+
return act(cmd, "view", { name: String(name) }, ctx)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** usage 账本读数(照 Hermes `hermes curator usage`):计数+时间戳,命令可复跑。 */
|
|
103
|
+
export async function skillUsageCmd(flags, ctx) {
|
|
104
|
+
const cmd = "skill.usage"
|
|
105
|
+
const usageMap = readUsage(ctx.L.root)
|
|
106
|
+
const names = Object.keys(usageMap)
|
|
107
|
+
const message = names.length
|
|
108
|
+
? names.map((n) => {
|
|
109
|
+
const u = usageMap[n]
|
|
110
|
+
return `${n}:use ${u.use_count ?? 0} / view ${u.view_count ?? 0} / patch ${u.patch_count ?? 0} · last ${u.last_activity_at ?? "-"}`
|
|
111
|
+
}).join(";")
|
|
112
|
+
: "账本为空"
|
|
113
|
+
return ok(cmd, message, { usage: usageMap })
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ── S3 生命周期的命令面(照 Hermes `hermes curator` 的机械面;LLM 整理是 S4)────
|
|
117
|
+
|
|
118
|
+
export async function skillArchiveCmd(flags, ctx) {
|
|
119
|
+
const cmd = "skill.archive"
|
|
120
|
+
const name = flags._?.[0]
|
|
121
|
+
if (!name) return usage(cmd)
|
|
122
|
+
const r = archiveSkill(ctx.L.root, String(name))
|
|
123
|
+
if (!r.ok) return fail(cmd, "REFUSED", r.error, { receipt: { status: "未生效", name: String(name), detail: r.error } })
|
|
124
|
+
return ok(cmd, `技能已归档(只归档不删除):${r.name} → ${r.dest}`, { name: r.name, dest: r.dest })
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export async function skillRestoreCmd(flags, ctx) {
|
|
128
|
+
const cmd = "skill.restore"
|
|
129
|
+
const name = flags._?.[0]
|
|
130
|
+
if (!name) return usage(cmd)
|
|
131
|
+
const r = restoreSkill(ctx.L.root, String(name))
|
|
132
|
+
if (!r.ok) return fail(cmd, "REFUSED", r.error, { receipt: { status: "未生效", name: String(name), detail: r.error } })
|
|
133
|
+
return ok(cmd, `技能已恢复(逐字节搬回):${r.name} → ${r.dest}`, { name: r.name, dest: r.dest })
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export async function skillPinCmd(flags, ctx) {
|
|
137
|
+
const cmd = "skill.pin"
|
|
138
|
+
const name = flags._?.[0]
|
|
139
|
+
if (!name) return usage(cmd)
|
|
140
|
+
setPinned(ctx.L.root, String(name), true)
|
|
141
|
+
return ok(cmd, `已 pin:${name}(自动迁移全旁路)`, { name: String(name), pinned: true })
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export async function skillUnpinCmd(flags, ctx) {
|
|
145
|
+
const cmd = "skill.unpin"
|
|
146
|
+
const name = flags._?.[0]
|
|
147
|
+
if (!name) return usage(cmd)
|
|
148
|
+
setPinned(ctx.L.root, String(name), false)
|
|
149
|
+
return ok(cmd, `已 unpin:${name}(恢复自动老化)`, { name: String(name), pinned: false })
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export async function skillLifecycleCmd(flags, ctx) {
|
|
153
|
+
const cmd = "skill.lifecycle"
|
|
154
|
+
const dryRun = Boolean(flags["dry-run"])
|
|
155
|
+
const r = applyLifecycleTransitions({ root: ctx.L.root, dryRun, origin: "foreground" })
|
|
156
|
+
const msg =
|
|
157
|
+
`生命周期迁移${dryRun ? "(dry-run:库/快照/时钟全不动)" : ""}:检查 ${r.checked} · 锚时钟 ${r.seeded} · ` +
|
|
158
|
+
`stale ${r.marked_stale} · 归档 ${r.archived} · 提案 ${r.staged} · 复活 ${r.reactivated}`
|
|
159
|
+
return ok(cmd, msg, r)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export async function skillRollbackCmd(flags, ctx) {
|
|
163
|
+
const cmd = "skill.rollback"
|
|
164
|
+
const id = flags._?.[0]
|
|
165
|
+
if (!id) {
|
|
166
|
+
// 无参数=快照列表(照 Hermes `curator rollback --list`)
|
|
167
|
+
const snaps = listSnapshots(ctx.L.root)
|
|
168
|
+
return ok(
|
|
169
|
+
cmd,
|
|
170
|
+
snaps.length ? `快照 ${snaps.length} 份:${snaps.join("、")}(回滚用 skill rollback <id>)` : "无快照",
|
|
171
|
+
{ snapshots: snaps },
|
|
172
|
+
)
|
|
173
|
+
}
|
|
174
|
+
const r = rollbackSkills(ctx.L.root, String(id))
|
|
175
|
+
if (!r.ok) return fail(cmd, "REFUSED", r.error, { receipt: { status: "未生效", name: String(id), detail: r.error } })
|
|
176
|
+
return ok(cmd, `已回滚到快照 ${r.id}(回滚前已再拍快照 ${r.backupId ?? "-"},自身可撤销)`, r)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export async function skillAdoptCmd(flags, ctx) {
|
|
180
|
+
const cmd = "skill.adopt"
|
|
181
|
+
const name = flags._?.[0]
|
|
182
|
+
if (!name) return usage(cmd)
|
|
183
|
+
const r = adoptSkill(ctx.L.root, String(name))
|
|
184
|
+
if (!r.ok) return fail(cmd, "REFUSED", r.error, { receipt: { status: "未生效", name: String(name), detail: r.error } })
|
|
185
|
+
return ok(cmd, r.message, { name: r.name })
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export async function skillUnmanagedCmd(flags, ctx) {
|
|
189
|
+
const cmd = "skill.unmanaged"
|
|
190
|
+
const names = listUnmanaged(ctx.L.root)
|
|
191
|
+
return ok(cmd, names.length ? `未托管 ${names.length} 个:${names.join("、")}(移交用 skill adopt <name>)` : "无未托管技能", { unmanaged: names })
|
|
192
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// 待批提案的**处置面**(人 / 运维侧),对齐 Hermes `tools/write_approval.py` 的待批协议与
|
|
2
|
+
// 命令面 `/memory pending|approve|reject`(决策 C8)。
|
|
3
|
+
//
|
|
4
|
+
// 为什么单独一个模块,而不是 store 上的一个方法:
|
|
5
|
+
// 契约 C05 要求 `createMemoryStore()` 上**不出现任何批准入口**(后台不得自批)。
|
|
6
|
+
// 批准是**命令行使用者的动作**,与「会话里的模型能做什么」是两件事。把它挂在 store 上
|
|
7
|
+
// 等于给模型一条自批的路;把它做成工具动作(MEMORY_ACTIONS)同理。
|
|
8
|
+
//
|
|
9
|
+
// 处置 = 锁内重读-改-写(走受信任写入原语:仍过威胁扫描与限额、仍原子替换)
|
|
10
|
+
// + 审计留痕(`approvedBy` 非空才可能落盘)
|
|
11
|
+
// + 移除待批文件(处置完成;**删除即拒绝**这条语义保持不变)。
|
|
12
|
+
//
|
|
13
|
+
// 失败方向(明写):应用成功、移除文件之前崩溃 ⇒ 待批文件仍在,再批准一次会**重复落一条**
|
|
14
|
+
// (可见、可撤),不会静默丢掉一条。宁可重复也不要静默丢失。
|
|
15
|
+
import fs from "node:fs"
|
|
16
|
+
import path from "node:path"
|
|
17
|
+
|
|
18
|
+
import { withCommitLock } from "./lock.mjs"
|
|
19
|
+
import { appendAudit } from "./audit.mjs"
|
|
20
|
+
import { createMemoryStore, storeHashOf } from "./memories.mjs"
|
|
21
|
+
|
|
22
|
+
const OPS = ["add", "update", "remove", "batch"]
|
|
23
|
+
const KINDS = ["memory", "user"]
|
|
24
|
+
|
|
25
|
+
/** 列出待批提案。origin 保留原值;后台来源标 `[auto]`(照 Hermes,人一眼能看出不是自己提的)。 */
|
|
26
|
+
export function listPending(L) {
|
|
27
|
+
const store = createMemoryStore({ root: L.root })
|
|
28
|
+
return store.pending().map((file) => {
|
|
29
|
+
let raw = {}
|
|
30
|
+
let unreadable = false
|
|
31
|
+
try {
|
|
32
|
+
raw = JSON.parse(fs.readFileSync(path.join(store.paths.pendingDir, file), "utf8"))
|
|
33
|
+
} catch {
|
|
34
|
+
unreadable = true
|
|
35
|
+
}
|
|
36
|
+
const origin = raw.origin ?? "unknown"
|
|
37
|
+
return {
|
|
38
|
+
file,
|
|
39
|
+
unreadable,
|
|
40
|
+
op: raw.op ?? null,
|
|
41
|
+
kind: raw.kind ?? null,
|
|
42
|
+
origin,
|
|
43
|
+
label: origin === "background" ? "[auto]" : null,
|
|
44
|
+
text: raw.text ?? null,
|
|
45
|
+
match: raw.match ?? null,
|
|
46
|
+
// 批量提案:列出条目数与动作分布——人要能一眼看出「在批什么、几笔」
|
|
47
|
+
operations: Array.isArray(raw.operations) ? raw.operations : null,
|
|
48
|
+
ops: Array.isArray(raw.operations) ? raw.operations.length : null,
|
|
49
|
+
stagedAt: raw.stagedAt ?? null,
|
|
50
|
+
}
|
|
51
|
+
})
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 把 `ref` 解析成**唯一**一个待批文件:先整名(含补 `.json`),再子串。
|
|
56
|
+
* 零命中与多命中都**不猜**(与库内子串寻址同一口径:歧义必须由人消解)。
|
|
57
|
+
*/
|
|
58
|
+
export function resolvePendingRef(L, ref) {
|
|
59
|
+
const want = typeof ref === "string" ? ref.trim() : ""
|
|
60
|
+
if (!want) return { ok: false, reason: "usage" }
|
|
61
|
+
const files = listPending(L).map((p) => p.file)
|
|
62
|
+
const exact = files.find((f) => f === want || f === `${want}.json`)
|
|
63
|
+
if (exact) return { ok: true, file: exact }
|
|
64
|
+
const hits = files.filter((f) => f.includes(want))
|
|
65
|
+
if (hits.length === 1) return { ok: true, file: hits[0] }
|
|
66
|
+
if (!hits.length) return { ok: false, reason: "not-found", files }
|
|
67
|
+
return { ok: false, reason: "ambiguous", hits }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 提案本身必须完整——不完整的提案连"可被批准"都不算,报出来让人处置。 */
|
|
71
|
+
function invalidReason(rec) {
|
|
72
|
+
if (!rec || typeof rec !== "object") return "提案不是对象"
|
|
73
|
+
if (!OPS.includes(rec.op)) return `未知的 op:${String(rec.op)}(可用:${OPS.join(" / ")})`
|
|
74
|
+
if (!KINDS.includes(rec.kind ?? "memory")) return `未知的库:${String(rec.kind)}(可用:${KINDS.join(" / ")})`
|
|
75
|
+
if (rec.op === "add" || rec.op === "update") {
|
|
76
|
+
if (typeof rec.text !== "string" || !rec.text.trim()) return `${rec.op} 提案缺少非空 text`
|
|
77
|
+
}
|
|
78
|
+
if (rec.op === "update" || rec.op === "remove") {
|
|
79
|
+
if (typeof rec.match !== "string" || !rec.match.trim()) return `${rec.op} 提案缺少非空 match`
|
|
80
|
+
}
|
|
81
|
+
if (rec.op === "batch") {
|
|
82
|
+
// 整批提案必须带完整的 operations(缺了它连「可被批准」都不算);逐项形态在应用时由
|
|
83
|
+
// `scanBatchOps` 再验一次(同一实现,不在这里另写一套)。
|
|
84
|
+
if (!Array.isArray(rec.operations) || !rec.operations.length) return "batch 提案缺少非空 operations"
|
|
85
|
+
}
|
|
86
|
+
return null
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 批准一条待批提案。
|
|
91
|
+
*
|
|
92
|
+
* 顺序:**先定位提案**(usage/not-found/ambiguous 是"你指的东西不对"),**再要署名**
|
|
93
|
+
* (没署名就不算批准——与 `review.confirmReview` 的 `HUMAN_APPROVAL_REQUIRED` 同一口径),
|
|
94
|
+
* 最后才在锁内应用。三种失败各自可达,不用一条错遮蔽另一条。
|
|
95
|
+
*
|
|
96
|
+
* @returns {{ok:true, file, op, kind, origin, approvedBy, pending}} 或 {{ok:false, reason, ...}}
|
|
97
|
+
*/
|
|
98
|
+
export function approvePending(L, ref, { approvedBy = null } = {}) {
|
|
99
|
+
const found = resolvePendingRef(L, ref)
|
|
100
|
+
if (!found.ok) return found
|
|
101
|
+
|
|
102
|
+
const who = typeof approvedBy === "string" ? approvedBy.trim() : ""
|
|
103
|
+
if (!who) return { ok: false, reason: "human-approval-required", file: found.file }
|
|
104
|
+
|
|
105
|
+
const store = createMemoryStore({ root: L.root })
|
|
106
|
+
const pendingPath = path.join(store.paths.pendingDir, found.file)
|
|
107
|
+
|
|
108
|
+
let rec = null
|
|
109
|
+
try {
|
|
110
|
+
rec = JSON.parse(fs.readFileSync(pendingPath, "utf8"))
|
|
111
|
+
} catch (err) {
|
|
112
|
+
return { ok: false, reason: "invalid", file: found.file, detail: `提案文件读不出来:${err?.message ?? err}` }
|
|
113
|
+
}
|
|
114
|
+
const bad = invalidReason(rec)
|
|
115
|
+
if (bad) return { ok: false, reason: "invalid", file: found.file, detail: bad }
|
|
116
|
+
|
|
117
|
+
const kind = rec.kind ?? "memory"
|
|
118
|
+
const locked = withCommitLock(L.lock, ({ fencing, assertStillOwner }) => {
|
|
119
|
+
try {
|
|
120
|
+
if (rec.op === "add") store.writeTrusted({ kind, text: rec.text })
|
|
121
|
+
else if (rec.op === "update") store.updateTrusted({ kind, match: rec.match, text: rec.text })
|
|
122
|
+
// 批量:整批一次性应用(仍走同一条批量核心:整批预扫 + 工作副本 + 终态预算 + 一次原子替换)
|
|
123
|
+
else if (rec.op === "batch") store.batchTrusted({ kind, operations: rec.operations })
|
|
124
|
+
else store.removeTrusted({ kind, match: rec.match })
|
|
125
|
+
} catch (err) {
|
|
126
|
+
// 应用失败(子串歧义/零命中/超限/命中威胁模式):**待批文件保留**,报原因让人处置。
|
|
127
|
+
return { ok: false, reason: "apply-failed", file: found.file, detail: err?.message ?? String(err) }
|
|
128
|
+
}
|
|
129
|
+
if (!assertStillOwner()) return { ok: false, reason: "lost", file: found.file }
|
|
130
|
+
|
|
131
|
+
fs.rmSync(pendingPath, { force: true })
|
|
132
|
+
appendAudit(L, {
|
|
133
|
+
event: "approve",
|
|
134
|
+
file: found.file,
|
|
135
|
+
op: rec.op,
|
|
136
|
+
kind,
|
|
137
|
+
origin: rec.origin ?? "unknown",
|
|
138
|
+
approvedBy: who,
|
|
139
|
+
generation: storeHashOf(L.root),
|
|
140
|
+
fence: fencing,
|
|
141
|
+
})
|
|
142
|
+
return {
|
|
143
|
+
ok: true,
|
|
144
|
+
file: found.file,
|
|
145
|
+
op: rec.op,
|
|
146
|
+
kind,
|
|
147
|
+
origin: rec.origin ?? "unknown",
|
|
148
|
+
approvedBy: who,
|
|
149
|
+
pending: listPending(L).length,
|
|
150
|
+
}
|
|
151
|
+
})
|
|
152
|
+
|
|
153
|
+
if (!locked.ok) return { ok: false, reason: locked.reason, file: found.file }
|
|
154
|
+
return locked.value
|
|
155
|
+
}
|
package/src/core/audit.mjs
CHANGED
|
@@ -38,3 +38,54 @@ export function readAudit(L, limit = 200) {
|
|
|
38
38
|
}
|
|
39
39
|
return { events: out.slice(-limit), skipped }
|
|
40
40
|
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 账本按龄归档(`curator ledger --compact`):把早于 `olderThanDays` 的条目搬进
|
|
44
|
+
* `audit/archive/<原文件>`,活文件重写成只剩新条目(空了就删)。
|
|
45
|
+
*
|
|
46
|
+
* 为什么不照抄 Hermes 的 `compact_ledger`:那是**blob GC**(每条 entry 里塞了内容 blob,compact
|
|
47
|
+
* 只丢未变更的路径、id 与回滚信息保留)。本仓账本条目里**没有 blob**(只有事件字段),照抄等于空转;
|
|
48
|
+
* 这里对应「会长的那个维度」=月文件随行数增长 ⇒ 按龄搬走,条目**逐字不改**(不丢 id、不丢字段)。
|
|
49
|
+
* 差异记 D113。
|
|
50
|
+
*/
|
|
51
|
+
export function compactAudit(L, { olderThanDays = 30, now = new Date() } = {}) {
|
|
52
|
+
const days = Number(olderThanDays)
|
|
53
|
+
if (!Number.isFinite(days) || days <= 0) return { ok: false, error: "olderThanDays 必须是正数" }
|
|
54
|
+
const cutoff = (now instanceof Date ? now.getTime() : new Date(now).getTime()) - days * 86400_000
|
|
55
|
+
let files = []
|
|
56
|
+
try {
|
|
57
|
+
files = fs.readdirSync(L.audit).filter((f) => f.endsWith(".jsonl")).sort()
|
|
58
|
+
} catch {
|
|
59
|
+
return { ok: true, moved: 0, kept: 0, files: 0, archived: null }
|
|
60
|
+
}
|
|
61
|
+
const archived = path.join(L.audit, "archive")
|
|
62
|
+
let moved = 0
|
|
63
|
+
let kept = 0
|
|
64
|
+
let touched = 0
|
|
65
|
+
for (const f of files) {
|
|
66
|
+
const abs = path.join(L.audit, f)
|
|
67
|
+
const lines = fs.readFileSync(abs, "utf8").split("\n").filter((l) => l.trim())
|
|
68
|
+
const old = []
|
|
69
|
+
const fresh = []
|
|
70
|
+
for (const line of lines) {
|
|
71
|
+
let ts = NaN
|
|
72
|
+
try {
|
|
73
|
+
ts = Date.parse(JSON.parse(line)?.ts ?? "")
|
|
74
|
+
} catch { /* 坏行按「新」处理:宁可留在活账本里,也不搬走(不静默丢弃) */ }
|
|
75
|
+
if (Number.isFinite(ts) && ts < cutoff) old.push(line)
|
|
76
|
+
else fresh.push(line)
|
|
77
|
+
}
|
|
78
|
+
if (!old.length) {
|
|
79
|
+
kept += fresh.length
|
|
80
|
+
continue
|
|
81
|
+
}
|
|
82
|
+
fs.mkdirSync(archived, { recursive: true })
|
|
83
|
+
fs.appendFileSync(path.join(archived, f), old.join("\n") + "\n")
|
|
84
|
+
moved += old.length
|
|
85
|
+
touched += 1
|
|
86
|
+
if (fresh.length) fs.writeFileSync(abs, fresh.join("\n") + "\n")
|
|
87
|
+
else fs.rmSync(abs, { force: true })
|
|
88
|
+
kept += fresh.length
|
|
89
|
+
}
|
|
90
|
+
return { ok: true, moved, kept, files: touched, archived: fs.existsSync(archived) ? archived : null }
|
|
91
|
+
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import fs from "node:fs"
|
|
2
2
|
import path from "node:path"
|
|
3
3
|
|
|
4
|
+
import { runSkillAction, skillGateFromHostConfig } from "./skill-actions.mjs"
|
|
5
|
+
|
|
4
6
|
// 后台复习的调度与有界(照 Hermes agent/background_review.py 的口径)
|
|
5
7
|
// 机制:回合结束触发一次「要不要复习」的检查 → 达阈值才派发 → 一次一个 → 新回合可取消(握手 ≤2s)
|
|
6
8
|
// 判定的三条(机制/触发/判定)都对齐 Hermes,第一版不加自造物。
|
|
@@ -207,6 +209,11 @@ export function createTurnEndHandler({ scheduler, review, sessionId = null } = {
|
|
|
207
209
|
async onUserTurnStart() {
|
|
208
210
|
return scheduler.cancel("user-turn-start")
|
|
209
211
|
},
|
|
212
|
+
// S1 通道④的触发源透传:宿主工具迭代(wire 按 callID 去重后)前进调度器计数。
|
|
213
|
+
// skill_manage 用过 ⇒ 重置(照 Hermes turn_iteration_prep)。
|
|
214
|
+
noteIteration(opts = {}) {
|
|
215
|
+
return scheduler.noteIteration(opts)
|
|
216
|
+
},
|
|
210
217
|
lastResult() { return lastResult },
|
|
211
218
|
lastKind() { return lastKind },
|
|
212
219
|
}
|
|
@@ -214,11 +221,35 @@ export function createTurnEndHandler({ scheduler, review, sessionId = null } = {
|
|
|
214
221
|
|
|
215
222
|
// ── 产出的解析与落地 ───────────────────────────────────────────────
|
|
216
223
|
// 解析:我们自己在提示词里定了格式,所以像解析**契约**一样严格:只认三类行,其余忽略。
|
|
224
|
+
// 技能车道(S1 通道④):`skill: <json>` 单行——闭集只有 create/patch(§6 规则④:
|
|
225
|
+
// 无人值守归档/删除不在闭集 ⇒ 忽略+浮出,绝不落盘)。
|
|
226
|
+
export const SKILL_REVIEW_OPS = Object.freeze(["create", "patch"])
|
|
227
|
+
|
|
217
228
|
export function parseReviewActions(text) {
|
|
218
229
|
if (typeof text !== "string" || !text.trim()) return []
|
|
219
230
|
const out = []
|
|
220
231
|
for (const raw of text.split("\n")) {
|
|
221
232
|
const line = raw.trim()
|
|
233
|
+
const sk = /^skill\s*:\s*(.+)$/i.exec(line)
|
|
234
|
+
if (sk) {
|
|
235
|
+
try {
|
|
236
|
+
const obj = JSON.parse(sk[1])
|
|
237
|
+
if (!obj || typeof obj !== "object" || Array.isArray(obj)) throw new Error("not an object")
|
|
238
|
+
out.push({
|
|
239
|
+
skill: true,
|
|
240
|
+
op: typeof obj.op === "string" ? obj.op.toLowerCase() : null,
|
|
241
|
+
name: typeof obj.name === "string" ? obj.name : null,
|
|
242
|
+
description: typeof obj.description === "string" ? obj.description : null,
|
|
243
|
+
content: typeof obj.content === "string" ? obj.content : null,
|
|
244
|
+
old_string: typeof obj.old_string === "string" ? obj.old_string : null,
|
|
245
|
+
new_string: typeof obj.new_string === "string" ? obj.new_string : null,
|
|
246
|
+
})
|
|
247
|
+
} catch {
|
|
248
|
+
// 坏 JSON 不许悄悄丢:记成 malformed 让落地口浮出(解析如契约般严格)
|
|
249
|
+
out.push({ skill: true, malformed: true, raw: sk[1].slice(0, 200) })
|
|
250
|
+
}
|
|
251
|
+
continue
|
|
252
|
+
}
|
|
222
253
|
const m = /^(add|update|remove)\s*:\s*(.+)$/i.exec(line)
|
|
223
254
|
if (!m) continue
|
|
224
255
|
out.push({ op: m[1].toLowerCase(), text: m[2].trim() })
|
|
@@ -239,7 +270,9 @@ function stageProposal(pendingDir, op) {
|
|
|
239
270
|
|
|
240
271
|
// 落地:新增直接写(受信任写入路径);改造/删除**只提案**(硬不变量)且提案必须浮出。
|
|
241
272
|
export function applyReviewOutcome({ store, actions = [], kind = "memory", gateEnabled = false, entries = null } = {}) {
|
|
242
|
-
|
|
273
|
+
// 技能形状的动作走技能车道(applySkillReviewActions);memory 车道只吃 add/update/remove。
|
|
274
|
+
const memActions = (Array.isArray(actions) ? actions : []).filter((a) => a && a.skill !== true)
|
|
275
|
+
const { direct, proposals, ignored, mustSurface } = classifyReviewOutcome({ actions: memActions, entries })
|
|
243
276
|
// A139:后台复习的写入**必须过写入闸门**(不再用 writeTrusted 旁路)。
|
|
244
277
|
// 闸开时按 Hermes evaluate_gate:后台来源一律进待批。
|
|
245
278
|
const pending = gateEnabled
|
|
@@ -259,3 +292,57 @@ export function applyReviewOutcome({ store, actions = [], kind = "memory", gateE
|
|
|
259
292
|
const surface = (pending.length || ignored.length) ? surfaceLine({ proposals: pending, ignored }) : null
|
|
260
293
|
return { written, staged, ignored, surface, mustSurface: mustSurface || ignored.length > 0 }
|
|
261
294
|
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* 通道④的技能车道落地(S1):`skill: <json>` 动作 → `skill-actions` 动作层。
|
|
298
|
+
* 口径照 60- §5.1.1 的 W8 裁定:回合后通道只动 **agent-created** 技能、create/patch **直写**
|
|
299
|
+
* (闸关时;闸开进同一待批队列——闸门在动作层里自己认,不在这里分叉);
|
|
300
|
+
* 归档/删除不在闭集 ⇒ 忽略+浮出(无人值守删落盘必须红)。
|
|
301
|
+
*
|
|
302
|
+
* 拒绝面必须浮出:动 user-owned / 外部来源 / 校验不过,都带着认账回执进 refused,
|
|
303
|
+
* 浮出行点名「只动 agent-created」——误报已交付的变异会被 test/review-skill-channel4 弄红。
|
|
304
|
+
*/
|
|
305
|
+
export async function applySkillReviewActions({ root, actions = [], identity = { origin: PROPOSAL_ORIGIN, agent: REVIEW_AGENT }, externalDirs = undefined, hostConfig = null } = {}) {
|
|
306
|
+
const skillActions = (Array.isArray(actions) ? actions : []).filter((a) => a && a.skill === true)
|
|
307
|
+
let written = 0
|
|
308
|
+
let staged = 0
|
|
309
|
+
const ignored = []
|
|
310
|
+
const refused = []
|
|
311
|
+
for (const a of skillActions) {
|
|
312
|
+
if (a.malformed) {
|
|
313
|
+
ignored.push({ op: "skill", raw: a.raw, reason: "malformed-json" })
|
|
314
|
+
continue
|
|
315
|
+
}
|
|
316
|
+
if (!SKILL_REVIEW_OPS.includes(a.op)) {
|
|
317
|
+
ignored.push({ op: a.op, name: a.name, reason: "unknown-op" })
|
|
318
|
+
continue
|
|
319
|
+
}
|
|
320
|
+
const gate = skillGateFromHostConfig({ hostConfig: hostConfig ?? {}, agent: identity?.agent ?? null, name: a.name ?? "" })
|
|
321
|
+
const r = await runSkillAction({
|
|
322
|
+
root,
|
|
323
|
+
identity,
|
|
324
|
+
action: a.op,
|
|
325
|
+
name: a.name,
|
|
326
|
+
description: a.description,
|
|
327
|
+
content: a.content,
|
|
328
|
+
old_string: a.old_string,
|
|
329
|
+
new_string: a.new_string,
|
|
330
|
+
hostPermission: gate.hostPermission,
|
|
331
|
+
agentSkillEnabled: gate.agentSkillEnabled,
|
|
332
|
+
...(externalDirs !== undefined ? { externalDirs } : {}),
|
|
333
|
+
})
|
|
334
|
+
if (r.ok === false) refused.push({ op: a.op, name: a.name, error: r.error, receipt: r.receipt ?? null })
|
|
335
|
+
else if (r.staged) staged += 1
|
|
336
|
+
else written += 1
|
|
337
|
+
}
|
|
338
|
+
const surface = (ignored.length || refused.length)
|
|
339
|
+
? [
|
|
340
|
+
"后台复习:技能面",
|
|
341
|
+
written ? `已写 ${written}` : null,
|
|
342
|
+
staged ? `待批 ${staged}` : null,
|
|
343
|
+
refused.length ? `被拒 ${refused.length}(${refused.map((f) => `${f.op}:${f.name ?? "?"}`).join("、")};只动 agent-created / 宿主闸)` : null,
|
|
344
|
+
ignored.length ? `忽略 ${ignored.length}(${ignored.map((i) => i.op).join("、")})` : null,
|
|
345
|
+
].filter(Boolean).join(" ")
|
|
346
|
+
: null
|
|
347
|
+
return { written, staged, ignored, refused, surface, mustSurface: ignored.length > 0 || refused.length > 0 }
|
|
348
|
+
}
|