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
|
@@ -0,0 +1,194 @@
|
|
|
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 pinned = r.skipped_pinned ?? []
|
|
157
|
+
const msg =
|
|
158
|
+
`生命周期迁移${dryRun ? "(dry-run:库/快照/时钟全不动)" : ""}:检查 ${r.checked} · 锚时钟 ${r.seeded} · ` +
|
|
159
|
+
`stale ${r.marked_stale} · 归档 ${r.archived} · 提案 ${r.staged} · 复活 ${r.reactivated}` +
|
|
160
|
+
(pinned.length ? ` · 跳过 pinned ${pinned.length}(${pinned.map((x) => x.name).join("、")})` : "")
|
|
161
|
+
return ok(cmd, msg, r)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export async function skillRollbackCmd(flags, ctx) {
|
|
165
|
+
const cmd = "skill.rollback"
|
|
166
|
+
const id = flags._?.[0]
|
|
167
|
+
if (!id) {
|
|
168
|
+
// 无参数=快照列表(照 Hermes `curator rollback --list`)
|
|
169
|
+
const snaps = listSnapshots(ctx.L.root)
|
|
170
|
+
return ok(
|
|
171
|
+
cmd,
|
|
172
|
+
snaps.length ? `快照 ${snaps.length} 份:${snaps.join("、")}(回滚用 skill rollback <id>)` : "无快照",
|
|
173
|
+
{ snapshots: snaps },
|
|
174
|
+
)
|
|
175
|
+
}
|
|
176
|
+
const r = rollbackSkills(ctx.L.root, String(id))
|
|
177
|
+
if (!r.ok) return fail(cmd, "REFUSED", r.error, { receipt: { status: "未生效", name: String(id), detail: r.error } })
|
|
178
|
+
return ok(cmd, `已回滚到快照 ${r.id}(回滚前已再拍快照 ${r.backupId ?? "-"},自身可撤销)`, r)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export async function skillAdoptCmd(flags, ctx) {
|
|
182
|
+
const cmd = "skill.adopt"
|
|
183
|
+
const name = flags._?.[0]
|
|
184
|
+
if (!name) return usage(cmd)
|
|
185
|
+
const r = adoptSkill(ctx.L.root, String(name))
|
|
186
|
+
if (!r.ok) return fail(cmd, "REFUSED", r.error, { receipt: { status: "未生效", name: String(name), detail: r.error } })
|
|
187
|
+
return ok(cmd, r.message, { name: r.name })
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export async function skillUnmanagedCmd(flags, ctx) {
|
|
191
|
+
const cmd = "skill.unmanaged"
|
|
192
|
+
const names = listUnmanaged(ctx.L.root)
|
|
193
|
+
return ok(cmd, names.length ? `未托管 ${names.length} 个:${names.join("、")}(移交用 skill adopt <name>)` : "无未托管技能", { unmanaged: names })
|
|
194
|
+
}
|
|
@@ -0,0 +1,295 @@
|
|
|
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
|
+
import { sha256 } from "./ids.mjs"
|
|
22
|
+
import { runSkillAction } from "./skill-actions.mjs"
|
|
23
|
+
import { snapshotSkills } from "./skill-backup.mjs"
|
|
24
|
+
import { readCreatedBy, SKILL_FILE, skillsDir } from "./skills.mjs"
|
|
25
|
+
|
|
26
|
+
const OPS = ["add", "update", "remove", "batch"]
|
|
27
|
+
const SKILL_OPS = ["create", "patch"]
|
|
28
|
+
const KINDS = ["memory", "user", "skills"]
|
|
29
|
+
|
|
30
|
+
const MAX_DIFF_LINES = 200
|
|
31
|
+
|
|
32
|
+
/** 行级 diff(够人读就行):公共前缀/后缀之外按行做 LCS,限幅避免大文件拖垮列表。 */
|
|
33
|
+
function lineDiff(oldText, newText) {
|
|
34
|
+
const a = String(oldText ?? "").split("\n")
|
|
35
|
+
const b = String(newText ?? "").split("\n")
|
|
36
|
+
let pre = 0
|
|
37
|
+
while (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++
|
|
38
|
+
let suf = 0
|
|
39
|
+
while (suf < a.length - pre && suf < b.length - pre && a[a.length - 1 - suf] === b[b.length - 1 - suf]) suf++
|
|
40
|
+
const A = a.slice(pre, a.length - suf)
|
|
41
|
+
const B = b.slice(pre, b.length - suf)
|
|
42
|
+
const out = []
|
|
43
|
+
for (let i = 0; i < Math.min(pre, 3); i++) out.push(` ${a[i]}`)
|
|
44
|
+
if (pre > 3) out.push(` …(前 ${pre - 3} 行相同)`)
|
|
45
|
+
if (A.length * B.length <= 40000) {
|
|
46
|
+
const dp = Array.from({ length: A.length + 1 }, () => new Int32Array(B.length + 1))
|
|
47
|
+
for (let i = A.length - 1; i >= 0; i--) {
|
|
48
|
+
for (let j = B.length - 1; j >= 0; j--) {
|
|
49
|
+
dp[i][j] = A[i] === B[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1])
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
let i = 0
|
|
53
|
+
let j = 0
|
|
54
|
+
while (i < A.length && j < B.length) {
|
|
55
|
+
if (A[i] === B[j]) { out.push(` ${A[i]}`); i++; j++ }
|
|
56
|
+
else if (dp[i + 1][j] >= dp[i][j + 1]) out.push(`- ${A[i++]}`)
|
|
57
|
+
else out.push(`+ ${B[j++]}`)
|
|
58
|
+
}
|
|
59
|
+
while (i < A.length) out.push(`- ${A[i++]}`)
|
|
60
|
+
while (j < B.length) out.push(`+ ${B[j++]}`)
|
|
61
|
+
} else {
|
|
62
|
+
for (const line of A) out.push(`- ${line}`)
|
|
63
|
+
for (const line of B) out.push(`+ ${line}`)
|
|
64
|
+
}
|
|
65
|
+
if (suf > 0) out.push(` …(后 ${suf} 行相同)`)
|
|
66
|
+
return out.slice(0, MAX_DIFF_LINES).join("\n")
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 技能提案的目标文件与「当初那份」的指纹(approve 时用来判过期)。 */
|
|
70
|
+
function skillTargetOf(L, name) {
|
|
71
|
+
const file = path.join(skillsDir(L.root), String(name), SKILL_FILE)
|
|
72
|
+
return {
|
|
73
|
+
file,
|
|
74
|
+
exists: fs.existsSync(file),
|
|
75
|
+
hash: fs.existsSync(file) ? sha256(fs.readFileSync(file)) : null,
|
|
76
|
+
createdBy: fs.existsSync(file) ? readCreatedBy(file) : null,
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 列出待批提案。origin 保留原值;后台来源标 `[auto]`(照 Hermes,人一眼能看出不是自己提的)。 */
|
|
81
|
+
export function listPending(L) {
|
|
82
|
+
const store = createMemoryStore({ root: L.root })
|
|
83
|
+
return store.pending().map((file) => {
|
|
84
|
+
let raw = {}
|
|
85
|
+
let unreadable = false
|
|
86
|
+
try {
|
|
87
|
+
raw = JSON.parse(fs.readFileSync(path.join(store.paths.pendingDir, file), "utf8"))
|
|
88
|
+
} catch {
|
|
89
|
+
unreadable = true
|
|
90
|
+
}
|
|
91
|
+
const origin = raw.origin ?? "unknown"
|
|
92
|
+
const entry = {
|
|
93
|
+
file,
|
|
94
|
+
unreadable,
|
|
95
|
+
op: raw.op ?? null,
|
|
96
|
+
kind: raw.kind ?? null,
|
|
97
|
+
origin,
|
|
98
|
+
label: origin === "background" ? "[auto]" : null,
|
|
99
|
+
text: raw.text ?? null,
|
|
100
|
+
match: raw.match ?? null,
|
|
101
|
+
// 批量提案:列出条目数与动作分布——人要能一眼看出「在批什么、几笔」
|
|
102
|
+
operations: Array.isArray(raw.operations) ? raw.operations : null,
|
|
103
|
+
ops: Array.isArray(raw.operations) ? raw.operations.length : null,
|
|
104
|
+
stagedAt: raw.stagedAt ?? null,
|
|
105
|
+
}
|
|
106
|
+
if (raw.kind === "skills") {
|
|
107
|
+
const target = skillTargetOf(L, raw.name)
|
|
108
|
+
const oldText = target.exists ? fs.readFileSync(target.file, "utf8") : ""
|
|
109
|
+
const newText = raw.op === "create" ? raw.text ?? "" : oldText.replace(String(raw.match ?? ""), String(raw.text ?? ""))
|
|
110
|
+
Object.assign(entry, {
|
|
111
|
+
name: raw.name ?? null,
|
|
112
|
+
description: raw.description ?? null,
|
|
113
|
+
oldText,
|
|
114
|
+
newText,
|
|
115
|
+
diff: lineDiff(oldText, newText),
|
|
116
|
+
// 过期预判:人不用等批准才知道提案已经跟不上了
|
|
117
|
+
stale: raw.op === "create" ? target.exists : !target.exists || (raw.baseHash ? target.hash !== raw.baseHash : false),
|
|
118
|
+
})
|
|
119
|
+
}
|
|
120
|
+
return entry
|
|
121
|
+
})
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* 把 `ref` 解析成**唯一**一个待批文件:先整名(含补 `.json`),再子串。
|
|
126
|
+
* 零命中与多命中都**不猜**(与库内子串寻址同一口径:歧义必须由人消解)。
|
|
127
|
+
*/
|
|
128
|
+
export function resolvePendingRef(L, ref) {
|
|
129
|
+
const want = typeof ref === "string" ? ref.trim() : ""
|
|
130
|
+
if (!want) return { ok: false, reason: "usage" }
|
|
131
|
+
const files = listPending(L).map((p) => p.file)
|
|
132
|
+
const exact = files.find((f) => f === want || f === `${want}.json`)
|
|
133
|
+
if (exact) return { ok: true, file: exact }
|
|
134
|
+
const hits = files.filter((f) => f.includes(want))
|
|
135
|
+
if (hits.length === 1) return { ok: true, file: hits[0] }
|
|
136
|
+
if (!hits.length) return { ok: false, reason: "not-found", files }
|
|
137
|
+
return { ok: false, reason: "ambiguous", hits }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** 提案本身必须完整——不完整的提案连"可被批准"都不算,报出来让人处置。 */
|
|
141
|
+
function invalidReason(rec) {
|
|
142
|
+
if (!rec || typeof rec !== "object") return "提案不是对象"
|
|
143
|
+
const kind = rec.kind ?? "memory"
|
|
144
|
+
if (!KINDS.includes(kind)) return `未知的库:${String(rec.kind)}(可用:${KINDS.join(" / ")})`
|
|
145
|
+
if (kind === "skills") {
|
|
146
|
+
if (!SKILL_OPS.includes(rec.op)) return `未知的技能 op:${String(rec.op)}(可用:${SKILL_OPS.join(" / ")})`
|
|
147
|
+
if (typeof rec.name !== "string" || !rec.name.trim()) return "技能提案缺少 name"
|
|
148
|
+
if (typeof rec.text !== "string" || !rec.text.trim()) return `${rec.op} 提案缺少非空 text`
|
|
149
|
+
if (rec.op === "patch" && (typeof rec.match !== "string" || !rec.match.trim())) return "patch 提案缺少 old_string(match)"
|
|
150
|
+
return null
|
|
151
|
+
}
|
|
152
|
+
if (!OPS.includes(rec.op)) return `未知的 op:${String(rec.op)}(可用:${OPS.join(" / ")})`
|
|
153
|
+
if (rec.op === "add" || rec.op === "update") {
|
|
154
|
+
if (typeof rec.text !== "string" || !rec.text.trim()) return `${rec.op} 提案缺少非空 text`
|
|
155
|
+
}
|
|
156
|
+
if (rec.op === "update" || rec.op === "remove") {
|
|
157
|
+
if (typeof rec.match !== "string" || !rec.match.trim()) return `${rec.op} 提案缺少非空 match`
|
|
158
|
+
}
|
|
159
|
+
if (rec.op === "batch") {
|
|
160
|
+
// 整批提案必须带完整的 operations(缺了它连「可被批准」都不算);逐项形态在应用时由
|
|
161
|
+
// `scanBatchOps` 再验一次(同一实现,不在这里另写一套)。
|
|
162
|
+
if (!Array.isArray(rec.operations) || !rec.operations.length) return "batch 提案缺少非空 operations"
|
|
163
|
+
}
|
|
164
|
+
return null
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 技能提案:先判过期(源或所有权变了就不许覆盖),再在快照之后按已批准的技能写路径应用。
|
|
169
|
+
* 过期判据是**内容指纹**:create 要求目标仍不存在;patch 要求目标仍存在、内容仍是当初那份、所有权没变。
|
|
170
|
+
*/
|
|
171
|
+
async function approveSkillPending(L, rec, file, who, pendingPath) {
|
|
172
|
+
const target = skillTargetOf(L, rec.name)
|
|
173
|
+
if (rec.op === "create" && target.exists) {
|
|
174
|
+
return { ok: false, reason: "stale", file, detail: `同名技能在待批期间出现:${path.relative(L.root, target.file)}` }
|
|
175
|
+
}
|
|
176
|
+
if (rec.op === "patch") {
|
|
177
|
+
if (!target.exists) return { ok: false, reason: "stale", file, detail: "目标技能在待批期间消失" }
|
|
178
|
+
if (rec.baseHash && target.hash !== rec.baseHash) return { ok: false, reason: "stale", file, detail: "目标内容在待批期间被改动" }
|
|
179
|
+
if (rec.createdBy && target.createdBy !== rec.createdBy) return { ok: false, reason: "stale", file, detail: `所有权从 ${rec.createdBy} 变成 ${target.createdBy}` }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// 跑前快照(照 curator 归档):批准写入也可回滚。
|
|
183
|
+
const snap = snapshotSkills(L.root, `approve:${rec.name}`)
|
|
184
|
+
if (!snap.ok) return { ok: false, reason: "snapshot-failed", file, detail: snap.error ?? "快照失败" }
|
|
185
|
+
|
|
186
|
+
const r = await runSkillAction({
|
|
187
|
+
root: L.root,
|
|
188
|
+
identity: { origin: "foreground", agent: null },
|
|
189
|
+
action: rec.op,
|
|
190
|
+
name: rec.name,
|
|
191
|
+
description: rec.description ?? undefined,
|
|
192
|
+
content: rec.op === "create" ? rec.text : undefined,
|
|
193
|
+
old_string: rec.op === "patch" ? rec.match : undefined,
|
|
194
|
+
new_string: rec.op === "patch" ? rec.text : undefined,
|
|
195
|
+
approved: { by: who }, // 人已经批准过;只剩执行(宿主 deny 仍压过)
|
|
196
|
+
})
|
|
197
|
+
if (!r.ok) {
|
|
198
|
+
// 应用失败:待批文件保留,人能重试或拒绝。
|
|
199
|
+
return { ok: false, reason: "apply-failed", file, detail: r.error ?? "技能写入失败" }
|
|
200
|
+
}
|
|
201
|
+
fs.rmSync(pendingPath, { force: true })
|
|
202
|
+
appendAudit(L, {
|
|
203
|
+
event: "approve",
|
|
204
|
+
file,
|
|
205
|
+
op: rec.op,
|
|
206
|
+
kind: "skills",
|
|
207
|
+
name: rec.name,
|
|
208
|
+
origin: rec.origin ?? "unknown",
|
|
209
|
+
approvedBy: who,
|
|
210
|
+
snapshot: snap.id ?? null,
|
|
211
|
+
generation: storeHashOf(L.root),
|
|
212
|
+
})
|
|
213
|
+
return {
|
|
214
|
+
ok: true,
|
|
215
|
+
file,
|
|
216
|
+
op: rec.op,
|
|
217
|
+
kind: "skills",
|
|
218
|
+
name: rec.name,
|
|
219
|
+
origin: rec.origin ?? "unknown",
|
|
220
|
+
approvedBy: who,
|
|
221
|
+
snapshot: snap.id ?? null,
|
|
222
|
+
pending: listPending(L).length,
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* 批准一条待批提案。
|
|
228
|
+
*
|
|
229
|
+
* 顺序:**先定位提案**(usage/not-found/ambiguous 是"你指的东西不对"),**再要署名**
|
|
230
|
+
* (没署名就不算批准——与 `review.confirmReview` 的 `HUMAN_APPROVAL_REQUIRED` 同一口径),
|
|
231
|
+
* 最后才在锁内应用。三种失败各自可达,不用一条错遮蔽另一条。
|
|
232
|
+
*
|
|
233
|
+
* @returns {{ok:true, file, op, kind, origin, approvedBy, pending}} 或 {{ok:false, reason, ...}}
|
|
234
|
+
*/
|
|
235
|
+
export async function approvePending(L, ref, { approvedBy = null } = {}) {
|
|
236
|
+
const found = resolvePendingRef(L, ref)
|
|
237
|
+
if (!found.ok) return found
|
|
238
|
+
|
|
239
|
+
const who = typeof approvedBy === "string" ? approvedBy.trim() : ""
|
|
240
|
+
if (!who) return { ok: false, reason: "human-approval-required", file: found.file }
|
|
241
|
+
|
|
242
|
+
const store = createMemoryStore({ root: L.root })
|
|
243
|
+
const pendingPath = path.join(store.paths.pendingDir, found.file)
|
|
244
|
+
|
|
245
|
+
let rec = null
|
|
246
|
+
try {
|
|
247
|
+
rec = JSON.parse(fs.readFileSync(pendingPath, "utf8"))
|
|
248
|
+
} catch (err) {
|
|
249
|
+
return { ok: false, reason: "invalid", file: found.file, detail: `提案文件读不出来:${err?.message ?? err}` }
|
|
250
|
+
}
|
|
251
|
+
const bad = invalidReason(rec)
|
|
252
|
+
if (bad) return { ok: false, reason: "invalid", file: found.file, detail: bad }
|
|
253
|
+
|
|
254
|
+
const kind = rec.kind ?? "memory"
|
|
255
|
+
// 技能提案:按 kind 分派到技能写路径(不是把批准器放宽成任意写入)。
|
|
256
|
+
if (kind === "skills") return await approveSkillPending(L, rec, found.file, who, pendingPath)
|
|
257
|
+
|
|
258
|
+
const locked = withCommitLock(L.lock, ({ fencing, assertStillOwner }) => {
|
|
259
|
+
try {
|
|
260
|
+
if (rec.op === "add") store.writeTrusted({ kind, text: rec.text })
|
|
261
|
+
else if (rec.op === "update") store.updateTrusted({ kind, match: rec.match, text: rec.text })
|
|
262
|
+
// 批量:整批一次性应用(仍走同一条批量核心:整批预扫 + 工作副本 + 终态预算 + 一次原子替换)
|
|
263
|
+
else if (rec.op === "batch") store.batchTrusted({ kind, operations: rec.operations })
|
|
264
|
+
else store.removeTrusted({ kind, match: rec.match })
|
|
265
|
+
} catch (err) {
|
|
266
|
+
// 应用失败(子串歧义/零命中/超限/命中威胁模式):**待批文件保留**,报原因让人处置。
|
|
267
|
+
return { ok: false, reason: "apply-failed", file: found.file, detail: err?.message ?? String(err) }
|
|
268
|
+
}
|
|
269
|
+
if (!assertStillOwner()) return { ok: false, reason: "lost", file: found.file }
|
|
270
|
+
|
|
271
|
+
fs.rmSync(pendingPath, { force: true })
|
|
272
|
+
appendAudit(L, {
|
|
273
|
+
event: "approve",
|
|
274
|
+
file: found.file,
|
|
275
|
+
op: rec.op,
|
|
276
|
+
kind,
|
|
277
|
+
origin: rec.origin ?? "unknown",
|
|
278
|
+
approvedBy: who,
|
|
279
|
+
generation: storeHashOf(L.root),
|
|
280
|
+
fence: fencing,
|
|
281
|
+
})
|
|
282
|
+
return {
|
|
283
|
+
ok: true,
|
|
284
|
+
file: found.file,
|
|
285
|
+
op: rec.op,
|
|
286
|
+
kind,
|
|
287
|
+
origin: rec.origin ?? "unknown",
|
|
288
|
+
approvedBy: who,
|
|
289
|
+
pending: listPending(L).length,
|
|
290
|
+
}
|
|
291
|
+
})
|
|
292
|
+
|
|
293
|
+
if (!locked.ok) return { ok: false, reason: locked.reason, file: found.file }
|
|
294
|
+
return locked.value
|
|
295
|
+
}
|
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
|
+
}
|