opencode-growth 0.1.74 → 0.1.75

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-growth",
3
- "version": "0.1.74",
3
+ "version": "0.1.75",
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",
@@ -16,7 +16,7 @@
16
16
  import fs from "node:fs"
17
17
  import path from "node:path"
18
18
 
19
- import { createHostReview } from "./review-runner.mjs"
19
+ import { createHostReview, REVIEW_READ_ONLY_TOOLS } from "./review-runner.mjs"
20
20
  import { stampCuratorClock, CLOCK_FILE, applyLifecycleTransitions } from "../core/skill-lifecycle.mjs"
21
21
  import { snapshotSkills } from "../core/skill-backup.mjs"
22
22
  import { skillsDir, SKILL_FILE, readExternalDirs, readCreatedBy } from "../core/skills.mjs"
@@ -26,6 +26,14 @@ import { appendAudit } from "../core/audit.mjs"
26
26
  import { layout } from "../core/paths.mjs"
27
27
 
28
28
  /** 照 Hermes `get_interval_hours()` 的默认(curator.interval_hours=7*24)。 */
29
+ /**
30
+ * 整理 pass 的工具面:只读 + **skill_manage**。
31
+ * 提示词要求「所有落盘都走 skill_manage(入账可回滚)」——若沿用复习面的只读白名单,
32
+ * 唯一落盘通道会被关掉,整理只剩报告(2026-11-20 实测:skill_manage=false)。
33
+ * 原生 `skill` 工具不放行:它绕过 OCG 的所有权/审批/审计。
34
+ */
35
+ export const CURATOR_TOOL_ALLOWLIST = Object.freeze([...REVIEW_READ_ONLY_TOOLS, "skill_manage"])
36
+
29
37
  export const DEFAULT_CURATOR_INTERVAL_HOURS = 168
30
38
 
31
39
  const iso = (d) => (d instanceof Date ? d : new Date(d)).toISOString()
