diff --git a/packages/core/src/plugin/provider/opencode-memory-capture.ts b/packages/core/src/plugin/provider/opencode-memory-capture.ts new file mode 100644 index 00000000000..01c06fcce24 --- /dev/null +++ b/packages/core/src/plugin/provider/opencode-memory-capture.ts @@ -0,0 +1,118 @@ +export * as OpencodeMemoryCapture from "./opencode-memory-capture.js" + +import { Option, Schema } from "effect" + +/** + * One thing a session did, as the harness saw it: recorded every turn, mechanically, without a model. `prompt` is the + * user's message, `shell` a finished command, `edit` and `read` the files a tool changed or read, `commit` a commit + * the session made, `subtask` a subagent finishing, `compaction` the conversation being compacted. + */ +export type Event = + | { readonly type: "prompt"; readonly text: string; readonly correction: boolean } + | { + readonly type: "shell" + readonly command: string + readonly exit: number + readonly failed: boolean + readonly test: boolean + /** The end of what it printed, where errors and test results are. */ + readonly tail: string + } + | { readonly type: "edit"; readonly files: ReadonlyArray } + | { readonly type: "read"; readonly files: ReadonlyArray } + | { readonly type: "commit"; readonly sha: string } + | { readonly type: "subtask" } + | { readonly type: "compaction" } + +/** A work-unit boundary the harness sees, where what happened since the last one may hold a lesson. */ +export type Boundary = "task" | "commit" | "test" | "correction" | "subtask" | "compaction" + +/** + * The boundary `event` closes after `segment`, the events since the last one, or undefined. A new task message, a + * commit, a test-like run passing after one failed, a user's correction, a subagent finishing, and compaction as a + * backstop. Only a commit or a passing run closes a segment without work (no command run, no file changed): a message + * that reads as a correction corrects work. + */ +export function boundary(segment: ReadonlyArray, event: Event): Boundary | undefined { + const worked = segment.some((item) => item.type === "shell" || item.type === "edit") + if (event.type === "commit") return "commit" + if (event.type === "shell" && event.test && !event.failed) + return segment.some((item) => item.type === "shell" && item.test && item.failed) ? "test" : undefined + if (!worked) return undefined + if (event.type === "prompt") return event.correction ? "correction" : "task" + if (event.type === "subtask") return "subtask" + if (event.type === "compaction") return "compaction" + return undefined +} + +const MAX_LOG = 16_000 + +/** The segment as the distiller reads it: one line per event, newest kept when it's long. */ +export function render(segment: ReadonlyArray) { + const lines = segment.map((event, index) => { + const at = `#${index + 1}` + if (event.type === "prompt") return `${at} user${event.correction ? " (correcting)" : ""}: ${event.text}` + if (event.type === "shell") + return `${at} ran \`${event.command}\` → exit ${event.exit}${event.failed ? " FAILED" : ""}\n${event.tail}` + if (event.type === "edit") return `${at} changed ${event.files.join(", ")}` + if (event.type === "read") return `${at} read ${event.files.join(", ")}` + if (event.type === "commit") return `${at} committed ${event.sha}` + if (event.type === "subtask") return `${at} a subtask finished` + return `${at} the conversation was compacted` + }) + const kept = lines.reduceRight( + (all, line) => (all.join("\n").length + line.length > MAX_LOG ? all : [line, ...all]), + [], + ) + return kept.join("\n") +} + +/** The distiller's instructions: at most a few typed candidates, usually none. */ +export function prompt(input: { readonly segment: ReadonlyArray; readonly boundary: Boundary }) { + return [ + "You read the record of a coding agent's work since its last work boundary and propose lessons for the team's shared memory. Most records yield nothing: then answer {\"candidates\": []}.", + "Propose only a verified, non-obvious finding that an agent on a DIFFERENT task in this repository would need, as it holds for the repository as committed: a cause found behind a failure, a dead end and why, a command or setting the repository needs, a correction the user made. Use only what the record shows; never guess. Never: task status or a summary of the change, what the code or docs already say, facts about this machine, files the agent added and didn't commit, secrets.", + 'Answer only JSON: {"candidates": [{"kind": "bug|convention|procedure|gotcha|decision|failed-approach", "title": "...", "body": "...", "paths": ["repository-relative paths"], "errors": ["exact error messages"]}]}, at most 2. Each body has these lines: Claim: / Applies when: / Action: / Verify: (or Avoid:) / Anchors: / Evidence:.', + `The boundary: ${input.boundary}.`, + "The record:", + render(input.segment), + ].join("\n\n") +} + +const Candidate = Schema.Struct({ + kind: Schema.Literals(["bug", "convention", "procedure", "gotcha", "decision", "failed-approach"]), + title: Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(200)), + body: Schema.String.check(Schema.isNonEmpty()), + paths: Schema.optional(Schema.Array(Schema.String)), + errors: Schema.optional(Schema.Array(Schema.String)), +}) +export type Candidate = typeof Candidate.Type +const Distilled = Schema.Struct({ candidates: Schema.Array(Schema.Unknown) }) + +/** The candidates in the distiller's answer that have every field right; the rest, and anything unparsable, dropped. */ +export function candidates(text: string): ReadonlyArray { + const json = text.slice(text.indexOf("{"), text.lastIndexOf("}") + 1) + return Option.match(Schema.decodeUnknownOption(Schema.fromJsonString(Distilled))(json), { + onNone: () => [], + onSome: (answer) => + answer.candidates.flatMap((item) => Option.toArray(Schema.decodeUnknownOption(Candidate)(item))), + }).slice(0, 2) +} + +/** + * What outside the agent's own say-so the segment shows, for Console to weigh: commits it made and test-like commands + * that passed after failing. In-session passes alone are weak evidence; Console holds candidates until stronger + * evidence arrives (a commit that survives with CI, a user's confirmation, the same lesson from other sessions). + */ +export function evidence(segment: ReadonlyArray) { + const failing = new Set() + return segment.flatMap((event): Array<{ readonly kind: "commit" | "test"; readonly ref: string }> => { + if (event.type === "commit") return [{ kind: "commit", ref: event.sha }] + if (event.type !== "shell" || !event.test) return [] + if (event.failed) { + failing.add(event.command) + return [] + } + return failing.size > 0 ? [{ kind: "test", ref: event.command.slice(0, 500) }] : [] + }) +} diff --git a/packages/core/src/plugin/provider/opencode-memory-policy.ts b/packages/core/src/plugin/provider/opencode-memory-policy.ts index 1e90aeabca6..26ab4de5e8f 100644 --- a/packages/core/src/plugin/provider/opencode-memory-policy.ts +++ b/packages/core/src/plugin/provider/opencode-memory-policy.ts @@ -65,18 +65,6 @@ export interface Signals { readonly injected: { readonly prompt: number; readonly failure: number } } -/** - * The session's test-like runs and edits, in the order its tools finished, for telling whether it verified a fix or - * worked past a dead end. - */ -export interface Work { - /** Tool calls finished so far; each run and edit is numbered by it. */ - readonly step: number - /** The step of the last file change, or -1 before any. */ - readonly lastEdit: number - readonly tests: ReadonlyArray<{ readonly step: number; readonly failed: boolean }> -} - /** What a session can tell Console about its work besides the query, as Console's inject and search take it. */ export interface Context { readonly repo?: string @@ -123,13 +111,8 @@ export interface Policy { readonly nudge: (entry: Given) => string /** Whether a command is a test or build run, the kind that tells whether a fix worked. Runs on every shell command. */ readonly test: (command: string) => boolean - /** - * What, in the session's work, may be worth publishing once its task is done: a verified fix or a dead end worked - * past, described for the reminder, or undefined for nothing. - */ - readonly lesson: (work: Work) => string | undefined - /** The one reminder a session gets when it would go idle after such work. */ - readonly reminder: (lesson: string) => string + /** Whether a user's message reads as correcting the agent. Runs on every prompt, so it must be cheap. */ + readonly corrective: (message: string) => boolean } // Placeholders until the retrieval benchmark and the correction study set them. @@ -200,19 +183,7 @@ export const initial: Policy = { .toSorted((a, b) => b.shared.length - a.shared.length)[0]?.entry }, test: (command) => TEST.test(command), - // The publish audit's WB2 triggers (bench/library/writes): a test-like run failing before the last edit and passing - // after it, or several failing runs before a passing one. - lesson: (work) => { - const passed = work.tests.find((test) => !test.failed && test.step > work.lastEdit) - if (passed === undefined) return undefined - if (work.tests.some((test) => test.failed && test.step < work.lastEdit)) - return "verified fix (tests that failed now pass)" - if (work.tests.filter((test) => test.failed && test.step < passed.step).length >= 2) - return "dead end you worked past (several failing attempts before a passing run)" - return undefined - }, - reminder: (lesson) => - `This session had a ${lesson}. If it taught something an agent on a different task in this repository would need, and it isn't already in the code, docs or memory, you may publish it with memory publish, following its template, as it holds for the repository as committed (not files or settings you added). Most sessions publish nothing; then just say so. Don't change the code any more.`, + corrective: (message) => CORRECTION.test(message), nudge: (entry) => `The user's last message may correct memory entry ${entry.id} r${entry.revision} "${line(entry.title)}". If it does, fix that entry now with memory \`edit\` (only the changed text, revision ${entry.revision}); otherwise ignore this.`, } diff --git a/packages/core/src/plugin/provider/opencode-memory.ts b/packages/core/src/plugin/provider/opencode-memory.ts index fd25a610c99..36475fd6707 100644 --- a/packages/core/src/plugin/provider/opencode-memory.ts +++ b/packages/core/src/plugin/provider/opencode-memory.ts @@ -16,7 +16,9 @@ import { ChildProcess } from "effect/process" import { Git } from "../../git.js" import { AbsolutePath } from "../../schema.js" import { normalizeContent } from "../../tool/runtime.js" +import { Flag } from "../../flag.js" import { OpencodeMemoryAccess } from "./opencode-memory-access.js" +import { OpencodeMemoryCapture } from "./opencode-memory-capture.js" import { OpencodeMemoryPolicy } from "./opencode-memory-policy.js" import { OpencodeWatches } from "./opencode-watches.js" @@ -29,8 +31,12 @@ const MAX_FILES = 20 /** Entries a session was given that a correction may name, and how much of each is kept to match it. */ const MAX_GIVEN = 10 const MAX_GIVEN_TEXT = 2000 -/** Test-like runs a session's publish reminder looks back over. */ -const MAX_TESTS = 50 +/** Events kept in memory since a session's last boundary; the log keeps them all. */ +const MAX_SEGMENT = 200 +/** Distillations per session: one per boundary, at most this many. */ +const MAX_DISTILLATIONS = 20 +/** The end of a command's output an event keeps. */ +const MAX_TAIL = 1500 /** How long the workspace's list of restricted repositories is reused before Console is asked again. */ const ANCHORS_MAX_AGE = 60 * 1000 /** The most repositories a reader's reachable set names, as Console takes it. */ @@ -165,10 +171,12 @@ type Tracked = { compactions: number /** A compaction ended since the delivered entries were last given. */ redeliver?: boolean - /** Test-like runs and edits, for the publish reminder. */ - readonly work: { step: number; lastEdit: number; readonly tests: Array<{ step: number; failed: boolean }> } - /** The session had its publish reminder. */ - reminded?: boolean + /** The session's events since its last work boundary, and where they start in its log. */ + readonly segment: Array + from: number + /** The next position in the session's event log, read from storage on its first event in this process. */ + next?: number + distillations: number /** The session took in outside input, so what it publishes is marked tainted and never promoted. */ tainted?: boolean task?: string @@ -195,6 +203,7 @@ export const make = Effect.fnUntraced(function* ( const scope = yield* Scope.Scope const git = yield* Git.Service const processes = yield* AppProcess.Service + const flags = yield* Flag.Service const github = OpencodeMemoryAccess.make(http, processes, yield* OpencodeMemoryAccess.GitHub) let current: { console: OpencodeWatches.Console; readonly lease: Scope.Closeable } | undefined const sessions = new Map() @@ -207,7 +216,9 @@ export const make = Effect.fnUntraced(function* ( shown: new Map(), delivered: new Map(), compactions: 0, - work: { step: 0, lastEdit: -1, tests: [] }, + segment: [], + from: 0, + distillations: 0, } sessions.delete(sessionID) sessions.set(sessionID, found) @@ -295,6 +306,14 @@ export const make = Effect.fnUntraced(function* ( }) }) + // The checkout's current commit, after the session committed. + const head = Effect.gen(function* () { + const result = yield* processes.run( + ChildProcess.make("git", ["rev-parse", "HEAD"], { cwd: (yield* roots).checkout, stdin: "ignore" }), + ) + return result.exitCode === 0 ? result.stdout.toString().trim() : undefined + }).pipe(Effect.orElseSucceed(() => undefined)) + /** * Refuses a write whose `paths` name a repository path that isn't there. Only clear paths (with a `/`) are checked: * globs, dotted module names and root files are taken as given, and git-ignored or generated files pass, as the @@ -471,8 +490,98 @@ export const make = Effect.fnUntraced(function* ( ...(input.errors === undefined ? {} : { errors: input.errors }), }) + // The model distillation runs on: a DeepSeek flash model when one is available, else OpenCode's default. + const distiller = yield* Effect.cached( + ctx.model.list({ types: ["chat"] }).pipe( + Effect.map((models) => { + const found = models.data.find((model) => /deepseek/i.test(model.id) && /flash/i.test(model.id)) + return found === undefined ? undefined : { id: found.id, providerID: found.providerID } + }), + Effect.orElseSucceed(() => undefined), + ), + ) + + /** + * Distils the segment a boundary closed into candidate entries, out of band (a stateless generation, nothing in the + * coding session), and sends each that passes the write checks to Console as pending, with the segment's evidence. + */ + const distill = ( + sessionID: Session.ID, + segment: ReadonlyArray, + boundary: OpencodeMemoryCapture.Boundary, + events: { readonly from: number; readonly to: number }, + ) => + Effect.gen(function* () { + const model = yield* distiller + const answer = yield* ctx.experimental.generate.text({ + prompt: OpencodeMemoryCapture.prompt({ segment, boundary }), + ...(model === undefined ? {} : { model }), + }) + const found = OpencodeMemoryCapture.candidates(answer.text) + if (found.length === 0) return + const source = yield* checkout + const anchor = + "repo" in source && source.repo + ? yield* anchored(source.repo.slice("https://".length)).pipe(Effect.orElseSucceed(() => undefined)) + : undefined + // Without its repository's id, who may read a candidate from a repository can't be recorded: none is sent. + if ("repo" in source && source.repo && anchor === undefined) return + const evidence = OpencodeMemoryCapture.evidence(segment) + yield* Effect.forEach(found, (candidate, index) => + Effect.gen(function* () { + const fields = yield* shared("publish", { ...metadata(candidate), body: candidate.body }) + yield* resolved("publish", Schema.decodeUnknownOption(Paths)(fields.paths).pipe(Option.getOrUndefined)) + yield* committed("publish", fields) + yield* call(Schema.Struct({ id: Schema.optional(Schema.String) }), "POST", "/api/memory/candidates", { + sessionID, + boundary, + ...fields, + ...(evidence.length === 0 ? {} : { evidence }), + events, + source: { ...source, sessionID }, + ...(anchor === undefined ? {} : { anchor }), + ...(tracked(sessionID).tainted ? { tainted: true } : {}), + ...(yield* reader), + idempotencyKey: `${sessionID}:${events.from}:${index}`.slice(0, 128), + }) + }).pipe(Effect.catch((cause) => Effect.logDebug("memory candidate not sent", { cause }))), + ) + }).pipe(Effect.catch((cause) => Effect.logDebug("memory distillation failed", { cause }))) + const start = Effect.fnUntraced(function* () { const lease = yield* Scope.Scope + const capturing = yield* flags.enabled("memory_capture") + /** + * Appends `event` to the session's event log, which only this plugin writes and nothing ever rewrites, and, when it + * closes a work boundary, distils what happened since the last one in the background. + */ + const record = (sessionID: Session.ID, event: OpencodeMemoryCapture.Event) => + Effect.gen(function* () { + if (!capturing) return + const state = tracked(sessionID) + const head = `memory-log-head:${sessionID}` + const at = + state.next ?? Option.getOrElse(Schema.decodeUnknownOption(Schema.Int)(yield* ctx.storage.get(head)), () => 0) + state.next = at + 1 + yield* ctx.storage.set(`memory-log:${sessionID}:${String(at).padStart(10, "0")}`, event) + yield* ctx.storage.set(head, at + 1) + const boundary = OpencodeMemoryCapture.boundary(state.segment, event) + // A new task message starts the next segment; every other boundary event ends the one it closes. + const closes = event.type === "prompt" && boundary === "task" ? [] : [event] + if (boundary === undefined) { + if (state.segment.length === 0) state.from = at + state.segment.push(event) + if (state.segment.length > MAX_SEGMENT) state.segment.splice(0, state.segment.length - MAX_SEGMENT) + return + } + const segment = [...state.segment, ...closes] + const events = { from: state.from, to: closes.length === 0 ? at - 1 : at } + state.segment.splice(0, state.segment.length, ...(closes.length === 0 ? [event] : [])) + state.from = closes.length === 0 ? at : at + 1 + if (state.distillations >= MAX_DISTILLATIONS) return + state.distillations++ + yield* distill(sessionID, segment, boundary, events).pipe(Effect.forkIn(lease, { startImmediately: true })) + }).pipe(Effect.catch((cause) => Effect.logDebug("failed to record a session event", { cause }))) // Read now, so the first moment doesn't wait on Git or GitHub. yield* repository.pipe(Effect.forkIn(lease, { startImmediately: true })) yield* reachable.pipe(Effect.forkIn(lease, { startImmediately: true })) @@ -524,6 +633,11 @@ export const make = Effect.fnUntraced(function* ( state.task ??= event.prompt.text const corrected = policy.correction(event.prompt.text, [...state.given.values()]) if (corrected) state.nudge = { entry: corrected, messageID: event.messageID } + yield* record(event.sessionID, { + type: "prompt", + text: event.prompt.text.slice(0, MAX_TAIL), + correction: corrected !== undefined || policy.corrective(event.prompt.text), + }) yield* begin(event.sessionID, { type: "prompt", text: event.prompt.text, @@ -543,15 +657,18 @@ export const make = Effect.fnUntraced(function* ( yield* ctx.tool.hook("execute.after", (event) => { if (event.status !== "completed") return Effect.void const files = touched(event.tool, event.input).map((file) => relative(ctx.location.directory, file)) - const work = tracked(event.sessionID).work - work.step++ + const recorded = + files.length > 0 + ? record(event.sessionID, { type: event.tool === "read" ? "read" : "edit", files }) + : event.tool === "subagent" + ? record(event.sessionID, { type: "subtask" }) + : Effect.void if ( event.tool === "webfetch" || event.tool === "websearch" || (event.tool === "read" && files.some((file) => path.isAbsolute(file))) ) tracked(event.sessionID).tainted = true - if (event.tool !== "read" && files.length > 0) work.lastEdit = work.step if (files.length > 0) { const state = tracked(event.sessionID) files.forEach((file) => { @@ -560,18 +677,33 @@ export const make = Effect.fnUntraced(function* ( }) state.files.splice(0, Math.max(0, state.files.length - MAX_FILES)) } - if (event.tool !== "shell") return Effect.void + if (event.tool !== "shell") return recorded const shell = Option.all({ input: Schema.decodeUnknownOption(ShellInput)(event.input), output: Schema.decodeUnknownOption(ShellOutput)(event.result.output), }) // A command still running in the background, or one a signal ended, has no exit code yet. if (Option.isNone(shell) || shell.value.output.exitCode === null) return Effect.void - if (OUTSIDE.test(shell.value.input.command)) tracked(event.sessionID).tainted = true - const failed = policy.failed(shell.value.input.command, shell.value.output.output, shell.value.output.exitCode) - if (policy.test(shell.value.input.command)) work.tests.push({ step: work.step, failed }) - if (work.tests.length > MAX_TESTS) work.tests.splice(0, work.tests.length - MAX_TESTS) - if (!failed) return Effect.void + const command = shell.value.input.command + const exitCode = shell.value.output.exitCode + if (OUTSIDE.test(command)) tracked(event.sessionID).tainted = true + const failed = policy.failed(command, shell.value.output.output, exitCode) + const ran = record(event.sessionID, { + type: "shell", + command: command.slice(0, MAX_TAIL), + exit: exitCode, + failed, + test: policy.test(command), + tail: shell.value.output.output.slice(-MAX_TAIL), + }).pipe( + // A commit the session made is a boundary of its own, with its hash as evidence. + Effect.andThen( + exitCode === 0 && /\bgit\b[^|;&]*\bcommit\b/.test(command) + ? head.pipe(Effect.flatMap((sha) => (sha ? record(event.sessionID, { type: "commit", sha }) : Effect.void))) + : Effect.void, + ), + ) + if (!failed) return ran const moment = { type: "failure" as const, command: shell.value.input.command, @@ -581,6 +713,7 @@ export const make = Effect.fnUntraced(function* ( // Appended to the failing command's own result, where the agent reads the failure, so it's in the next request // without a message of its own. The command's result waits for Console at most the policy's timeout. return Effect.gen(function* () { + yield* ran const entries = yield* ask(event.sessionID, moment) if (entries === undefined || entries.length === 0) return const ids = entries.map((entry) => `${entry.id}@${entry.revision}`) @@ -595,36 +728,16 @@ export const make = Effect.fnUntraced(function* ( deliver(tracked(event.sessionID), entries) }) }) - // Once its task is done, a session that verified a fix or worked past a dead end is reminded, once, that it may - // publish what it learned (the publish audit's WB2: agents publish nothing unprompted). Not while its own work runs - // in the background, and not in a subagent's or fork's session, whose parent decides. - yield* ctx.session.hook("experimental.idle", (event) => - Effect.gen(function* () { - const state = sessions.get(event.sessionID) - if (!state || state.reminded || event.background.some((job) => job.sessionID === event.sessionID)) return - const lesson = policy.lesson(state.work) - if (lesson === undefined) return - const session = yield* ctx.session.get({ sessionID: event.sessionID }) - if (session.parentID !== undefined || session.fork) return - state.reminded = true - yield* ctx.session.synthetic({ - sessionID: event.sessionID, - id: messageID(event.sessionID, "publish-reminder"), - text: policy.reminder(lesson), - description: "Memory: the session may publish what it learned", - metadata: { source: "console.memory", kind: "publish-reminder", lesson }, - }) - }).pipe(Effect.catch((cause) => Effect.logWarning("failed to remind the session to publish", { cause }))), - ) // A compaction drops what was injected from the conversation, and the agent's view of entries with it. yield* ctx.event.subscribe({ types: ["session.compaction.ended"] }).pipe( Stream.runForEach((event) => - Effect.sync(() => { + Effect.gen(function* () { const state = sessions.get(event.data.sessionID) if (!state) return state.compactions++ state.shown.clear() if (state.delivered.size > 0) state.redeliver = true + yield* record(event.data.sessionID, { type: "compaction" }) }), ), Effect.forkIn(lease, { startImmediately: true }), diff --git a/packages/core/test/plugin/provider-opencode-memory.test.ts b/packages/core/test/plugin/provider-opencode-memory.test.ts index 4e2f685a172..9bae68a5dfd 100644 --- a/packages/core/test/plugin/provider-opencode-memory.test.ts +++ b/packages/core/test/plugin/provider-opencode-memory.test.ts @@ -25,13 +25,36 @@ import { Session } from "@opencode/core/session" import { SessionMessage } from "@opencode/core/session/message" import { Tool } from "@opencode/core/tool" import { initGit } from "../fixture/git" -import { eventually } from "../lib/eventually" +import { eventually, waitUntil } from "../lib/eventually" import { testEffect } from "../lib/effect" -import { PluginTestLayer } from "./fixture" +import { Generate } from "@opencode/core/generate" +import { OpencodeMemoryCapture } from "@opencode/core/plugin/provider/opencode-memory-capture" +import { makePluginTestLayer, PluginTestLayer } from "./fixture" const withFlags = (overrides: string) => testEffect(PluginTestLayer.pipe(Layer.provide(Layer.succeed(Flag.Overrides, overrides)))) const it = withFlags("console_memory") +/** What the stand-in model answers a distillation, and the prompts it was given. */ +const distiller = { reply: "", prompts: new Array() } +const generating = Layer.succeed( + Generate.Service, + Generate.Service.of({ + text: (input) => + Effect.sync(() => { + distiller.prompts.push(input.prompt) + return distiller.reply + }), + image: () => Effect.die("unused"), + decisions: () => Effect.die("unused"), + video: { + start: () => Effect.die("unused"), + status: () => Effect.die("unused"), + result: () => Effect.die("unused"), + }, + }), +) +const capturing = (overrides: string) => + testEffect(makePluginTestLayer(undefined, generating).pipe(Layer.provide(Layer.succeed(Flag.Overrides, overrides)))) const released = withFlags("-console_memory") type Synthetic = Parameters[0] @@ -133,6 +156,7 @@ function fakeConsole() { if (url.pathname === "/api/memory/search") return Response.json({ status: state.hits.length === 0 ? "no_reliable_entry" : "ok", results: state.hits }) if (url.pathname === "/api/memory/inject") return Response.json({ entries: state.injected }) + if (url.pathname === "/api/memory/candidates") return Response.json({ id: "cand_1", status: "pending" }) if (url.pathname === "/api/memory/entries" && request.method === "POST") { const key = String(body?.idempotencyKey) const saved = state.published.get(key) @@ -862,63 +886,6 @@ describe("OpencodePlugin memory", () => { ), ) - it.effect("reminds a session once, when it would go idle after a verified fix, that it may publish", () => - withConsole((console) => - Effect.gen(function* () { - const { host, synthetic } = yield* start(console) - const hooks = yield* PluginHooks.Service - const idle = (sessionID: Session.ID, background: ReadonlyArray<{ sessionID: Session.ID }> = []) => - hooks.trigger("session", "experimental.idle", { sessionID, background } as never) - const fix = (sessionID: Session.ID) => - Effect.gen(function* () { - yield* ran(sessionID, "shell", { command: "bun test" }, { exitCode: 1, output: "(fail) dayKey\n 1 fail" }) - yield* ran(sessionID, "edit", { path: "src/dates.ts", oldString: "a", newString: "b" }) - yield* ran(sessionID, "shell", { command: "bun test" }, { exitCode: 0, output: " 2 pass\n 0 fail" }) - }) - - // Nothing learned yet: no reminder. - const session = yield* host.session.create({}) - yield* ran(session.id, "shell", { command: "bun test" }, { exitCode: 0, output: " 2 pass\n 0 fail" }) - yield* idle(session.id) - expect(synthetic).toEqual([]) - - yield* fix(session.id) - // While its own shell still runs in the background, the session isn't done. - yield* idle(session.id, [{ sessionID: session.id }]) - expect(synthetic).toEqual([]) - yield* idle(session.id) - expect(synthetic).toMatchObject([ - { - sessionID: session.id, - text: OpencodeMemoryPolicy.initial.reminder("verified fix (tests that failed now pass)"), - metadata: { - source: "console.memory", - kind: "publish-reminder", - lesson: "verified fix (tests that failed now pass)", - }, - }, - ]) - expect(synthetic[0]).not.toHaveProperty("resume") - // Once per session. - yield* fix(session.id) - yield* idle(session.id) - expect(synthetic).toHaveLength(1) - - // A subagent's session leaves publishing to its parent. - const child = yield* host.session.create({ parentID: session.id }) - yield* fix(child.id) - yield* idle(child.id) - expect(synthetic).toHaveLength(1) - - // The publish tool's description is the template the reminder points at. - const publish = yield* memoryTool("publish") - expect(publish.description.split("\n")[0]).toStartWith("Most sessions should publish nothing.") - expect(publish.description).toContain("\nClaim: ") - expect(publish.description).toContain("\nVerify: the command to run and the result to expect. / Avoid: ") - }), - ), - ) - it.effect("checks paths exist, marks a session that took in outside input as tainted, and passes on evidence", () => withConsole((console) => Effect.gen(function* () { @@ -1269,6 +1236,152 @@ describe("OpencodePlugin memory", () => { ) }) +describe("OpencodePlugin memory capture", () => { + capturing("console_memory,memory_capture").effect( + "logs every turn, distils at a boundary out of band, and sends what it finds as a pending candidate", + () => + withConsole((console) => + Effect.gen(function* () { + distiller.prompts.length = 0 + distiller.reply = JSON.stringify({ + candidates: [ + { + kind: "procedure", + title: "Tests need ACME_DB_URL", + body: "Claim: plain bun test fails without ACME_DB_URL.\nApplies when: test/\nAction: run ACME_DB_URL=memory://test bun test\nVerify: 2 pass\nAnchors: src/config.ts\nEvidence: failed, then passed with it", + errors: ["Error: ACME_DB_URL is not set"], + }, + { kind: "nonsense", title: "dropped" }, + ], + }) + const { host, synthetic } = yield* start(console) + const hooks = yield* PluginHooks.Service + const session = yield* host.session.create({}) + yield* prompt(session.id, "Add isWeekend to src/dates.ts and make the tests pass") + yield* hooks.trigger("session", "context", request(session.id, "Add isWeekend")) + yield* ran( + session.id, + "shell", + { command: "bun test" }, + { exitCode: 1, output: "Error: ACME_DB_URL is not set\n 1 fail" }, + ) + yield* ran(session.id, "edit", { path: "src/dates.ts", oldString: "a", newString: "b" }) + // Nothing distilled yet: no boundary. + expect(distiller.prompts).toEqual([]) + yield* ran( + session.id, + "shell", + { command: "ACME_DB_URL=memory://test bun test" }, + { exitCode: 0, output: " 2 pass\n 0 fail" }, + ) + + // A test that passes after one failed closes the segment: one distillation, in the background. + yield* waitUntil( + Effect.sync(() => console.state.requests.some((item) => item.path === "/api/memory/candidates")), + ) + expect(distiller.prompts).toHaveLength(1) + expect(distiller.prompts[0]).toContain("The boundary: test.") + expect(distiller.prompts[0]).toContain("#2 ran `bun test` → exit 1 FAILED\nError: ACME_DB_URL is not set") + const sent = console.state.requests.filter((item) => item.path === "/api/memory/candidates") + expect(sent).toHaveLength(1) + expect(sent[0]?.body).toEqual({ + sessionID: session.id, + boundary: "test", + kind: "procedure", + title: "Tests need ACME_DB_URL", + body: expect.stringMatching(/^Claim: plain bun test fails/), + errors: ["Error: ACME_DB_URL is not set"], + evidence: [{ kind: "test", ref: "ACME_DB_URL=memory://test bun test" }], + events: { from: 0, to: 3 }, + source: { sessionID: session.id }, + idempotencyKey: `${session.id}:0:0`, + }) + // The coding session got no message from any of it. + expect(synthetic).toEqual([]) + + // Every event is in the plugin's own log, in order. + const log = yield* host.storage.scan({ prefix: `memory-log:${session.id}:`, limit: 50 }) + expect(log.entries.map((item) => (item.value as { type: string }).type)).toEqual([ + "prompt", + "shell", + "edit", + "shell", + ]) + + // No reminder when the session would go idle. + yield* hooks.trigger("session", "experimental.idle", { sessionID: session.id, background: [] } as never) + expect(synthetic).toEqual([]) + }), + ), + ) + + capturing("console_memory,-memory_capture").effect("records and distils nothing with the switch off", () => + withConsole((console) => + Effect.gen(function* () { + distiller.prompts.length = 0 + const { host } = yield* start(console) + const session = yield* host.session.create({}) + yield* ran(session.id, "shell", { command: "bun test" }, { exitCode: 1, output: " 1 fail" }) + yield* ran(session.id, "shell", { command: "bun test" }, { exitCode: 0, output: " 1 pass" }) + const log = yield* host.storage.scan({ prefix: `memory-log:${session.id}:`, limit: 50 }) + expect(log.entries).toEqual([]) + expect(distiller.prompts).toEqual([]) + }), + ), + ) +}) + +describe("OpencodeMemoryCapture", () => { + const shell = (command: string, failed: boolean, test = true): OpencodeMemoryCapture.Event => ({ + type: "shell", + command, + exit: failed ? 1 : 0, + failed, + test, + tail: "", + }) + const edit: OpencodeMemoryCapture.Event = { type: "edit", files: ["src/a.ts"] } + const ask = (text: string, correction = false): OpencodeMemoryCapture.Event => ({ type: "prompt", text, correction }) + + test("finds the work boundaries the harness sees", () => { + const boundary = OpencodeMemoryCapture.boundary + expect(boundary([shell("bun test", true), edit], shell("bun test", false))).toBe("test") + expect(boundary([edit], shell("bun test", false))).toBeUndefined() + expect(boundary([], { type: "commit", sha: "abc" })).toBe("commit") + expect(boundary([edit], ask("Now add a test"))).toBe("task") + expect(boundary([edit], ask("No, don't change the config", true))).toBe("correction") + expect(boundary([edit], { type: "subtask" })).toBe("subtask") + expect(boundary([edit], { type: "compaction" })).toBe("compaction") + // Without work in between: no task, correction, subtask or compaction boundary. + expect(boundary([ask("Hi")], ask("Don't do that", true))).toBeUndefined() + expect(boundary([{ type: "read", files: ["a"] }], { type: "compaction" })).toBeUndefined() + }) + + test("links commits and passing runs after failures as evidence, and keeps only well-formed candidates", () => { + expect( + OpencodeMemoryCapture.evidence([ + shell("bun test", false), + shell("bun test", true), + edit, + shell("bun test", false), + { type: "commit", sha: "abc123" }, + ]), + ).toEqual([ + { kind: "test", ref: "bun test" }, + { kind: "commit", ref: "abc123" }, + ]) + expect(OpencodeMemoryCapture.candidates("no json here")).toEqual([]) + expect( + OpencodeMemoryCapture.candidates( + '```json\n{"candidates": [{"kind": "gotcha", "title": "T", "body": "B"}, {"kind": "x"}]}\n```', + ), + ).toEqual([{ kind: "gotcha", title: "T", body: "B" }]) + expect(OpencodeMemoryCapture.prompt({ segment: [edit], boundary: "commit" })).toContain( + 'Most records yield nothing: then answer {"candidates": []}.', + ) + }) +}) + describe("OpencodeMemoryPolicy.initial", () => { const session = (overrides: Record = {}) => ({ time: { created: 0, updated: 0 }, ...overrides }) as unknown as Session.Info @@ -1316,31 +1429,6 @@ describe("OpencodeMemoryPolicy.initial", () => { ).toBeUndefined() }) - test("finds a verified fix or a dead end worked past in a session's test runs and edits", () => { - const lesson = OpencodeMemoryPolicy.initial.lesson - const work = (lastEdit: number, ...tests: Array<[number, boolean]>) => ({ - step: 10, - lastEdit, - tests: tests.map(([step, failed]) => ({ step, failed })), - }) - expect(lesson(work(3, [1, true], [5, false]))).toBe("verified fix (tests that failed now pass)") - expect(lesson(work(8, [1, true], [2, true], [9, false]))).toBe("verified fix (tests that failed now pass)") - // Failing runs, all after the last edit, then a passing one: worked past without a change, a dead end. - expect(lesson(work(-1, [1, true], [2, true], [3, false]))).toBe( - "dead end you worked past (several failing attempts before a passing run)", - ) - // Passing without a failure first, one failure without an edit before it, or no pass after the last edit: nothing. - expect(lesson(work(3, [5, false]))).toBeUndefined() - expect(lesson(work(-1, [1, true], [2, false]))).toBeUndefined() - expect(lesson(work(6, [1, true], [5, false]))).toBeUndefined() - expect(OpencodeMemoryPolicy.initial.test("ACME_DB_URL=memory://test bun test 2>&1 | tail -20")).toBe(true) - expect(OpencodeMemoryPolicy.initial.test("uv run pytest -x tests/test_x.py")).toBe(true) - expect(OpencodeMemoryPolicy.initial.test("git status && ls src")).toBe(false) - expect(OpencodeMemoryPolicy.initial.reminder("verified fix (tests that failed now pass)")).toStartWith( - "This session had a verified fix (tests that failed now pass). If it taught something", - ) - }) - test("counts a command as failed by its exit code, or by its output when a pipe hides the exit code", () => { const failed = OpencodeMemoryPolicy.initial.failed expect(failed("bun test", "error: x\n 1 fail", 1)).toBe(true) diff --git a/packages/schema/src/config/flag.ts b/packages/schema/src/config/flag.ts index 588f6dd2081..2ef0bf71f8f 100644 --- a/packages/schema/src/config/flag.ts +++ b/packages/schema/src/config/flag.ts @@ -18,6 +18,8 @@ export const registry = { "Watch Slack threads, GitHub pull requests, issues, commits and Actions runs, and the workspace's MCP servers' events through OpenCode Console, and wake sessions when they change.", console_memory: "Give agents the OpenCode Console workspace's shared memory: tools to search, read, publish and update its entries, and relevant entries delivered when a task starts.", + memory_capture: + "Record every coding session's turns into a plugin-owned event log, distil candidate memory entries at work boundaries (a new task, a commit, a test that starts passing, a correction, a finished subtask, compaction) out of band, and send them to OpenCode Console as pending until outside evidence backs them.", mcp_events: "Enable experimental MCP Events, a draft MCP extension: declare support to MCP servers and read the events of servers that offer them.", full_codemode: