opencode-growth 0.1.59 → 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.
@@ -3,7 +3,8 @@
3
3
  // 三条纪律:①请求由宿主进程发起("看起来是 opencode 调用的")②工具受限(plan 只读)
4
4
  // ③适配器故障绝不允许浮到宿主进程里。
5
5
  import fs from "node:fs"
6
- import { REVIEW_AGENT, createReviewScheduler, createTurnEndHandler, applyReviewOutcome, applySkillReviewActions, parseReviewActions } from "../core/background-review.mjs"
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([
@@ -21,10 +22,27 @@ export const REVIEW_INSTRUCTIONS = Object.freeze([
21
22
  "新增可以直接写;改动或删除既有条目一律只提案,等人处置。",
22
23
  ])
23
24
 
24
- const textOf = (m) => (typeof m === "string" ? m : m?.text ?? m?.content ?? JSON.stringify(m))
25
+ // 后台复习吃的是「整份回合会话」,而浮出的通知也是 user 消息(ignored + metadata.ocg)。
26
+ // 主模型上下文与 ③层召回都过滤了它,这里也必须过滤:否则 OCG 会把自己的机器通知当成用户说的话,
27
+ // 再蒸馏进记忆(这正是「不被 OCG 当用户输入」要防的那条路径)。
28
+ const isSurfacePart = (part) => part?.ignored === true || part?.metadata?.ocg === REVIEW_SURFACE_MARK
29
+
30
+ const textOf = (m) => {
31
+ if (typeof m === "string") return m
32
+ const parts = Array.isArray(m?.parts) ? m.parts : null
33
+ if (parts) {
34
+ return parts
35
+ .filter((part) => part && part.type === "text" && typeof part.text === "string" && !isSurfacePart(part))
36
+ .map((part) => part.text)
37
+ .join("\n")
38
+ .trim()
39
+ }
40
+ return m?.text ?? m?.content ?? JSON.stringify(m)
41
+ }
25
42
 
26
43
  export function buildReviewPrompt(history = []) {
27
- const lines = history.map((m) => "- " + textOf(m))
44
+ // 过滤后为空的消息(例如整条都是通知)不占一行:`- ` 空行会让模型以为用户说了句空话。
45
+ const lines = history.map((m) => "- " + textOf(m)).filter((line) => line.trim() !== "-")
28
46
  return [
29
47
  "【本回合会话(整份)】",
30
48
  ...lines,
@@ -54,19 +72,19 @@ export const REVIEW_READ_ONLY_TOOLS = Object.freeze(["read", "grep", "glob", "li
54
72
  // 拿不到宿主工具清单时的兜底:至少把这些已知会改盘/会派活的关掉,并如实标 `enumerated:false`。
55
73
  const KNOWN_MUTATING_TOOLS = Object.freeze(["write", "edit", "patch", "apply_patch", "multiedit", "bash", "shell", "task", "skill", "question", "plan"])
56
74
 
57
- export function toolRestrictionFor(hostToolIds = null) {
75
+ export function toolRestrictionFor(hostToolIds = null, allow = REVIEW_READ_ONLY_TOOLS) {
58
76
  if (Array.isArray(hostToolIds) && hostToolIds.length) {
59
77
  const map = {}
60
78
  for (const id of hostToolIds) {
61
79
  if (typeof id !== "string" || !id) continue
62
- map[id] = REVIEW_READ_ONLY_TOOLS.includes(id) // 白名单外(含没见过的)⇒ false
80
+ map[id] = allow.includes(id) // 白名单外(含没见过的)⇒ false
63
81
  }
64
82
  return { tools: map, enumerated: true, allowed: Object.keys(map).filter((k) => map[k]), denied: Object.keys(map).filter((k) => !map[k]) }
65
83
  }
66
84
  const map = {}
67
85
  for (const id of KNOWN_MUTATING_TOOLS) map[id] = false
68
- for (const id of REVIEW_READ_ONLY_TOOLS) map[id] = true
69
- 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]) }
70
88
  }
71
89
 
72
90
  // 真宿主 `client.session.messages()` 回来的是**包装对象**(`{data:[…]}`),直连 SDK 时也可能
@@ -96,7 +114,7 @@ async function abortable(fn, signal) {
96
114
  }
97
115
  }
98
116
 
99
- 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 } = {}) {
100
118
  const call = (fn) => signal ? abortable(fn, signal) : fn() // 默认路径不增加async跳数
101
119
  return async () => {
102
120
  try {
@@ -113,12 +131,15 @@ export function createHostReview({ client, sessionId, agent = REVIEW_AGENT, onCh
113
131
  const rows = listed?.data ?? listed ?? null
114
132
  if (Array.isArray(rows)) hostToolIds = rows.map((t) => (typeof t === "string" ? t : t?.id)).filter(Boolean)
115
133
  } catch { hostToolIds = null }
116
- const restriction = toolRestrictionFor(hostToolIds)
134
+ const restriction = toolRestrictionFor(hostToolIds, toolsAllow ?? REVIEW_READ_ONLY_TOOLS)
117
135
  if (typeof onRestriction === "function") onRestriction(restriction)
118
136
  // 子会话挂在主会话下 ⇒ 结果留在宿主会话体系里,可被取回
119
137
  const created = await call(() => client.session.create({ body: { parentID: sessionId } }))
120
138
  const childId = created?.data?.id ?? created?.id ?? null
121
139
  if (!childId) return { ok: false, error: "子会话没建起来" }
140
+ // S0:建出即登记。工具面用 `ctx.sessionID` 查这张表,子会话里的写入才按后台口径走
141
+ // (agent 名是 `plan`,与用户自己的 plan 会话同名,不能拿它当身份)。
142
+ registerBackgroundSubsession(childId, { kind, parent: sessionId })
122
143
  // 交出去:取消要靠**这个** id 对宿主发 abort(执行体是唯一持有它的人)
123
144
  if (typeof onChild === "function") onChild(childId)
124
145
  // **不要在事件回调里等同步 prompt**:真机链实测(2026-09-21)——子会话真的产出了内容,
@@ -328,10 +349,24 @@ export function createReviewPipeline({ client, thresholds, store = null, root =
328
349
  surface: landed.surface ?? null,
329
350
  skillSurface: skillLanded.surface ?? null,
330
351
  }
331
- if (typeof audit === "function") { try { audit(decision) } catch { /* 记账失败不许把宿主弄崩 */ } }
332
352
  // 提案必须浮出:有人看得见的那一行,发回宿主会话(memory 与技能两条车道的浮出行合并)
333
- const surfaceText = [landed.surface, skillLanded.surface].filter(Boolean).join(";") || null
334
- const surfaced = surfaceText ? await surfaceToHost({ client, sessionId, line: surfaceText }) : { posted: false }
353
+ // 通知行=这次复习**做了什么**的摘要(直接写入也要报),不再是「只有提案才说话」。
354
+ const surfaceText = backgroundReviewBead({
355
+ memoryWritten: landed.written ?? 0,
356
+ memoryStaged: landed.staged ?? 0,
357
+ skillWritten: skillLanded.written ?? 0,
358
+ skillStaged: skillLanded.staged ?? 0,
359
+ refused: (skillLanded.refused ?? []).length,
360
+ ignored: (landed.ignored ?? []).length + (skillLanded.ignored ?? []).length,
361
+ })
362
+ const surfaced = surfaceText
363
+ ? await surfaceToHost({ client, sessionId, line: surfaceText, childId: out.childId ?? null })
364
+ : { posted: false, reason: "nothing-to-surface" }
365
+ // 投没投出去是两件事:决策条目里如实记(失败=未投递,不许写成功)
366
+ decision.surfacePosted = surfaced.posted === true
367
+ decision.surfaceReason = surfaced.reason ?? null
368
+ decision.surfaceChannel = surfaced.channel ?? null
369
+ if (typeof audit === "function") { try { audit(decision) } catch { /* 记账失败不许把宿主弄崩 */ } }
335
370
  return { ...out, actions: actions.length, ...landed, skillLanded, surfaced, decision }
336
371
  },
337
372
  })
@@ -400,24 +435,82 @@ export function createReviewPipeline({ client, thresholds, store = null, root =
400
435
  }
401
436
  }
402
437
 
403
- // 提案浮出:把那一行发到**宿主会话**里,人一眼看得见(后台做事不能悄没声)。
404
- // 发不出去就吞掉并如实标记——适配器不许把宿主的会话弄崩。
405
- // A141 更正(照 Hermes background_review.py:640-660 `_action_lines`):浮出**不许**用
406
- // `session.prompt` —— 那条路等价 POST /session/:id/message,会**真驱动一次模型回合**(人也得多掏一次钱)。
407
- // 默认走不驱动模型的那条面:待批文件本身(`D/pending/` + 命令面 `/ocg-pending`)已经把提案摆到人眼前;
408
- // 这里只把那一行**返回给调用方**(宿主日志/进度页可见),并把降级如实标出来。
409
- // 显式要求 `mode: "prompt"` 时才走会驱动模型的那条(留给将来找到非驱动通道前的兜底)。
410
- export async function surfaceToHost({ client, sessionId, line, mode = "pending-surface" } = {}) {
438
+ // 提案浮出(S1,通道已按 1.18.30 源码 + 真 TUI 探针定案):
439
+ // noReply:true ⇒ prompt.ts 直接 return,不进 agent loop(不驱动模型回合、不多花钱)
440
+ // part.ignored ⇒ message-v2 / compaction 都剔除(不进模型上下文与压缩摘要),但 TUI 仍渲染
441
+ // **不设 synthetic** ⇒ TUI 的 UserMessage 只拼 `type==="text" && !synthetic` 的 part,设了整段渲染为空
442
+ // part.metadata.ocg ⇒ 机器判定用,不靠文本前缀猜
443
+ // 只投给**已经有真实用户回合**的会话:标题生成也把「parts 不全是 synthetic 的用户消息」当真实用户消息,
444
+ // 新会话 + 默认标题 + 只收通知这条路会额外发一次模型请求(实测:计数 stub 0 次 vs 真实提示词 1 次)。
445
+ // 发不出去要如实记「未投递」,不许写成功;宿主调用失败一律吞掉(适配器不许弄崩宿主)。
446
+ const SURFACE_DEDUPE_MS = 10 * 60 * 1000
447
+ const surfaceSeen = new Map()
448
+
449
+ const lineDigest = (s) => {
450
+ let h = 2166136261
451
+ for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0 }
452
+ return h.toString(16)
453
+ }
454
+ const seenRecently = (key, nowMs = Date.now()) => {
455
+ const ts = surfaceSeen.get(key)
456
+ return typeof ts === "number" && nowMs - ts <= SURFACE_DEDUPE_MS
457
+ }
458
+ const rememberSurface = (key, nowMs = Date.now()) => {
459
+ surfaceSeen.set(key, nowMs)
460
+ for (const [k, ts] of surfaceSeen) if (nowMs - ts > SURFACE_DEDUPE_MS) surfaceSeen.delete(k)
461
+ while (surfaceSeen.size > 200) surfaceSeen.delete(surfaceSeen.keys().next().value)
462
+ }
463
+
464
+ const isRealUserTurn = (m) => {
465
+ const role = m?.info?.role ?? m?.role
466
+ if (role !== "user") return false
467
+ const parts = Array.isArray(m?.parts) ? m.parts : []
468
+ if (parts.length === 0) return typeof m?.text === "string" && m.text.trim().length > 0
469
+ return parts.some((p) => p && p.type === "text" && typeof p.text === "string" && p.text.trim() && !p.ignored && !p.synthetic && p?.metadata?.ocg !== REVIEW_SURFACE_MARK)
470
+ }
471
+
472
+ async function sessionHasRealTurn(client, sessionId) {
473
+ const res = await client.session.messages({ path: { id: sessionId } })
474
+ const list = Array.isArray(res) ? res : Array.isArray(res?.data) ? res.data : null
475
+ if (!list) return false
476
+ return list.some(isRealUserTurn)
477
+ }
478
+
479
+ export async function surfaceToHost({ client, sessionId, line, childId = null, mode = "notify" } = {}) {
411
480
  if (!line) return { posted: false, reason: "nothing-to-surface" }
412
- if (mode !== "prompt") {
413
- return { posted: false, reason: "non-driving-surface", degraded: false, line }
414
- }
481
+ if (mode === "pending-surface") return { posted: false, reason: "non-driving-surface", degraded: false, line }
415
482
  if (!sessionId) return { posted: false, reason: "no-session" }
416
483
  if (!client?.session?.prompt) return { posted: false, reason: "no-channel" }
484
+ if (mode === "prompt") {
485
+ // 兼容面:显式要求走会驱动模型的那条路(如实标注,调用方自己决定要不要)
486
+ try {
487
+ await client.session.prompt({ path: { id: sessionId }, body: { parts: [{ type: "text", text: String(line) }] } })
488
+ return { posted: true, drivesModelTurn: true, channel: "prompt" }
489
+ } catch {
490
+ return { posted: false, reason: "post-failed", channel: "prompt" }
491
+ }
492
+ }
493
+ const key = `${sessionId}|${childId ?? "-"}|${lineDigest(String(line))}`
494
+ if (seenRecently(key)) return { posted: false, reason: "duplicate", channel: "notify", line: String(line) }
495
+ if (typeof client.session.messages !== "function") return { posted: false, reason: "no-session-state", channel: "notify", line: String(line) }
496
+ let real = false
497
+ try {
498
+ real = await sessionHasRealTurn(client, sessionId)
499
+ } catch {
500
+ return { posted: false, reason: "session-state-failed", channel: "notify", line: String(line) }
501
+ }
502
+ if (!real) return { posted: false, reason: "no-real-turn", channel: "notify", line: String(line) }
417
503
  try {
418
- await client.session.prompt({ path: { id: sessionId }, body: { parts: [{ type: "text", text: line }] } })
419
- return { posted: true, drivesModelTurn: true } // 如实标注:这条路会驱动一次模型回合
504
+ await client.session.prompt({
505
+ path: { id: sessionId },
506
+ body: {
507
+ noReply: true,
508
+ parts: [{ type: "text", text: String(line), ignored: true, metadata: { ocg: REVIEW_SURFACE_MARK, childId } }],
509
+ },
510
+ })
511
+ rememberSurface(key)
512
+ return { posted: true, drivesModelTurn: false, reason: "posted", channel: "notify", childId, line: String(line) }
420
513
  } catch {
421
- return { posted: false, reason: "post-failed" }
514
+ return { posted: false, reason: "post-failed", channel: "notify", line: String(line) }
422
515
  }
423
516
  }
@@ -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 })
@@ -11,7 +11,7 @@ import path from "node:path"
11
11
 
12
12
  import { KINDS, SCHEMA_VERSION, MIN_READER } from "../core/paths.mjs"
13
13
  import { sha256 } from "../core/ids.mjs"
14
- import { createMemoryStore, ENTRY_DELIMITER } from "../core/memories.mjs"
14
+ import { createMemoryStore, resolveMemoryLimits, ENTRY_DELIMITER } from "../core/memories.mjs"
15
15
  import { listCandidates, readCandidate } from "../core/candidate.mjs"
16
16
  import { forget } from "../core/writer.mjs"
17
17
  import { storeInitMarker } from "../adapter-opencode/install.mjs"
@@ -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 {
@@ -174,8 +175,11 @@ export function status(opts, ctx) {
174
175
  const candidates = {}
175
176
  for (const c of listCandidates(L)) candidates[c.status] = (candidates[c.status] ?? 0) + 1
176
177
 
178
+ const limits = resolveMemoryLimits(L.root)
177
179
  const data = {
178
180
  store: L.root,
181
+ // 生效上限(与写入/批准/批量同一口径):诊断要能回答"现在到底卡在多少"
182
+ limits,
179
183
  storeId: storeIdFor(L),
180
184
  schemaVersion: SCHEMA_VERSION,
181
185
  // 世代号的替代:**常驻库内容 hash**(只作"当前快照"标识,不声称单调世代)
@@ -187,7 +191,7 @@ export function status(opts, ctx) {
187
191
  candidates,
188
192
  kinds: KINDS,
189
193
  }
190
- return ok("status", `${entries} entrie(s) resident, ${chars} char(s), ${pending} pending`, data)
194
+ return ok("status", `${entries} entrie(s) resident, ${chars} char(s), ${pending} pending · limits ${limits.memory}/${limits.user}(改 config.json 后下一次动作生效)`, data)
191
195
  }
192
196
 
193
197
  // ── install(S7 part B:安装入口)─────────────────────────────────────────────
@@ -200,7 +204,7 @@ export function status(opts, ctx) {
200
204
  *
201
205
  * 它**不碰** D 里的记忆与快照:只建目录、写宿主侧的两个文件。
202
206
  */
203
- export function installCmd(opts, ctx) {
207
+ export async function installCmd(opts, ctx) {
204
208
  const { L } = ctx
205
209
  try {
206
210
  const out = installAll({
@@ -209,9 +213,13 @@ export function installCmd(opts, ctx) {
209
213
  queuePath: opts.queue ? String(opts.queue) : null,
210
214
  dryRun: Boolean(opts["dry-run"]),
211
215
  })
216
+ // 装完顺手点亮历史搜索:有宿主默认库就绑一次,没有就如实说「未启用 + 怎么开」。
217
+ // dry-run 不碰任何东西(计划模式一个字节都不写)。
218
+ const sessionIndex = opts["dry-run"] ? null : await lightUpHistorySearch(L.root)
219
+ const line = historySearchLine(sessionIndex)
212
220
  return ok(
213
221
  "install",
214
- opts["dry-run"] ? "dry-run:只是计划,一个字节都没写" : `装好了:${out.shim}`,
222
+ (opts["dry-run"] ? "dry-run:只是计划,一个字节都没写" : `装好了:${out.shim}${line ? `\n${line}` : ""}`),
215
223
  {
216
224
  store: out.store,
217
225
  ...storeProvenance(ctx),
@@ -221,8 +229,12 @@ export function installCmd(opts, ctx) {
221
229
  configFile: out.configFile,
222
230
  skillsPath: out.skillsPath,
223
231
  configCreated: out.created,
232
+ configWouldCreate: out.wouldCreate,
233
+ storeConfig: out.storeConfig,
234
+ resident: out.resident,
224
235
  dryRun: Boolean(opts["dry-run"]),
225
236
  plan: out.report,
237
+ sessionIndex,
226
238
  },
227
239
  )
228
240
  } catch (err) {
@@ -348,12 +360,12 @@ export function memoryPendingCmd(opts, ctx) {
348
360
  })
349
361
  }
350
362
 
351
- export function memoryApproveCmd(opts, ctx) {
363
+ export async function memoryApproveCmd(opts, ctx) {
352
364
  const { L } = ctx
353
365
  const ref = opts._[0]
354
366
  if (!ref) return fail("memory.approve", "USAGE", "memory approve <pendingFile|ref> --as <who-you-are>")
355
367
  const who = opts.as ?? null
356
- const r = approvePending(L, String(ref), { approvedBy: who })
368
+ const r = await approvePending(L, String(ref), { approvedBy: who })
357
369
  if (r.ok) {
358
370
  return ok("memory.approve", `${r.op} applied — approved by ${r.approvedBy}`, {
359
371
  file: r.file,
@@ -371,6 +383,8 @@ export function memoryApproveCmd(opts, ctx) {
371
383
  invalid: "INVALID_PROPOSAL",
372
384
  "human-approval-required": "HUMAN_APPROVAL_REQUIRED",
373
385
  "apply-failed": "APPLY_FAILED",
386
+ stale: "STALE_PROPOSAL",
387
+ "snapshot-failed": "SNAPSHOT_FAILED",
374
388
  busy: "BUSY",
375
389
  lost: "LOCK_LOST",
376
390
  }
@@ -380,6 +394,8 @@ export function memoryApproveCmd(opts, ctx) {
380
394
  invalid: `这条提案不完整、不能批准:${r.detail ?? ""}`,
381
395
  "human-approval-required": "批准需要署名:--as <who-you-are>(没有署名的批准不算批准)",
382
396
  "apply-failed": `应用失败、待批文件已保留:${r.detail ?? ""}`,
397
+ stale: `提案已过期、未应用(也没有覆盖新内容):${r.detail ?? ""}`,
398
+ "snapshot-failed": `写入前快照失败,未应用:${r.detail ?? ""}`,
383
399
  busy: "提交锁被占用,稍后重试",
384
400
  lost: "提交锁在写入期间易主,本次未生效",
385
401
  }
@@ -394,51 +410,39 @@ export function memoryApproveCmd(opts, ctx) {
394
410
  // ── learn ────────────────────────────────────────────────────────────
395
411
 
396
412
  /**
397
- * Distil the corrections captured since the last pass into candidates.
413
+ * 旧学习链的执行入口**已退役**(欠账收口 · S1)。
398
414
  *
399
- * This is the link S6 deliberately left out: capturing a correction inside an OpenCode session
400
- * writes a queue line, and something outside the session has to turn it into a candidate. It is
401
- * a scheduling command, so it is idempotent — running it twice distils nothing the second time.
415
+ * 退役依据:日常主链已换成「回合结束后台复习」,两条链会处理同一次纠正;旧链的子会话还带着
416
+ * 可写穿常驻记忆的工具面。**只退执行,不退数据**:队列、游标、候选、audit 与旧读取器全部原样,
417
+ * 历史可追溯,升级不重放积压。
402
418
  *
403
- * It does NOT publish. Learning produces candidates; a person still has to confirm them.
419
+ * · `learn run --dry-run` 仍可看积压(只读,不移动游标)。
420
+ * · 普通 `learn run` 明确报退役并**非零退出**(旧调度器靠退出码判断失败,不能让它误报成功)。
421
+ * · 不再 spawn 学习子会话,也不再写了队列没人消费。
404
422
  */
405
423
  export async function learnRun(opts, ctx) {
406
424
  const { L } = ctx
407
- const limit = opts.limit === undefined ? Infinity : Number(opts.limit)
408
- if (Number.isNaN(limit) || limit < 0) {
409
- 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
+ )
410
432
  }
411
433
 
412
434
  const before = queueOffset(L)
413
435
  const res = await consumeQueue(L, {
414
436
  projectDir: opts.project ?? L.root,
415
- limit,
416
- dryRun: Boolean(opts["dry-run"]),
437
+ dryRun: true,
417
438
  })
418
439
 
419
- if (res.dryRun) {
420
- return ok("learn.run", `${res.pending} correction(s) waiting (dry run: nothing was learned)`, {
421
- dryRun: true,
422
- pending: res.pending,
423
- torn: res.torn,
424
- offset: before,
425
- })
426
- }
427
-
428
- const summary = res.processed === 0
429
- ? "nothing new to learn"
430
- : `${res.processed} correction(s): ${res.succeeded} produced candidates, ${res.failed} failed, ${res.skipped} skipped`
431
- return ok("learn.run", summary, {
432
- dryRun: false,
433
- processed: res.processed,
434
- succeeded: res.succeeded,
435
- failed: res.failed,
436
- skipped: res.skipped,
440
+ return ok("learn.run", `${res.pending} correction(s) waiting (dry run: nothing was learned)`, {
441
+ dryRun: true,
442
+ retired: true,
437
443
  pending: res.pending,
438
444
  torn: res.torn,
439
- offsetBefore: before,
440
- offsetAfter: queueOffset(L),
441
- entries: res.entries,
445
+ offset: before,
442
446
  })
443
447
  }
444
448
 
@@ -482,11 +486,21 @@ function storeProvenance(ctx) {
482
486
 
483
487
  /** uninstall:只撤我们写的东西(回执 + shim + 我们追加的那条 skills path),幂等。 */
484
488
  export function uninstallCmd(opts, ctx) {
489
+ const allowed = new Set(["_", "store", "config", "from", "json", "no-color"])
490
+ for (const key of Object.keys(opts)) {
491
+ if (!allowed.has(key)) return fail("uninstall", "USAGE", `uninstall 不支持选项 --${key};恢复回执使用 --from <manifest>`)
492
+ }
493
+ for (const key of ["store", "config", "from"]) {
494
+ if (opts[key] !== undefined && (typeof opts[key] !== "string" || !opts[key].trim())) {
495
+ return fail("uninstall", "USAGE", `--${key} 需要且只接受一个非空值,未做任何改动`)
496
+ }
497
+ }
485
498
  const { L } = ctx
486
499
  try {
487
- const out = uninstallAll({ store: L.root, configDir: opts.config ? String(opts.config) : null })
500
+ const out = uninstallAll({ store: L.root, configDir: opts.config ?? null, from: opts.from ?? null })
488
501
  return ok("uninstall",
489
- out.removed.length ? `撤掉了 ${out.removed.length} 项` : "没有需要撤的东西(幂等)",
502
+ out.retained.length ? `撤掉了 ${out.removed.length} 项,保留 ${out.retained.length} 项`
503
+ : out.removed.length ? `撤掉了 ${out.removed.length} 项` : "没有需要撤的东西(幂等)",
490
504
  { ...out })
491
505
  } catch (e) {
492
506
  return fail("uninstall", "REFUSED", e?.message ?? String(e))
@@ -41,9 +41,11 @@ function mechanicalPass(cmd, label, flags, ctx) {
41
41
  const dryRun = Boolean(flags["dry-run"])
42
42
  const r = applyLifecycleTransitions({ root: ctx.L.root, dryRun, origin: "foreground" })
43
43
  if (!r.ok) return fail(cmd, "DEGRADED", `机械维护失败:${r.error ?? "未知原因"}`)
44
+ const pinned = r.skipped_pinned ?? []
44
45
  const msg =
45
46
  `${label}${dryRun ? "(dry-run:库/快照/时钟/审计全不动)" : ""}:检查 ${r.checked} · 锚时钟 ${r.seeded} · ` +
46
- `stale ${r.marked_stale} · 归档 ${r.archived} · 提案 ${r.staged} · 复活 ${r.reactivated}`
47
+ `stale ${r.marked_stale} · 归档 ${r.archived} · 提案 ${r.staged} · 复活 ${r.reactivated}` +
48
+ (pinned.length ? ` · 跳过 pinned ${pinned.length}(${pinned.map((x) => x.name).join("、")})` : "")
47
49
  return ok(cmd, msg, r)
48
50
  }
49
51
 
package/src/cli/main.mjs CHANGED
@@ -50,12 +50,14 @@ Usage: oc-grow [--store <dir>] [--json] <command> [args]
50
50
  recorded approver. Rejecting needs no command: delete the
51
51
  file. A ref that matches zero or several is never guessed
52
52
  install [--config <dir>] [--dry-run]
53
- uninstall [--config <dir>]
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
  }
@@ -2,9 +2,10 @@
2
2
  // 与工具面共用查询核心(src/core/session-index.mjs);信封与退码走 envelope.mjs 统一口径。
3
3
  // 能力缺失(源形状认不出/源不可用)一律退码 5 DEGRADED——绝不绿着说「无匹配」。
4
4
  import { fail, ok } from "./envelope.mjs"
5
- import { readStore, rebindStore, searchStore, statusStore, syncStore } from "../core/session-index.mjs"
5
+ import { readStore, rebindStore, repairHintFor, searchStore, statusStore, syncStore } from "../core/session-index.mjs"
6
6
 
7
7
  const CAP_STATES = new Set([
8
+ "not-configured",
8
9
  "unsupported-schema",
9
10
  "source-missing",
10
11
  "source-unavailable",
@@ -50,14 +51,26 @@ export function sessionIndexSearchCmd(options) {
50
51
  since: options.since != null ? Number(options.since) : null,
51
52
  until: options.until != null ? Number(options.until) : null,
52
53
  })
53
- return ok("session-index search", r.message ?? `${r.count} 命中`, r)
54
+ // 能力缺失/未配置:没有缓存命中时**不得**报成功零结果(那与「有效源无命中」不可分)。
55
+ if (repairHintFor(r.state) && !r.count) {
56
+ return fail("session-index search", "DEGRADED", `历史索引不可用(state ${r.state})`, {
57
+ ...r, repair_hint: repairHintFor(r.state),
58
+ })
59
+ }
60
+ const prefix = r.stale ? `历史索引降级(state ${r.state},as_of ${r.as_of ?? "未知"})· ` : ""
61
+ return ok("session-index search", `${prefix}${r.message ?? `${r.count} 命中`}`, r)
54
62
  }
55
63
 
56
64
  export function sessionIndexStatusCmd(options) {
57
65
  const st = statusStore({ root: options.store })
58
66
  if (st.state === "ok") return ok("session-index status", `state ok · parts ${st.counts.parts ?? 0}`, st)
59
67
  // 能力缺失/未完成对账:退码 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)
68
+ const facts = st.facts?.length ? ` · ${st.facts.map((f) => `${f.code}:${f.detail}`).join(";")}` : ""
69
+ const hint = repairHintFor(st.state)
70
+ const label = st.state === "not-configured" ? " · 历史来源尚未绑定" : ""
71
+ return fail("session-index status", "DEGRADED", `state ${st.state}${facts}${label}${hint ? ` · ${hint}` : ""}`, {
72
+ ...st, repair_hint: hint,
73
+ })
61
74
  }
62
75
 
63
76
  export function sessionIndexReadCmd(options) {
@@ -153,9 +153,11 @@ export async function skillLifecycleCmd(flags, ctx) {
153
153
  const cmd = "skill.lifecycle"
154
154
  const dryRun = Boolean(flags["dry-run"])
155
155
  const r = applyLifecycleTransitions({ root: ctx.L.root, dryRun, origin: "foreground" })
156
+ const pinned = r.skipped_pinned ?? []
156
157
  const msg =
157
158
  `生命周期迁移${dryRun ? "(dry-run:库/快照/时钟全不动)" : ""}:检查 ${r.checked} · 锚时钟 ${r.seeded} · ` +
158
- `stale ${r.marked_stale} · 归档 ${r.archived} · 提案 ${r.staged} · 复活 ${r.reactivated}`
159
+ `stale ${r.marked_stale} · 归档 ${r.archived} · 提案 ${r.staged} · 复活 ${r.reactivated}` +
160
+ (pinned.length ? ` · 跳过 pinned ${pinned.length}(${pinned.map((x) => x.name).join("、")})` : "")
159
161
  return ok(cmd, msg, r)
160
162
  }
161
163