mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 03:24:54 +00:00
feat(core): a repository's test recipe goes first in the task-start rules
A session that gets the tests running after a failed attempt shows the repository's test recipe. Capture it from what the harness saw, without a model: a test run that passed after a different one failed, with an agent's chain (`cd x && a && b 2>&1 | tail; echo $?`) reduced to its setup, build and test steps and its outcome read from the output too. It goes to Console as a procedure tagged `recipe`, backed by the passing run at HEAD unless the session took in outside input (opencode-memory-recipe.ts). At a task's start, a repository procedure that carries a command and is about testing, setup or building goes first among the rules, up to two, without the repo-wide judgement, so the agent has the working command before its first attempt rather than after a failure. Edge lab S10 (exploration, 5 cells, same-batch controls, DeepSeek V4.1 Flash): tool calls -22% and tokens -27% vs production, -20% calls vs the same capture delivered through the judged rules, success equal (CIs exclude 0).
This commit is contained in:
parent
2e19a5cfe4
commit
d0c2e68ed0
3 changed files with 170 additions and 3 deletions
83
packages/core/src/plugin/provider/opencode-memory-recipe.ts
Normal file
83
packages/core/src/plugin/provider/opencode-memory-recipe.ts
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
export * as OpencodeMemoryRecipe from "./opencode-memory-recipe.js"
|
||||
|
||||
/**
|
||||
* A repository's test recipe, taken from what the harness saw rather than from a model: the command that made the tests
|
||||
* run and pass after a different one failed. Agents chain their commands (`cd x && a && b 2>&1 | tail; echo $?`), so a
|
||||
* chain is reduced to its setup, build and test steps, in order, as one command another session can rerun, and whether
|
||||
* it passed is read from its output as well as its exit code (a trailing `echo` hides the exit code).
|
||||
*/
|
||||
|
||||
const STEP =
|
||||
/\b(?:pytest|unittest|tox|nox|vitest|jest|mocha|go test|cargo (?:test|build)|run-tests|tests?|pip3? install|uv (?:sync|pip)|npm (?:ci|install|run|test)|bun (?:install|run|test)|poetry install|make|bootstrap|setup|gen|regen|build|compile)\b/
|
||||
const TEST = /\b(?:pytest|unittest|tox|nox|vitest|jest|mocha|go test|cargo test|run-tests|tests?)\b/
|
||||
const NOISE =
|
||||
/^(?:cd|echo|ls|cat|git|pwd|sed|grep|rg|find|head|tail|printf|true|false|set|wc|sort|diff|rm|mkdir|which|env|export|sleep)\b/
|
||||
const COMMAND = /`[^`]{3,}`|\.\/[\w.-]+|\bpython3? (?:-m )?\S+|\bmake \w+|\b(?:npm|bun|pnpm|yarn) (?:run )?\w+/
|
||||
const ABOUT = /\b(?:tests?|unittest|pytest|set ?up|setup|bootstrap|build|lint)\b/i
|
||||
|
||||
/** The setup, build and test steps of a command or chain, in order, without `cd`, output plumbing or echoes. */
|
||||
export const steps = (command: string) =>
|
||||
command
|
||||
.split(/\s*(?:&&|\|\||;|\n)\s*/)
|
||||
.map((one) =>
|
||||
one
|
||||
.split(/\s\|\s/)[0]
|
||||
.replace(/\s*\d?>&\d|\s*2>\/dev\/null|\s*>\s*\S+$/g, "")
|
||||
.trim(),
|
||||
)
|
||||
.filter((one) => one !== "" && !NOISE.test(one) && STEP.test(one))
|
||||
|
||||
/** Whether a finished run's output shows tests that ran and passed. */
|
||||
export const passed = (output: string) =>
|
||||
/Ran [1-9]\d* tests?[\s\S]*\bOK\b|\b[1-9]\d* pass(?:ed|ing)\b/.test(output) &&
|
||||
!/FAILED|\b[1-9]\d* fail(?:ed|ing|ures?)\b/.test(output)
|
||||
|
||||
export interface State {
|
||||
readonly failed: string[]
|
||||
found: boolean
|
||||
}
|
||||
|
||||
export const make = (): State => ({ failed: [], found: false })
|
||||
|
||||
/**
|
||||
* The recipe a finished shell call shows, once per session: a test run that passed after a different one failed in
|
||||
* the same session. Anything else only updates `state`.
|
||||
*/
|
||||
export const observe = (
|
||||
state: State,
|
||||
run: { readonly command: string; readonly output: string; readonly failed: boolean },
|
||||
) => {
|
||||
const recipe = steps(run.command).join(" && ")
|
||||
if (!steps(recipe).some((one) => TEST.test(one))) return undefined
|
||||
if (run.failed || !passed(run.output)) {
|
||||
state.failed.push(recipe)
|
||||
return undefined
|
||||
}
|
||||
const before = state.failed.findLast((one) => one !== recipe)
|
||||
if (state.found || before === undefined) return undefined
|
||||
state.found = true
|
||||
return { recipe, before }
|
||||
}
|
||||
|
||||
/** The entry a recipe becomes for repository `repo`. */
|
||||
export const entry = (found: { readonly recipe: string; readonly before: string }, repo: string) => ({
|
||||
kind: "procedure" as const,
|
||||
title: `To test ${repo}, run \`${found.recipe}\``.slice(0, 200),
|
||||
body: `In ${repo}, run the tests with \`${found.recipe.slice(0, 300)}\`: it passed after \`${found.before.slice(0, 200)}\` failed.`,
|
||||
})
|
||||
|
||||
/**
|
||||
* A repository rule that is its recipe: a procedure that carries a command and is about testing, setting up or building
|
||||
* the repository. At a task's start it goes first among the rules, so the agent has the working command before its
|
||||
* first attempt rather than after a failure.
|
||||
*/
|
||||
export const isRecipe = (entry: {
|
||||
readonly kind: string
|
||||
readonly title: string
|
||||
readonly body: string
|
||||
readonly via?: string
|
||||
}) =>
|
||||
entry.kind === "procedure" &&
|
||||
entry.via === "repository" &&
|
||||
COMMAND.test(`${entry.title}\n${entry.body}`) &&
|
||||
ABOUT.test(entry.title)
|
||||
|
|
@ -31,6 +31,7 @@ import { OpencodeMemoryAccess } from "./opencode-memory-access.js"
|
|||
import { OpencodeMemoryCapture } from "./opencode-memory-capture.js"
|
||||
import { OpencodeMemoryDecide } from "./opencode-memory-decide.js"
|
||||
import { OpencodeMemoryPolicy } from "./opencode-memory-policy.js"
|
||||
import { OpencodeMemoryRecipe } from "./opencode-memory-recipe.js"
|
||||
import { OpencodeMemoryVerify } from "./opencode-memory-verify.js"
|
||||
import { OpencodeWatches } from "./opencode-watches.js"
|
||||
|
||||
|
|
@ -85,6 +86,8 @@ const DELIVERIES = "/api/memory/deliveries"
|
|||
const MAX_DELIVERED = 3
|
||||
/** And at a task's start, the most of the repository's rules for all its work, besides. */
|
||||
const MAX_RULES = 3
|
||||
/** And the most of its test recipes, which go first and aren't judged: a working command is a rule by what it is. */
|
||||
const MAX_RECIPES = 2
|
||||
/** The most deliveries one call records, as Console takes them. */
|
||||
const MAX_RECORDED = 20
|
||||
/** The instructions source that holds the instruction files: AGENTS.md (or CLAUDE.md) and configured ones. */
|
||||
|
|
@ -910,6 +913,33 @@ export const make = Effect.fnUntraced(function* (
|
|||
agent.hidden = true
|
||||
}),
|
||||
)
|
||||
// A test recipe a session just showed (opencode-memory-recipe.ts) goes to Console as a procedure, backed by the
|
||||
// passing run at HEAD unless the session took in outside input. A duplicate refusal means Console already holds it.
|
||||
const recipes = new WeakMap<Tracked, OpencodeMemoryRecipe.State>()
|
||||
const learn = (sessionID: Session.ID, command: string, output: string, failed: boolean) =>
|
||||
Effect.gen(function* () {
|
||||
if (!capturing) return
|
||||
const state = tracked(sessionID)
|
||||
const seen = recipes.get(state) ?? OpencodeMemoryRecipe.make()
|
||||
recipes.set(state, seen)
|
||||
const found = OpencodeMemoryRecipe.observe(seen, { command, output, failed })
|
||||
if (found === undefined) return
|
||||
const source = yield* checkout
|
||||
const outside = yield* tainted(sessionID)
|
||||
const written = yield* call(Written, "POST", "/api/memory/entries", {
|
||||
...OpencodeMemoryRecipe.entry(found, yield* label),
|
||||
tags: ["recipe"],
|
||||
source: { ...source, sessionID },
|
||||
...(outside ? { tainted: true } : {}),
|
||||
idempotencyKey: `${sessionID}:recipe:${Hash.sha256(found.recipe).slice(0, 16)}`,
|
||||
})
|
||||
const sha = yield* head
|
||||
if (outside || sha === undefined || written.id === undefined) return
|
||||
yield* call(Schema.Unknown, "POST", `/api/memory/entries/${encodeURIComponent(written.id)}/evidence`, {
|
||||
evidence: [{ kind: VERIFIED, ref: sha }],
|
||||
source: { ...source, sessionID },
|
||||
})
|
||||
}).pipe(Effect.catchCause((cause) => Effect.logDebug("memory recipe not sent", { cause })))
|
||||
/**
|
||||
* Adds `event` to the session's segment and, when it closes a work boundary, distils the segment in the background.
|
||||
* Kept in memory only: a restart loses the open segment, never anything published.
|
||||
|
|
@ -1088,8 +1118,10 @@ export const make = Effect.fnUntraced(function* (
|
|||
// At a task's start each candidate is asked whether it's a rule for all the repository's work, and a ranked one
|
||||
// whether it applies to the task too; elsewhere only whether it applies.
|
||||
const name = yield* label
|
||||
const recipes =
|
||||
moment.type === "prompt" ? entries.filter(OpencodeMemoryRecipe.isRecipe).slice(0, MAX_RECIPES) : []
|
||||
const judged = yield* Effect.forEach(
|
||||
entries,
|
||||
entries.filter((entry) => !recipes.includes(entry)),
|
||||
(entry) =>
|
||||
Effect.all(
|
||||
{
|
||||
|
|
@ -1112,7 +1144,7 @@ export const make = Effect.fnUntraced(function* (
|
|||
const applying = judged
|
||||
.filter((item) => !rules.includes(item) && (item.applies ?? 0) >= OpencodeMemoryDecide.APPLIES)
|
||||
.toSorted((a, b) => (b.applies ?? 0) - (a.applies ?? 0))
|
||||
if (rules.length === 0 && applying.length === 0) return { entries: [], rules: [] } satisfies Delivery
|
||||
if (rules.length === 0 && applying.length === 0) return { entries: [], rules: recipes } satisfies Delivery
|
||||
const instructions = yield* Deferred.await(state.instructions)
|
||||
const [fitting, kept] = yield* Effect.all(
|
||||
[
|
||||
|
|
@ -1129,7 +1161,7 @@ export const make = Effect.fnUntraced(function* (
|
|||
],
|
||||
{ concurrency: 2 },
|
||||
)
|
||||
return { entries: fitting, rules: kept } satisfies Delivery
|
||||
return { entries: fitting, rules: [...recipes, ...kept] } satisfies Delivery
|
||||
})
|
||||
/**
|
||||
* Up to `budget` of `entries`, in order, that the instruction files don't already state, asking only as many at a
|
||||
|
|
@ -1329,6 +1361,9 @@ export const make = Effect.fnUntraced(function* (
|
|||
test: policy.test(command),
|
||||
tail: shell.value.output.output.slice(-MAX_TAIL),
|
||||
})
|
||||
yield* learn(event.sessionID, command, shell.value.output.output.slice(-MAX_TAIL), failed).pipe(
|
||||
Effect.forkIn(lease, { startImmediately: true }),
|
||||
)
|
||||
// A commit the session made, when `git commit` moved HEAD, is a boundary of its own with its hash as evidence.
|
||||
const sha = committing && exitCode === 0 ? yield* head : undefined
|
||||
if (sha !== undefined && sha !== before) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,49 @@
|
|||
import { describe, expect, test } from "bun:test"
|
||||
import { OpencodeMemoryRecipe } from "@opencode/core/plugin/provider/opencode-memory-recipe"
|
||||
|
||||
describe("opencode memory recipe", () => {
|
||||
test("a chained test run that passes after another failed is the recipe, reduced to its steps", () => {
|
||||
const state = OpencodeMemoryRecipe.make()
|
||||
const runs = [
|
||||
{
|
||||
command: 'cd /work && python3 -m unittest discover -s tests/unit 2>&1; echo "exit=$?"',
|
||||
output: "Ran 2 tests in 0.000s\n\nFAILED (errors=2)\nexit=1",
|
||||
failed: false,
|
||||
},
|
||||
{ command: "git status --short", output: "", failed: false },
|
||||
{
|
||||
command:
|
||||
'python3 tools/bootstrap.py && PYTHONPATH=src python3 -m unittest discover -s tests/unit 2>&1 | tail -5; echo "exit=$?"',
|
||||
output: "Ran 5 tests in 0.001s\n\nOK\nexit=0",
|
||||
failed: false,
|
||||
},
|
||||
{ command: "make test", output: "Ran 5 tests\n\nOK", failed: false },
|
||||
]
|
||||
const found = runs.map((run) => OpencodeMemoryRecipe.observe(state, run))
|
||||
expect(found).toEqual([
|
||||
undefined,
|
||||
undefined,
|
||||
{
|
||||
recipe: "python3 tools/bootstrap.py && PYTHONPATH=src python3 -m unittest discover -s tests/unit",
|
||||
before: "python3 -m unittest discover -s tests/unit",
|
||||
},
|
||||
undefined,
|
||||
])
|
||||
const entry = { ...OpencodeMemoryRecipe.entry(found[2]!, "github.com/acme/rates"), via: "repository" }
|
||||
expect(entry.title).toBe(
|
||||
"To test github.com/acme/rates, run `python3 tools/bootstrap.py && PYTHONPATH=src python3 -m unittest discover -s tests/unit`",
|
||||
)
|
||||
expect(OpencodeMemoryRecipe.isRecipe(entry)).toBe(true)
|
||||
// Only repository procedures that carry a command are recipes.
|
||||
expect(OpencodeMemoryRecipe.isRecipe({ ...entry, kind: "convention" })).toBe(false)
|
||||
expect(OpencodeMemoryRecipe.isRecipe({ ...entry, via: "ranking" })).toBe(false)
|
||||
expect(
|
||||
OpencodeMemoryRecipe.isRecipe({
|
||||
kind: "procedure",
|
||||
via: "repository",
|
||||
title: "Tests need a recorded run",
|
||||
body: "Ask in #qa.",
|
||||
}),
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
Loading…
Add table
Reference in a new issue