Repository navigation
feat: improvement sprint — cache-safe injection, memory-aware compaction, opt-in capture, portability - #4
Merged
Merged
Conversation
Removes the dead V1 SDK (@opencode-ai/[email protected], no file imported it) and adds @opencode/plugin@^2.0.32 as a devDependency. The exported plugin object is now pinned against the real SDK contract at compile time. Deviations from the plan (rule 8: adapt minimally to runtime reality): 1. Type-only import instead of a value import of Plugin.define (a variant of the documented fallback; the plain { id, setup } object is kept). The plan pins @opencode/plugin as a DEV dependency, but a value import would need it at runtime: opencode installs npm plugins into an isolated cache containing runtime dependencies only (~/.cache/opencode/npm/<pkg>@<ver>/<ts>/node_modules, verified on this machine), so 'import { Plugin } from "@opencode/plugin"' would MODULE_NOT_FOUND at plugin load for every published consumer - and the planned local-path smoke test would never catch it. The official V2 docs (Publish section) require the SDK as a runtime dependency for package plugins, but that would pull effect + @opencode/client into every install, re-creating the dead-weight this phase removes. Plugin.define is an identity function at runtime, so 'const plugin: Plugin = { id, setup }' with a type-only import gives the identical compile-time contract for zero runtime cost and zero install cost. 2. The contract interface is imported from '@opencode/plugin/promise/plugin': the package main entry re-exports Plugin as a namespace, which TypeScript 7 (tsgo) refuses to use as a type annotation. 3. The setup body was kept byte-identical inside a private 'impl' holder (instead of being re-indented into a standalone setupImpl function) to keep the diff auditable: only the wrapper lines changed. Gate: bun test 84 pass / 4 skip / 0 fail; bunx tsc --noEmit clean; grep for @opencode-ai/plugin across .ts/.json is empty.
…(cache-safe)
The injected 'Relevant durable memory' block is now frozen per session epoch.
An epoch is invalidated ONLY on (a) the first prompt of the session, (b) the
memory store changing since the epoch was computed (fingerprint
`${activeCount}:${maxActiveTs}` from storeVersion()), or (c) a compaction for
that session. Relevance is scored against the prompt that STARTED the epoch -
accepted staleness, documented at the prompt hook - traded for a stable system
prefix so the provider prompt cache survives ordinary turns.
- src/inject.ts: +storeVersion(), +capToBudget() (whole-line truncation, ''
when even the header exceeds the budget); relevantKnowledge() signature and
contextualPull() unchanged.
- src/config.ts: +injectBudget() - OPENCODE_MEMORY_INJECT_BUDGET, default 1200.
- src/index.ts: epoch Map replaces pendingKnowledge; prompt hook recomputes
only on invalidation and records ev=epoch_recompute
{session,reason:first|store_changed,chars}; context hook delivers
epoch.get(sid)?.block; compaction hook drops the epoch; budget read once at
setup from ctx.options.injectBudget (object form in opencode.json(c)),
falling back to injectBudget().
- test/epoch.test.ts (new): the four contract cases (frozen across prompts;
store-change invalidation; compaction invalidation; budget respected at
whole-line boundaries with 20 matching memories) plus unit coverage for
capToBudget/injectBudget/storeVersion and epoch_recompute evidence lines.
No existing tests needed updating: gated-injection.test.ts and
scenarios.test.ts exercise module-level functions, not the prompt hook, and
plugin.test.ts's delivery tests already match the epoch policy (first prompt
computes and delivers). Production invariants unchanged: hooks stay fail-closed
via guarded(), event.prompt.text is only read, evidence stays out of context
(I3), store stays outside repos (I2).
Gate: bun test 92 pass / 4 skip / 0 fail (baseline 84/4/0 + 8 new);
bunx tsc --noEmit clean; sanity bun test test/epoch.test.ts
test/gated-injection.test.ts test/inject.test.ts green.
compactionAnchor() (src/inject.ts) builds a '## Durable memory to preserve in
this summary' block (up to 10 open threads newest-first + up to 5 newest
settled, capToBudget 2500, "" when no active memories) and the session
compaction hook pushes it as a {type:"text"} system part AFTER onCompacting,
so the summarizer model sees durable facts (compaction-amnesia fix). event
.result is never set (the summarizer call is not skipped).
Deviations (plan section 8):
- compactionAnchor(limit=12): 'limit' is interpreted as the TOTAL row cap
(open rows take priority up to 10, settled fill the rest up to 5); the
plan fixed the section sizes and the param but not their interaction.
- test/harness.ts V1 compaction adapter now passes {sessionID, system: []}
and copies pushed part texts onto output.system when the caller provided
an array (mirrors the context adapter); callers passing only {context}
are unaffected, so existing contract tests stay green unchanged.
- Added a third case beyond the plan's two: anchor capped at 2500 chars at
whole-line boundaries.
Gate: bun test 95 pass / 4 skip / 0 fail (baseline 92+4, +3 new); tsc clean.
Default OFF (zero-token installs never call ctx.event.subscribe). When options.autoCapture === true AND captureModel parses as provider/id, setup subscribes to session events; each session.idle (5-min per-session cooldown) flattens the transcript, runs ONE cheap ctx.generate.text call, and feeds the parsed candidates through the existing runWriteGate (tag auto-capture, evidence auto_capture_<action>) — capture can never write outside the gate and swallows all its own errors. setup now returns a single cleanup fn that aborts the subscription; an invalid/missing captureModel logs one console.warn and skips registering the subscription entirely. New pure core src/capture.ts (buildCapturePrompt, parseCandidates, parseModelRef, flattenTranscript — all total, never throw) + test/capture.test.ts (17 cases incl. end-to-end dupe-collapse, cooldown, default-OFF, cleanup). Deviations (plan section 8): - TYPES/STATUSES moved from index.ts to new src/types.ts (plan allowed config.ts or types.ts; types.ts keeps config.ts path/env-only). - buildCapturePrompt takes an optional 2nd arg max=3 so the prompt states the configured captureMax (plan's 1-arg signature could not know it). - CaptureCandidate.status is typed "open"|"settled" (plan: string), narrowed during parsing for the WriteCandidate boundary. - Harness fake event queue is an async GENERATOR: Bun 1.4.3 drops async [Symbol.asyncIterator] methods from transpiled object literals (found by a red test; async-generator form works and matches the AsyncIterable contract). Gate: bun test 112 pass / 4 skip / 0 fail (Phase-3 baseline 95, +17 new); tsc clean; plugin.test.ts 9-tool assertion untouched.
The harness fakes are closures, so the detached assignment passed tests, but a real client method reading `this` would fail inside the fail-closed catch and silently disable capture. Call through an arrow with optional chaining (receiver preserved; undefined degrades to an empty transcript). ctx.event/ctx.generate were already called with receivers preserved.
Phase 5 (portability). src/portable.ts: exportMemories writes the ACTIVE
store as JSONL ({ts,type,scope,content,status,tags,issue}) to
memoryRoot()/exports/<YYYY-MM-DDTHHMMSS>.jsonl by default; importMemories
reads JSONL, skips malformed lines (bad JSON, unknown type, empty
scope/content) into a tally, and runs every valid row through a typed
gate callback — index.ts wires it to runWriteGate, so imports face the
same 4 gates as any write (blocked/collapsed are tallied outcomes, only a
missing file throws); findStaleOpen(days) returns active open rows older
than the cutoff, oldest first.
Three new tools (options: direct), tool-list assertion updated to 12:
memory_export, memory_import, memory_decay.
Decay details:
- dryRun DEFAULTS to true (only an explicit false mutates); dry-run lists
the stale rows and writes only an evidence line (decay_dry_run).
- A real run snapshots BEFORE any mutation by calling snapshotFiles() —
the same helper prune() uses in memory.ts (prune.ts reaches it via
prune()); markSuperseded's internal per-row snapshot still applies too.
- Rows are superseded, never deleted: markSuperseded(ts,
{superseded_by: "decay", reason: "decay"}) — idempotent, recoverable
via memory_undo; one decay_applied evidence line per run with the
retired ts list and snapshot paths.
Deviations from the plan (minimal, documented):
- The import gate callback MERGES the row's original tags with "import"
instead of replacing them with ["import"], so provenance tags survive
an export->import round trip; dedup is unaffected (GATE-3 compares
type+content only).
- superseded_by has no successor row for decay, so it carries the
literal "decay" (reason is also "decay").
- Dry-run records decay_dry_run evidence (plan specified only
decay_applied); it mutates no store data.
Tests: test/portable.test.ts (12 cases: export shape/filter/empty,
import malformed/sanitize/tally/missing-file, findStaleOpen ordering,
tool round-trip incl. fresh-store import + dedupe on re-import, decay
dry-run/real-run/threshold/idempotence). Import tests ground the session
with a tool.execute.after read (GATE-4 engagement, same pattern as
test/capture.test.ts) — intended gate behavior, not weakened.
Gate: 124 pass / 4 skip / 0 fail, tsc clean.
Phase 6 (part 1). bench/inject-cost.ts measures the pre-0.2 injection policy (recompute top-3 per prompt, uncapped) against the shipped one (epoch freeze via the real storeVersion() + the real capToBudget() at the default 1200-char budget, 3 mid-session store writes) over 50 seeded memories and 20 prompts, and reports chars/turn, worst-case block, and the compaction anchor size. Prints a markdown table and writes bench/RESULTS.md (committed). Determinism: fixed-seed LCG (no Math.random), synthetic memory timestamps, no wall clock anywhere in the output — two consecutive runs are byte-identical (stdout and RESULTS.md). Measured: 27748 -> 20654 chars over 20 turns (-25.6%), worst block 1575 -> 1157, recomputes 20 -> 4, anchor 2249 chars. Also: "bench" script in package.json (scripts only, version untouched); tsconfig include gains bench/ so the gate typechecks the script (minimal deviation from the plan, keeps the new file under the same quality gate as src/).
…ions Phase 6 (part 2). README gains a 'Token cost, on purpose' section with the measured bench table (bun bench/inject-cost.ts, byte-reproducible) and the epoch-freeze/budget/cache-safety rationale, an 'Options' section for the object form of the plugin entry in opencode.json(c) (injectBudget, autoCapture, captureModel, captureMax — auto-capture OFF by default), and feature bullets for memory-aware compaction, JSONL export/import, and decay. Existing structure and tone kept; tagline unchanged; no announcement content.
…apture troubleshooting row
|
🎉 This PR is included in version 0.2.0 🎉 The release is available on: Your semantic-release bot 📦🚀 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this is
The improvement sprint from
opencode-self-improvement-plan.md: everything that makes the memory layer cheaper, compaction-safe, and portable — with measured numbers. No breaking changes; zero-config default behavior is unchanged and stays zero-token.Changes
be53e90@opencode/pluginis now a devDependency used type-only — a value import would break published installs because opencode installs npm plugins with runtime deps only. Zero runtime deps remains true.ef2f4bfinjectBudgetoption /OPENCODE_MEMORY_INJECT_BUDGET).48844d2compactionhook's system parts, so summaries preserve them. Never overrides the summarizer call.fed7539autoCapture+captureModel): on session idle, one cheapctx.generate.textpass proposes candidates — every one goes through the same 4-gate write pipeline, 5-minute per-session cooldown, all failures swallowed. Default off.3c20c9esession.contextreceiver-bound in the capture loop (harness fakes are closures; a real client readingthiswould fail silently behind the fail-closed catch).e038abamemory_export/memory_import(JSONL; imported rows re-enter through the write gates) andmemory_decay(retires stale open threads; dry run by default, snapshot-first, supersede-not-delete, undoable).669851c,97ce45f,ebda44abench/inject-cost.ts(deterministic, byte-identical reruns) + README cost model, Options table, and feature bullets.Measured cost (real injection code, deterministic workload)
50 memories, 20 prompts, 3 mid-session store writes, default 1200-char budget:
25.6% fewer injected characters — and the bigger win is structural: B's block is byte-identical between store changes, so the prompt-cache prefix stays warm across ordinary turns. Reproduce with
bun bench/inject-cost.ts.Verification
bun test: 128 tests (was 96 pre-sprint), 4 skip, 0 fail;bunx tsc --noEmitclean at every commit.epoch_recomputeevidence emitted; all 12memory_*tools registered.Notes for review
memory_export,memory_import,memory_decay(9 → 12).0.2.0; a small follow-up will bump the README install pins.