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.
Files changed (48) hide show
  1. package/README.md +72 -13
  2. package/package.json +1 -1
  3. package/src/adapter-opencode/curator-runner.mjs +257 -0
  4. package/src/adapter-opencode/index.mjs +309 -19
  5. package/src/adapter-opencode/install.mjs +329 -52
  6. package/src/adapter-opencode/journey-tool.mjs +57 -0
  7. package/src/adapter-opencode/memory-tool.mjs +57 -5
  8. package/src/adapter-opencode/provider-tools.mjs +237 -0
  9. package/src/adapter-opencode/review-runner.mjs +180 -37
  10. package/src/adapter-opencode/session-search-tool.mjs +66 -0
  11. package/src/adapter-opencode/skill-tool.mjs +221 -0
  12. package/src/cli/commands.mjs +98 -5
  13. package/src/cli/curator-cmd.mjs +149 -0
  14. package/src/cli/journey-cmd.mjs +61 -0
  15. package/src/cli/journey-view.mjs +174 -0
  16. package/src/cli/main.mjs +173 -26
  17. package/src/cli/memory-cmd.mjs +165 -0
  18. package/src/cli/session-index-cmd.mjs +87 -0
  19. package/src/cli/skill-cmd.mjs +194 -0
  20. package/src/core/approve.mjs +295 -0
  21. package/src/core/audit.mjs +51 -0
  22. package/src/core/background-review.mjs +114 -2
  23. package/src/core/home.mjs +56 -21
  24. package/src/core/journey.mjs +298 -0
  25. package/src/core/lock.mjs +6 -0
  26. package/src/core/memories.mjs +215 -10
  27. package/src/core/memory-actions.mjs +73 -18
  28. package/src/core/paths.mjs +0 -1
  29. package/src/core/session-freshness.mjs +201 -0
  30. package/src/core/session-index.mjs +508 -0
  31. package/src/core/session-query.mjs +161 -0
  32. package/src/core/session-source.mjs +209 -0
  33. package/src/core/session-tool.mjs +189 -0
  34. package/src/core/skill-actions.mjs +391 -0
  35. package/src/core/skill-backup.mjs +95 -0
  36. package/src/core/skill-lifecycle.mjs +277 -0
  37. package/src/core/skill-usage.mjs +119 -0
  38. package/src/core/skills.mjs +30 -3
  39. package/src/core/sqlite-runtime.mjs +35 -0
  40. package/src/core/write-approval.mjs +13 -9
  41. package/src/host/rest-client.mjs +70 -0
  42. package/src/index.mjs +0 -1
  43. package/src/provider/config.mjs +187 -0
  44. package/src/provider/openviking-rest.mjs +742 -0
  45. package/src/provider/runtime.mjs +417 -0
  46. package/src/provider/wiring.mjs +164 -0
  47. package/src/core/budget.mjs +0 -64
  48. package/src/core/retrieve.mjs +0 -127
package/README.md CHANGED
@@ -9,13 +9,48 @@ review and withdrawal.
9
9
  >
10
10
  > ```bash
11
11
  > npm i -g opencode-growth # provides the `oc-grow` command
12
- > oc-grow install # writes the host plugin file, registers D/skills/
13
- > oc-grow --store ~/.opencode-growth status
14
- > oc-grow --store ~/.opencode-growth doctor # exits 5 when a capability is missing
12
+ > oc-grow install --dry-run # print the plan; writes nothing
13
+ > oc-grow install # plugin file, D/skills/, three command files
14
+ > oc-grow status # what is in effect, what is pending
15
+ > oc-grow doctor # exits 5 when a capability is missing
15
16
  > ```
16
17
  >
