opencode-growth 0.1.59 → 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.
@@ -3,7 +3,7 @@
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
7
 
8
8
  // 照抄 Hermes 的复习提示词约束(第一版逐条对齐,不自造)。
9
9
  export const REVIEW_INSTRUCTIONS = Object.freeze([
@@ -21,10 +21,27 @@ export const REVIEW_INSTRUCTIONS = Object.freeze([
21
21
  "新增可以直接写;改动或删除既有条目一律只提案,等人处置。",
22
22
  ])
23
23
 
24
- const textOf = (m) => (typeof m === "string" ? m : m?.text ?? m?.content ?? JSON.stringify(m))
24
+ // 后台复习吃的是「整份回合会话」,而浮出的通知也是 user 消息(ignored + metadata.ocg)。
25
+ // 主模型上下文与 ③层召回都过滤了它,这里也必须过滤:否则 OCG 会把自己的机器通知当成用户说的话,
26
+ // 再蒸馏进记忆(这正是「不被 OCG 当用户输入」要防的那条路径)。
27
+ const isSurfacePart = (part) => part?.ignored === true || part?.metadata?.ocg === REVIEW_SURFACE_MARK
28
+
29
+ const textOf = (m) => {
30
+ if (typeof m === "string") return m
31
+ const parts = Array.isArray(m?.parts) ? m.parts : null
32
+ if (parts) {
33
+ return parts
34
+ .filter((part) => part && part.type === "text" && typeof part.text === "string" && !isSurfacePart(part))
35
+ .map((part) => part.text)
36
+ .join("\n")
37
+ .trim()
38
+ }
39
+ return m?.text ?? m?.content ?? JSON.stringify(m)
40
+ }
25
41
 
26
42
  export function buildReviewPrompt(history = []) {
27
- const lines = history.map((m) => "- " + textOf(m))
43
+ // 过滤后为空的消息(例如整条都是通知)不占一行:`- ` 空行会让模型以为用户说了句空话。
44
+ const lines = history.map((m) => "- " + textOf(m)).filter((line) => line.trim() !== "-")
28
45
  return [
29
46
  "【本回合会话(整份)】",
30
47
  ...lines,
@@ -328,10 +345,24 @@ export function createReviewPipeline({ client, thresholds, store = null, root =
328
345
  surface: landed.surface ?? null,
329
346
  skillSurface: skillLanded.surface ?? null,
330
347
  }
331
- if (typeof audit === "function") { try { audit(decision) } catch { /* 记账失败不许把宿主弄崩 */ } }
332
348
  // 提案必须浮出:有人看得见的那一行,发回宿主会话(memory 与技能两条车道的浮出行合并)
333
- const surfaceText = [landed.surface, skillLanded.surface].filter(Boolean).join(";") || null
334
- const surfaced = surfaceText ? await surfaceToHost({ client, sessionId, line: surfaceText }) : { posted: false }
349
+ // 通知行=这次复习**做了什么**的摘要(直接写入也要报),不再是「只有提案才说话」。
350
+ const surfaceText = backgroundReviewBead({
351
+ memoryWritten: landed.written ?? 0,
352
+ memoryStaged: landed.staged ?? 0,
353
+ skillWritten: skillLanded.written ?? 0,
354
+ skillStaged: skillLanded.staged ?? 0,
355
+ refused: (skillLanded.refused ?? []).length,
356
+ ignored: (landed.ignored ?? []).length + (skillLanded.ignored ?? []).length,
357
+ })
358
+ const surfaced = surfaceText
359
+ ? await surfaceToHost({ client, sessionId, line: surfaceText, childId: out.childId ?? null })
360
+ : { posted: false, reason: "nothing-to-surface" }
361
+ // 投没投出去是两件事:决策条目里如实记(失败=未投递,不许写成功)
362
+ decision.surfacePosted = surfaced.posted === true
363
+ decision.surfaceReason = surfaced.reason ?? null
364
+ decision.surfaceChannel = surfaced.channel ?? null
365
+ if (typeof audit === "function") { try { audit(decision) } catch { /* 记账失败不许把宿主弄崩 */ } }
335
366
  return { ...out, actions: actions.length, ...landed, skillLanded, surfaced, decision }
336
367
  },
337
368
  })
@@ -400,24 +431,82 @@ export function createReviewPipeline({ client, thresholds, store = null, root =
400
431
  }
401
432
  }
402
433
 
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" } = {}) {
434
+ // 提案浮出(S1,通道已按 1.18.30 源码 + 真 TUI 探针定案):
435
+ // noReply:true ⇒ prompt.ts 直接 return,不进 agent loop(不驱动模型回合、不多花钱)
436
+ // part.ignored ⇒ message-v2 / compaction 都剔除(不进模型上下文与压缩摘要),但 TUI 仍渲染
437
+ // **不设 synthetic** ⇒ TUI 的 UserMessage 只拼 `type==="text" && !synthetic` 的 part,设了整段渲染为空
438
+ // part.metadata.ocg ⇒ 机器判定用,不靠文本前缀猜
439
+ // 只投给**已经有真实用户回合**的会话:标题生成也把「parts 不全是 synthetic 的用户消息」当真实用户消息,
440
+ // 新会话 + 默认标题 + 只收通知这条路会额外发一次模型请求(实测:计数 stub 0 次 vs 真实提示词 1 次)。
441
+ // 发不出去要如实记「未投递」,不许写成功;宿主调用失败一律吞掉(适配器不许弄崩宿主)。
442
+ const SURFACE_DEDUPE_MS = 10 * 60 * 1000
443
+ const surfaceSeen = new Map()
444
+
445
+ const lineDigest = (s) => {
446
+ let h = 2166136261
447
+ for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0 }
448
+ return h.toString(16)
449
+ }
450
+ const seenRecently = (key, nowMs = Date.now()) => {
451
+ const ts = surfaceSeen.get(key)
452
+ return typeof ts === "number" && nowMs - ts <= SURFACE_DEDUPE_MS
453
+ }
454
+ const rememberSurface = (key, nowMs = Date.now()) => {
455
+ surfaceSeen.set(key, nowMs)
456
+ for (const [k, ts] of surfaceSeen) if (nowMs - ts > SURFACE_DEDUPE_MS) surfaceSeen.delete(k)
457
+ while (surfaceSeen.size > 200) surfaceSeen.delete(surfaceSeen.keys().next().value)
458
+ }
459
+
460
+ const isRealUserTurn = (m) => {
461
+ const role = m?.info?.role ?? m?.role
462
+ if (role !== "user") return false
463
+ const parts = Array.isArray(m?.parts) ? m.parts : []
464
+ if (parts.length === 0) return typeof m?.text === "string" && m.text.trim().length > 0
465
+ 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)
466
+ }
467
+
468
+ async function sessionHasRealTurn(client, sessionId) {
469
+ const res = await client.session.messages({ path: { id: sessionId } })
470
+ const list = Array.isArray(res) ? res : Array.isArray(res?.data) ? res.data : null
471
+ if (!list) return false
472
+ return list.some(isRealUserTurn)
473
+ }
474
+
475
+ export async function surfaceToHost({ client, sessionId, line, childId = null, mode = "notify" } = {}) {
411
476
  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
- }
477
+ if (mode === "pending-surface") return { posted: false, reason: "non-driving-surface", degraded: false, line }
415
478
  if (!sessionId) return { posted: false, reason: "no-session" }
