opencode-vcc-compaction 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,7 +15,7 @@ Port of [`dsh-compaction-vcc`](https://github.com/tingfeng-droid/dsh-compaction-
15
15
  directly against `@opencode/plugin/effect` (canonical runtime), so no
16
16
  convert-to-Effect task ever arises. The VCC reference engine is vendored
17
17
  byte-identical from `../compiler/` into `./engine/` (sync-enforced).
18
- Version: `opencode-vcc-compaction@0.2.0`.
18
+ Version: `opencode-vcc-compaction@0.3.1`.
19
19
 
20
20
  ## How it works
21
21
 
@@ -241,7 +241,8 @@ pointers against the per-session snapshot.
241
241
 
242
242
  ## Commands
243
243
 
244
- Server-only slash commands (no `./tui`): `/vcc-recall`, `/vcc-search`,
244
+ Server slash commands (plus the `./tui` companion below):
245
+ `/vcc-recall`, `/vcc-search`,
245
246
  `/vcc-status`. Command invocations cannot read history directly, so the
246
247
  `context` hook (with `compaction` as backup) persists a cleaned snapshot
247
248
  of the session's messages to `ctx.storage` (`vcc-snapshot/<sessionID>`,
@@ -259,10 +260,29 @@ recall/search; `/vcc-status` reports its age.
259
260
  (`maxTokens`/`keepMessages`/reasoning/hide/noise counts), and snapshot
260
261
  freshness (version, message count, lastID, age).
261
262
 
262
- Results feed back through `session.prompt`, so the agent presents them.
263
+ Results travel as an RPC event the TUI companion renders: each command
264
+ emits `rpc.opencode-vcc-compaction.replied` and returns void with no
265
+ prompt call, so there is no model turn and no chatter — the TUI toasts
266
+ short replies and dialogs long ones (see `./tui` below). This requires
267
+ the companion: add the package to `cli.json` `plugins`. Without a
268
+ connected TUI the emit goes nowhere and the reply is silent — by
269
+ design (no wake), so non-interactive use stays quiet. Only when RPC
270
+ itself is unavailable (or an emit fails) do replies fall back to
271
+ `session.prompt`, where the agent presents them.
263
272
  A nothing-to-do stays silent (log line only, never an empty agent turn);
264
273
  a storage read failure replies explicitly ("snapshot read failed, try
265
- again in a moment"), never a misleading "none yet".
274
+ again in a moment"), never a misleading "none yet". Unexpected command
275
+ errors attempt a visible "command failed, try again" prompt reply before
276
+ giving up to the log.
277
+
278
+ ## TUI companion (`./tui` export)
279
+
280
+ `tui.tsx` listens for the reply event and renders it immediately: short
281
+ replies as toasts, long ones as large centered dialogs. No keymap
282
+ commands — none are needed, since the event carries its session. Add
283
+ the package to `cli.json` `plugins` (TUI-only surface, also works
284
+ against a remote server). The server commands stay as the transcript
285
+ record; the companion is the quiet visible channel.
266
286
 
267
287
  ## Message mapping
268
288
 
@@ -309,19 +329,21 @@ and control bytes are stripped deterministically before counting.
309
329
  ## Verify
310
330
 
311
331
  ```sh
312
- node --check vcc-plugin/index.ts
313
- node vcc-plugin/selftest.mjs
314
- node scripts/check-engine-sync.mjs
315
- node compiler/selftest.mjs
332
+ npm run typecheck # node --check index.ts + tsc -p tsconfig.tui.json
333
+ npm run test # both selftests + engine-sync
334
+ npm run lint:md # markdown lint over the tree
316
335
  ```
317
336
 
337
+ Run from the repo root (workspace scripts; toolchain installs with `npm ci`).
338
+
318
339
  Live compaction runs only with explicit approval + explicit `--model`,
319
340
  from a scratch project, never a real one.
320
341
 
321
342
  ## Status and limits
322
343
 
323
- - v0.2.0 ships the hook + three server-only slash commands
324
- (`/vcc-recall`, `/vcc-search`, `/vcc-status`; no `./tui`). `(seq N)`
344
+ - v0.3.0 ships the hook + three server slash commands
345
+ (`/vcc-recall`, `/vcc-search`, `/vcc-status`) plus the `./tui`
346
+ companion that renders their replies quietly. `(seq N)`
325
347
  pointers are 1-based ordinals over the compiled messages (skipped
326
348
  messages consume no seq); recall/search resolve them against the
327
349
  per-session snapshot.
package/events.mjs ADDED
@@ -0,0 +1,55 @@
1
+ // Event contract for the vcc TUI companion (dependency-free).
2
+ //
3
+ // The server cannot emit visible output without waking the agent, so
4
+ // /vcc-* replies travel as an RPC event the TUI toasts: the server
5
+ // emits `rpc.opencode-vcc-compaction.replied` with the reply payload
6
+ // and returns void with no prompt call (no wake, no chatter, no inbox
7
+ // row). The TUI filters `ctx.data.listen` by `replyEventType()` and
8
+ // renders it.
9
+ //
10
+ // Both `index.ts` (server, Rpc.define + emit) and `tui.tsx` (TUI,
11
+ // listen + dialog) import this module so the type string and payload
12
+ // shape have a single source of truth. No external imports so
13
+ // `selftest.mjs` runs it without node_modules.
14
+
15
+ export const VCC_RPC_ID = "opencode-vcc-compaction";
16
+
17
+ export const VCC_REPLY_EVENT = "replied";
18
+
19
+ export function replyEventType() {
20
+ return `rpc.${VCC_RPC_ID}.${VCC_REPLY_EVENT}`;
21
+ }
22
+
23
+ // The bus carries the whole reply; cap pathological payloads (a huge
24
+ // recall range) so one event cannot flood it. Truncation is explicit.
25
+ export const MAX_REPLY_TEXT = 30000;
26
+
27
+ // Payload the server emits per command reply. `command` is the slash
28
+ // name without arguments ("/vcc-status"); `text` the rendered reply.
29
+ // Non-string text is coerced so a future caller passing unvalidated
30
+ // data gets a payload (which `isReplyPayload` still accepts) instead
31
+ // of an exception on `.length`.
32
+ export function buildReplyPayload(sessionID, command, text) {
33
+ const body = typeof text === "string" ? text : String(text);
34
+ return {
35
+ sessionID,
36
+ command,
37
+ text:
38
+ body.length > MAX_REPLY_TEXT
39
+ ? `${body.slice(0, MAX_REPLY_TEXT)}\n\n[truncated: reply exceeds ${MAX_REPLY_TEXT} chars — narrow the selection and retry]`
40
+ : body,
41
+ };
42
+ }
43
+
44
+ // Short replies toast; longer ones need a large centered dialog.
45
+ export const MAX_TOAST_TEXT = 300;
46
+
47
+ export function isReplyPayload(value) {
48
+ return (
49
+ typeof value === "object" &&
50
+ value !== null &&
51
+ typeof value.sessionID === "string" &&
52
+ typeof value.command === "string" &&
53
+ typeof value.text === "string"
54
+ );
55
+ }
package/index.ts CHANGED
@@ -1,9 +1,13 @@
1
- import { Plugin } from "@opencode/plugin/effect"
2
- import { Effect } from "effect"
1
+ import { Plugin, Rpc } from "@opencode/plugin/effect"
2
+ import type { SessionInbox } from "@opencode/schema/session-inbox"
3
+ import { Effect, Schema } from "effect"
3
4
  import { buildConfig, compileCompaction } from "./adapter.mjs"
5
+ import { VCC_REPLY_EVENT, VCC_RPC_ID, buildReplyPayload } from "./events.mjs"
4
6
  import {
5
7
  COMPILER_REV,
8
+ MAX_SNAPSHOT_WRITE_BYTES,
6
9
  SNAPSHOT_KEY_PREFIX,
10
+ WATCH_STATS_KEY_PREFIX,
7
11
  buildSnapshot,
8
12
  classifySnapshotStore,
9
13
  formatRecallReply,
@@ -15,6 +19,8 @@ import {
15
19
  resolveRecallSelections,
16
20
  searchSnapshot,
17
21
  snapshotNeedsWrite,
22
+ snapshotWriteBytes,
23
+ updateWatchStats,
18
24
  } from "./snapshot.mjs"
19
25
 
20
26
  // opencode-vcc-compaction: deterministic LLM-free compaction summaries.
@@ -25,18 +31,140 @@ import {
25
31
  // metadata.keepID. When the adapter abstains (no message id at/after the
26
32
  // keep cut), result stays unset and the host falls back to model compaction.
27
33
  // Alongside, context + compaction hooks snapshot cleaned raw messages
28
- // (snapshot.mjs, growth-guarded by version/count/lastID, warn-and-continue)
29
- // so the vcc- commands can recall/search history the command ctx cannot
30
- // read directly.
34
+ // (snapshot.mjs: growth-guarded by version/count/lastID, >1MB single-write
35
+ // warn tripwire + queryable per-session watch stats (`vcc-stats/` key:
36
+ // maxWriteBytes, tripCount), every failure path warn-and-continue) so the vcc-
37
+ // commands can recall/search history the command ctx cannot read directly.
31
38
  //
32
39
  // Effect-direct by owner decision: written against @opencode/plugin/effect
33
40
  // from the start, so no convert-to-Effect task ever arises.
41
+ //
42
+ // Command replies travel as an RPC event the TUI companion toasts:
43
+ // the server emits `rpc.opencode-vcc-compaction.replied` and returns
44
+ // void with no prompt call (no wake, no chatter, no inbox row) — the
45
+ // goal-plugin pattern (`get` + event). Without the companion the
46
+ // event goes nowhere, and without RPC itself replies fall back to
47
+ // `session.prompt` (visible + wakes), so output is never lost.
48
+ // Payload shape shared with events.mjs (runtime single source of truth
49
+ // lives there for the dependency-free selftest; this alias only types
50
+ // the emit call site).
51
+ type ReplyPayload = { sessionID: string; command: string; text: string }
52
+
53
+ const VccRpc = Rpc.define({ id: VCC_RPC_ID,
54
+ methods: {
55
+ get: {
56
+ input: Schema.toStandardSchemaV1(Schema.Struct({ sessionID: Schema.String })),
57
+ output: Schema.toStandardSchemaV1(
58
+ Schema.NullOr(
59
+ Schema.Struct({
60
+ version: Schema.Number,
61
+ messages: Schema.Array(Schema.Unknown),
62
+ count: Schema.Number,
63
+ lastID: Schema.optional(Schema.String),
64
+ writtenAt: Schema.Number,
65
+ }),
66
+ ),
67
+ ),
68
+ },
69
+ },
70
+ events: {
71
+ [VCC_REPLY_EVENT]: {
72
+ schema: Schema.toStandardSchemaV1(
73
+ Schema.Struct({ sessionID: Schema.String, command: Schema.String, text: Schema.String }),
74
+ ),
75
+ },
76
+ },
77
+ })
34
78
 
35
79
  export default Plugin.define({
36
80
  id: "opencode-vcc-compaction",
37
81
  effect: Effect.fn(function* (ctx) {
38
82
  const config = buildConfig(ctx.options)
39
- const seen = new Map<string, { version: number; count: number; lastID: string | undefined }>()
83
+ const seen = new Map<string, { version: number; count: number; lastID: string | undefined; stats: unknown; statsLoaded: boolean }>()
84
+
85
+ const readStored = (sessionID: string, label: string) =>
86
+ Effect.catch(
87
+ ctx.storage.get(`${SNAPSHOT_KEY_PREFIX}${sessionID}`),
88
+ (error) =>
89
+ Effect.sync(() => {
90
+ console.warn(`[opencode-vcc-compaction] ${label}: snapshot read failed:`, error)
91
+ return { __vccReadFailed: true as const }
92
+ }),
93
+ )
94
+
95
+ // RPC registration must never break init: a JS try/catch around
96
+ // yield* cannot intercept Effect failures, so catch the cause
97
+ // channel explicitly and degrade to prompt replies.
98
+ const rpc = yield* Effect.catchCause(
99
+ ctx.rpc.register(VccRpc, {
100
+ get: (input) =>
101
+ Effect.flatMap(readStored(input.sessionID, "rpc.get"), (stored) => {
102
+ const classified = classifySnapshotStore(stored as never)
103
+ if (classified.status !== "ready") return Effect.succeed(null)
104
+ const candidate = classified.stored as Partial<
105
+ Record<"version" | "messages" | "count" | "lastID" | "writtenAt", unknown>
106
+ >
107
+ // The store only guarantees a non-empty messages array; project
108
+ // the five schema fields (or null) instead of trusting the
109
+ // envelope, so hand-written or older shapes fail soft.
110
+ return Effect.succeed(
111
+ typeof candidate.version === "number" &&
112
+ Array.isArray(candidate.messages) &&
113
+ typeof candidate.count === "number" &&
114
+ typeof candidate.writtenAt === "number"
115
+ ? {
116
+ version: candidate.version,
117
+ messages: candidate.messages,
118
+ count: candidate.count,
119
+ ...(typeof candidate.lastID === "string" ? { lastID: candidate.lastID } : {}),
120
+ writtenAt: candidate.writtenAt,
121
+ }
122
+ : null,
123
+ )
124
+ }),
125
+ }),
126
+ (cause) =>
127
+ Effect.flatMap(
128
+ Effect.sync(() => {
129
+ console.warn("[opencode-vcc-compaction] rpc unavailable; /vcc-* replies fall back to prompt:", cause)
130
+ }),
131
+ () => Effect.succeed(null),
132
+ ),
133
+ )
134
+ const emitReply: ((payload: ReplyPayload) => Effect.Effect<void, unknown>) | null =
135
+ rpc === null ? null : (payload) => rpc.events.emit(VCC_REPLY_EVENT, payload)
136
+
137
+ // Primary path emits the reply event for the TUI companion (silent,
138
+ // no wake). Fallbacks keep output visible: emit failure or missing
139
+ // RPC revert to session.prompt (visible + wakes, 0.2.0 behavior).
140
+ // The host passes `input.prompt` as `{ text }`; normalize a plain
141
+ // string too so a host-shape change degrades to working, not to a
142
+ // permanent usage error.
143
+ const promptText = (input: { prompt: unknown }) =>
144
+ typeof input.prompt === "string" ? input.prompt : ((input.prompt as { text?: unknown })?.text ?? "")
145
+
146
+ const reply = (input: { sessionID: string; delivery?: SessionInbox.Delivery }, command: string, text: string) =>
147
+ emitReply === null
148
+ ? ctx.session.prompt({
149
+ sessionID: input.sessionID,
150
+ text,
151
+ delivery: input.delivery,
152
+ })
153
+ : Effect.catch(
154
+ emitReply(buildReplyPayload(input.sessionID, command, text)),
155
+ (error) =>
156
+ Effect.flatMap(
157
+ Effect.sync(() => {
158
+ console.warn("[opencode-vcc-compaction] reply emit failed; falling back to prompt:", error)
159
+ }),
160
+ () =>
161
+ ctx.session.prompt({
162
+ sessionID: input.sessionID,
163
+ text,
164
+ delivery: input.delivery,
165
+ }),
166
+ ),
167
+ )
40
168
 
41
169
  const remember = (sessionID: unknown, messages: unknown) =>
42
170
  Effect.catch(
@@ -50,26 +178,70 @@ export default Plugin.define({
50
178
  }),
51
179
  (snap) => {
52
180
  if (snap === null) return Effect.void
53
- const prev = seen.get(sessionID as string)
181
+ const key = sessionID as string
182
+ const prev = seen.get(key)
54
183
  if (!snapshotNeedsWrite(prev, snap)) return Effect.void
184
+ const at = Date.now()
185
+ const envelope = {
186
+ version: snap.version,
187
+ messages: snap.messages,
188
+ count: snap.count,
189
+ ...(snap.lastID === undefined ? {} : { lastID: snap.lastID }),
190
+ writtenAt: at,
191
+ }
192
+ const writeBytes = snapshotWriteBytes(envelope)
193
+ // Watch stats live in their own kv key (not the envelope, so
194
+ // recall/search/RPC readers never change shape): lazy-load once
195
+ // per session, fold purely, persist only on new max or trip.
196
+ const loadStats =
197
+ prev?.statsLoaded === true
198
+ ? Effect.succeed(prev.stats)
199
+ : Effect.catch(
200
+ ctx.storage.get(`${WATCH_STATS_KEY_PREFIX}${key}`),
201
+ (error) =>
202
+ Effect.sync(() => {
203
+ console.warn("[opencode-vcc-compaction] watch stats read failed; folding from zero:", error)
204
+ return undefined
205
+ }),
206
+ )
55
207
  return Effect.catch(
56
- Effect.flatMap(
57
- ctx.storage.set(`${SNAPSHOT_KEY_PREFIX}${sessionID}`, {
58
- version: snap.version,
59
- messages: snap.messages,
60
- count: snap.count,
61
- ...(snap.lastID === undefined ? {} : { lastID: snap.lastID }),
62
- writtenAt: Date.now(),
63
- }),
64
- () =>
65
- Effect.sync(() => {
66
- seen.set(sessionID as string, {
67
- version: snap.version,
68
- count: snap.count,
69
- lastID: snap.lastID,
70
- })
71
- }),
72
- ),
208
+ Effect.flatMap(loadStats, (storedStats) => {
209
+ const fold = updateWatchStats(storedStats, writeBytes, at)
210
+ const recordStats = fold.changed
211
+ ? Effect.catch(
212
+ ctx.storage.set(`${WATCH_STATS_KEY_PREFIX}${key}`, fold.stats),
213
+ (error) =>
214
+ Effect.sync(() => {
215
+ console.warn("[opencode-vcc-compaction] watch stats write failed:", error)
216
+ }),
217
+ )
218
+ : Effect.void
219
+ return Effect.flatMap(
220
+ writeBytes > MAX_SNAPSHOT_WRITE_BYTES
221
+ ? Effect.sync(() => {
222
+ console.warn(
223
+ `[opencode-vcc-compaction] snapshot write large: session ${sessionID} count=${snap.count} ~${writeBytes} bytes (O(n²) watch: full envelope rewritten per turn)`,
224
+ )
225
+ })
226
+ : Effect.void,
227
+ () =>
228
+ Effect.flatMap(
229
+ ctx.storage.set(`${SNAPSHOT_KEY_PREFIX}${key}`, envelope),
230
+ () =>
231
+ Effect.flatMap(recordStats, () =>
232
+ Effect.sync(() => {
233
+ seen.set(key, {
234
+ version: snap.version,
235
+ count: snap.count,
236
+ lastID: snap.lastID,
237
+ stats: fold.stats,
238
+ statsLoaded: true,
239
+ })
240
+ }),
241
+ ),
242
+ ),
243
+ )
244
+ }),
73
245
  (error) =>
74
246
  Effect.sync(() => {
75
247
  console.warn("[opencode-vcc-compaction] snapshot write failed:", error)
@@ -83,19 +255,42 @@ export default Plugin.define({
83
255
  }),
84
256
  )
85
257
 
258
+ // True when the context hook below registered: snapshots are then
259
+ // maintained on every turn and the compaction hook can skip its own
260
+ // rebuild. When false (host without a context hook), every
261
+ // compaction must rebuild — `seen` presence alone would go stale
262
+ // after the first compaction-time write.
263
+ let snapshotsViaContext = false
86
264
  try {
87
265
  yield* ctx.session.hook("context", (event) =>
88
266
  remember((event as { sessionID: string }).sessionID, (event as { messages: unknown }).messages),
89
267
  )
268
+ snapshotsViaContext = true
90
269
  } catch (error) {
91
270
  console.warn("[opencode-vcc-compaction] context hook unavailable; snapshots via compaction only:", error)
92
271
  }
93
272
 
94
273
  yield* ctx.session.hook("compaction", (event) =>
95
274
  Effect.flatMap(
96
- remember((event as { sessionID: string }).sessionID, (event as { messages: unknown }).messages),
97
- () =>
98
- Effect.sync(() => {
275
+ // Snapshots land via the context hook on every turn; rebuilding
276
+ // the same append-only log here would duplicate that work once
277
+ // per compaction. Skip only when the context path is proven
278
+ // live (registered above AND this session already seen) —
279
+ // otherwise rebuild, exactly as before.
280
+ Effect.sync(
281
+ () =>
282
+ snapshotsViaContext && seen.has((event as { sessionID: string }).sessionID),
283
+ ),
284
+ (ready) =>
285
+ Effect.flatMap(
286
+ ready
287
+ ? Effect.void
288
+ : remember(
289
+ (event as { sessionID: string }).sessionID,
290
+ (event as { messages: unknown }).messages,
291
+ ),
292
+ () =>
293
+ Effect.sync(() => {
99
294
  let outcome
100
295
  try {
101
296
  outcome = compileCompaction(event.messages, config)
@@ -109,6 +304,7 @@ export default Plugin.define({
109
304
  metadata: { keepID: outcome.keepID },
110
305
  }
111
306
  }),
307
+ ),
112
308
  ),
113
309
  )
114
310
 
@@ -120,32 +316,17 @@ export default Plugin.define({
120
316
  execute: (input) =>
121
317
  Effect.catchCause(
122
318
  Effect.flatMap(
123
- Effect.sync(() => parseRecallArgs((input.prompt as { text?: unknown })?.text ?? "")),
319
+ Effect.sync(() => parseRecallArgs(promptText(input))),
124
320
  (parsed) => {
125
321
  if ("error" in parsed) {
126
- return ctx.session.prompt({
127
- sessionID: input.sessionID,
128
- text: `**/vcc-recall** — ${parsed.error}`,
129
- delivery: input.delivery,
130
- })
322
+ return reply(input, "/vcc-recall", `**/vcc-recall** — ${parsed.error}`)
131
323
  }
132
324
  return Effect.flatMap(
133
- Effect.catch(
134
- ctx.storage.get(`${SNAPSHOT_KEY_PREFIX}${input.sessionID}`),
135
- (error) =>
136
- Effect.sync(() => {
137
- console.warn("[opencode-vcc-compaction] vcc-recall: snapshot read failed:", error)
138
- return { __vccReadFailed: true as const }
139
- }),
140
- ),
325
+ readStored(input.sessionID, "vcc-recall"),
141
326
  (stored) => {
142
327
  const classified = classifySnapshotStore(stored as never)
143
328
  if (classified.status === "failed") {
144
- return ctx.session.prompt({
145
- sessionID: input.sessionID,
146
- text: "**/vcc-recall** — snapshot read failed, try again in a moment",
147
- delivery: input.delivery,
148
- })
329
+ return reply(input, "/vcc-recall", "**/vcc-recall** — snapshot read failed, try again in a moment")
149
330
  }
150
331
  if (classified.status === "empty") {
151
332
  console.log("[opencode-vcc-compaction] vcc-recall: no snapshot yet for this session")
@@ -153,26 +334,30 @@ export default Plugin.define({
153
334
  }
154
335
  const resolved = resolveRecallSelections(classified.messages as never, parsed.type, parsed.id)
155
336
  if (resolved.errors.length > 0 || resolved.selections.length === 0) {
156
- return ctx.session.prompt({
157
- sessionID: input.sessionID,
158
- text: `**/vcc-recall** — ${resolved.errors.join("; ") || "nothing to recall"}`,
159
- delivery: input.delivery,
160
- })
337
+ return reply(
338
+ input,
339
+ "/vcc-recall",
340
+ `**/vcc-recall** — ${resolved.errors.join("; ") || "nothing to recall"}`,
341
+ )
161
342
  }
162
343
  const recalled = recallFromSnapshot(classified.messages as never, resolved.selections)
163
- return ctx.session.prompt({
164
- sessionID: input.sessionID,
165
- text: formatRecallReply(parsed.type, parsed.id, recalled as never),
166
- delivery: input.delivery,
167
- })
344
+ return reply(input, "/vcc-recall", formatRecallReply(parsed.type, parsed.id, recalled as never))
168
345
  },
169
346
  )
170
347
  },
171
348
  ),
172
349
  (cause) =>
173
- Effect.sync(() => {
174
- console.warn("[opencode-vcc-compaction] vcc-recall failed:", cause)
175
- }),
350
+ Effect.catchCause(
351
+ ctx.session.prompt({
352
+ sessionID: input.sessionID,
353
+ text: "**/vcc-recall** — command failed, try again in a moment",
354
+ delivery: input.delivery,
355
+ }),
356
+ () =>
357
+ Effect.sync(() => {
358
+ console.warn("[opencode-vcc-compaction] vcc-recall failed:", cause)
359
+ }),
360
+ ),
176
361
  ),
177
362
  })
178
363
  editor.add({
@@ -181,32 +366,17 @@ export default Plugin.define({
181
366
  execute: (input) =>
182
367
  Effect.catchCause(
183
368
  Effect.flatMap(
184
- Effect.sync(() => parseSearchArgs((input.prompt as { text?: unknown })?.text ?? "")),
369
+ Effect.sync(() => parseSearchArgs(promptText(input))),
185
370
  (parsed) => {
186
371
  if ("error" in parsed) {
187
- return ctx.session.prompt({
188
- sessionID: input.sessionID,
189
- text: `**/vcc-search** — ${parsed.error}`,
190
- delivery: input.delivery,
191
- })
372
+ return reply(input, "/vcc-search", `**/vcc-search** — ${parsed.error}`)
192
373
  }
193
374
  return Effect.flatMap(
194
- Effect.catch(
195
- ctx.storage.get(`${SNAPSHOT_KEY_PREFIX}${input.sessionID}`),
196
- (error) =>
197
- Effect.sync(() => {
198
- console.warn("[opencode-vcc-compaction] vcc-search: snapshot read failed:", error)
199
- return { __vccReadFailed: true as const }
200
- }),
201
- ),
375
+ readStored(input.sessionID, "vcc-search"),
202
376
  (stored) => {
203
377
  const classified = classifySnapshotStore(stored as never)
204
378
  if (classified.status === "failed") {
205
- return ctx.session.prompt({
206
- sessionID: input.sessionID,
207
- text: "**/vcc-search** — snapshot read failed, try again in a moment",
208
- delivery: input.delivery,
209
- })
379
+ return reply(input, "/vcc-search", "**/vcc-search** — snapshot read failed, try again in a moment")
210
380
  }
211
381
  if (classified.status === "empty") {
212
382
  console.log("[opencode-vcc-compaction] vcc-search: no snapshot yet for this session")
@@ -216,25 +386,29 @@ export default Plugin.define({
216
386
  try {
217
387
  found = searchSnapshot(classified.messages as never, parsed.pattern)
218
388
  } catch (error) {
219
- return ctx.session.prompt({
220
- sessionID: input.sessionID,
221
- text: `**/vcc-search** — ${error instanceof Error ? error.message : String(error)}`,
222
- delivery: input.delivery,
223
- })
389
+ return reply(
390
+ input,
391
+ "/vcc-search",
392
+ `**/vcc-search** — ${error instanceof Error ? error.message : String(error)}`,
393
+ )
224
394
  }
225
- return ctx.session.prompt({
226
- sessionID: input.sessionID,
227
- text: formatSearchReply(parsed.pattern, found as never),
228
- delivery: input.delivery,
229
- })
395
+ return reply(input, "/vcc-search", formatSearchReply(parsed.pattern, found as never))
230
396
  },
231
397
  )
232
398
  },
233
399
  ),
234
400
  (cause) =>
235
- Effect.sync(() => {
236
- console.warn("[opencode-vcc-compaction] vcc-search failed:", cause)
237
- }),
401
+ Effect.catchCause(
402
+ ctx.session.prompt({
403
+ sessionID: input.sessionID,
404
+ text: "**/vcc-search** — command failed, try again in a moment",
405
+ delivery: input.delivery,
406
+ }),
407
+ () =>
408
+ Effect.sync(() => {
409
+ console.warn("[opencode-vcc-compaction] vcc-search failed:", cause)
410
+ }),
411
+ ),
238
412
  ),
239
413
  })
240
414
  editor.add({
@@ -243,39 +417,36 @@ export default Plugin.define({
243
417
  execute: (input) =>
244
418
  Effect.catchCause(
245
419
  Effect.flatMap(
246
- Effect.catch(
247
- ctx.storage.get(`${SNAPSHOT_KEY_PREFIX}${input.sessionID}`),
248
- (error) =>
249
- Effect.sync(() => {
250
- console.warn("[opencode-vcc-compaction] vcc-status: snapshot read failed:", error)
251
- return { __vccReadFailed: true as const }
252
- }),
253
- ),
420
+ readStored(input.sessionID, "vcc-status"),
254
421
  (stored) => {
255
422
  const classified = classifySnapshotStore(stored as never)
256
423
  if (classified.status === "failed") {
257
- return ctx.session.prompt({
258
- sessionID: input.sessionID,
259
- text: "**/vcc-status** — snapshot read failed, try again in a moment",
260
- delivery: input.delivery,
261
- })
424
+ return reply(input, "/vcc-status", "**/vcc-status** — snapshot read failed, try again in a moment")
262
425
  }
263
- return ctx.session.prompt({
264
- sessionID: input.sessionID,
265
- text: formatStatusText(
426
+ return reply(
427
+ input,
428
+ "/vcc-status",
429
+ formatStatusText(
266
430
  classified.status === "ready" ? classified.stored as never : undefined,
267
431
  config as never,
268
432
  COMPILER_REV as string,
269
433
  Date.now(),
270
434
  ),
271
- delivery: input.delivery,
272
- })
435
+ )
273
436
  },
274
437
  ),
275
438
  (cause) =>
276
- Effect.sync(() => {
277
- console.warn("[opencode-vcc-compaction] vcc-status failed:", cause)
278
- }),
439
+ Effect.catchCause(
440
+ ctx.session.prompt({
441
+ sessionID: input.sessionID,
442
+ text: "**/vcc-status** — command failed, try again in a moment",
443
+ delivery: input.delivery,
444
+ }),
445
+ () =>
446
+ Effect.sync(() => {
447
+ console.warn("[opencode-vcc-compaction] vcc-status failed:", cause)
448
+ }),
449
+ ),
279
450
  ),
280
451
  })
281
452
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-vcc-compaction",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "Deterministic LLM-free compaction summaries for OpenCode V2 (VCC reference engine, Effect-direct hook).",
5
5
  "license": "MIT",
6
6
  "author": "jwitmann <jerome_witmann@witmanco.net>",
@@ -24,12 +24,22 @@
24
24
  ],
25
25
  "type": "module",
26
26
  "main": "./index.ts",
27
- "files": ["index.ts", "adapter.mjs", "snapshot.mjs", "engine/", "README.md"],
27
+ "exports": {
28
+ ".": "./index.ts",
29
+ "./tui": "./tui.tsx",
30
+ "./package.json": "./package.json"
31
+ },
32
+ "files": ["index.ts", "adapter.mjs", "snapshot.mjs", "events.mjs", "tui.tsx", "engine/", "README.md"],
28
33
  "engines": {
29
34
  "node": ">=18"
30
35
  },
31
36
  "peerDependencies": {
32
37
  "@opencode/plugin": "^2.0.0",
33
38
  "effect": "^4.0.0"
39
+ },
40
+ "devDependencies": {
41
+ "@opentui/solid": "^0.5.17",
42
+ "solid-js": "^1.9.12",
43
+ "typescript": "^5.9.2"
34
44
  }
35
45
  }
package/snapshot.mjs CHANGED
@@ -31,9 +31,10 @@
31
31
  * Search deviation (documented): upstream `search.mjs` scans positionally
32
32
  * (`events[seq]` with `event.seq === seq`, 0-based) over the array the
33
33
  * session yields, which can never match 1-based seqs. `searchSnapshot`
34
- * pads a dummy seq-0 entry so the verbatim `searchSession` contract holds,
35
- * then delegates — no forked search loop to hand-sync. Same hits, honest
36
- * seqs.
34
+ * leaves index 0 empty (a hole the engine skips via its own
35
+ * `event === undefined` guard) so the verbatim `searchSession` contract
36
+ * holds, then delegates — no forked search loop to hand-sync, no phantom
37
+ * hit, no stolen hit-slot or budget. Same hits, honest seqs.
37
38
  *
38
39
  * The session log is append-only: `snapshotNeedsWrite` is a growth guard
39
40
  * (version/count/lastID). In-place edits to middle messages are not
@@ -313,6 +314,65 @@ export function snapshotNeedsWrite(previous, next) {
313
314
  return next.lastID !== previous.lastID;
314
315
  }
315
316
 
317
+ // Tripwire for the O(n²) write-amplification watch: one full-envelope
318
+ // rewrite per turn, so warn when a single write exceeds ~1MB. Real
319
+ // sessions run ~5KB/message (tool-result JSON + reasoning), far above
320
+ // the 160B/message synthetic fillers the original thresholds assumed.
321
+ export const MAX_SNAPSHOT_WRITE_BYTES = 1000000;
322
+
323
+ /**
324
+ * Estimate the serialized size of a snapshot envelope.
325
+ * Unserializable input measures 0 (never trips; the write path
326
+ * warn-and-continues exactly like every other snapshot failure).
327
+ * @param envelope - the snapshot value about to be written.
328
+ * @returns JSON length in chars, or 0 when unserializable.
329
+ */
330
+ export function snapshotWriteBytes(envelope) {
331
+ try {
332
+ const text = JSON.stringify(envelope);
333
+ return typeof text === "string" ? text.length : 0;
334
+ } catch {
335
+ return 0;
336
+ }
337
+ }
338
+
339
+ export const WATCH_STATS_VERSION = 1;
340
+
341
+ /** Storage key prefix; full key is `${WATCH_STATS_KEY_PREFIX}${sessionID}`. */
342
+ export const WATCH_STATS_KEY_PREFIX = "vcc-stats/";
343
+
344
+ /**
345
+ * Fold one snapshot write into the O(n²) watch stats.
346
+ * Pure; malformed previous stats fold from zero (fail-soft, like every
347
+ * snapshot read path). Kept in a separate kv key so the snapshot envelope
348
+ * (and its recall/search/RPC readers) never changes shape.
349
+ * @param previous - stored stats value (or undefined on first write).
350
+ * @param writeBytes - serialized bytes of the write being recorded.
351
+ * @param now - current epoch ms.
352
+ * @returns `{ stats, changed }`: changed when a new max landed or the
353
+ * tripwire fired — the only cases the caller persists.
354
+ */
355
+ export function updateWatchStats(previous, writeBytes, now) {
356
+ const prev = previous !== null && typeof previous === "object" ? previous : {};
357
+ const prevMax = typeof prev.maxWriteBytes === "number" && prev.maxWriteBytes > 0 ? prev.maxWriteBytes : 0;
358
+ const prevTrips = typeof prev.tripCount === "number" && prev.tripCount > 0 ? Math.floor(prev.tripCount) : 0;
359
+ const prevTripAt = typeof prev.lastTripwireAt === "number" ? prev.lastTripwireAt : null;
360
+ const prevMaxAt = typeof prev.maxAt === "number" ? prev.maxAt : null;
361
+ const bytes = typeof writeBytes === "number" && writeBytes > 0 ? writeBytes : 0;
362
+ const tripped = bytes > MAX_SNAPSHOT_WRITE_BYTES;
363
+ const newMax = bytes > prevMax;
364
+ return {
365
+ stats: {
366
+ version: WATCH_STATS_VERSION,
367
+ maxWriteBytes: newMax ? bytes : prevMax,
368
+ maxAt: newMax ? now : prevMaxAt,
369
+ tripCount: prevTrips + (tripped ? 1 : 0),
370
+ lastTripwireAt: tripped ? now : prevTripAt,
371
+ },
372
+ changed: newMax || tripped,
373
+ };
374
+ }
375
+
316
376
  /**
317
377
  * Map one cleaned part to a recall block.
318
378
  * @param part - cleaned part.
@@ -456,8 +516,13 @@ export function recallFromSnapshot(cleanedMessages, selections, maxRecallTokens
456
516
 
457
517
  /**
458
518
  * Search a snapshot for a pattern by delegating to the verbatim
459
- * `searchSession`: pad a dummy seq-0 entry so the positional
460
- * `events[seq]` + `seq === seq` contract holds for 1-based seqs.
519
+ * `searchSession`: leave index 0 empty (a hole, not a dummy event) so the
520
+ * positional `events[seq]` + `seq === seq` contract holds for 1-based seqs
521
+ * while the hole itself is skipped by the engine's own
522
+ * `event === undefined` guard — it can never match, never consume a
523
+ * maxSearchHits slot, and never burn search budget. A defensive
524
+ * seq-0 filter stays on the output in case the vendored engine ever
525
+ * changes shape.
461
526
  * @param cleanedMessages - snapshot `messages`.
462
527
  * @param patternSource - raw regex/keyword.
463
528
  * @param config - `{ maxSearchHits, maxRecallTokens }` (defaults to engine defaults).
@@ -473,27 +538,28 @@ export function searchSnapshot(cleanedMessages, patternSource, config = {}) {
473
538
  : DEFAULT_MAX_RECALL_TOKENS;
474
539
  const inner = makeSnapshotSession(cleanedMessages);
475
540
  const live = inner.snapshotEvents();
476
- const padded = [{ seq: 0, type: "session.created", data: {} }, ...live];
477
- const paddedSession = {
541
+ const aligned = [undefined, ...live];
542
+ const alignedSession = {
478
543
  snapshotEvents() {
479
- return padded;
544
+ return aligned;
480
545
  },
481
546
  eventAt(seq) {
482
- if (seq === 0) return padded[0];
547
+ if (seq === 0) return undefined;
483
548
  return inner.eventAt(seq);
484
549
  },
485
550
  get events() {
486
- return padded;
551
+ return aligned;
487
552
  },
488
553
  deriveEventMessage(event) {
489
- if (event?.seq === 0) return null;
554
+ if (event === undefined || event === null) return null;
490
555
  return inner.deriveEventMessage(event);
491
556
  },
492
557
  };
493
- const out = searchSession(paddedSession, patternSource, { maxSearchHits, maxRecallTokens });
494
- // The seq-0 pad satisfies the verbatim positional scan but must never
495
- // surface: seq 0 is unrecallable (`parseSeqSpec` rejects it), so drop any
496
- // phantom hit and rebuild the summary around the live hits.
558
+ const out = searchSession(alignedSession, patternSource, { maxSearchHits, maxRecallTokens });
559
+ // Defense in depth: the index-0 hole can never surface as a hit (the
560
+ // engine skips it before matching), but seq 0 is unrecallable
561
+ // (`parseSeqSpec` rejects it), so drop any phantom hit and rebuild the
562
+ // summary around the live hits.
497
563
  const hits = out.hits.filter((hit) => hit.seq !== 0);
498
564
  const dropped = out.hits.length - hits.length;
499
565
  const totalMatches = out.totalMatches - dropped;
package/tui.tsx ADDED
@@ -0,0 +1,52 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+
3
+ import { Plugin } from "@opencode/plugin/tui"
4
+ import { isReplyPayload, MAX_TOAST_TEXT, replyEventType } from "./events.mjs"
5
+
6
+ // opencode-vcc-compaction TUI companion: quiet visible output for the
7
+ // server /vcc-* commands. The server emits
8
+ // `rpc.opencode-vcc-compaction.replied` and returns void (no wake, no
9
+ // chatter); this listener toasts/dialogs the reply. No keymap commands:
10
+ // slash lookup has no session context, and none is needed — the event
11
+ // carries its session. (ODF tui.tsx pattern: dialog.alert large +
12
+ // centered for long content.)
13
+
14
+ const replyType = replyEventType()
15
+
16
+ export default Plugin.define({
17
+ id: "opencode-vcc-compaction",
18
+ setup(ctx) {
19
+ ctx.data.listen((event) => {
20
+ try {
21
+ const details = (event as { details?: unknown }).details as
22
+ | { type?: unknown; data?: unknown }
23
+ | undefined
24
+ if (details?.type !== replyType) return
25
+ const payload = (details as { data?: unknown }).data
26
+ // Runtime shape already validated; the guard lives in untyped
27
+ // .mjs (no node_modules for real types), so narrow by cast.
28
+ if (!isReplyPayload(payload)) return
29
+ const reply = payload as { sessionID: string; command: string; text: string }
30
+ const title = `vcc ${reply.command}`
31
+ if (reply.text.length < MAX_TOAST_TEXT) {
32
+ // Host-native attribution: the toast ties itself to the
33
+ // reply's session (session title + open offer when its family
34
+ // is not open). Dialogs have no such option (see below).
35
+ void ctx.ui.toast.show({ title, message: reply.text, variant: "info", sessionID: reply.sessionID })
36
+ return
37
+ }
38
+ // ODF dialog pattern: alert, then presentation, then drop the handle.
39
+ // Broadcast by design: DialogAlertOptions carries no sessionID, so a
40
+ // long reply dialogs in whatever session is viewed. Suppression was
41
+ // considered (via ctx.ui.router.current()) and rejected — a user who
42
+ // fires /vcc-recall and switches sessions mid-flight should still
43
+ // see the answer, and the title names the command.
44
+ const shown = ctx.ui.dialog.alert({ title, message: reply.text })
45
+ ctx.ui.dialog.set({ size: "large", centered: true })
46
+ void shown
47
+ } catch (error) {
48
+ console.warn("[opencode-vcc-compaction] reply render failed:", error)
49
+ }
50
+ })
51
+ },
52
+ })