17
- > `install` and `uninstall` only add or remove the host plugin file. Nothing inside the store is
18
- > touched — your Markdown stays yours. Node >= 24.
18
+ > First install creates the two resident libraries as **empty** files (`MEMORY.md`, `USER.md`) so
19
+ > you can edit them straight away; later runs never write their content and never recreate a file
20
+ > you deleted. `install`/`uninstall` add or remove only what they registered — the host plugin,
21
+ > the `D/skills/` path and the command files. Your Markdown stays yours. Node >= 24, and no
22
+ > external memory service is required.
23
+
24
+ ## First run, end to end
25
+
26
+ 1. `oc-grow install --dry-run` — the plan names what will be created, filled in and kept; the
27
+ isolated tree is byte-identical afterwards.
28
+ 2. `oc-grow install` — then **restart OpenCode**: host configuration is not hot-reloaded.
29
+ 3. `oc-grow status` — the store path in use, resident entry counts, pending proposals.
30
+ 4. In a session, say one thing worth keeping ("always use pnpm here"); the `memory` tool writes it.
31
+ 5. Open a **different** project and ask about it — memory is global, so it answers there too.
32
+ 6. `oc-grow doctor` — if a capability is missing it exits 5 and names it, rather than reporting a
33
+ false green.
34
+
35
+ History search is optional and off until you bind a source: `oc-grow session-index status` says
36
+ which state it is in (`not-configured`, `source-missing`, `unsupported-schema`,
37
+ `source-unavailable`, a normal zero-hit result, or a degraded answer that carries `as_of`), and
38
+ `oc-grow session-index sync` / `rebuild` bind or repair the source. Memory and skills work whether
39
+ or not it is configured.
40
+
41
+ ### Reinstall and receipt recovery
42
+
43
+ A store has one current registered host configuration root. Reinstalling through a physical
44
+ alias keeps the original registration; changing to another root is refused before any write,
45
+ including in dry-run. Uninstall the old registration before installing a new root.
46
+
47
+ `oc-grow uninstall` uses the default receipt. For a saved receipt, explicitly use
48
+ `oc-grow uninstall --from /absolute/path/to/install-manifest.json` with the corresponding store.
49
+ Recovery accepts ownership version 2 with normalized absolute paths and valid ownership fields;
50
+ it removes only that receipt's original targets whose recorded contents still match. Modified
51
+ or unreadable files and all store data are kept. An invalid explicit receipt is refused, never
52
+ silently replaced by the default receipt. See `docs/RUNBOOK-agent.md` for the narrower moved-store
53
+ case and partial-uninstall checks.
19
54
 
20
55
  ## What it does
21
56
 
@@ -29,10 +64,27 @@ host.
29
64
  full.
30
65
  - **Retrieval over history.** Ask about something said in another project and get the original
31
66
  wording back — Chinese or English, down to two characters.
32
- - **Learns after your turns.** A background review runs between turns and turns your
33
- corrections into proposals, which are consumed at the session boundary.
67
+ - **Learns after your turns.** A background review runs between turns. When it finishes it
68
+ reports what it did as one line in the conversation you were already in — what it wrote, what
69
+ it staged, what it skipped — so nothing is learned behind your back. The report is part of the
70
+ transcript; it does not start another model turn and is never re-read as something you said.
34
71
  - **Safe when nobody is watching.** Unattended, additions apply directly while edits and
35
72
  removals are staged for your approval.
73
+ - **Pinned means pinned.** `oc-grow skill pin <name>` keeps a skill out of archiving at every
74
+ entry point — the lifecycle pass, the curator and the skill tool — and each refusal names the
75
+ skill and the reason. Editing a pinned skill still works; `oc-grow skill unpin <name>` makes
76
+ it archivable again.
77
+ - **The limits you set are the limits used.** `memory_limit` and `user_limit` under `memory` in
78
+ the store's `config.json` (defaults 2200 and 1375 characters) are read by every write path —
79
+ the tool, a batch, an approved proposal, the CLI and `oc-grow status`. Lowering a limit never
80
+ truncates or deletes what is already stored; raising it lets a write that previously failed
81
+ go through, without a reinstall.
82
+ - **Approval is optional, and off by default.** Turn on `memory.write_approval` or
83
+ `skills.write_approval` and create/patch stage a proposal instead of writing: the target file
84
+ stays byte-identical until you run `oc-grow memory pending` and
85
+ `oc-grow memory approve <id> --as <who-you-are>`, then read the result back. Rejecting means
86
+ deleting the proposal; nothing applies on its own. Background edits and removals are staged
87
+ whether or not the gate is on.
36
88
  - **Two stores.** Memory and user profile live in separate files (`MEMORY.md`, `USER.md`), each
37
89
  with its own limits.
38
90
  - **Addressable.** Edits and removals address an entry by a substring of its text; an ambiguous
@@ -49,10 +101,16 @@ host.
49
101
  via `session.create`).
50
102
  - It does not need OpenViking or any external memory service.
51
103
  - It does not touch OpenCode's source, and it does not assume Hermes is present.
104
+ - It does not push or export memory to other agents or hosts: the store is plain text, and reading it is the other side's business.
52
105
 
53
- ## Not built yet
106
+ ## What exists, and what stays out of scope
54
107
 
55
- Sharing one memory store with other agents, and a timeline of what has been learned.
108
+ - A journey view of what has been learned exists (`oc-grow journey`, `oc-grow journey list`); it is
109
+ a timeline over recorded events, not a semantic summary of your sessions.
110
+ - Semantic retrieval over a large history is not claimed: history search is keyword-plus-index,
111
+ bound to an optional `session-index` source.
112
+ - No automatic registration in a skill marketplace, and no third-party distribution channel: the
113
+ package is the distribution, and external skill directories are read-only inputs.
56
114
 
57
115
  ## Platforms
58
116
 
@@ -61,10 +119,11 @@ Run and verified on Windows (native), WSL2, macOS (arm64) and Linux.
61
119
  ## Layout
62
120
 
