diff --git a/packages/core/src/git.ts b/packages/core/src/git.ts index 1c387412e15..50a9ba83311 100644 --- a/packages/core/src/git.ts +++ b/packages/core/src/git.ts @@ -169,6 +169,11 @@ export interface Interface { repository: Repository paths: readonly RelativePath[] }) => Effect.Effect, OperationError> + /** Of `paths`, the files and directories the index tracks: a directory when it tracks a file under it. */ + readonly tracked: (input: { + repository: Repository + paths: readonly RelativePath[] + }) => Effect.Effect, OperationError> } readonly tree: { readonly capture: (input: CaptureInput) => Effect.Effect @@ -641,6 +646,32 @@ const layer = Layer.effect( return new Set(nuls(result.stdout.toString("utf8")).map((file) => RelativePath.make(file))) }) + const tracked = Effect.fn("Git.index.tracked")(function* (input: { + repository: Repository + paths: readonly RelativePath[] + }) { + if (!input.paths.length) return new Set() + const result = yield* repositoryRun("list_files", input.repository, [ + "ls-files", + "-z", + "--cached", + "--", + ...input.paths.map(literalPathspec), + ]) + if (result.exitCode !== 0) + return yield* new OperationError({ + operation: "list_files", + directory: input.repository.worktree, + message: result.stderr.toString("utf8").trim() || "Failed to list tracked paths", + }) + const files = nuls(result.stdout.toString("utf8")) + return new Set( + input.paths.filter((item) => + files.some((file) => file === item || file.startsWith(`${item.replace(/\/$/, "")}/`)), + ), + ) + }) + const writeTree = Effect.fn("Git.tree.write")(function* (repository: Repository, index?: string) { const tree = (yield* retryConcurrentObjectWrite( repositoryOperation("write_tree", repository, ["write-tree"], { index }), @@ -1458,7 +1489,7 @@ const layer = Layer.effect( history: { head, branch, defaultRemoteBranch: remoteHead, rootCommits: roots }, sync: { fetchRemotes: fetch, fetchBranch, checkoutRemoteBranch: checkout, resetHard: reset }, worktree: { create: worktreeCreate, remove: worktreeRemove, list: worktreeList }, - index: { refresh, ignored }, + index: { refresh, ignored, tracked }, tree: { capture: captureTree, write: (repository) => writeTree(repository), diff --git a/packages/core/src/plugin/internal.ts b/packages/core/src/plugin/internal.ts index 41da7f721c5..90aa7a32fef 100644 --- a/packages/core/src/plugin/internal.ts +++ b/packages/core/src/plugin/internal.ts @@ -67,6 +67,7 @@ import { Ripgrep } from "../ripgrep.js" import { Automation } from "../automation.js" import { Session } from "../session.js" import { SessionCompaction } from "../session/compaction.js" +import { SessionEnvironment } from "../session/environment.js" import { SessionInstructions } from "../session/instructions.js" import { SubagentJob } from "../session/subagent-job.js" import { SharedCache } from "../shared-cache.js" @@ -166,6 +167,7 @@ const services = [ Automation.Service, Session.Service, SessionCompaction.Service, + SessionEnvironment.Service, SessionInstructions.Service, SubagentJob.Service, SharedCache.Service, @@ -229,6 +231,7 @@ export const requirements = LayerNode.group([ Automation.node, Session.node, SessionCompaction.node, + SessionEnvironment.node, SessionInstructions.node, SubagentJob.node, SharedCache.node, diff --git a/packages/core/src/plugin/provider/opencode-memory-verify.ts b/packages/core/src/plugin/provider/opencode-memory-verify.ts new file mode 100644 index 00000000000..fc602fc59b6 --- /dev/null +++ b/packages/core/src/plugin/provider/opencode-memory-verify.ts @@ -0,0 +1,132 @@ +export * as OpencodeMemoryVerify from "./opencode-memory-verify.js" + +import fs from "fs/promises" +import os from "os" +import path from "path" +import type { AppProcess } from "@opencode/util/process" +import { Effect, Semaphore } from "effect" +import { ChildProcess } from "effect/process" +import type { Git } from "../../git.js" +import { AbsolutePath } from "../../schema.js" +import { ShellSelect } from "../../shell/select.js" + +/** A test file, by its path: under a test directory, or named as one. */ +const TEST_FILE = /(?:^|\/)(?:tests?|spec|__tests__)\/|(?:^|\/)test_[^/]+$|[._-](?:test|spec)\.[^/]+$/ +/** How long one verification, all four runs and the worktree included, may take. */ +const TIMEOUT = "10 minutes" + +/** What a user turn showed: the commits the session made and its test runs, in order. */ +export interface Turn { + readonly commits: ReadonlyArray + readonly tests: ReadonlyArray<{ readonly command: string; readonly failed: boolean }> +} + +/** + * Strict local evidence that an observed fix holds, for work no CI checks. `verify` answers the commit of `turn` that + * changed every file in `paths` when a test of the turn that failed, then passed, fails twice at the commit's parent + * with the commit's test files added and passes twice at the commit, re-run in the session's shell and environment in + * a temporary worktree of `repository`, removed afterwards. `false` when the re-run fell short or didn't finish in + * time, undefined while the turn shows no such commit and test yet. One verification runs at a time. + */ +export const make = (deps: { + readonly git: Git.Interface + readonly processes: AppProcess.Interface + readonly shell: Effect.Effect +}) => { + const one = Semaphore.makeUnsafe(1) + const git = (cwd: string, args: ReadonlyArray) => + deps.processes.run(ChildProcess.make("git", [...args], { cwd, stdin: "ignore" })).pipe( + Effect.map((result) => (result.exitCode === 0 ? result.stdout.toString() : undefined)), + Effect.orElseSucceed(() => undefined), + ) + + const verify = Effect.fnUntraced(function* (input: { + readonly repository: Git.Repository + readonly turn: Turn + readonly paths: ReadonlyArray + readonly env: Readonly> + }) { + const test = input.turn.tests.findLast( + (run, index) => + !run.failed && input.turn.tests.slice(0, index).some((item) => item.failed && item.command === run.command), + ) + // Only files: a glob or nothing named can't be shown to be what the commit changed. + if (test === undefined || input.paths.length === 0 || input.paths.some((item) => /[*?[\]{}]/.test(item))) + return undefined + const root = input.repository.worktree + const commits = yield* Effect.forEach(input.turn.commits.toReversed(), (sha) => + changed(root, sha).pipe(Effect.map((files) => ({ sha, files: files ?? [] }))), + ) + const commit = commits.find((item) => + input.paths.every((entry) => + entry.endsWith("/") ? item.files.some((file) => file.startsWith(entry)) : item.files.includes(entry), + ), + ) + if (commit === undefined) return undefined + const sha = commit.sha + const files = commit.files + const shell = yield* deps.shell + const run = (cwd: string) => + deps.processes + .run( + ChildProcess.make(shell, ShellSelect.args(shell, test.command), { + cwd, + env: { ...input.env }, + extendEnv: false, + stdin: "ignore", + }), + ) + .pipe( + Effect.map((result) => result.exitCode), + Effect.orElseSucceed(() => undefined), + ) + const twice = (cwd: string, pass: boolean) => + Effect.gen(function* () { + for (const _ of [1, 2]) { + const code = yield* run(cwd) + if (code === undefined || code === null || (code === 0) !== pass) return false + } + return true + }) + return yield* Effect.acquireUseRelease( + Effect.promise(() => fs.mkdtemp(path.join(os.tmpdir(), "opencode-memory-verify-"))), + (directory) => + Effect.gen(function* () { + const worktree = AbsolutePath.make(path.join(directory, "checkout")) + yield* deps.git.worktree.create({ repository: input.repository, directory: worktree, ref: `${sha}^` }) + const tests = files.filter((file) => TEST_FILE.test(file)) + if ( + tests.length > 0 && + (yield* git(worktree, ["checkout", sha, "--", ...tests.map((file) => `:(literal)${file}`)])) === undefined + ) + return false + if (!(yield* twice(worktree, false))) return false + if ((yield* git(worktree, ["checkout", "--force", "--detach", sha])) === undefined) return false + return (yield* twice(worktree, true)) ? sha : false + }), + (directory) => + deps.git.worktree + .remove({ + repository: input.repository, + directory: AbsolutePath.make(path.join(directory, "checkout")), + force: true, + }) + .pipe( + Effect.ignore, + Effect.andThen(Effect.promise(() => fs.rm(directory, { recursive: true, force: true }))), + ), + ).pipe( + Effect.timeout(TIMEOUT), + Effect.orElseSucceed(() => false as const), + one.withPermit, + ) + }) + + // The files a commit changed against its parent, or undefined for a root commit or an unknown one. + const changed = (root: string, sha: string) => + git(root, ["diff-tree", "--no-commit-id", "--name-only", "-r", "-z", `${sha}^`, sha]).pipe( + Effect.map((text) => text?.split("\0").filter(Boolean)), + ) + + return verify +} diff --git a/packages/core/src/plugin/provider/opencode-memory.ts b/packages/core/src/plugin/provider/opencode-memory.ts index 9a3fdfe78d5..c0cef491d88 100644 --- a/packages/core/src/plugin/provider/opencode-memory.ts +++ b/packages/core/src/plugin/provider/opencode-memory.ts @@ -22,9 +22,12 @@ import { Integration } from "../../integration.js" import { AbsolutePath, RelativePath } from "../../schema.js" import { normalizeContent, normalizedName } from "../../tool/runtime.js" import { Flag } from "../../flag.js" +import { SessionEnvironment } from "../../session/environment.js" +import { ShellSelect } from "../../shell/select.js" import { OpencodeMemoryAccess } from "./opencode-memory-access.js" import { OpencodeMemoryCapture } from "./opencode-memory-capture.js" import { OpencodeMemoryPolicy } from "./opencode-memory-policy.js" +import { OpencodeMemoryVerify } from "./opencode-memory-verify.js" import { OpencodeWatches } from "./opencode-watches.js" /** The `GET /api/v2/config` response header Console sends while the caller may use the workspace's memory. */ @@ -65,6 +68,8 @@ const WRITER = Agent.ID.make("memory-writer") * from, so what its tools answer isn't outside input. */ const CONSOLE_MCP = "opencode_console" +/** The evidence a fix the plugin re-ran itself carries, with the commit's hash. */ +const VERIFIED = "verified-fix" /** The session instruction entries memory keeps: entries again after a compaction, and a correction reminder. */ const DELIVERED = "memory.delivered" const CORRECTION = "memory.correction" @@ -200,10 +205,8 @@ const Evidence = Schema.Array(Schema.Struct({ kind: Schema.Literals(["pr", "test description: "What shows it holds: a test or command you ran and saw pass, or a PR. Recorded with the entry; it doesn't make an entry live by itself", }) -/** A session that read this has taken in outside input: the web, issue text or other repositories. */ -const OUTSIDE = /\b(?:curl|wget|gh (?:issue|pr|api|repo clone)|git clone)\b/ -/** Tools whose results are outside input; MCP servers' tools are too. */ -const OUTSIDE_TOOLS = new Set(["webfetch", "websearch", "opencode_read_mcp_resource"]) +/** What reading an MCP resource names: the server it comes from. */ +const ResourceInput = Schema.Struct({ server: Schema.String }) /** `git commit`, after any global options, as its own command. */ const COMMIT = /(?:^|[;&|(]\s*)git(?:\s+(?:-[Cc]\s+\S+|--?[\w-]+(?:=\S+)?))*\s+commit\b/m const KindInput = Kind.annotate({ @@ -236,6 +239,14 @@ type Tracked = { allowance: number /** Commits the session made, as the harness saw them: evidence for what it publishes. */ readonly commits: string[] + /** Files the session wrote with its own edit tools, which aren't outside input when it reads them back. */ + readonly wrote: Set + /** The current user turn: its commits and test runs, and the observed entries published in it, still unverified. */ + turn: OpencodeMemoryVerify.Turn & { + readonly commits: string[] + readonly tests: Array<{ readonly command: string; readonly failed: boolean }> + readonly pending: Array<{ readonly id: string; readonly revision: number; readonly paths: ReadonlyArray }> + } /** The session took in outside input, so what it writes is marked tainted and never promoted; also stored. */ tainted?: boolean /** The entry the session's correction reminder names, until it's written or a compaction ends. */ @@ -268,6 +279,9 @@ export const make = Effect.fnUntraced(function* ( const processes = yield* AppProcess.Service const flags = yield* Flag.Service const config = yield* Config.Service + const environments = yield* SessionEnvironment.Service + const shells = yield* ShellSelect.Service + const verify = OpencodeMemoryVerify.make({ git, processes, shell: shells.resolve({ priority: "config" }) }) const github = yield* OpencodeMemoryAccess.make(http, processes, yield* OpencodeMemoryAccess.GitHub) let current: { console: OpencodeWatches.Console; readonly lease: Scope.Closeable } | undefined const sessions = new Map() @@ -284,6 +298,8 @@ export const make = Effect.fnUntraced(function* ( segment: [], allowance: DISTILLATIONS_PER_TURN, commits: [], + wrote: new Set(), + turn: { commits: [], tests: [], pending: [] }, about: new Map(), } sessions.delete(sessionID) @@ -506,6 +522,8 @@ export const make = Effect.fnUntraced(function* ( id: string, revision: number, change: Record, + // "user" when the change rests only on the user's own words, which outside input the session took in doesn't touch. + basis: "session" | "user" = "session", ) => Effect.gen(function* () { const state = tracked(sessionID) @@ -538,7 +556,7 @@ export const make = Effect.fnUntraced(function* ( ...fields, source: { ...(yield* checkout), sessionID }, // A revision from a session that took in outside input is marked as one, as its publishes are. - ...((yield* tainted(sessionID)) ? { tainted: true } : {}), + ...(basis === "session" && (yield* tainted(sessionID)) ? { tainted: true } : {}), ...(yield* reader), }, ) @@ -648,6 +666,7 @@ export const make = Effect.fnUntraced(function* ( sessionID: Session.ID, segment: ReadonlyArray, boundary: OpencodeMemoryCapture.Boundary, + turn: Tracked["turn"], ) => Effect.gen(function* () { const models = yield* distillers @@ -734,7 +753,8 @@ export const make = Effect.fnUntraced(function* ( ...(remaining.length === 0 ? {} : { supersedes: remaining }), source: { ...source, sessionID, ...writer }, ...(anchor === undefined ? {} : { anchor }), - ...((yield* tainted(sessionID)) ? { tainted: true } : {}), + // A rule the user confirmed in their own words rests on them, not on what else the session read. + ...(backing !== "confirmed" && (yield* tainted(sessionID)) ? { tainted: true } : {}), ...set, // Keyed by what was distilled: no two distillations share a key, before a restart or after it. idempotencyKey: `${sessionID}:${boundary}:${Hash.sha256(prompt).slice(0, 16)}:${index}`.slice(0, 128), @@ -750,6 +770,13 @@ export const make = Effect.fnUntraced(function* ( }).pipe(Effect.as(undefined)) }), ) + // An observed claim the session can back itself waits for this turn's commit and test to be re-run. + if (published?.id !== undefined && backing === "observed") + turn.pending.push({ + id: published.id, + revision: published.revision ?? 1, + paths: Option.getOrElse(Schema.decodeUnknownOption(Paths)(fields.paths), () => []), + }) // The session knows what it published: a later correction can reverse it. if (published?.id !== undefined) give(state, { @@ -790,8 +817,8 @@ export const make = Effect.fnUntraced(function* ( const retitled = title !== entry.title && title !== "" ? { title } : {} return yield* ( edits.length > 0 - ? write("edit", sessionID, id, entry.revision, { edits, ...retitled, evidence }) - : write("rewrite", sessionID, id, entry.revision, { body: candidate.body, evidence }) + ? write("edit", sessionID, id, entry.revision, { edits, ...retitled, evidence }, "user") + : write("rewrite", sessionID, id, entry.revision, { body: candidate.body, evidence }, "user") ).pipe( Effect.as(true), Effect.catch((cause) => @@ -852,13 +879,45 @@ export const make = Effect.fnUntraced(function* ( const opens = event.type === "prompt" && boundary === "task" const segment = opens ? [...state.segment] : [...state.segment, event] state.segment.splice(0, state.segment.length, ...(opens ? [event] : [])) - yield* distill(sessionID, segment, boundary).pipe(Effect.forkIn(lease, { startImmediately: true })) + const turn = state.turn + yield* distill(sessionID, segment, boundary, turn).pipe( + Effect.andThen(attempt(sessionID, turn)), + Effect.forkIn(lease, { startImmediately: true }), + ) }) + /** + * Re-runs, in the background, the fix behind each observed entry the session published this turn, once the turn + * shows a commit that changed its files and a test that failed, then passed; one that holds gets the evidence, + * which Console promotes on. Never for a session that took in outside input. + */ + const attempt = (sessionID: Session.ID, turn: Tracked["turn"]) => + Effect.gen(function* () { + const found = yield* discovered + if (turn.pending.length === 0 || !found || (yield* tainted(sessionID))) return + const env = (yield* environments.get(sessionID)) ?? process.env + yield* Effect.forEach( + [...turn.pending], + (entry) => + Effect.gen(function* () { + const sha = yield* verify({ repository: found, turn, paths: entry.paths, env }) + if (sha === undefined) return + turn.pending.splice(turn.pending.indexOf(entry), 1) + if (sha === false) return + yield* call(Schema.Unknown, "POST", `/api/memory/entries/${encodeURIComponent(entry.id)}/evidence`, { + evidence: [{ kind: VERIFIED, ref: sha }], + revision: entry.revision, + source: { ...(yield* checkout), sessionID }, + ...(yield* reader), + }) + }), + { discard: true }, + ) + }).pipe(Effect.catchCause((cause) => Effect.logDebug("memory fix not verified", { 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 })) - // The prefixes of MCP servers' tools, whose results are outside input: all but the Console's own, while the server - // config ends up with under its name is the one the Console delivered rather than one of the user's. + // The MCP servers whose tools and resources are outside input, by tool prefix and name: all but the Console's own, + // while the server config ends up with under its name is the one the Console delivered rather than one of the user's. const servers = yield* Effect.cachedWithTTL( Effect.all([ctx.mcp.list(), config.entries()]).pipe( Effect.map(([answer, entries]) => { @@ -872,12 +931,43 @@ export const make = Effect.fnUntraced(function* ( return answer.data .map((server) => normalizedName({ name: server.name })) .filter((name) => !(own && name === CONSOLE_MCP)) - .map((name) => `${name}_`) }), Effect.orElseSucceed(() => new Array()), ), "1 minute", ) + /** + * Whether a completed tool call took in outside input: the web, an MCP server other than the Console's own, or a + * read past the checkout or of a file the repository doesn't track that the session didn't write itself, such as a + * download. What a command printed is local output and never is. + */ + const outside = (event: { tool: string; input: unknown; sessionID: Session.ID }, files: ReadonlyArray) => + Effect.gen(function* () { + const outsiders = yield* servers + if (event.tool === "webfetch" || event.tool === "websearch") return true + if (outsiders.some((name) => event.tool.startsWith(`${name}_`))) return true + if (event.tool === "opencode_read_mcp_resource") + return Option.match(Schema.decodeUnknownOption(ResourceInput)(event.input), { + onNone: () => true, + onSome: (input) => + normalizedName({ name: input.server }) !== CONSOLE_MCP || outsiders.includes(CONSOLE_MCP), + }) + if (event.tool !== "read") return false + if (files.some((file) => path.isAbsolute(file))) return true + const state = tracked(event.sessionID) + const found = yield* discovered + const unwritten = files.filter((file) => !state.wrote.has(file)) + if (!found || unwritten.length === 0) return false + const paths = unwritten.map((file) => + RelativePath.make( + path.relative(found.worktree, path.join(ctx.location.directory, file)).split(path.sep).join("/"), + ), + ) + const known = yield* git.index + .tracked({ repository: found, paths }) + .pipe(Effect.orElseSucceed(() => new Set(paths))) + return paths.some((item) => !known.has(item)) + }) // HEAD when a `git commit` started, by tool call, to tell whether it made one. const heads = new Map() // The entries Console gives for a moment the policy picks, within its timeout; none when it picks none or fails. @@ -947,6 +1037,8 @@ export const make = Effect.fnUntraced(function* ( correction: user && (corrected !== undefined || policy.corrective(event.prompt.text)), user, }) + // The distillation this message started has the turn it closed; a new one begins. + state.turn = { commits: [], tests: [], pending: [] } if (corrected) yield* remind(event.sessionID, corrected) yield* begin(event.sessionID, { type: "prompt", @@ -979,12 +1071,8 @@ export const make = Effect.fnUntraced(function* ( .filter((file) => file !== ".") if (files.length > 0) yield* record(event.sessionID, { type: event.tool === "read" ? "read" : "edit", files }) if (event.tool === "subagent") yield* record(event.sessionID, { type: "subtask" }) - if ( - OUTSIDE_TOOLS.has(event.tool) || - (event.tool === "read" && files.some((file) => path.isAbsolute(file))) || - (yield* servers).some((prefix) => event.tool.startsWith(prefix)) - ) - yield* taint(event.sessionID) + if (event.tool !== "read") files.forEach((file) => tracked(event.sessionID).wrote.add(file)) + if (yield* outside(event, files)) yield* taint(event.sessionID) if (files.length > 0) { const state = tracked(event.sessionID) files.forEach((file) => { @@ -1002,8 +1090,8 @@ export const make = Effect.fnUntraced(function* ( if (Option.isNone(shell) || shell.value.output.exitCode === null) return const command = shell.value.input.command const exitCode = shell.value.output.exitCode - if (OUTSIDE.test(command)) yield* taint(event.sessionID) const failed = policy.failed(command, shell.value.output.output, exitCode) + if (policy.test(command)) tracked(event.sessionID).turn.tests.push({ command, failed }) yield* record(event.sessionID, { type: "shell", command: command.slice(0, MAX_TAIL), @@ -1018,7 +1106,9 @@ export const make = Effect.fnUntraced(function* ( const state = tracked(event.sessionID) state.commits.push(sha) state.commits.splice(0, Math.max(0, state.commits.length - MAX_COMMITS)) + state.turn.commits.push(sha) yield* record(event.sessionID, { type: "commit", sha }) + yield* attempt(event.sessionID, state.turn).pipe(Effect.forkIn(lease, { startImmediately: true })) } if (!failed) return const moment = { type: "failure" as const, command, output: shell.value.output.output, exitCode } diff --git a/packages/core/src/plugin/provider/opencode.ts b/packages/core/src/plugin/provider/opencode.ts index b032e32bdd9..45a520e654d 100644 --- a/packages/core/src/plugin/provider/opencode.ts +++ b/packages/core/src/plugin/provider/opencode.ts @@ -23,6 +23,8 @@ import { SkillFile } from "../../config/plugin/skill-file.js" import { ConsoleAccess } from "../../console-access.js" import { Credential } from "../../credential.js" import { Flag } from "../../flag.js" +import { SessionEnvironment } from "../../session/environment.js" +import { ShellSelect } from "../../shell/select.js" import { Git } from "../../git.js" import { InstructionDiscovery } from "../../instruction-discovery.js" import { Integration } from "../../integration.js" @@ -191,7 +193,9 @@ export const OpencodePlugin = define< | Flag.Service | Git.Service | InstructionDiscovery.Service + | SessionEnvironment.Service | SharedCache.Service + | ShellSelect.Service | Skill.Service | Scope.Scope >({ diff --git a/packages/core/test/git.test.ts b/packages/core/test/git.test.ts index 5042beb9aa9..bcf55a1a3da 100644 --- a/packages/core/test/git.test.ts +++ b/packages/core/test/git.test.ts @@ -32,6 +32,32 @@ describe("Git", () => { }), ) + it.live("tells which paths the index tracks, a directory by the files under it", () => + Effect.gen(function* () { + const root = yield* tmpdirScoped() + yield* Effect.promise(async () => { + await initGit(root.path) + await fs.mkdir(path.join(root.path, "src"), { recursive: true }) + await Promise.all([ + Bun.write(path.join(root.path, "src", "a.ts"), "a"), + Bun.write(path.join(root.path, "src", "b.ts"), "b"), + Bun.write(path.join(root.path, "notes.txt"), "n"), + ]) + await $`git add src/a.ts`.cwd(root.path).quiet() + }) + const git = yield* Git.Service + const repository = yield* git.repo.discover( + AbsolutePath.make(yield* Effect.promise(() => fs.realpath(root.path))), + ) + const paths = ["src/a.ts", "src/b.ts", "notes.txt", "src", "src/", "gone.ts"].map((item) => + RelativePath.make(item), + ) + expect(yield* git.index.tracked({ repository: repository!, paths })).toEqual( + new Set(["src/a.ts", "src", "src/"].map((item) => RelativePath.make(item))), + ) + }), + ) + it.live("clones a remote and reads checkout metadata", () => withRemote((fixture) => Effect.gen(function* () { diff --git a/packages/core/test/plugin/fixture.ts b/packages/core/test/plugin/fixture.ts index 62c3be94183..167355279dd 100644 --- a/packages/core/test/plugin/fixture.ts +++ b/packages/core/test/plugin/fixture.ts @@ -19,6 +19,8 @@ import { Global } from "@opencode/util/global" import { Form } from "@opencode/core/form" import { Generate } from "@opencode/core/generate" import { Git } from "@opencode/core/git" +import { SessionEnvironment } from "@opencode/core/session/environment" +import { ShellSelect } from "@opencode/core/shell/select" import { InstructionDiscovery } from "@opencode/core/instruction-discovery" import { Integration } from "@opencode/core/integration" import { Job } from "@opencode/core/job" @@ -129,6 +131,8 @@ export const makePluginTestLayer = (permission = permissionLayer, generate = gen KV.node, Mcp.node, Session.node, + SessionEnvironment.node, + ShellSelect.node, SharedCache.node, InstructionEntry.node, PersistentPty.node, diff --git a/packages/core/test/plugin/provider-opencode-memory-verify.test.ts b/packages/core/test/plugin/provider-opencode-memory-verify.test.ts new file mode 100644 index 00000000000..7707f5baa1c --- /dev/null +++ b/packages/core/test/plugin/provider-opencode-memory-verify.test.ts @@ -0,0 +1,94 @@ +import { describe, expect } from "bun:test" +import fs from "fs/promises" +import path from "path" +import { $ } from "bun" +import { Effect } from "effect" +import { LayerNode } from "@opencode/util/effect/layer-node" +import { AppProcess } from "@opencode/util/process" +import { Git } from "@opencode/core/git" +import { OpencodeMemoryVerify } from "@opencode/core/plugin/provider/opencode-memory-verify" +import { AbsolutePath } from "@opencode/core/schema" +import { ShellSelect } from "@opencode/core/shell/select" +import { initRepo } from "../fixture/git" +import { tmpdirScoped } from "../fixture/tmpdir" +import { testEffect } from "../lib/effect" + +const it = testEffect(LayerNode.compile(LayerNode.group([Git.node, AppProcess.node, ShellSelect.node]))) + +const TEST = "bun test test/value.test.ts" +const SPEC = + 'import { expect, test } from "bun:test"\nimport fs from "fs"\ntest("value", () => expect(fs.readFileSync("src/value.txt", "utf8").trim()).toBe("fixed"))\n' + +/** A repository whose last commit fixes src/value.txt and adds the test that shows it; `before` is what it had. */ +const repository = (before: string) => + Effect.gen(function* () { + const root = yield* tmpdirScoped() + const sha = yield* Effect.promise(async () => { + await initRepo(root.path) + await fs.mkdir(path.join(root.path, "src"), { recursive: true }) + await fs.writeFile(path.join(root.path, "src/value.txt"), `${before}\n`) + await $`git add -A && git commit -qm broken`.cwd(root.path).quiet() + await fs.mkdir(path.join(root.path, "test"), { recursive: true }) + await fs.writeFile(path.join(root.path, "test/value.test.ts"), SPEC) + await fs.writeFile(path.join(root.path, "src/value.txt"), "fixed\n") + await $`git add -A && git commit -qm fix`.cwd(root.path).quiet() + return (await $`git rev-parse HEAD`.cwd(root.path).text()).trim() + }) + const git = yield* Git.Service + const found = yield* git.repo.discover(AbsolutePath.make(yield* Effect.promise(() => fs.realpath(root.path)))) + const shells = yield* ShellSelect.Service + const verify = OpencodeMemoryVerify.make({ + git, + processes: yield* AppProcess.Service, + shell: shells.resolve({ priority: "config" }), + }) + const turn = { + commits: [sha], + tests: [ + { command: TEST, failed: true }, + { command: TEST, failed: false }, + ], + } + return { git, repository: found!, sha, verify, turn } + }) + +describe("OpencodeMemoryVerify", () => { + it.live( + "verifies a fix whose test fails twice before the commit and passes twice at it, in a worktree it removes", + () => + Effect.gen(function* () { + const fixture = yield* repository("broken") + const verify = (paths: ReadonlyArray, turn = fixture.turn) => + fixture.verify({ repository: fixture.repository, turn, paths, env: process.env }) + expect(yield* verify(["src/value.txt"])).toBe(fixture.sha) + // Only an entry about what the commit changed, and only with a test that failed, then passed. + expect(yield* verify(["src/other.txt"])).toBeUndefined() + expect(yield* verify(["src/*.txt"])).toBeUndefined() + expect(yield* verify(["src/value.txt"], { ...fixture.turn, tests: [{ command: TEST, failed: false }] })).toBe( + undefined, + ) + expect((yield* fixture.git.worktree.list(fixture.repository)).map((item) => item.directory)).toEqual([ + fixture.repository.worktree, + ]) + }), + ) + + it.live("refuses a fix whose test already passed before the commit", () => + Effect.gen(function* () { + // The value was already right, only padded: the commit changes the file, but the test passes at the parent too, + // so it shows nothing the commit fixed. + const fixture = yield* repository("fixed ") + expect( + yield* fixture.verify({ + repository: fixture.repository, + turn: fixture.turn, + paths: ["src/value.txt"], + env: process.env, + }), + ).toBe(false) + expect((yield* fixture.git.worktree.list(fixture.repository)).map((item) => item.directory)).toEqual([ + fixture.repository.worktree, + ]) + }), + ) +}) diff --git a/packages/core/test/plugin/provider-opencode-memory.test.ts b/packages/core/test/plugin/provider-opencode-memory.test.ts index a99359c352f..ee90fbd5d36 100644 --- a/packages/core/test/plugin/provider-opencode-memory.test.ts +++ b/packages/core/test/plugin/provider-opencode-memory.test.ts @@ -1040,9 +1040,14 @@ describe("OpencodePlugin memory", () => { it.effect("checks paths exist, marks a session that took in outside input as tainted, and passes on evidence", () => withConsole((console) => Effect.gen(function* () { - const { host } = yield* start(console) const directory = (yield* Location.Service).directory - yield* Effect.promise(() => fs.mkdir(path.join(directory, "src"), { recursive: true })) + yield* Effect.promise(async () => { + await initGit(directory, "-b", "main") + await fs.mkdir(path.join(directory, "src"), { recursive: true }) + await fs.writeFile(path.join(directory, "src/dates.ts"), "export {}\n") + await $`git add src/dates.ts && git commit -qm dates`.cwd(directory).quiet() + }) + const { host } = yield* start(console) const publish = yield* memoryTool("publish") const session = yield* host.session.create({}) const entry = { kind: "gotcha", title: "Dates are UTC", body: "Use toISOString" } @@ -1068,9 +1073,10 @@ describe("OpencodePlugin memory", () => { expect(console.state.requests.at(-1)?.body).toMatchObject({ evidence }) expect(console.state.requests.at(-1)?.body).not.toHaveProperty("tainted") - // Reading the checkout, its root included, isn't outside input; a file elsewhere is. + // Reading the checkout's tracked files, its root included, isn't outside input; a file elsewhere is. yield* ran(session.id, "read", { path: directory }) yield* ran(session.id, "read", { path: path.join(directory, "src") }) + yield* ran(session.id, "read", { path: path.join(directory, "src/dates.ts") }) yield* publish.execute(entry, context(session.id, "call_root")) expect(console.state.requests.at(-1)?.body).not.toHaveProperty("tainted") const outside = yield* host.session.create({}) @@ -1083,15 +1089,26 @@ describe("OpencodePlugin memory", () => { yield* ran(browsing.id, "webfetch", { url: "https://example.com" }, { output: "page" }) yield* publish.execute(entry, context(browsing.id, "call_web")) expect(console.state.requests.at(-1)?.body).toMatchObject({ tainted: true }) - const cloned = yield* host.session.create({}) + // What a command printed is local output, whatever the command; a file it downloaded that the repository doesn't + // track is outside input once read. A file the session wrote itself isn't. + const fetched = yield* host.session.create({}) yield* ran( - cloned.id, + fetched.id, "shell", - { command: "git clone https://github.com/x/y /tmp/y" }, + { command: "curl -o data.json https://example.com/data.json" }, { exitCode: 0, output: "ok" }, ) - yield* publish.execute(entry, context(cloned.id, "call_clone")) + yield* publish.execute(entry, context(fetched.id, "call_curl")) + expect(console.state.requests.at(-1)?.body).not.toHaveProperty("tainted") + yield* Effect.promise(() => fs.writeFile(path.join(directory, "data.json"), "{}\n")) + yield* ran(fetched.id, "read", { path: "data.json" }) + yield* publish.execute(entry, context(fetched.id, "call_download")) expect(console.state.requests.at(-1)?.body).toMatchObject({ tainted: true }) + const writing = yield* host.session.create({}) + yield* ran(writing.id, "write", { path: "notes.md" }) + yield* ran(writing.id, "read", { path: "notes.md" }) + yield* publish.execute(entry, context(writing.id, "call_own")) + expect(console.state.requests.at(-1)?.body).not.toHaveProperty("tainted") // A teammate who checked an entry backs it with evidence through edit. yield* (yield* memoryTool("edit")).execute({ id: "mem_1", revision: 1, evidence }, context(session.id)) @@ -1508,10 +1525,19 @@ describe("OpencodePlugin memory evidence and taint", () => { yield* publish.execute(entry, context(tasks.id, "call_tasks")) expect(published()?.body).not.toHaveProperty("tainted") + // Its resources too; another server's are outside input. + yield* ran(tasks.id, "opencode_read_mcp_resource", { server: "opencode_console", uri: "task://tsk_1" }) + yield* publish.execute(entry, context(tasks.id, "call_resource")) + expect(published()?.body).not.toHaveProperty("tainted") + const issues = yield* host.session.create({}) yield* ran(issues.id, "linear_get_issue", { id: 7 }, { text: "issue body" }) yield* publish.execute(entry, context(issues.id, "call_issues")) expect(published()?.body).toMatchObject({ tainted: true }) + const resource = yield* host.session.create({}) + yield* ran(resource.id, "opencode_read_mcp_resource", { server: "linear", uri: "issue://7" }) + yield* publish.execute(entry, context(resource.id, "call_issue_resource")) + expect(published()?.body).toMatchObject({ tainted: true }) // A server of the user's own under the Console's name is outside input like any other. const config = yield* Config.Test @@ -1934,6 +1960,105 @@ describe("OpencodePlugin memory capture", () => { const publishes = (console: ReturnType) => console.state.requests.filter((item) => item.path === "/api/memory/entries") + capturing("console_memory,memory_capture").effect( + "sends a rule the user stated without the session's taint, while what it observed stays tainted", + () => + withConsole((console) => + Effect.gen(function* () { + const rule = "From now on we always put the issue number in the commit message" + const claim = (title: string, extra: Record) => ({ + kind: "convention", + title, + body: "Claim: x\nApplies when: x\nAction: x\nVerify: x\nAnchors: x\nEvidence: x", + ...extra, + }) + distiller.reply = JSON.stringify({ + candidates: [ + claim("Commit messages name the issue", { basis: "user", quote: rule }), + claim("The changelog is generated", { basis: "observed" }), + ], + }) + const { host } = yield* start(console) + const session = yield* host.session.create({}) + // The session read the web, so what it observed rests on outside input; the user's own words don't. + yield* ran(session.id, "webfetch", { url: "https://example.com" }, { output: "page" }) + yield* prompt(session.id, rule) + yield* waitUntil(Effect.sync(() => publishes(console).length === 2)) + const sent = (title: string) => + publishes(console).find((item) => (item.body as { title?: string }).title === title)?.body + expect(sent("Commit messages name the issue")).toMatchObject({ + evidence: [{ kind: "confirmation", ref: rule }], + }) + expect(sent("Commit messages name the issue")).not.toHaveProperty("tainted") + expect(sent("The changelog is generated")).toMatchObject({ tainted: true }) + }), + ), + ) + + capturing("console_memory,memory_capture").effect( + "backs an observed fix with evidence once its test fails before the turn's commit and passes at it", + () => + withConsole((console) => + Effect.gen(function* () { + const directory = (yield* Location.Service).directory + const run = (command: string) => + Effect.promise(() => + $`sh -c ${command}` + .cwd(directory) + .quiet() + .nothrow() + .then((result) => result.exitCode), + ) + yield* Effect.promise(async () => { + await initGit(directory, "-b", "main") + await fs.mkdir(path.join(directory, "src"), { recursive: true }) + await fs.writeFile(path.join(directory, "src/value.txt"), "broken\n") + await $`git add -A && git commit -qm broken`.cwd(directory).quiet() + }) + distiller.reply = JSON.stringify({ + candidates: [ + { + kind: "bug", + title: "The value must read fixed", + body: "Claim: x\nApplies when: x\nAction: x\nVerify: x\nAnchors: x\nEvidence: x", + paths: ["src/value.txt"], + }, + ], + }) + const { host } = yield* start(console) + const session = yield* host.session.create({}) + const test = "bun test test/value.test.ts" + // The turn: the test fails, the fix and its test are written, the test passes, and the session commits. + yield* prompt(session.id, "Fix the value") + yield* shell(session.id, test, Effect.succeed(1)) + yield* Effect.promise(async () => { + await fs.mkdir(path.join(directory, "test"), { recursive: true }) + await fs.writeFile( + path.join(directory, "test/value.test.ts"), + 'import { expect, test } from "bun:test"\nimport fs from "fs"\ntest("value", () => expect(fs.readFileSync("src/value.txt", "utf8").trim()).toBe("fixed"))\n', + ) + await fs.writeFile(path.join(directory, "src/value.txt"), "fixed\n") + }) + yield* shell(session.id, test, Effect.succeed(0)) + yield* shell(session.id, "git add -A && git commit -qm fix", run("git add -A && git commit -qm fix")) + const sha = (yield* Effect.promise(() => $`git rev-parse HEAD`.cwd(directory).text())).trim() + // Re-run in the background, before the commit and at it; the fix holds, so its entry gets the evidence. + const verified = () => + console.state.requests.filter( + (item) => + item.path === "/api/memory/entries/mem_new0/evidence" && + JSON.stringify(item.body).includes("verified-fix"), + ) + yield* waitUntil(Effect.sync(() => verified().length > 0)) + expect(verified()[0]?.body).toMatchObject({ + evidence: [{ kind: "verified-fix", ref: sha }], + revision: 1, + source: expect.objectContaining({ sessionID: session.id }), + }) + }), + ), + ) + capturing("console_memory,memory_capture").effect( "corrects an entry the session holds as a new revision of it, from its whole text, instead of superseding it", () =>