416
479
  if (!client?.session?.prompt) return { posted: false, reason: "no-channel" }
480
+ if (mode === "prompt") {
481
+ // 兼容面:显式要求走会驱动模型的那条路(如实标注,调用方自己决定要不要)
482
+ try {
483
+ await client.session.prompt({ path: { id: sessionId }, body: { parts: [{ type: "text", text: String(line) }] } })
484
+ return { posted: true, drivesModelTurn: true, channel: "prompt" }
485
+ } catch {
486
+ return { posted: false, reason: "post-failed", channel: "prompt" }
487
+ }
488
+ }
489
+ const key = `${sessionId}|${childId ?? "-"}|${lineDigest(String(line))}`
490
+ if (seenRecently(key)) return { posted: false, reason: "duplicate", channel: "notify", line: String(line) }
491
+ if (typeof client.session.messages !== "function") return { posted: false, reason: "no-session-state", channel: "notify", line: String(line) }
492
+ let real = false
493
+ try {
494
+ real = await sessionHasRealTurn(client, sessionId)
495
+ } catch {
496
+ return { posted: false, reason: "session-state-failed", channel: "notify", line: String(line) }
497
+ }
498
+ if (!real) return { posted: false, reason: "no-real-turn", channel: "notify", line: String(line) }
417
499
  try {
418
- await client.session.prompt({ path: { id: sessionId }, body: { parts: [{ type: "text", text: line }] } })
419
- return { posted: true, drivesModelTurn: true } // 如实标注:这条路会驱动一次模型回合
500
+ await client.session.prompt({
501
+ path: { id: sessionId },
502
+ body: {
503
+ noReply: true,
504
+ parts: [{ type: "text", text: String(line), ignored: true, metadata: { ocg: REVIEW_SURFACE_MARK, childId } }],
505
+ },
506
+ })
507
+ rememberSurface(key)
508
+ return { posted: true, drivesModelTurn: false, reason: "posted", channel: "notify", childId, line: String(line) }
420
509
  } catch {
421
- return { posted: false, reason: "post-failed" }
510
+ return { posted: false, reason: "post-failed", channel: "notify", line: String(line) }
422
511
  }