@@ -238,6 +246,8 @@ export async function runCuratorPass({ client, sessionId, root = null, skills =
238
246
  const review = createHostReview({
239
247
  client,
240
248
  sessionId,
249
+ kind: "curator",
250
+ toolsAllow: CURATOR_TOOL_ALLOWLIST,
241
251
  ...(agent !== undefined ? { agent } : {}),
242
252
  onChild: (id) => { childId = id; if (signal?.aborted) abortChild(); if (typeof onChild === "function") onChild(id) },
243
253
  onRestriction,
@@ -23,7 +23,6 @@ import { homedir } from "node:os"
23
23
 
24
24
  import { layout } from "../core/paths.mjs"
25
25
  import { resolveStoreRoot } from "../core/home.mjs"
26
- import { resolveProject } from "../core/identity.mjs"
27
26
  import { frozenBlockFor, BLOCK_MARKER } from "../core/snapshot.mjs"
28
27
  import { bumpSkillUse } from "../core/skill-usage.mjs"
29
28
  import { formationGuidanceBlock, SKILL_FORMATION_FENCE } from "../core/skills.mjs"
@@ -72,24 +71,6 @@ export function isExplicitCorrection(text) {
72
71
  /** 家目录取不到就当没有(fail closed,解析会退回「拿不到唯一根」而不是猜一个)。 */
73
72
  const safeHomedir = () => { try { return homedir() || null } catch { return null } }
74
73
 
75
- function appendQueueLine(queuePath, entry) {
76
- fs.mkdirSync(path.dirname(queuePath), { recursive: true })
77
- // Append-only: two corrections are two entries, and a crash mid-append can at worst leave a
78
- // torn last line, which the consumer skips.
79
- fs.appendFileSync(queuePath, JSON.stringify(entry) + "\n")
80
- }
81
-
82
- function resolveProjectId(storeDir, directory) {
83
- try {
84
- const L = layout(storeDir)
85
- fs.mkdirSync(L.state, { recursive: true })
86
- const project = resolveProject(directory, L.projects)
87
- return project?.projectId ?? null
88
- } catch {
89
- return null
90
- }
91
- }
92
-
93
74
  /**
94
75
  * Build the hooks. `store` may be null — that is the "not configured" case, not an error.
95
76
  * Exported separately from the plugin factory so the behaviour above is testable without an
@@ -213,7 +194,7 @@ export function createAdapter({
213
194
  runtime = null,
214
195
  providerToolDefs = null,
215
196
  providerScenario = null,
216
- // ③层能力面(S3):`auto`=自动面(召回注入/写镜像),`tools`=工具面(六件 viking_*)。
197
+ // ③层能力面(S3):`auto`=自动面(召回注入/写镜像),`tools`=工具面(五件可用 viking_*)。
217
198
  // 缺省(null)=既有行为:两面都开。显式关哪一面只关哪一面 —— 让官方插件接管自动面、
218
199
  // 或把工具面交给外部 MCP,而不必连 ①② 与本地技能一起关掉。
219
200
  providerCapabilities = null,
@@ -235,12 +216,6 @@ export function createAdapter({
235
216
  interactive: binding?.interactive ?? null,
236
217
  queuePath: queuePath ?? null,
237
218
  })
238
- const resolvedQueue = queuePath
239
- ?? process.env.OCG_QUEUE
240
- ?? (storeDir ? path.join(storeDir, "state", "learn-queue.jsonl") : null)
241
-
242
- // One API call per session, not one per fire (the hook fires three times per run).
243
- const sessionDirs = new Map()
244
219
  // ③层查询段要「当前 query」,但 `experimental.chat.system.transform` 的 input **只有**
245
220
  // {sessionID, model}(1.18.30 实测;见本文件注入块的实测注记)⇒ 只能由 `chat.message`
246
221
  // 在每轮用户消息提交时供给。逐会话存最近一轮文本(照 H「检索只对当前 query」,:1553)。
@@ -278,23 +253,6 @@ export function createAdapter({
278
253
  onSkillUse: storeDir ? (n) => { bumpSkillUse(storeDir, n) } : null,
279
254
  })
280
255
 
281
- async function directoryForSession(sessionId) {
282
- if (!client?.session?.get || !sessionId) return null
283
- if (sessionDirs.has(sessionId)) return sessionDirs.get(sessionId)
284
- let dir = null
285
- try {
286
- const res = await client.session.get({ path: { id: sessionId } })
287
- const found = res?.data?.directory
288
- if (typeof found === "string" && found.trim()) dir = found
289
- } catch {
290
- // **不回退**(审计 A20):拿不到会话自己的目录时,答案只能是 null。
291
- // 原来这里回退到工厂的 directory —— 而工厂可能属于**另一个**实例/目录,
292
- // 于是 A 项目的记录会被算进 B 会话的账。宁可不知道,也不要猜错。
293
- }
294
- sessionDirs.set(sessionId, dir)
295
- return dir
296
- }
297
-
298
256
  return {
299
257
  /** C① 实例自证:这个适配器绑在哪个 D / 哪个目录 / 值哪来的(多实例并存时可核对)。 */
300
258
  binding: () => bindInfo,
@@ -380,33 +338,9 @@ export function createAdapter({
380
338
 
381
339
  event: async ({ event } = {}) => {
382
340
  if (idleWire) await idleWire({ event })
383
- try {
384
- const text = event?.properties?.text ?? event?.properties?.message?.text ?? null
385
- if (!text || !isExplicitCorrection(text)) return
386
- if (!resolvedQueue) return
387
- const sessionId = event?.properties?.sessionID ?? event?.sessionID ?? null
388
- // The message id, so the eventual candidate can be traced back to the utterance that
389
- // prompted it. Read from every shape OpenCode was seen to use rather than one guess; a
390
- // missing id is recorded as null, never invented (audit A16).
391
- const messageId =
392
- event?.properties?.messageID ??
393
- event?.properties?.message?.id ??
394
- event?.properties?.part?.messageID ??
395
- null
396
- appendQueueLine(resolvedQueue, {
397
- state: "pending",
398
- capturedAt: new Date().toISOString(),
399
- sessionId,
400
- messageId,
401
- projectId: storeDir ? resolveProjectId(storeDir, await directoryForSession(sessionId)) : null,
402
- excerpt: String(text).slice(0, 400),
403
- origin: "opencode-capture",
404
- })
405
- // Deliberately nothing else: no spawn, no candidate, no publish. The scheduler owns
406
- // what happens next, because an in-session child would be killed by the parent's exit.
407
- } catch {
408
- // Same rule as above: capture failing must not break the host.
409
- }
341
+ // 纠正捕获**已退役**(欠账收口 · S1):日常学习由回合后的后台复习承担,
342
+ // 旧队列不再接收新行(不再制造无人消费的 state:"pending")。
343
+ // 历史队列、游标、候选、audit 与旧读取器全部保留;升级不重放、不移动游标。
410
344
  },
411
345
  }
412
346
  }
@@ -448,7 +382,7 @@ export const OcgGrowth = async ({ directory, client, z, tool } = {}) => {
448
382
  }
449
383
  } catch { runtime = null }
450
384
  }
451
- // ③层工具面(六件 viking_*,形制逐字照 H `_TOOL_SCHEMAS`):**只在 provider 在场、
385
+ // ③层工具面(五件可用 viking_*;`viking_add_resource` 未实现不注册):**只在 provider 在场、
452
386
  // 且工具面归我们时**注册 ——provider 缺席/工具面外让时,宿主看到的工具面与从前逐字相同。
453
387
  let providerToolDefs = null
454
388
  if (runtime && providerCapabilities?.tools !== false && z?.string) {
@@ -16,6 +16,7 @@ import path from "node:path"
16
16
  import { pathToFileURL } from "node:url"
17
17
 
18
18
  import { MEMORY_ACTIONS, identityFor, runMemoryAction } from "../core/memory-actions.mjs"
19
+ import { backgroundSubsessionKind } from "../core/subsessions.mjs"
19
20
 
20
21
  /** 宿主的 `tool()` 实测就是恒等函数(`packages/plugin/src/tool.ts`:`return input`)。 */
21
22
  const identityTool = (def) => def
@@ -116,6 +117,7 @@ export function buildMemoryTool({
116
117
  interactive,
117
118
  backgroundAgents,
118
119
  foregroundAgents,
120
+ backgroundKind: backgroundSubsessionKind(ctx?.sessionID),
119
121
  })
120
122
  const r = await runMemoryAction({
121
123
  operations: Array.isArray(args?.operations) && args.operations.length ? args.operations : undefined,
@@ -1,5 +1,6 @@
1
- // S3 · ③层工具面(照 Hermes 六件:viking_search / viking_read / viking_browse /
2
- // viking_remember / viking_forget / viking_add_resource)。
1
+ // S3 · ③层工具面(照 Hermes 的六件 schema;**注册五件**:viking_search / viking_read /
2
+ // viking_browse / viking_remember / viking_forget)。`viking_add_resource` 的资源索引面
3
+ // 未实现(恒返 gap)⇒ 0.1.75 起**不注册**:模型工具表里不放空壳。
3
4
  //
4
5
  // 对齐口径(锁版本 b9d5e4d1):
5
6
  // - **名称/描述/参数逐字照 H** `_TOOL_SCHEMAS`(:390-450 的六个 schema 常量)
@@ -10,8 +11,9 @@
10
11
  // - 批读上限照 H `:70-71`:一次最多 3 个 URI;多 URI 时 full 单条限 2500 字符
11
12
  // - 工具面**只在 provider 在场时**注册(与 H 同:插件没启用就没有这些工具)
12
13
  //
13
- // 我们的缺口**如实返回**(不假装成功):`add_resource` 走临时上传/资源索引,我们的适配器
14
- // 尚未实现该面 ⇒ 返回 `{ok:false, gap}`(沿用 provider `update/remove` 的既有先例)。
14
+ // 缺口如实记录而不是注册空壳:`viking_add_resource` 需要 temp_upload + 资源提交/清理,
15
+ // 是独立的产品功能。astrA 评审的推翻条件:同候选包能经已配置 provider 正常导入受支持来源、
16
+ // 拿回资源回执并查回内容,才按真实支持范围重新注册。
15
17
  import { RECALL_FENCE } from "../provider/runtime.mjs"
16
18
 
17
19
  /** 一次读取的批量上限(照 H `:70`)。 */
@@ -168,36 +170,6 @@ export function buildProviderTools({ provider, z, tool = null } = {}) {
168
170
  },
169
171
  })
170
172
 
171
- tools.viking_add_resource = mk({
172
- description:
173
- "Add a remote URL or local file/directory to the OpenViking knowledge base. Remote resources must be public http(s), git, " +
174
- "or ssh URLs. Local files are uploaded first using OpenViking temp_upload. The system automatically parses, indexes, and " +
175
- "generates summaries.",
176
- parameters: {
177
- url: z.string().describe("Remote URL or local file/directory path to add."),
178
- reason: z.string().optional().describe("Why this resource is relevant (improves search)."),
179
- to: z.string().optional().describe("Optional target viking:// URI for the resource."),
180
- parent: z.string().optional().describe("Optional parent viking:// URI. Cannot be used with to."),
181
- instruction: z.string().optional().describe("Optional processing instruction for semantic extraction."),
182
- wait: z.boolean().optional().describe("Whether to wait for processing to complete."),
183
- timeout: z.number().optional().describe("Timeout in seconds when wait is true."),
184
- },
185
- async execute(input = {}) {
186
- const url = String(input.url ?? "").trim()
187
- if (!url) return { output: JSON.stringify({ ok: false, error: "url is required" }), metadata: { ok: false } }
188
- // 实现缺口(如实返回,不假装成功):我们的适配器只覆盖「记忆条目」面,
189
- // 资源索引面(temp_upload / resources add)未实现 —— 与 update/remove 同款先例。
190
- return {
191
- output: JSON.stringify({
192
- ok: false,
193
- gap: "viking_add_resource 未实现:资源索引面(temp_upload / 资源新增)不在本适配器的能力面内",
194
- url,
195
- }),
196
- metadata: { ok: false, state: "gap" },
197
- }
198
- },
199
- })
200
-
201
173
  return tools
202
174
  }
203
175
 
@@ -229,9 +201,11 @@ async function readUri(provider, uri, level, maxCharsOverride) {
229
201
  }
230
202
 
231
203
  /** 工具名清单(注册侧与测试用;与 H `_OPENVIKING_RECALL_TOOL_NAMES` 区分:只读三件不回灌)。 */
232
- export const PROVIDER_TOOL_NAMES = ["viking_search", "viking_read", "viking_browse", "viking_remember", "viking_forget", "viking_add_resource"]
204
+ export const PROVIDER_TOOL_NAMES = ["viking_search", "viking_read", "viking_browse", "viking_remember", "viking_forget"]
205
+ /** 未实现、因此**不注册**的工具名(缺口写进文档;别把它当能力面)。 */
206
+ export const PROVIDER_HIDDEN_TOOL_NAMES = ["viking_add_resource"]
233
207
  /** 只读三件:结果不许再喂回记忆面(照 H 的 recall-tool 名单)。 */
234
208
  export const PROVIDER_RECALL_TOOL_NAMES = ["viking_search", "viking_read", "viking_browse"]
235
209
 
236
210
  /** 供注册侧使用的字符串 schema 形(z 缺席时的降级说明用,不参与真机注册)。 */
237
- export const PROVIDER_SCHEMA_FALLBACK_NOTE = `${PROVIDER_TOOLS_SOURCE}(六件:${PROVIDER_TOOL_NAMES.join(" / ")};围栏 ${RECALL_FENCE.open})`
211
+ export const PROVIDER_SCHEMA_FALLBACK_NOTE = `${PROVIDER_TOOLS_SOURCE}(五件:${PROVIDER_TOOL_NAMES.join(" / ")};未实现不注册:${PROVIDER_HIDDEN_TOOL_NAMES.join(" / ")};围栏 ${RECALL_FENCE.open})`
@@ -4,6 +4,7 @@
4
4
  // ③适配器故障绝不允许浮到宿主进程里。
5
5
  import fs from "node:fs"
6
6
  import { REVIEW_AGENT, REVIEW_SURFACE_MARK, backgroundReviewBead, createReviewScheduler, createTurnEndHandler, applyReviewOutcome, applySkillReviewActions, parseReviewActions } from "../core/background-review.mjs"
7
+ import { registerBackgroundSubsession } from "../core/subsessions.mjs"
7
8
 
8
9
  // 照抄 Hermes 的复习提示词约束(第一版逐条对齐,不自造)。
9
10
  export const REVIEW_INSTRUCTIONS = Object.freeze([
@@ -71,19 +72,19 @@ export const REVIEW_READ_ONLY_TOOLS = Object.freeze(["read", "grep", "glob", "li
71
72
  // 拿不到宿主工具清单时的兜底:至少把这些已知会改盘/会派活的关掉,并如实标 `enumerated:false`。
72
73
  const KNOWN_MUTATING_TOOLS = Object.freeze(["write", "edit", "patch", "apply_patch", "multiedit", "bash", "shell", "task", "skill", "question", "plan"])
73
74
 
74
- export function toolRestrictionFor(hostToolIds = null) {
75
+ export function toolRestrictionFor(hostToolIds = null, allow = REVIEW_READ_ONLY_TOOLS) {
75
76
  if (Array.isArray(hostToolIds) && hostToolIds.length) {
76
77
  const map = {}
77
78
  for (const id of hostToolIds) {
78
79
  if (typeof id !== "string" || !id) continue
79
- map[id] = REVIEW_READ_ONLY_TOOLS.includes(id) // 白名单外(含没见过的)⇒ false
80
+ map[id] = allow.includes(id) // 白名单外(含没见过的)⇒ false
80
81
  }
81
82
  return { tools: map, enumerated: true, allowed: Object.keys(map).filter((k) => map[k]), denied: Object.keys(map).filter((k) => !map[k]) }
82
83
  }
83
84
  const map = {}
84
85
  for (const id of KNOWN_MUTATING_TOOLS) map[id] = false
85
- for (const id of REVIEW_READ_ONLY_TOOLS) map[id] = true
86
- return { tools: map, enumerated: false, allowed: [...REVIEW_READ_ONLY_TOOLS], denied: [...KNOWN_MUTATING_TOOLS] }
86
+ for (const id of allow) map[id] = true
87
+ return { tools: map, enumerated: false, allowed: [...allow], denied: Object.keys(map).filter((k) => !map[k]) }
87
88
  }
88
89
 
89
90
  // 真宿主 `client.session.messages()` 回来的是**包装对象**(`{data:[…]}`),直连 SDK 时也可能
@@ -113,7 +114,7 @@ async function abortable(fn, signal) {
113
114
  }
114
115
  }
115
116
 
116
- export function createHostReview({ client, sessionId, agent = REVIEW_AGENT, onChild = null, onRestriction = null, pollMs = 60000, prompt = null, signal = null } = {}) {
117
+ export function createHostReview({ client, sessionId, agent = REVIEW_AGENT, kind = "review", onChild = null, onRestriction = null, pollMs = 60000, prompt = null, signal = null, toolsAllow = null } = {}) {
117
118
  const call = (fn) => signal ? abortable(fn, signal) : fn() // 默认路径不增加async跳数
118
119
  return async () => {
119
120
  try {
@@ -130,12 +131,15 @@ export function createHostReview({ client, sessionId, agent = REVIEW_AGENT, onCh
130
131
  const rows = listed?.data ?? listed ?? null
131
132
  if (Array.isArray(rows)) hostToolIds = rows.map((t) => (typeof t === "string" ? t : t?.id)).filter(Boolean)
132
133
  } catch { hostToolIds = null }
133
- const restriction = toolRestrictionFor(hostToolIds)
134
+ const restriction = toolRestrictionFor(hostToolIds, toolsAllow ?? REVIEW_READ_ONLY_TOOLS)
134
135
  if (typeof onRestriction === "function") onRestriction(restriction)
135
136
  // 子会话挂在主会话下 ⇒ 结果留在宿主会话体系里,可被取回
136
137
  const created = await call(() => client.session.create({ body: { parentID: sessionId } }))
137
138
  const childId = created?.data?.id ?? created?.id ?? null
138
139
  if (!childId) return { ok: false, error: "子会话没建起来" }
140
+ // S0:建出即登记。工具面用 `ctx.sessionID` 查这张表,子会话里的写入才按后台口径走
141
+ // (agent 名是 `plan`,与用户自己的 plan 会话同名,不能拿它当身份)。
142
+ registerBackgroundSubsession(childId, { kind, parent: sessionId })
139
143
  // 交出去:取消要靠**这个** id 对宿主发 abort(执行体是唯一持有它的人)
140
144
  if (typeof onChild === "function") onChild(childId)
141
145
  // **不要在事件回调里等同步 prompt**:真机链实测(2026-09-21)——子会话真的产出了内容,
@@ -17,6 +17,7 @@ import { pathToFileURL } from "node:url"
17
17
 
18
18
  import { SKILL_ACTIONS, runSkillAction, skillGateFromHostConfig } from "../core/skill-actions.mjs"
19
19
  import { identityFor } from "../core/memory-actions.mjs"
20
+ import { backgroundSubsessionKind } from "../core/subsessions.mjs"
20
21
  import { readExternalDirs } from "../core/skills.mjs"
21
22
 
22
23
  /** 宿主的 `tool()` 实测就是恒等函数(`packages/plugin/src/tool.ts`:`return input`)。 */
@@ -116,6 +117,8 @@ export function buildSkillTool({
116
117
  interactive,
117
118
  backgroundAgents,
118
119
  foregroundAgents,
120
+ // S0:OCG 派发的子会话身份来自**子会话 id**(curator/复习子会话都以 plan 身份跑)。
121
+ backgroundKind: backgroundSubsessionKind(ctx?.sessionID),
119
122
  })
120
123
  const name = args?.name ?? ""
121
124
  const gate = skillGateFromHostConfig({ hostConfig: hostConfig ?? {}, agent: ctx?.agent ?? null, name })
@@ -24,6 +24,7 @@ import { installAll, resolveInstallPaths, uninstallAll } from "../adapter-openco
24
24
  import { storeHashOf } from "../core/memories.mjs"
25
25
  import { listPending, approvePending } from "../core/approve.mjs"
26
26
  import { doctorSkillsSection, readExternalDirs, skillsDir } from "../core/skills.mjs"
27
+ import { lightUpHistorySearch, historySearchLine } from "../core/session-bootstrap.mjs"
27
28
 
28
29
  const isDir = (p) => {
29
30
  try {
@@ -203,7 +204,7 @@ export function status(opts, ctx) {
203
204
  *
204
205
  * 它**不碰** D 里的记忆与快照:只建目录、写宿主侧的两个文件。
205
206
  */
206
- export function installCmd(opts, ctx) {
207
+ export async function installCmd(opts, ctx) {
207
208
  const { L } = ctx
208
209
  try {
209
210
  const out = installAll({
@@ -212,9 +213,13 @@ export function installCmd(opts, ctx) {
212
213
  queuePath: opts.queue ? String(opts.queue) : null,
213
214
  dryRun: Boolean(opts["dry-run"]),
214
215
  })
216
+ // 装完顺手点亮历史搜索:有宿主默认库就绑一次,没有就如实说「未启用 + 怎么开」。
217
+ // dry-run 不碰任何东西(计划模式一个字节都不写)。
218
+ const sessionIndex = opts["dry-run"] ? null : await lightUpHistorySearch(L.root)
219
+ const line = historySearchLine(sessionIndex)
215
220
  return ok(
216
221
  "install",
217
- opts["dry-run"] ? "dry-run:只是计划,一个字节都没写" : `装好了:${out.shim}`,
222
+ (opts["dry-run"] ? "dry-run:只是计划,一个字节都没写" : `装好了:${out.shim}${line ? `\n${line}` : ""}`),
218
223
  {
219
224
  store: out.store,
220
225
  ...storeProvenance(ctx),
@@ -229,6 +234,7 @@ export function installCmd(opts, ctx) {
229
234
  resident: out.resident,
230
235
  dryRun: Boolean(opts["dry-run"]),
231
236
  plan: out.report,
237
+ sessionIndex,
232
238
  },
233
239
  )
234
240
  } catch (err) {
@@ -404,51 +410,39 @@ export async function memoryApproveCmd(opts, ctx) {
404
410
  // ── learn ────────────────────────────────────────────────────────────
405
411
 
406
412
  /**
407
- * Distil the corrections captured since the last pass into candidates.
413
+ * 旧学习链的执行入口**已退役**(欠账收口 · S1)。
408
414
  *
409
- * This is the link S6 deliberately left out: capturing a correction inside an OpenCode session
410
- * writes a queue line, and something outside the session has to turn it into a candidate. It is
411
- * a scheduling command, so it is idempotent — running it twice distils nothing the second time.
415
+ * 退役依据:日常主链已换成「回合结束后台复习」,两条链会处理同一次纠正;旧链的子会话还带着
416
+ * 可写穿常驻记忆的工具面。**只退执行,不退数据**:队列、游标、候选、audit 与旧读取器全部原样,
417
+ * 历史可追溯,升级不重放积压。
412
418
  *
413
- * It does NOT publish. Learning produces candidates; a person still has to confirm them.
419
+ * · `learn run --dry-run` 仍可看积压(只读,不移动游标)。
420
+ * · 普通 `learn run` 明确报退役并**非零退出**(旧调度器靠退出码判断失败,不能让它误报成功)。
421
+ * · 不再 spawn 学习子会话,也不再写了队列没人消费。
414
422
  */
415
423
  export async function learnRun(opts, ctx) {
416
424
  const { L } = ctx
417
- const limit = opts.limit === undefined ? Infinity : Number(opts.limit)
418
- if (Number.isNaN(limit) || limit < 0) {
419
- return fail("learn.run", "USAGE", "--limit must be a non-negative number")
425
+ if (!opts["dry-run"]) {
426
+ return fail(
427
+ "learn.run",
428
+ "RETIRED",
429
+ "learn run 已退役:旧学习链不再提炼候选(历史队列与游标原样保留)。用 `learn run --dry-run` 查看积压;学习由回合后的后台复习承担。",
430
+ { retired: true, pendingOffset: queueOffset(L) },
431
+ )
420
432
  }
421
433
 
422
434
  const before = queueOffset(L)
423
435
  const res = await consumeQueue(L, {
424
436
  projectDir: opts.project ?? L.root,
425
- limit,
426
- dryRun: Boolean(opts["dry-run"]),
437
+ dryRun: true,
427
438
  })
428
439
 
429
- if (res.dryRun) {
430
- return ok("learn.run", `${res.pending} correction(s) waiting (dry run: nothing was learned)`, {
431
- dryRun: true,
432
- pending: res.pending,
433
- torn: res.torn,
434
- offset: before,
435
- })
436
- }
437
-
438
- const summary = res.processed === 0
439
- ? "nothing new to learn"
440
- : `${res.processed} correction(s): ${res.succeeded} produced candidates, ${res.failed} failed, ${res.skipped} skipped`
441
- return ok("learn.run", summary, {
442
- dryRun: false,
443
- processed: res.processed,
444
- succeeded: res.succeeded,
445
- failed: res.failed,
446
- skipped: res.skipped,
440
+ return ok("learn.run", `${res.pending} correction(s) waiting (dry run: nothing was learned)`, {
441
+ dryRun: true,
442
+ retired: true,
447
443
  pending: res.pending,
448
444
  torn: res.torn,
449
- offsetBefore: before,
450
- offsetAfter: queueOffset(L),
451
- entries: res.entries,
445
+ offset: before,
452
446
  })
453
447
  }
454
448
 
package/src/cli/main.mjs CHANGED
@@ -53,9 +53,11 @@ Usage: oc-grow [--store <dir>] [--json] <command> [args]
53
53
  uninstall [--config <dir>] [--from <manifest>]
54
54
  write the host plugin file + register D/skills/;
55
55
  changes nothing inside D
56
- learn run [--limit <n>] [--dry-run]
57
- distil corrections captured since the last pass into
58
- candidates; never publishes anything
56
+ learn run [--dry-run]
57
+ RETIRED: the old learning chain no longer distils
58
+ candidates (background review owns learning now).
59
+ --dry-run still reports the captured backlog;
60
+ history (queue/offset/candidates/audit) stays as-is
59
61
  journey [--since <dur>] [--kind <k>] [--state <s>] [--reveal 0..1]
60
62
  [--play] [--fps <n>] [--json]
61
63
  what has been learned: a timeline graph (default full
@@ -270,10 +272,19 @@ function render(command, env) {
270
272
  ].join("\n")
271
273
  case "memory.pending": {
272
274
  if (!d.pending?.length) return "no staged proposals"
275
+ const flat = (v) => String(v ?? "").split("\n").map((x) => x.trim()).filter(Boolean).join(" ")
276
+ const oldLine = (p) => {
277
+ if (p.matchState === "ambiguous") return `旧:歧义(${p.matchHits} 条命中「${p.match}」)${p.oldCandidates?.length ? `: ${p.oldCandidates.map(flat).join(" | ")}` : ""}`
278
+ if (p.matchState === "not-found") return `旧:未找到(「${p.match}」零命中,批准会失败)`
279
+ return `旧:${flat(p.oldText)}`
280
+ }
273
281
  return d.pending
274
282
  .map((p) => {
275
- const what = String(p.text ?? p.match ?? "").split("\n")[0]
276
- return ` ${p.file} ${p.op ?? "?"} ${p.kind ?? "?"}${p.label ? ` ${p.label}` : ""} ${what}`
283
+ const head = ` ${p.file} ${p.op ?? "?"} ${p.kind ?? "?"}${p.label ? ` ${p.label}` : ""}`
284
+ // 人读行的判据:update/remove 要能看见**被替换/删除的那一条全文**,不是只有新文或定位子串。
285
+ if (p.op === "update") return `${head}\n ${oldLine(p)}\n 新:${flat(p.text)}`
286
+ if (p.op === "remove") return `${head}\n ${oldLine(p)}`
287
+ return `${head} ${flat(p.text ?? p.match ?? "")}`
277
288
  })
278
289
  .join("\n")
279
290
  }
@@ -103,6 +103,20 @@ export function listPending(L) {
103
103
  ops: Array.isArray(raw.operations) ? raw.operations.length : null,
104
104
  stagedAt: raw.stagedAt ?? null,
105
105
  }
106
+ // S3:update/remove 的「批的是哪一条」必须能回答 —— 把人要看的**旧条目全文**取出来。
107
+ // 零命中/歧义如实标出,不挑一条当旧文(批准时 updateTrusted 仍会因歧义失败)。
108
+ if ((raw.kind ?? "memory") !== "skills" && (entry.op === "update" || entry.op === "remove")) {
109
+ const kind = raw.kind === "user" ? "user" : "memory"
110
+ const needle = String(raw.match ?? "")
111
+ let resident = []
112
+ try { resident = store.read({ kind }) ?? [] } catch { resident = [] }
113
+ const hits = needle ? resident.filter((e) => e.includes(needle)) : []
114
+ entry.matchHits = hits.length
115
+ entry.matchState = hits.length === 0 ? "not-found" : hits.length > 1 ? "ambiguous" : "ok"
116
+ entry.oldText = hits.length === 1 ? hits[0] : null
117
+ // 歧义时把命中的条目也带上:人得看出「该写成哪一条」才能改提案。
118
+ entry.oldCandidates = hits.length > 1 ? hits : null
119
+ }
106
120
  if (raw.kind === "skills") {
107
121
  const target = skillTargetOf(L, raw.name)
108
122
  const oldText = target.exists ? fs.readFileSync(target.file, "utf8") : ""
@@ -21,6 +21,7 @@ import path from "node:path"
21
21
 
22
22
  import { createMemoryStore, findEntryIndex } from "./memories.mjs"
23
23
  import { decideWrite } from "./write-approval.mjs"
24
+ import { BACKGROUND_SUBSESSION_KINDS } from "./subsessions.mjs"
24
25
 
25
26
  /**
26
27
  * 动作是**封闭枚举**。加动作等于改工具契约——加 `approve` 就等于给了自批的口子。
@@ -61,7 +62,13 @@ export function identityFor({
61
62
  interactive = false,
62
63
  backgroundAgents = [],
63
64
  foregroundAgents = [],
65
+ // S0:OCG 自己派发的子会话按**子会话 id** 登记(core/subsessions.mjs),身份从那里来。
66
+ // 优先级最高:它是「谁派发的」的直接证据,比 agent 名与部署方名单都强。
67
+ backgroundKind = null,
64
68
  } = {}) {
69
+ if (typeof backgroundKind === "string" && BACKGROUND_SUBSESSION_KINDS.includes(backgroundKind)) {
70
+ return { origin: "background", agent: `ocg-${backgroundKind}` }
71
+ }
65
72
  if (agent && Array.isArray(backgroundAgents) && backgroundAgents.includes(agent)) {
66
73
  return { origin: "background", agent }
67
74
  }
@@ -0,0 +1,53 @@
1
+ // 首装点亮历史搜索:装完就该能用「查历史会话」,而不是让用户先学会跑一条 CLI。
2
+ // 判据(照 deferred-and-user-risks §6-P2):**已知默认位置存在 ⇒ 绑定一次**;
3
+ // 不存在就**不猜**、保持 not-configured,但把「未启用 + 怎么启用」说出口。
4
+ import fs from "node:fs"
5
+ import os from "node:os"
6
+ import path from "node:path"
7
+
8
+ import { repairHintFor, statusStore, syncStore } from "./session-index.mjs"
9
+
10
+ /**
11
+ * 宿主 opencode.db 的已知默认位置(不扫盘、不嗅探进程):
12
+ * `OCG_SESSION_SOURCE` 显式给了就用它;否则按平台默认数据目录列。
13
+ */
14
+ export function hostDbCandidates({ env = process.env, platform = process.platform, home = os.homedir() } = {}) {
15
+ const out = []
16
+ const explicit = env.OCG_SESSION_SOURCE || env.OPENCODE_DB
17
+ if (explicit) out.push(explicit)
18
+ const xdg = env.XDG_DATA_HOME || path.join(home, ".local", "share")
19
+ out.push(path.join(xdg, "opencode", "opencode.db"))
20
+ if (platform === "darwin") out.push(path.join(home, "Library", "Application Support", "opencode", "opencode.db"))
21
+ if (platform === "win32" && env.APPDATA) out.push(path.join(env.APPDATA, "opencode", "opencode.db"))
22
+ return [...new Set(out.map((p) => path.resolve(String(p))))]
23
+ }
24
+
25
+ /**
26
+ * 装完那一步:已绑定就不动;有默认库就绑一次;没有就如实说「未启用」。
27
+ * `sync` 是测试注入缝(默认走真 syncStore)。
28
+ */
29
+ export async function lightUpHistorySearch(root, { env = process.env, platform = process.platform, home = os.homedir(), sync = syncStore } = {}) {
30
+ const before = statusStore({ root })
31
+ if (before.state === "ok") return { state: "already", parts: before.counts?.parts ?? null, source: before.source ?? null }
32
+ const candidates = hostDbCandidates({ env, platform, home })
33
+ const found = candidates.find((p) => {
34
+ try {
35
+ return fs.statSync(p).isFile()
36
+ } catch {
37
+ return false
38
+ }
39
+ })
40
+ if (!found) return { state: "absent", hint: repairHintFor("not-configured"), candidates }
41
+ const r = await sync({ root, sourcePath: found })
42
+ if (!r?.ok) return { state: "failed", source: found, error: r?.error ?? "绑定失败", candidates }
43
+ return { state: "bound", source: found, parts: r.parts ?? null }
44
+ }
45
+
46
+ /** 人读一行:装完到底能不能查历史。 */
47
+ export function historySearchLine(area) {
48
+ if (!area) return null
49
+ if (area.state === "already") return null
50
+ if (area.state === "bound") return `历史搜索已启用:${area.source}${Number.isFinite(area.parts) ? `(${area.parts} 个片段)` : ""}`
51
+ if (area.state === "failed") return `历史搜索未启用:绑定 ${area.source} 失败(${area.error})`
52
+ return `历史搜索未启用(没找到宿主库):${area.hint}`
53
+ }
@@ -0,0 +1,65 @@
1
+ // OCG 自建子会话的身份登记表(S0)。
2
+ //
3
+ // 为什么要它:复习/整理都是**以宿主身份派发的子会话**,提示词里跑的 agent 是 `plan`
4
+ // (`REVIEW_AGENT`),而 `plan` 同时也是用户自己会开的 agent。只按 agent 名判身份,
5
+ // 要么把后台当未知(闸关时改删直接落盘),要么把所有 `plan` 会话一刀切成后台
6
+ // (用户自己在前台 plan 里的写入会被送进待批)。两种都错。
7
+ //
8
+ // 真源是**宿主给的子会话 id**:`createHostReview` 建出子会话的那一刻就知道它是什么,
9
+ // 登记在这里;工具面执行时用 `ctx.sessionID` 查表。进程内、只记 id 与 kind,
10
+ // 不落盘(子会话本身活在宿主里;进程重启后旧的子会话也不会再被派发新回合)。
11
+ const TTL_MS = 6 * 60 * 60 * 1000
12
+ const MAX_ENTRIES = 500
13
+ const registry = new Map()
14
+
15
+ /** 允许登记的来源种类。加新种类=扩身份契约,先想清楚它该不该有写权限。 */
16
+ export const BACKGROUND_SUBSESSION_KINDS = Object.freeze(["review", "curator", "learn"])
17
+
18
+ /**
19
+ * 登记一个 OCG 派发的后台子会话。
20
+ * @returns {{sessionId:string,kind:string,parent:string|null,at:number}|null} 空 id / 未知 kind ⇒ null(不登记)
21
+ */
22
+ export function registerBackgroundSubsession(sessionId, { kind = "review", parent = null, now = Date.now() } = {}) {
23
+ if (typeof sessionId !== "string" || !sessionId) return null
24
+ if (!BACKGROUND_SUBSESSION_KINDS.includes(kind)) return null
25
+ const at = Number.isFinite(Number(now)) ? Number(now) : Date.now()
26
+ registry.set(sessionId, { kind, parent: parent ?? null, at })
27
+ prune(at)
28
+ return { sessionId, kind, parent: parent ?? null, at }
29
+ }
30
+
31
+ /** 查一个会话是不是登记过的后台子会话;过期/未知 ⇒ null。 */
32
+ export function backgroundSubsessionKind(sessionId, { now = Date.now() } = {}) {
33
+ if (typeof sessionId !== "string" || !sessionId) return null
34
+ const rec = registry.get(sessionId)
35
+ if (!rec) return null
36
+ const t = Number(now)
37
+ if (Number.isFinite(t) && t - rec.at > TTL_MS) {
38
+ registry.delete(sessionId)
39
+ return null
40
+ }
41
+ return rec.kind
42
+ }
43
+
44
+ /** 子会话结束/取消时精确移除;不存在 ⇒ false。 */
45
+ export function forgetBackgroundSubsession(sessionId) {
46
+ if (typeof sessionId !== "string" || !sessionId) return false
47
+ return registry.delete(sessionId)
48
+ }
49
+
50
+ /** 可核对的当前清单(页面/诊断用;不暴露写口)。 */
51
+ export function listBackgroundSubsessions({ now = Date.now() } = {}) {
52
+ const t = Number(now)
53
+ const out = []
54
+ for (const [sessionId, rec] of registry) {
55
+ if (Number.isFinite(t) && t - rec.at > TTL_MS) { registry.delete(sessionId); continue }
56
+ out.push({ sessionId, kind: rec.kind, parent: rec.parent, at: rec.at })
57
+ }
58
+ return out
59
+ }
60
+
61
+ function prune(now) {
62
+ for (const [id, rec] of registry) if (now - rec.at > TTL_MS) registry.delete(id)
63
+ // 上限只防失控:正常情况下在途子会话远少于此,超出按插入顺序淘汰最旧的。
64
+ while (registry.size > MAX_ENTRIES) registry.delete(registry.keys().next().value)
65
+ }
@@ -24,8 +24,21 @@ import { makeScope } from "../core/identity.mjs"
24
24
  export const ORIGIN = "headless-learning"
25
25
 
26
26
  /** Tools the learning session must not hold. `write` is in the list on purpose: denying
27
- * `edit` alone still leaves a session that can rewrite files it was told to read. */
28
- export const DENIED_TOOLS = ["bash", "edit", "write"]
27
+ * `edit` alone still leaves a session that can rewrite files it was told to read.
28
+ *
29
+ * 欠账收口 · S1:过渡期里这条链若仍被调用,工具面必须在**分发层**就只读——
30
+ * memory(常驻记忆)、skill(技能面)、provider 的写三件(remember/forget/add_resource)
31
+ * 一律 deny。只靠提示词说「不要写」不算判据:宿主按 project permission 从这里删 schema。 */
32
+ export const DENIED_TOOLS = [
33
+ "bash",
34
+ "edit",
35
+ "write",
36
+ "memory",
37
+ "skill",
38
+ "viking_remember",
39
+ "viking_forget",
40
+ "viking_add_resource",
41
+ ]
29
42
 
30
43
  export const DEFAULT_OPENCODE_BIN = process.env.OCG_OPENCODE_BIN
31
44
  ?? path.join(os.homedir(), "opt", "oc-v1", "bin", "opencode")
@@ -23,7 +23,7 @@ export const PROVIDERS = Object.freeze({
23
23
 
24
24
  /**
25
25
  * ③层的**能力面**(S3 四场景共存职责):`auto` 管自动面(起点/查询段召回 + 记忆写镜像),
26
- * `tools` 管工具面(六件 `viking_*`)。
26
+ * `tools` 管工具面(五件可用 `viking_*`;`viking_add_resource` 未实现,不注册)。
27
27
  *
28
28
  * 为什么必须在**同一份配置**里各开各的:官方插件接管 ③ 的自动面、或只有外部 MCP 提供工具时,
29
29
  * 「谁负责哪一面」是**用户的显式声明**,不是我们猜出来的(不据包名、不据 MCP 连接推断)。