63
121
  ```
64
- src/core/ storage, candidates, writer, audit, lock, budget, threats, retrieval
65
- src/core/snapshot.mjs the frozen per-session block (MEMORY.md / USER.md)
66
- src/core/skills.mjs skill index (always resident) vs. body (on demand)
67
- src/adapter-opencode/ the host plugin: memory tool, review runner, installer
122
+ src/core/ store, memory, skills, review, lifecycle, approval, audit, lock, index
123
+ src/adapter-opencode/ the host plugin: memory, skill and session tools, review + curator
124
+ runners, installer
125
+ src/provider/ optional semantic provider wiring (OpenViking over REST)
126
+ src/host/ the client used to reach a running host
68
127
  src/learn/ headless consume path (corrections -> candidates)
69
128
  src/cli/ `oc-grow` commands and the single JSON envelope
70
129
  test/contracts/ acceptance tests
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-growth",
3
- "version": "0.1.2",
3
+ "version": "0.1.74",
4
4
  "description": "OpenCode growth kit: cross-project memory (memory / capability / preference / fact) with evidence and withdrawal.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -0,0 +1,257 @@
1
+ // S4 curator 整理 pass —— 照 Hermes `agent/curator.py`(UMBRELLA-BUILDING 复习叉):
2
+ // · 提示词蒸馏自 `CURATOR_REVIEW_PROMPT` 的硬规则①–⑤与三法,工具面换成我们的
3
+ // `skill_manage`(create/patch/view/list/archive,archive 必带 absorbed_into);
4
+ // · `CURATOR_DRY_RUN_BANNER` 语义:dry-run 只报告、不动手(产物=报告本身);
5
+ // · 到期判定照 `should_run_now`:interval_hours 默认 7 天,按 `.curator_state.last_run_at`;
6
+ // · 执行体复用 review-runner 的受限子会话(同一条宿主 client 路,不自行调模型 API);
7
+ // · dry-run 三抑制同源:dry-run 不拨时钟(stampCuratorClock 只在 live 后拨)。
8
+ // 可恢复归档前后台都自动直写+跑前快照;不将记忆W8的改/删限制扩张到技能面。
9
+ //
10
+ // S2(自动与手动**默认一致**):
11
+ // · 自动 pass 的**默认=确定性生命周期维护**(`applyLifecycleTransitions`:老化/归档/锚时钟),
12
+ // 与 `oc-grow curator run` 不带宽 `--consolidate` 时**同一个函数、同一套判定** —— 零宿主零模型;
13
+ // · **内容合并(借宿主模型)只有显式启用才做**:CLI 侧是 `--consolidate`,自动侧是 store 配置
14
+ // `skills.curator_consolidate`(缺省/坏配置/非白名单值一律当关,照 write_approval 的 fail-closed 口径)。
15
+ // 对齐参照:Hermes 的定时/自动面只跑 `apply_automatic_transitions`,`--consolidate` 是人显式要的那次。
16
+ import fs from "node:fs"
17
+ import path from "node:path"
18
+
19
+ import { createHostReview } from "./review-runner.mjs"
20
+ import { stampCuratorClock, CLOCK_FILE, applyLifecycleTransitions } from "../core/skill-lifecycle.mjs"
21
+ import { snapshotSkills } from "../core/skill-backup.mjs"
22
+ import { skillsDir, SKILL_FILE, readExternalDirs, readCreatedBy } from "../core/skills.mjs"
23
+ import { readUsage } from "../core/skill-usage.mjs"
24
+ import { normalizeEnabled } from "../core/write-approval.mjs"
25
+ import { appendAudit } from "../core/audit.mjs"
26
+ import { layout } from "../core/paths.mjs"
27
+
28
+ /** 照 Hermes `get_interval_hours()` 的默认(curator.interval_hours=7*24)。 */
29
+ export const DEFAULT_CURATOR_INTERVAL_HOURS = 168
30
+
31
+ const iso = (d) => (d instanceof Date ? d : new Date(d)).toISOString()
32
+
33
+ export const CURATOR_DRY_RUN_BANNER = [
34
+ "═══════════════════════════════════════════════════════════════",
35
+ "DRY-RUN — 只报告,不动手。不要对技能库做任何写入。",
36
+ "═══════════════════════════════════════════════════════════════",
37
+ "",
38
+ "这是预览跑:照下面所有指令**产出报告**,但把动作写成「将会做」而非「已做」。",
39
+ "报告原样包含你会在 live 跑产出的人读总结与结构化块,供人决定要不要放 live。",
40
+ "",
41
+ ].join("\n")
42
+
43
+ /**
44
+ * 整理提示词(UMBRELLA-BUILDING):把散技能蒸馏进类级伞技能。
45
+ * 硬规则照 Hermes ①–⑤;工具面换成我们的 skill_manage(archive 必带 absorbed_into)。
46
+ */
47
+ export function buildCuratorPrompt({ skills = [], dryRun = false } = {}) {
48
+ const list = skills.length
49
+ ? skills.map((s) => `- ${s.name}${s.description ? ` —— ${s.description}` : ""}`).join("\n")
50
+ : "(候选清单为空——若你仍能从 skill list 看到技能,以 list 为准)"
51
+ const body = [
52
+ "你是技能库的后台 CURATOR,跑的是 UMBRELLA-BUILDING 合并整理(不是找茬、不是查重器)。",
53
+ "",
54
+ "目标形态:**类级指令与经验库**。一堆一人一事的窄技能是库的失败;一个带小节的伞技能,",
55
+ "在可发现性上强过五个窄邻居(模型按 description 匹配,触发句前 57 字符是路由信号)。",
56
+ "合并=蒸馏:被吸收的内容变成祈使句规则(一 clause 的 why),同一教训出现两次就并成一条,",
57
+ "事故叙事、日期、工单号、引语一律丢掉——规则要能独立站住。",
58
+ "",
59
+ "硬规则(不许违反):",
60
+ "1. 只动本地托管技能(agent-created/adopt 后)。外部来源(skills.external_dirs)只读,一律不碰;user-owned 不动——需要动它就先让人 `skill adopt` 移交。",
61
+ "2. **只归档不删除**。归档(skills/.archive/)是最大破坏动作;归档件可恢复,删除不存在。",
62
+ " 归档必须带 absorbed_into=<伞技能名> 点名合并去向(伞须已存在);没有吸收去向的纯裁剪不是本 pass 的活。",
63
+ "3. pinned 的技能整个跳过。use=0 不是保留理由也不是裁剪理由——按**内容**判断重叠,别拿使用计数说事。",
64
+ "4. 「每个技能触发器不同」不是拒绝合并的理由。判据是:「人会写成 N 个技能,还是一个技能带 N 个小节?」",
65
+ " 是后者就并。名字太窄(带 PR 号/代号/具体报错串/一次会话产物)的技能一律属于某个伞的小节或 support 文件。",
66
+ "5. 三法按簇选用:(a) 并进既有伞(给伞 patch 出每个兄弟的独特小节,然后归档兄弟);",
67
+ " (b) 新建伞(没有足够宽的成员时 create 一个类级技能再吸收);",
68
+ " (c) 降级进伞的 references/<主题>.md、templates/、scripts/(按主题命名、合并进已有主题文件,",
69
+ " 不许逐字照搬 <兄弟名>.md),随后归档原技能。打包件整体处理:有 support 文件或相对链接的技能",
70
+ " 要么整个搬进伞的规范目录并改写指引,要么原样整包归档,绝不留指向旧目录的死链。",
71
+ "",
72
+ "工具面:skill_manage(create/patch/view/list/archive)。读前写:patch/archive 前先 view 同一目标。",
73
+ "archive 必带 absorbed_into。你没有终端,所有落盘都走 skill_manage(入账可回滚)。",
74
+ "",
75
+ "候选清单(本地托管技能):",
76
+ list,
77
+ "",
78
+ "产出:人读总结 + 一段结构化 YAML 块(consolidated/archived/kept 各列名与去向),供后续工具分辨合并与裁剪。",
79
+ ].join("\n")
80
+ return (dryRun ? CURATOR_DRY_RUN_BANNER : "") + body
81
+ }
82
+
83
+ /** 到期判定(照 Hermes `should_run_now`):按 .curator_state.last_run_at + interval。 */
84
+ export function curatorDue({ root, now = new Date(), intervalHours = null } = {}) {
85
+ let interval = Number(intervalHours)
86
+ if (!Number.isFinite(interval) || interval <= 0) {
87
+ try {
88
+ const cfg = JSON.parse(fs.readFileSync(path.join(root, "config.json"), "utf8")) ?? {}
89
+ interval = Number(cfg?.skills?.curator_interval_hours)
90
+ } catch { /* 无配置 */ }
91
+ }
92
+ if (!Number.isFinite(interval) || interval <= 0) interval = DEFAULT_CURATOR_INTERVAL_HOURS
93
+ let last = null
94
+ try {
95
+ last = JSON.parse(fs.readFileSync(path.join(skillsDir(root), CLOCK_FILE), "utf8"))?.last_run_at ?? null
96
+ } catch { /* 无时钟=首跑 */ }
97
+ const lastMs = typeof last === "string" ? Date.parse(last) : NaN
98
+ const nowMs = now instanceof Date ? now.getTime() : new Date(now).getTime()
99
+ const due = !Number.isFinite(lastMs) || nowMs - lastMs >= interval * 3600_000
100
+ return { due, lastRunAt: last, intervalHours: interval }
101
+ }
102
+
103
+ /**
104
+ * 候选清单=**已预过滤**的本地托管技能(照 Hermes:candidate list already filtered to local
105
+ * curator-managed only):created_by=agent(adopt 后也算)、pinned 跳过、外部不进清单。
106
+ */
107
+ export function listCuratorCandidates(root) {
108
+ const all = readUsage(root)
109
+ const externals = readExternalDirs(root) ?? []
110
+ let entries = []
111
+ try {
112
+ entries = fs.readdirSync(skillsDir(root))
113
+ } catch {
114
+ return []
115
+ }
116
+ const inExternal = (name) =>
117
+ externals.some((dir) => fs.existsSync(path.join(dir, name, SKILL_FILE)))
118
+ const out = []
119
+ for (const d of entries) {
120
+ if (d.startsWith(".")) continue
121
+ if (!fs.existsSync(path.join(skillsDir(root), d, SKILL_FILE))) continue
122
+ const rec = all[d] ?? {}
123
+ if (readCreatedBy(path.join(skillsDir(root), d, SKILL_FILE)) !== "agent") continue // frontmatter是托管授权真源;遥测不能授予或撤回
124
+ if (rec.pinned) continue // pinned 全旁路
125
+ if (inExternal(d)) continue // 外部同名不碰
126
+ const raw = fs.readFileSync(path.join(skillsDir(root), d, SKILL_FILE), "utf8")
127
+ const dm = /^description:\s*(.+)$/m.exec(raw)
128
+ out.push({ name: d, description: dm ? dm[1].trim() : null })
129
+ }
130
+ return out.sort((a, b) => a.name.localeCompare(b.name))
131
+ }
132
+
133
+ /**
134
+ * 给复习链的 onIdle 包一层 curator 触发(照 Hermes 的调度面:到点就派发整理 pass)。
135
+ * dispatch 不 await(与复习同款);归档是自动直写、可恢复、跑前快照。
136
+ *
137
+ * **默认走机械维护**(S2):到点跑 `applyLifecycleTransitions`(origin仅作审计来源),
138
+ * 只有显式开启 `skills.curator_consolidate` 才派发模型 pass。`onDispatch` 如实报 mode:
139
+ * `mechanical`(默认)/ `model`(显式开启)/ `none`(不 due)。
140
+ */
141
+ /**
142
+ * 自动面是否允许借宿主模型做**内容合并**:store 配置 `skills.curator_consolidate`。
143
+ * fail-closed:文件读不到 / 坏 JSON / 值不在白名单(含数值 1)一律**当关** —— 与写入闸门同一口径
144
+ * (`core/write-approval.mjs::normalizeEnabled`,"一个判定真源")。
145
+ */
146
+ export function curatorConsolidateEnabled(root) {
147
+ if (!root) return false
148
+ try {
149
+ const cfg = JSON.parse(fs.readFileSync(path.join(root, "config.json"), "utf8"))
150
+ return normalizeEnabled(cfg?.skills?.curator_consolidate) === true
151
+ } catch {
152
+ return false
153
+ }
154
+ }
155
+
156
+ export function wrapCuratorTrigger({ pipeline, client, root, now = () => new Date(), onDispatch = null } = {}) {
157
+ const base = pipeline ?? {}
158
+ const origIdle = typeof base.onIdle === "function" ? base.onIdle.bind(base) : null
159
+ const origUser = typeof base.onUserTurnStart === "function" ? base.onUserTurnStart.bind(base) : null
160
+ let active = null // curator是库级维护,同一插件实例只允许一份在途(不按session重复叉跑)
161
+ const audit = (data) => {
162
+ try { appendAudit(layout(root), { event: "skill-curator", ...data }) } catch { /* 审计故障不炸宿主 */ }
163
+ }
164
+ return {
165
+ ...base,
166
+ onIdle: async (sessionId) => {
167
+ const r = origIdle ? await origIdle(sessionId) : undefined
168
+ try {
169
+ if (active) {
170
+ if (typeof onDispatch === "function") onDispatch({ mode: "none", reason: "running" })
171
+ return r
172
+ }
173
+ const due = curatorDue({ root, now: now() })
174
+ if (!due.due || !root) {
175
+ if (typeof onDispatch === "function") onDispatch({ due, skills: null, mode: "none" })
176
+ return r
177
+ }
178
+ if (curatorConsolidateEnabled(root) && client) {
179
+ const skills = listCuratorCandidates(root)
180
+ const started = now()
181
+ const run = { sessionId, controller: new AbortController(), dispatchedAt: new Date(started).getTime(), pending: null }
182
+ active = run
183
+ const p = runCuratorPass({ client, sessionId, root, skills, now: started, signal: run.controller.signal })
184
+ .catch((e) => ({ ok: false, error: String(e?.message ?? e) }))
185
+ .then((out) => { audit({ mode: "model", sessionId, ok: out.ok, cancelled: Boolean(out.cancelled), error: out.error ?? null, childId: out.childId ?? null }); return out })
186
+ .finally(() => { if (active === run) active = null })
187
+ run.pending = p
188
+ if (typeof onDispatch === "function") onDispatch({ due, skills, mode: "model", pending: p })
189
+ return r
190
+ }
191
+ // 默认:确定性生命周期维护(零宿主零模型),与 `curator run`(无 --consolidate)同一个函数
192
+ const mechanical = applyLifecycleTransitions({ root, now: now(), origin: "background" })
193
+ audit({ mode: "mechanical", sessionId, ok: mechanical.ok, archived: mechanical.archived,
194
+ // 无人值守通道也要留下「哪些 pinned 被跳过」——否则插件静默运行时这个原因不可见(复核观察 5)
195
+ skipped_pinned: (mechanical.skipped_pinned ?? []).map((x) => x.name),
196
+ error: mechanical.error ?? null })
197
+ if (typeof onDispatch === "function") onDispatch({ due, skills: null, mode: "mechanical", mechanical })
198
+ } catch { /* 触发失败不影响复习链 */ }
199
+ return r
200
+ },
201
+ onUserTurnStart: async (sessionId, info = {}) => {
202
+ const baseTask = origUser ? origUser(sessionId, info) : Promise.resolve({ cancelled: false, reason: "idle" })
203
+ const run = active
204
+ const hasEvidence = Boolean(info.messageId) || typeof info.createdAt === "number"
205
+ if (!run || run.sessionId !== sessionId || !hasEvidence ||
206
+ (typeof info.createdAt === "number" && info.createdAt <= run.dispatchedAt)) return baseTask
207
+ run.controller.abort()
208
+ let timer
209
+ let settled
210
+ try {
211
+ settled = await Promise.race([run.pending.then(() => true, () => true), new Promise((r) => { timer = setTimeout(() => r(false), 2000) })])
212
+ } finally { clearTimeout(timer) }
213
+ return { ...(await baseTask), curator: { cancelled: true, settled } }
214
+ },
215
+ }
216
+ }
217
+
218
+ /**
219
+ * 跑一次整理 pass:复用 review-runner 的受限子会话(宿主 client 发一次请求、轮询取回)。
220
+ * dry-run ⇒ 提示词带横幅、**不拨时钟、零快照**;live **跑前先快照**(照 Hermes `curator_backup`
221
+ * every run,2026-09-25 修正:归档自动直写,快照是兑底)再跑、跑完拨 `.curator_state.last_run_at`。
222
+ */
223
+ export async function runCuratorPass({ client, sessionId, root = null, skills = [], dryRun = false, now = new Date(), agent = undefined, onChild = null, onRestriction = null, pollMs = 60000, signal = null } = {}) {
224
+ if (signal?.aborted) return { ok: false, cancelled: true, error: "curator已取消" }
225
+ const prompt = buildCuratorPrompt({ skills, dryRun })
226
+ if (root && !dryRun) {
227
+ const snapshot = snapshotSkills(root, "curator")
228
+ if (!snapshot.ok) return { ok: false, error: `整理跑前快照失败:${snapshot.error ?? "未知原因"}` }
229
+ }
230
+ let childId = null
231
+ let abortSent = false
232
+ const abortChild = () => {
233
+ if (!childId || abortSent || !client?.session?.abort) return
234
+ abortSent = true
235
+ try { Promise.resolve(client.session.abort({ path: { id: childId } })).catch(() => {}) } catch { /* 不炸前台 */ }
236
+ }
237
+ signal?.addEventListener("abort", abortChild, { once: true })
238
+ const review = createHostReview({
239
+ client,
240
+ sessionId,
241
+ ...(agent !== undefined ? { agent } : {}),
242
+ onChild: (id) => { childId = id; if (signal?.aborted) abortChild(); if (typeof onChild === "function") onChild(id) },
243
+ onRestriction,
244
+ pollMs,
245
+ prompt,
246
+ signal,
247
+ })
248
+ let r
249
+ try { r = await review() } finally { signal?.removeEventListener("abort", abortChild) }
250
+ if (signal?.aborted) return { ...r, ok: false, cancelled: true, childId, error: "curator已取消" }
251
+ const hasReport = (r?.messages ?? []).some((m) =>
252
+ (m?.role ?? m?.info?.role) === "assistant" &&
253
+ (String(m?.text ?? "").trim() || (m?.parts ?? []).some((p) => p?.type === "text" && String(p.text ?? "").trim())))
254
+ if (r?.ok && !hasReport) return { ...r, ok: false, error: "整理pass未取回报告(超时或空结果)" }
255
+ if (r?.ok && root && !dryRun) stampCuratorClock(root, { now, origin: "curator" })
256
+ return r
257
+ }