423
512
  }
@@ -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"
@@ -174,8 +174,11 @@ export function status(opts, ctx) {
174
174
  const candidates = {}
175
175
  for (const c of listCandidates(L)) candidates[c.status] = (candidates[c.status] ?? 0) + 1
176
176
 
177
+ const limits = resolveMemoryLimits(L.root)
177
178
  const data = {
178
179
  store: L.root,
180
+ // 生效上限(与写入/批准/批量同一口径):诊断要能回答"现在到底卡在多少"
181
+ limits,
179
182
  storeId: storeIdFor(L),
180
183
  schemaVersion: SCHEMA_VERSION,
181
184
  // 世代号的替代:**常驻库内容 hash**(只作"当前快照"标识,不声称单调世代)
@@ -187,7 +190,7 @@ export function status(opts, ctx) {
187
190
  candidates,
188
191
  kinds: KINDS,
189
192
  }
190
- return ok("status", `${entries} entrie(s) resident, ${chars} char(s), ${pending} pending`, data)
193
+ return ok("status", `${entries} entrie(s) resident, ${chars} char(s), ${pending} pending · limits ${limits.memory}/${limits.user}(改 config.json 后下一次动作生效)`, data)
191
194
  }
192
195
 
193
196
  // ── install(S7 part B:安装入口)─────────────────────────────────────────────
@@ -221,6 +224,9 @@ export function installCmd(opts, ctx) {
221
224
  configFile: out.configFile,
222
225
  skillsPath: out.skillsPath,
223
226
  configCreated: out.created,
227
+ configWouldCreate: out.wouldCreate,
228
+ storeConfig: out.storeConfig,
229
+ resident: out.resident,
224
230
  dryRun: Boolean(opts["dry-run"]),
225
231
  plan: out.report,
226
232
  },
@@ -348,12 +354,12 @@ export function memoryPendingCmd(opts, ctx) {
348
354
  })
349
355
  }
350
356
 
351
- export function memoryApproveCmd(opts, ctx) {
357
+ export async function memoryApproveCmd(opts, ctx) {
352
358
  const { L } = ctx
353
359
  const ref = opts._[0]
354
360
  if (!ref) return fail("memory.approve", "USAGE", "memory approve <pendingFile|ref> --as <who-you-are>")
355
361
  const who = opts.as ?? null
356
- const r = approvePending(L, String(ref), { approvedBy: who })
362
+ const r = await approvePending(L, String(ref), { approvedBy: who })
357
363
  if (r.ok) {
358
364
  return ok("memory.approve", `${r.op} applied — approved by ${r.approvedBy}`, {
359
365
  file: r.file,
@@ -371,6 +377,8 @@ export function memoryApproveCmd(opts, ctx) {
371
377
  invalid: "INVALID_PROPOSAL",
372
378
  "human-approval-required": "HUMAN_APPROVAL_REQUIRED",
373
379
  "apply-failed": "APPLY_FAILED",
380
+ stale: "STALE_PROPOSAL",
381
+ "snapshot-failed": "SNAPSHOT_FAILED",
374
382
  busy: "BUSY",
375
383
  lost: "LOCK_LOST",
376
384
  }
@@ -380,6 +388,8 @@ export function memoryApproveCmd(opts, ctx) {
380
388
  invalid: `这条提案不完整、不能批准:${r.detail ?? ""}`,
381
389
  "human-approval-required": "批准需要署名:--as <who-you-are>(没有署名的批准不算批准)",
382
390
  "apply-failed": `应用失败、待批文件已保留:${r.detail ?? ""}`,
391
+ stale: `提案已过期、未应用(也没有覆盖新内容):${r.detail ?? ""}`,
392
+ "snapshot-failed": `写入前快照失败,未应用:${r.detail ?? ""}`,
383
393
  busy: "提交锁被占用,稍后重试",
384
394
  lost: "提交锁在写入期间易主,本次未生效",
385
395
  }
@@ -482,11 +492,21 @@ function storeProvenance(ctx) {
482
492
 
483
493
  /** uninstall:只撤我们写的东西(回执 + shim + 我们追加的那条 skills path),幂等。 */
484
494
  export function uninstallCmd(opts, ctx) {
495
+ const allowed = new Set(["_", "store", "config", "from", "json", "no-color"])
496
+ for (const key of Object.keys(opts)) {
497
+ if (!allowed.has(key)) return fail("uninstall", "USAGE", `uninstall 不支持选项 --${key};恢复回执使用 --from <manifest>`)
498
+ }
499
+ for (const key of ["store", "config", "from"]) {
500
+ if (opts[key] !== undefined && (typeof opts[key] !== "string" || !opts[key].trim())) {
501
+ return fail("uninstall", "USAGE", `--${key} 需要且只接受一个非空值,未做任何改动`)
502
+ }
503
+ }
485
504
  const { L } = ctx
486
505
  try {
487
- const out = uninstallAll({ store: L.root, configDir: opts.config ? String(opts.config) : null })
506
+ const out = uninstallAll({ store: L.root, configDir: opts.config ?? null, from: opts.from ?? null })
488
507
  return ok("uninstall",
489
- out.removed.length ? `撤掉了 ${out.removed.length} 项` : "没有需要撤的东西(幂等)",
508
+ out.retained.length ? `撤掉了 ${out.removed.length} 项,保留 ${out.retained.length} 项`
509
+ : out.removed.length ? `撤掉了 ${out.removed.length} 项` : "没有需要撤的东西(幂等)",
490
510
  { ...out })
491
511
  } catch (e) {
492
512
  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,7 +50,7 @@ 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
56
  learn run [--limit <n>] [--dry-run]
@@ -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
 
@@ -18,9 +18,64 @@ import path from "node:path"
18
18
  import { withCommitLock } from "./lock.mjs"
19
19
  import { appendAudit } from "./audit.mjs"
20
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"
21
25
 
22
26
  const OPS = ["add", "update", "remove", "batch"]
23
- const KINDS = ["memory", "user"]
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
+ }
24
79
 
25
80
  /** 列出待批提案。origin 保留原值;后台来源标 `[auto]`(照 Hermes,人一眼能看出不是自己提的)。 */
26
81
  export function listPending(L) {
@@ -34,7 +89,7 @@ export function listPending(L) {
34
89
  unreadable = true
35
90
  }
36
91
  const origin = raw.origin ?? "unknown"
37
- return {
92
+ const entry = {
38
93
  file,
39
94
  unreadable,
40
95
  op: raw.op ?? null,
@@ -48,6 +103,21 @@ export function listPending(L) {
48
103
  ops: Array.isArray(raw.operations) ? raw.operations.length : null,
49
104
  stagedAt: raw.stagedAt ?? null,
50
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
51
121
  })
52
122
  }
53
123
 
@@ -70,8 +140,16 @@ export function resolvePendingRef(L, ref) {
70
140
  /** 提案本身必须完整——不完整的提案连"可被批准"都不算,报出来让人处置。 */
71
141
  function invalidReason(rec) {
72
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
+ }
73
152
  if (!OPS.includes(rec.op)) return `未知的 op:${String(rec.op)}(可用:${OPS.join(" / ")})`
74
- if (!KINDS.includes(rec.kind ?? "memory")) return `未知的库:${String(rec.kind)}(可用:${KINDS.join(" / ")})`
75
153
  if (rec.op === "add" || rec.op === "update") {
76
154
  if (typeof rec.text !== "string" || !rec.text.trim()) return `${rec.op} 提案缺少非空 text`
77
155
  }
@@ -86,6 +164,65 @@ function invalidReason(rec) {
86
164
  return null
87
165
  }
88
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
+
89
226
  /**
90
227
  * 批准一条待批提案。
91
228
  *
@@ -95,7 +232,7 @@ function invalidReason(rec) {
95
232
  *
96
233
  * @returns {{ok:true, file, op, kind, origin, approvedBy, pending}} 或 {{ok:false, reason, ...}}
97
234
  */
98
- export function approvePending(L, ref, { approvedBy = null } = {}) {
235
+ export async function approvePending(L, ref, { approvedBy = null } = {}) {
99
236
  const found = resolvePendingRef(L, ref)
100
237
  if (!found.ok) return found
101
238
 
@@ -115,6 +252,9 @@ export function approvePending(L, ref, { approvedBy = null } = {}) {
115
252
  if (bad) return { ok: false, reason: "invalid", file: found.file, detail: bad }
116
253
 
117
254
  const kind = rec.kind ?? "memory"
255
+ // 技能提案:按 kind 分派到技能写路径(不是把批准器放宽成任意写入)。
256
+ if (kind === "skills") return await approveSkillPending(L, rec, found.file, who, pendingPath)
257
+
118
258
  const locked = withCommitLock(L.lock, ({ fencing, assertStillOwner }) => {
119
259
  try {
120
260
  if (rec.op === "add") store.writeTrusted({ kind, text: rec.text })
@@ -47,6 +47,9 @@ export function createReviewScheduler({
47
47
  interrupt = null,
48
48
  thresholds = REVIEW_THRESHOLDS,
49
49
  now = () => Date.now(),
50
+ // 握手上限可注入:默认照 Hermes 2.0s;夹具用一个小值来证明「到点就放弃」,
51
+ // 不再拿墙钟当判据(满载时 Node24 实测 3.5s,会把语义正确的实现判红)。
52
+ cancelTimeoutMs = REVIEW_LIMITS.cancelTimeoutMs,
50
53
  // C③:**工具可用性前置**(照 Hermes)。mem 记 memory 工具、skills 记宿主 skill 工具;
51
54
  // 值只认 true(可用)/ false(明确不可用)/ null(未知 —— 也当不可用,fail-closed)。
52
55
  //
@@ -115,7 +118,7 @@ export function createReviewScheduler({
115
118
  const kind = inflightKind
116
119
  const timedOut = Symbol("timeout")
117
120
  let timer
118
- const timeout = new Promise((res) => { timer = setTimeout(() => res(timedOut), REVIEW_LIMITS.cancelTimeoutMs) })
121
+ const timeout = new Promise((res) => { timer = setTimeout(() => res(timedOut), cancelTimeoutMs) })
119
122
  const settled = await Promise.race([inFlight.then(() => "done").catch(() => "done"), timeout])
120
123
  clearTimeout(timer)
121
124
  const waitedMs = now() - t0
@@ -178,11 +181,33 @@ export function surfaceLine({ proposals = [], ignored = [] } = {}) {
178
181
  return parts.join(";")
179
182
  }
180
183
 
184
+ /**
185
+ * 一次后台复习的**一行摘要**(照 Hermes `agent/background_review.py::_action_lines` +
186
+ * `summarize_background_review_actions` 的口径:直接写入也要报,不是只有提案才说话)。
187
+ * 什么都没发生(没有写入/提案/拒绝/忽略)⇒ null(Hermes 同样返回空列表,不刷屏)。
188
+ */
189
+ export function backgroundReviewBead({ memoryWritten = 0, memoryStaged = 0, skillWritten = 0, skillStaged = 0, refused = 0, ignored = 0 } = {}) {
190
+ const bits = []
191
+ if (memoryWritten) bits.push(`记忆 +${memoryWritten}`)
192
+ if (memoryStaged) bits.push(`记忆提案 ${memoryStaged}`)
193
+ if (skillWritten) bits.push(`技能 +${skillWritten}`)
194
+ if (skillStaged) bits.push(`技能提案 ${skillStaged}`)
195
+ if (refused) bits.push(`拒绝 ${refused}`)
196
+ if (ignored) bits.push(`忽略 ${ignored}`)
197
+ if (!bits.length) return null
198
+ const tail = memoryStaged + skillStaged > 0 ? "(待批:oc-grow memory pending)" : ""
199
+ return `后台复习:${bits.join(" · ")}${tail}`
200
+ }
201
+
181
202
  // 触发源(对齐 Hermes agent/turn_finalizer.py):宿主 `session.idle` = 回合结束。
182
203
  // 每次回合结束都做一次「要不要复习」的检查;前台新回合先取消在跑的那次(握手 ≤2s)。
183
204
  // 复习本身以**宿主身份**跑在**受限 agent**(只读 plan)里 ⇒ 工具被限定,且发生在宿主会话体系内。
184
205
  export const REVIEW_AGENT = "plan"
185
206
 
207
+ // 后台复习浮出的那一行带这个机器标记(part.metadata.ocg)。消费者(召回查询段、会话索引、学习队列)
208
+ // 用它把「后台通知」和「用户真的说了什么」分开——不靠文本前缀猜。
209
+ export const REVIEW_SURFACE_MARK = "review-surface"
210
+
186
211
  export function createTurnEndHandler({ scheduler, review, sessionId = null } = {}) {
187
212
  if (!scheduler || typeof review !== "function") throw new TypeError("createTurnEndHandler 需要 scheduler 与 review")
188
213
  let lastResult = null
@@ -59,6 +59,27 @@ export function fileForTarget(target) {
59
59
 
60
60
  export const DEFAULT_LIMITS = { memory: 2200, user: 1375 }
61
61
 
62
+ /**
63
+ * 生效上限:D/config.json 的 `memory.memory_char_limit` / `memory.user_char_limit`
64
+ * (与 Hermes config_defaults.py 同名同义)。
65
+ * 读不到 / 非法 / 非正数一律回默认——配置坏掉不许把正常写入判成超限(fail 到 Hermes 值)。
66
+ * 这是**唯一**的解析口径:store、批准、批量、CLI 与诊断都从这里取,不在各入口复制默认值。
67
+ */
68
+ export function resolveMemoryLimits(root) {
69
+ let cfg = null
70
+ try {
71
+ cfg = JSON.parse(fs.readFileSync(path.join(root, "config.json"), "utf8"))
72
+ } catch {
73
+ cfg = null
74
+ }
75
+ const mem = cfg && typeof cfg === "object" ? cfg.memory ?? {} : {}
76
+ const pick = (v, dflt) => {
77
+ const n = Number(v)
78
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : dflt
79
+ }
80
+ return { memory: pick(mem.memory_char_limit, DEFAULT_LIMITS.memory), user: pick(mem.user_char_limit, DEFAULT_LIMITS.user) }
81
+ }
82
+
62
83
  const KINDS = ["memory", "user"]
63
84
  const FILES = { memory: "MEMORY.md", user: "USER.md" }
64
85
  const ORIGINS = ["foreground", "background", "unknown"]
@@ -175,7 +196,13 @@ function acquireLock(root, { timeoutMs = LOCK_TIMEOUT_MS } = {}) {
175
196
 
176
197
  export function createMemoryStore({ root, identity = null, limits = {}, enabled = {} } = {}) {
177
198
  if (!root) throw new Error("createMemoryStore 需要 root(即 D 目录)")
178
- const limitOf = (kind) => limits[kind] ?? DEFAULT_LIMITS[kind]
199
+ // 每次判定都重新解析(配置文件很小):长驻进程(插件)改了配置,下一次动作就生效,
200
+ // 不必重启宿主;显式入参(夹具/嵌入方)仍然优先。
201
+ const limitOf = (kind) => {
202
+ const explicit = Number(limits?.[kind])
203
+ if (Number.isFinite(explicit) && explicit > 0) return Math.floor(explicit)
204
+ return resolveMemoryLimits(root)[kind]
205
+ }
179
206
  const enabledOf = (kind) => enabled[kind] !== false
180
207
  // 身份**只认登记值**:调用方在每次动作里传的 origin 一律忽略(extra#4)。
181
208
  const originOf = () => {
@@ -247,6 +274,7 @@ export function createMemoryStore({ root, identity = null, limits = {}, enabled
247
274
  const overLimitError = (kind, used, limit) =>
248
275
  new Error(
249
276
  `写入会超过上限:当前 ${used} / 上限 ${limit} 字符(${kind})。` +
277
+ `这笔文字会一直占用常驻上下文(每次会话都随系统提示带上,按 token 计费)。` +
250
278
  `请在当轮整理后再写:合并或删减既有条目,或把详情移到别处。本次写入未落盘。`,
251
279
  )
252
280
 
@@ -36,7 +36,6 @@ export function layout(root) {
36
36
  learnOffset: p("state", "learn-queue.offset"),
37
37
  manifest: p("state", "manifest.json"),
38
38
  projects: p("state", "projects.json"),
39
- budget: p("state", "budget.json"),
40
39
  watermark: p("state", "watermark.json"),
41
40
  policy: p("state", "policy.json"),
42
41
  schema: p("state", "schema.json"),