Merge remote-tracking branch 'origin/dev' into opencode/mighty-wolf
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect } from "bun:test"
|
||||
import {
|
||||
BOULDER_CONTINUATION_PROMPT,
|
||||
SINGLE_TASK_DIRECTIVE,
|
||||
VERIFICATION_REMINDER,
|
||||
VERIFICATION_REMINDER_GEMINI,
|
||||
} from "./system-reminder-templates"
|
||||
@@ -32,8 +33,8 @@ describe("BOULDER_CONTINUATION_PROMPT", () => {
|
||||
expect(checkboxMarkingMatch).not.toBeNull()
|
||||
expect(proceedMatch).not.toBeNull()
|
||||
|
||||
const checkboxPosition = checkboxMarkingMatch!.index
|
||||
const proceedPosition = proceedMatch!.index
|
||||
const checkboxPosition = checkboxMarkingMatch!.index ?? -1
|
||||
const proceedPosition = proceedMatch!.index ?? -1
|
||||
|
||||
expect(checkboxPosition).toBeLessThan(proceedPosition)
|
||||
})
|
||||
@@ -51,3 +52,19 @@ describe("VERIFICATION_REMINDER_GEMINI", () => {
|
||||
expect(VERIFICATION_REMINDER_GEMINI).toContain(":!node_modules")
|
||||
})
|
||||
})
|
||||
|
||||
describe("SINGLE_TASK_DIRECTIVE", () => {
|
||||
it("does not contain refusal language", () => {
|
||||
// given
|
||||
const lowerCaseDirective = SINGLE_TASK_DIRECTIVE.toLowerCase()
|
||||
|
||||
// when / then
|
||||
expect(lowerCaseDirective).not.toContain("refuse")
|
||||
expect(SINGLE_TASK_DIRECTIVE).not.toContain("I refuse")
|
||||
})
|
||||
|
||||
it("contains systematic execution guidance", () => {
|
||||
expect(SINGLE_TASK_DIRECTIVE).toContain("EXECUTION PROTOCOL")
|
||||
expect(SINGLE_TASK_DIRECTIVE).toContain("VERIFICATION IS MANDATORY")
|
||||
})
|
||||
})
|
||||
|
||||
@@ -217,33 +217,26 @@ export const SINGLE_TASK_DIRECTIVE = `
|
||||
|
||||
${createSystemDirective(SystemDirectiveTypes.SINGLE_TASK_ONLY)}
|
||||
|
||||
**STOP. READ THIS BEFORE PROCEEDING.**
|
||||
**EXECUTION PROTOCOL**
|
||||
|
||||
If you were given **multiple genuinely independent goals** (unrelated tasks, parallel workstreams, separate features), you MUST:
|
||||
1. **IMMEDIATELY REFUSE** this request
|
||||
2. **DEMAND** the orchestrator provide a single goal
|
||||
Work systematically. Each unit must be verified before proceeding.
|
||||
|
||||
**What counts as multiple independent tasks (REFUSE):**
|
||||
- "Implement feature A. Also, add feature B."
|
||||
- "Fix bug X. Then refactor module Y. Also update the docs."
|
||||
- Multiple unrelated changes bundled into one request
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
**What is a single task with sequential steps (PROCEED):**
|
||||
- A single goal broken into numbered steps (e.g., "Implement X by: 1. finding files, 2. adding logic, 3. writing tests")
|
||||
- Multi-step context where all steps serve ONE objective
|
||||
- Orchestrator-provided context explaining approach for a single deliverable
|
||||
| Step | Action | Verification |
|
||||
|------|--------|--------------|
|
||||
| 1 | Identify first atomic unit | Smallest complete piece of work |
|
||||
| 2 | Execute fully | Implement the change |
|
||||
| 3 | Verify | \`lsp_diagnostics\`, tests, build |
|
||||
| 4 | Report | State what's done, what remains |
|
||||
| 5 | Continue | Next unit, or await if scope unclear |
|
||||
|
||||
**Your response if genuinely independent tasks are detected:**
|
||||
> "I refuse to proceed. You provided multiple independent tasks. Each task needs full attention.
|
||||
>
|
||||
> PROVIDE EXACTLY ONE GOAL. One deliverable. One clear outcome.
|
||||
>
|
||||
> Batching unrelated tasks causes: incomplete work, missed edge cases, broken tests, wasted context."
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
**WARNING TO ORCHESTRATOR:**
|
||||
- Bundling unrelated tasks RUINS deliverables
|
||||
- Each independent goal needs FULL attention and PROPER verification
|
||||
- Batch delegation of separate concerns = sloppy work = rework = wasted tokens
|
||||
**VERIFICATION IS MANDATORY.** No skipping. No batching completions.
|
||||
|
||||
**REFUSE genuinely multi-task requests. ALLOW single-goal multi-step workflows.**
|
||||
**IF SCOPE SEEMS BROAD:**
|
||||
Complete the first logical unit. Report progress. Await further instruction if needed.
|
||||
|
||||
**REMEMBER:** Prometheus already decomposed the work. Execute what you receive.
|
||||
`
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
/// <reference types="bun-types" />
|
||||
|
||||
import { afterEach, describe, expect, it, spyOn } from "bun:test"
|
||||
import type { LoadedSkill } from "../../features/opencode-skill-loader"
|
||||
import * as shared from "../../shared"
|
||||
import * as slashcommand from "../../tools/slashcommand"
|
||||
import { executeSlashCommand } from "./executor"
|
||||
import * as slashcommand from "../../tools/slashcommand/command-discovery"
|
||||
|
||||
let resolveCommandsInTextSpy: { mockRestore: () => void } | undefined
|
||||
let resolveFileReferencesInTextSpy: { mockRestore: () => void } | undefined
|
||||
@@ -38,6 +39,11 @@ function restoreExecutorSpies(): void {
|
||||
discoverCommandsSyncSpy = undefined
|
||||
}
|
||||
|
||||
async function executeSlashCommand(...args: Parameters<typeof import("./executor").executeSlashCommand>): ReturnType<typeof import("./executor").executeSlashCommand> {
|
||||
const module = await import(`./executor?test=${Date.now()}-${Math.random()}`)
|
||||
return module.executeSlashCommand(...args)
|
||||
}
|
||||
|
||||
afterEach(restoreExecutorSpies)
|
||||
|
||||
function createRestrictedSkill(): LoadedSkill {
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { dirname } from "path"
|
||||
import {
|
||||
resolveCommandsInText,
|
||||
resolveFileReferencesInText,
|
||||
} from "../../shared"
|
||||
import { resolveCommandsInText } from "../../shared/command-executor/resolve-commands-in-text"
|
||||
import { resolveFileReferencesInText } from "../../shared/file-reference-resolver"
|
||||
import { discoverAllSkills, type LoadedSkill, type LazyContentLoader } from "../../features/opencode-skill-loader"
|
||||
import { discoverCommandsSync } from "../../tools/slashcommand"
|
||||
import * as commandDiscovery from "../../tools/slashcommand/command-discovery"
|
||||
import type { CommandInfo as DiscoveredCommandInfo, CommandMetadata } from "../../tools/slashcommand/types"
|
||||
import type { ParsedSlashCommand } from "./types"
|
||||
|
||||
@@ -47,7 +45,7 @@ export interface ExecutorOptions {
|
||||
|
||||
|
||||
async function discoverAllCommands(options?: ExecutorOptions): Promise<CommandInfo[]> {
|
||||
const discoveredCommands = discoverCommandsSync(options?.directory ?? process.cwd(), {
|
||||
const discoveredCommands = commandDiscovery.discoverCommandsSync(options?.directory ?? process.cwd(), {
|
||||
pluginsEnabled: options?.pluginsEnabled,
|
||||
enabledPluginsOverride: options?.enabledPluginsOverride,
|
||||
})
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import type { PluginInput } from "@opencode-ai/plugin"
|
||||
import { isGptModel, isGpt5_4Model } from "../../agents/types"
|
||||
import { isGptModel, isGptNativeSisyphusModel } from "../../agents/types"
|
||||
import {
|
||||
getSessionAgent,
|
||||
resolveRegisteredAgentName,
|
||||
updateSessionAgent,
|
||||
} from "../../features/claude-code-session-state"
|
||||
import { log } from "../../shared"
|
||||
import { AGENT_MODEL_REQUIREMENTS, log } from "../../shared"
|
||||
import { getAgentConfigKey } from "../../shared/agent-display-names"
|
||||
|
||||
const TOAST_TITLE = "NEVER Use Sisyphus with GPT"
|
||||
const TOAST_MESSAGE = [
|
||||
"Sisyphus works best with Claude Opus, and works fine with Kimi/GLM models.",
|
||||
"Do NOT use Sisyphus with GPT (except GPT-5.4 which has specialized support).",
|
||||
"For GPT models (other than 5.4), always use Hephaestus.",
|
||||
"Do NOT use Sisyphus with GPT (except GPT-5.4 and GPT-5.5 which have specialized support).",
|
||||
"For other GPT models, always use Hephaestus.",
|
||||
].join("\n")
|
||||
function showToast(ctx: PluginInput, sessionID: string): void {
|
||||
ctx.client.tui.showToast({
|
||||
@@ -30,6 +30,18 @@ function showToast(ctx: PluginInput, sessionID: string): void {
|
||||
})
|
||||
}
|
||||
|
||||
function getNativeSisyphusGptVariant(model: { providerID: string; modelID: string }): string | undefined {
|
||||
const chain = AGENT_MODEL_REQUIREMENTS["sisyphus"]?.fallbackChain ?? []
|
||||
const exactMatch = chain.find((entry) =>
|
||||
entry.providers.includes(model.providerID) && entry.model === model.modelID
|
||||
)
|
||||
if (exactMatch?.variant !== undefined) {
|
||||
return exactMatch.variant
|
||||
}
|
||||
|
||||
return chain.find((entry) => entry.model === model.modelID)?.variant
|
||||
}
|
||||
|
||||
export function createNoSisyphusGptHook(ctx: PluginInput) {
|
||||
return {
|
||||
"chat.message": async (input: {
|
||||
@@ -43,7 +55,21 @@ export function createNoSisyphusGptHook(ctx: PluginInput) {
|
||||
const agentKey = getAgentConfigKey(rawAgent)
|
||||
const modelID = input.model?.modelID
|
||||
|
||||
if (agentKey === "sisyphus" && modelID && isGptModel(modelID) && !isGpt5_4Model(modelID)) {
|
||||
if (
|
||||
agentKey === "sisyphus"
|
||||
&& input.model
|
||||
&& modelID
|
||||
&& isGptNativeSisyphusModel(modelID)
|
||||
&& output?.message
|
||||
&& output.message.variant === undefined
|
||||
) {
|
||||
const variant = getNativeSisyphusGptVariant(input.model)
|
||||
if (variant !== undefined) {
|
||||
output.message.variant = variant
|
||||
}
|
||||
}
|
||||
|
||||
if (agentKey === "sisyphus" && modelID && isGptModel(modelID) && !isGptNativeSisyphusModel(modelID)) {
|
||||
showToast(ctx, input.sessionID)
|
||||
input.agent = resolveRegisteredAgentName("hephaestus") ?? "hephaestus"
|
||||
if (output?.message) {
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
/// <reference types="bun-types" />
|
||||
|
||||
import { describe, expect, spyOn, test } from "bun:test"
|
||||
import type { PluginInput } from "@opencode-ai/plugin"
|
||||
import { _resetForTesting, updateSessionAgent } from "../../features/claude-code-session-state"
|
||||
import { getAgentDisplayName } from "../../shared/agent-display-names"
|
||||
import { createNoSisyphusGptHook } from "./index"
|
||||
@@ -6,20 +9,29 @@ import { createNoSisyphusGptHook } from "./index"
|
||||
const SISYPHUS_DISPLAY = getAgentDisplayName("sisyphus")
|
||||
const HEPHAESTUS_DISPLAY = getAgentDisplayName("hephaestus")
|
||||
|
||||
function createOutput() {
|
||||
type HookOutput = {
|
||||
message: { agent?: string; variant?: string; [key: string]: unknown }
|
||||
parts: unknown[]
|
||||
}
|
||||
|
||||
function createOutput(): HookOutput {
|
||||
return {
|
||||
message: {},
|
||||
parts: [],
|
||||
}
|
||||
}
|
||||
|
||||
function createHookContext(showToast: (input: unknown) => Promise<unknown>): PluginInput {
|
||||
return {
|
||||
client: { tui: { showToast } },
|
||||
} as unknown as PluginInput
|
||||
}
|
||||
|
||||
describe("no-sisyphus-gpt hook", () => {
|
||||
test("shows toast on every chat.message when sisyphus uses gpt model", async () => {
|
||||
// given - sisyphus (display name) with gpt model
|
||||
const showToast = spyOn({ fn: async () => ({}) }, "fn")
|
||||
const hook = createNoSisyphusGptHook({
|
||||
client: { tui: { showToast } },
|
||||
} as any)
|
||||
const hook = createNoSisyphusGptHook(createHookContext(showToast))
|
||||
|
||||
const output1 = createOutput()
|
||||
const output2 = createOutput()
|
||||
@@ -40,10 +52,11 @@ describe("no-sisyphus-gpt hook", () => {
|
||||
expect(showToast).toHaveBeenCalledTimes(2)
|
||||
expect(output1.message.agent).toBe("hephaestus")
|
||||
expect(output2.message.agent).toBe("hephaestus")
|
||||
expect(showToast.mock.calls[0]?.[0]).toMatchObject({
|
||||
const firstToastCall = (showToast.mock.calls as Array<Array<unknown>>)[0]?.[0]
|
||||
expect(firstToastCall).toMatchObject({
|
||||
body: {
|
||||
title: "NEVER Use Sisyphus with GPT",
|
||||
message: expect.stringContaining("For GPT models (other than 5.4), always use Hephaestus."),
|
||||
message: expect.stringContaining("For other GPT models, always use Hephaestus."),
|
||||
variant: "error",
|
||||
},
|
||||
})
|
||||
@@ -52,9 +65,7 @@ describe("no-sisyphus-gpt hook", () => {
|
||||
test("does not show toast for gpt-5.4 model (Sisyphus has specialized support)", async () => {
|
||||
// given - sisyphus with gpt-5.4 model (should be allowed)
|
||||
const showToast = spyOn({ fn: async () => ({}) }, "fn")
|
||||
const hook = createNoSisyphusGptHook({
|
||||
client: { tui: { showToast } },
|
||||
} as any)
|
||||
const hook = createNoSisyphusGptHook(createHookContext(showToast))
|
||||
|
||||
const output = createOutput()
|
||||
|
||||
@@ -70,12 +81,69 @@ describe("no-sisyphus-gpt hook", () => {
|
||||
expect(output.message.agent).toBeUndefined()
|
||||
})
|
||||
|
||||
test("does not show toast for gpt-5.5 model (native Sisyphus support)", async () => {
|
||||
// given - sisyphus with gpt-5.5 model (should be allowed)
|
||||
const showToast = spyOn({ fn: async () => ({}) }, "fn")
|
||||
const hook = createNoSisyphusGptHook(createHookContext(showToast))
|
||||
|
||||
const output = createOutput()
|
||||
|
||||
// when - chat.message runs with gpt-5.5
|
||||
await hook["chat.message"]?.({
|
||||
sessionID: "ses_gpt55",
|
||||
agent: SISYPHUS_DISPLAY,
|
||||
model: { providerID: "openai", modelID: "gpt-5.5" },
|
||||
}, output)
|
||||
|
||||
// then - no toast, agent NOT switched to Hephaestus
|
||||
expect(showToast).toHaveBeenCalledTimes(0)
|
||||
expect(output.message.agent).toBeUndefined()
|
||||
})
|
||||
|
||||
test("sets medium variant for gpt-5.5 model when native Sisyphus support is used", async () => {
|
||||
// given - sisyphus with gpt-5.5 model and no selected variant
|
||||
const showToast = spyOn({ fn: async () => ({}) }, "fn")
|
||||
const hook = createNoSisyphusGptHook(createHookContext(showToast))
|
||||
|
||||
const output = createOutput()
|
||||
|
||||
// when - chat.message runs with gpt-5.5
|
||||
await hook["chat.message"]?.({
|
||||
sessionID: "ses_gpt55_medium",
|
||||
agent: SISYPHUS_DISPLAY,
|
||||
model: { providerID: "openai", modelID: "gpt-5.5" },
|
||||
}, output)
|
||||
|
||||
// then - Sisyphus stays active and receives its configured GPT-5.5 variant
|
||||
expect(showToast).toHaveBeenCalledTimes(0)
|
||||
expect(output.message.agent).toBeUndefined()
|
||||
expect(output.message.variant).toBe("medium")
|
||||
})
|
||||
|
||||
test("preserves selected variant for gpt-5.5 model when native Sisyphus support is used", async () => {
|
||||
// given - sisyphus with gpt-5.5 model and a selected variant
|
||||
const showToast = spyOn({ fn: async () => ({}) }, "fn")
|
||||
const hook = createNoSisyphusGptHook(createHookContext(showToast))
|
||||
|
||||
const output: HookOutput = { message: { variant: "high" }, parts: [] }
|
||||
|
||||
// when - chat.message runs with gpt-5.5
|
||||
await hook["chat.message"]?.({
|
||||
sessionID: "ses_gpt55_high",
|
||||
agent: SISYPHUS_DISPLAY,
|
||||
model: { providerID: "openai", modelID: "gpt-5.5" },
|
||||
}, output)
|
||||
|
||||
// then - user-selected variant is not overwritten
|
||||
expect(showToast).toHaveBeenCalledTimes(0)
|
||||
expect(output.message.agent).toBeUndefined()
|
||||
expect(output.message.variant).toBe("high")
|
||||
})
|
||||
|
||||
test("does not show toast for non-gpt model", async () => {
|
||||
// given - sisyphus with claude model
|
||||
const showToast = spyOn({ fn: async () => ({}) }, "fn")
|
||||
const hook = createNoSisyphusGptHook({
|
||||
client: { tui: { showToast } },
|
||||
} as any)
|
||||
const hook = createNoSisyphusGptHook(createHookContext(showToast))
|
||||
|
||||
const output = createOutput()
|
||||
|
||||
@@ -94,9 +162,7 @@ describe("no-sisyphus-gpt hook", () => {
|
||||
test("does not show toast for non-sisyphus agent", async () => {
|
||||
// given - hephaestus with gpt model
|
||||
const showToast = spyOn({ fn: async () => ({}) }, "fn")
|
||||
const hook = createNoSisyphusGptHook({
|
||||
client: { tui: { showToast } },
|
||||
} as any)
|
||||
const hook = createNoSisyphusGptHook(createHookContext(showToast))
|
||||
|
||||
const output = createOutput()
|
||||
|
||||
@@ -117,9 +183,7 @@ describe("no-sisyphus-gpt hook", () => {
|
||||
_resetForTesting()
|
||||
updateSessionAgent("ses_4", SISYPHUS_DISPLAY)
|
||||
const showToast = spyOn({ fn: async () => ({}) }, "fn")
|
||||
const hook = createNoSisyphusGptHook({
|
||||
client: { tui: { showToast } },
|
||||
} as any)
|
||||
const hook = createNoSisyphusGptHook(createHookContext(showToast))
|
||||
|
||||
const output = createOutput()
|
||||
|
||||
|
||||
@@ -2,6 +2,65 @@ import { describe, expect, test } from "bun:test"
|
||||
import { injectContinuationPrompt } from "./continuation-prompt-injector"
|
||||
|
||||
describe("ralph-loop continuation prompt injector", () => {
|
||||
test("#given inherited message agent has ZWSP prefix #when injecting continuation prompt #then promptAsync receives normalized agent", async () => {
|
||||
// given
|
||||
let promptBody: { agent?: string } | undefined
|
||||
const ctx = {
|
||||
client: {
|
||||
session: {
|
||||
messages: async () => ({
|
||||
data: [{ info: { agent: "\u200bSisyphus - Ultraworker" } }],
|
||||
}),
|
||||
promptAsync: async (input: { body: { agent?: string } }) => {
|
||||
promptBody = input.body
|
||||
return {}
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// when
|
||||
await injectContinuationPrompt(ctx as never, {
|
||||
sessionID: "ses_ralph_zwsp_agent",
|
||||
prompt: "continue",
|
||||
directory: "/tmp/test",
|
||||
apiTimeoutMs: 50,
|
||||
})
|
||||
|
||||
// then
|
||||
expect(promptBody?.agent).toBe("sisyphus")
|
||||
expect(promptBody?.agent).not.toContain("\u200b")
|
||||
})
|
||||
|
||||
test("#given inherited message agent has no ZWSP prefix #when injecting continuation prompt #then promptAsync receives normalized agent", async () => {
|
||||
// given
|
||||
let promptBody: { agent?: string } | undefined
|
||||
const ctx = {
|
||||
client: {
|
||||
session: {
|
||||
messages: async () => ({
|
||||
data: [{ info: { agent: "Sisyphus - Ultraworker" } }],
|
||||
}),
|
||||
promptAsync: async (input: { body: { agent?: string } }) => {
|
||||
promptBody = input.body
|
||||
return {}
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// when
|
||||
await injectContinuationPrompt(ctx as never, {
|
||||
sessionID: "ses_ralph_clean_agent",
|
||||
prompt: "continue",
|
||||
directory: "/tmp/test",
|
||||
apiTimeoutMs: 50,
|
||||
})
|
||||
|
||||
// then
|
||||
expect(promptBody?.agent).toBe("sisyphus")
|
||||
})
|
||||
|
||||
test("#given inherited message model includes variant #when injecting continuation prompt #then promptAsync receives variant as a top-level field", async () => {
|
||||
// given
|
||||
let promptBody:
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
normalizeSDKResponse,
|
||||
resolveInheritedPromptTools,
|
||||
} from "../../shared"
|
||||
import { normalizeAgentForPromptKey } from "../../shared/agent-display-names"
|
||||
|
||||
type MessageInfo = {
|
||||
agent?: string
|
||||
@@ -69,6 +70,7 @@ export async function injectContinuationPrompt(
|
||||
}
|
||||
|
||||
const inheritedTools = resolveInheritedPromptTools(sourceSessionID, tools)
|
||||
const cleanAgent = normalizeAgentForPromptKey(agent)
|
||||
|
||||
const launchModel = model
|
||||
? { providerID: model.providerID, modelID: model.modelID }
|
||||
@@ -78,7 +80,7 @@ export async function injectContinuationPrompt(
|
||||
await ctx.client.session.promptAsync({
|
||||
path: { id: options.sessionID },
|
||||
body: {
|
||||
...(agent !== undefined ? { agent } : {}),
|
||||
...(cleanAgent !== undefined ? { agent: cleanAgent } : {}),
|
||||
...(launchModel ? { model: launchModel } : {}),
|
||||
...(launchVariant ? { variant: launchVariant } : {}),
|
||||
...(inheritedTools ? { tools: inheritedTools } : {}),
|
||||
|
||||
@@ -17,7 +17,7 @@ describe("ralph-loop", () => {
|
||||
let mockSessionMessages: Array<{ info?: { role?: string }; parts?: Array<{ type: string; text?: string }> }>
|
||||
let mockMessagesApiResponseShape: "data" | "array"
|
||||
|
||||
function createMockPluginInput() {
|
||||
function createMockPluginInput(): Parameters<typeof createRalphLoopHook>[0] {
|
||||
return {
|
||||
client: {
|
||||
session: {
|
||||
@@ -63,7 +63,7 @@ describe("ralph-loop", () => {
|
||||
},
|
||||
},
|
||||
directory: TEST_DIR,
|
||||
} as unknown as Parameters<typeof createRalphLoopHook>[0]
|
||||
} as Parameters<typeof createRalphLoopHook>[0]
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -304,6 +304,33 @@ describe("ralph-loop", () => {
|
||||
expect(state?.iteration).toBe(2)
|
||||
})
|
||||
|
||||
test("should skip continuation when background task is running", async () => {
|
||||
// given - active loop state with a running background task
|
||||
const hook = createRalphLoopHook(createMockPluginInput(), {
|
||||
backgroundManager: {
|
||||
getTasksByParentSession: (sessionID: string) => sessionID === "session-123"
|
||||
? [{ status: "running" }]
|
||||
: [],
|
||||
},
|
||||
})
|
||||
hook.startLoop("session-123", "Build a feature", { maxIterations: 10 })
|
||||
|
||||
// when - session goes idle
|
||||
await hook.event({
|
||||
event: {
|
||||
type: "session.idle",
|
||||
properties: { sessionID: "session-123" },
|
||||
},
|
||||
})
|
||||
|
||||
// then - no continuation should be injected
|
||||
expect(promptCalls.length).toBe(0)
|
||||
|
||||
// then - iteration should not be incremented
|
||||
const state = hook.getState()
|
||||
expect(state?.iteration).toBe(1)
|
||||
})
|
||||
|
||||
test("should stop loop when max iterations reached", async () => {
|
||||
// given - loop at max iteration
|
||||
const hook = createRalphLoopHook(createMockPluginInput())
|
||||
@@ -359,8 +386,8 @@ describe("ralph-loop", () => {
|
||||
expect(hook.getState()).not.toBeNull()
|
||||
})
|
||||
|
||||
test("should skip injection during recovery", async () => {
|
||||
// given - active loop and session in recovery
|
||||
test("should continue after non-abort session error", async () => {
|
||||
// given - active loop and non-abort session error
|
||||
const hook = createRalphLoopHook(createMockPluginInput())
|
||||
hook.startLoop("session-123", "Test task")
|
||||
|
||||
@@ -371,7 +398,7 @@ describe("ralph-loop", () => {
|
||||
},
|
||||
})
|
||||
|
||||
// when - session goes idle immediately
|
||||
// when - session goes idle immediately after the error
|
||||
await hook.event({
|
||||
event: {
|
||||
type: "session.idle",
|
||||
@@ -379,8 +406,9 @@ describe("ralph-loop", () => {
|
||||
},
|
||||
})
|
||||
|
||||
// then - no continuation injected
|
||||
expect(promptCalls.length).toBe(0)
|
||||
// then - continuation is injected without a recovery skip
|
||||
expect(promptCalls.length).toBe(1)
|
||||
expect(hook.getState()?.iteration).toBe(2)
|
||||
})
|
||||
|
||||
test("should clear state on session deletion", async () => {
|
||||
@@ -1144,20 +1172,14 @@ Original task: Build something`
|
||||
test("should not hang when session.messages() throws", async () => {
|
||||
// given - API that throws (simulates timeout error)
|
||||
let apiCallCount = 0
|
||||
const errorMock = {
|
||||
...createMockPluginInput(),
|
||||
client: {
|
||||
...createMockPluginInput().client,
|
||||
session: {
|
||||
...createMockPluginInput().client.session,
|
||||
messages: async () => {
|
||||
apiCallCount++
|
||||
throw new Error("API timeout")
|
||||
},
|
||||
},
|
||||
const errorMock = createMockPluginInput()
|
||||
Object.defineProperty(errorMock.client.session, "messages", {
|
||||
value: async () => {
|
||||
apiCallCount++
|
||||
throw new Error("API timeout")
|
||||
},
|
||||
}
|
||||
const hook = createRalphLoopHook(errorMock as any, {
|
||||
})
|
||||
const hook = createRalphLoopHook(errorMock, {
|
||||
getTranscriptPath: () => join(TEST_DIR, "nonexistent.jsonl"),
|
||||
apiTimeout: 100,
|
||||
})
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
type SessionState = {
|
||||
isRecovering?: boolean
|
||||
}
|
||||
|
||||
export function createLoopSessionRecovery(options?: { recoveryWindowMs?: number }) {
|
||||
const recoveryWindowMs = options?.recoveryWindowMs ?? 5000
|
||||
const sessions = new Map<string, SessionState>()
|
||||
|
||||
function getSessionState(sessionID: string): SessionState {
|
||||
let state = sessions.get(sessionID)
|
||||
if (!state) {
|
||||
state = {}
|
||||
sessions.set(sessionID, state)
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
return {
|
||||
isRecovering(sessionID: string): boolean {
|
||||
return getSessionState(sessionID).isRecovering === true
|
||||
},
|
||||
markRecovering(sessionID: string): void {
|
||||
const state = getSessionState(sessionID)
|
||||
state.isRecovering = true
|
||||
setTimeout(() => {
|
||||
state.isRecovering = false
|
||||
}, recoveryWindowMs)
|
||||
},
|
||||
clear(sessionID: string): void {
|
||||
sessions.delete(sessionID)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/// <reference types="bun-types" />
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
|
||||
import { existsSync, mkdirSync, rmSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { createRalphLoopHook } from "./index"
|
||||
import { clearState } from "./storage"
|
||||
|
||||
describe("ralph-loop non-abort error continuation", () => {
|
||||
const testDirectory = join(tmpdir(), `ralph-loop-non-abort-error-${Date.now()}`)
|
||||
let promptCalls: Array<{ sessionID: string; text: string }>
|
||||
let messagesCalls: Array<{ sessionID: string }>
|
||||
|
||||
beforeEach(() => {
|
||||
promptCalls = []
|
||||
messagesCalls = []
|
||||
mkdirSync(testDirectory, { recursive: true })
|
||||
clearState(testDirectory)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
clearState(testDirectory)
|
||||
if (existsSync(testDirectory)) {
|
||||
rmSync(testDirectory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("continues on next idle after non-abort session error", async () => {
|
||||
// given - an active Ralph Loop receives a recoverable command error
|
||||
const hook = createRalphLoopHook({
|
||||
directory: testDirectory,
|
||||
project: testDirectory,
|
||||
worktree: testDirectory,
|
||||
serverUrl: "http://localhost:4096",
|
||||
$: async () => ({}),
|
||||
client: {
|
||||
session: {
|
||||
messages: async (options: { path: { id: string } }) => {
|
||||
messagesCalls.push({ sessionID: options.path.id })
|
||||
return { data: [] }
|
||||
},
|
||||
promptAsync: async (options: {
|
||||
path: { id: string }
|
||||
body: { parts: Array<{ type: string; text: string }> }
|
||||
}) => {
|
||||
promptCalls.push({
|
||||
sessionID: options.path.id,
|
||||
text: options.body.parts[0]?.text ?? "",
|
||||
})
|
||||
return {}
|
||||
},
|
||||
prompt: async (options: {
|
||||
path: { id: string }
|
||||
body: { parts: Array<{ type: string; text: string }> }
|
||||
}) => {
|
||||
promptCalls.push({
|
||||
sessionID: options.path.id,
|
||||
text: options.body.parts[0]?.text ?? "",
|
||||
})
|
||||
return {}
|
||||
},
|
||||
},
|
||||
tui: {
|
||||
showToast: async () => ({}),
|
||||
},
|
||||
},
|
||||
} as never)
|
||||
|
||||
hook.startLoop("session-123", "Keep working", {
|
||||
messageCountAtStart: 0,
|
||||
maxIterations: 5,
|
||||
})
|
||||
|
||||
await hook.event({
|
||||
event: {
|
||||
type: "session.error",
|
||||
properties: {
|
||||
sessionID: "session-123",
|
||||
error: { name: "CommandFailedError" },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// when - OpenCode emits the idle event caused by that failed command
|
||||
await hook.event({
|
||||
event: { type: "session.idle", properties: { sessionID: "session-123" } },
|
||||
})
|
||||
|
||||
// then - the loop should continue instead of skipping idle as recovery
|
||||
expect(promptCalls).toHaveLength(1)
|
||||
expect(promptCalls[0]?.sessionID).toBe("session-123")
|
||||
expect(promptCalls[0]?.text).toContain("Keep working")
|
||||
expect(messagesCalls.length).toBeGreaterThan(0)
|
||||
expect(hook.getState()?.iteration).toBe(2)
|
||||
})
|
||||
})
|
||||
@@ -11,11 +11,6 @@ import { continueIteration } from "./iteration-continuation"
|
||||
import { handlePendingVerification } from "./pending-verification-handler"
|
||||
import { handleDeletedLoopSession, handleErroredLoopSession } from "./session-event-handler"
|
||||
|
||||
type SessionRecovery = {
|
||||
isRecovering: (sessionID: string) => boolean
|
||||
markRecovering: (sessionID: string) => void
|
||||
clear: (sessionID: string) => void
|
||||
}
|
||||
type LoopStateController = {
|
||||
getState: () => RalphLoopState | null
|
||||
clear: () => boolean
|
||||
@@ -25,7 +20,7 @@ type LoopStateController = {
|
||||
setVerificationSessionID: (sessionID: string, verificationSessionID: string) => RalphLoopState | null
|
||||
restartAfterFailedVerification: (sessionID: string, messageCountAtStart?: number) => RalphLoopState | null
|
||||
}
|
||||
type RalphLoopEventHandlerOptions = { directory: string; apiTimeoutMs: number; getTranscriptPath: (sessionID: string) => string | undefined; checkSessionExists?: RalphLoopOptions["checkSessionExists"]; sessionRecovery: SessionRecovery; loopState: LoopStateController }
|
||||
type RalphLoopEventHandlerOptions = { directory: string; apiTimeoutMs: number; getTranscriptPath: (sessionID: string) => string | undefined; checkSessionExists?: RalphLoopOptions["checkSessionExists"]; backgroundManager?: RalphLoopOptions["backgroundManager"]; loopState: LoopStateController }
|
||||
|
||||
export function createRalphLoopEventHandler(
|
||||
ctx: PluginInput,
|
||||
@@ -48,14 +43,17 @@ export function createRalphLoopEventHandler(
|
||||
inFlightSessions.add(sessionID)
|
||||
|
||||
try {
|
||||
|
||||
if (options.sessionRecovery.isRecovering(sessionID)) {
|
||||
log(`[${HOOK_NAME}] Skipped: in recovery`, { sessionID })
|
||||
const state = options.loopState.getState()
|
||||
if (!state || !state.active) {
|
||||
return
|
||||
}
|
||||
|
||||
const state = options.loopState.getState()
|
||||
if (!state || !state.active) {
|
||||
const hasRunningBackgroundTasks = options.backgroundManager
|
||||
? options.backgroundManager.getTasksByParentSession(sessionID).some((task: { status: string }) => task.status === "running")
|
||||
: false
|
||||
|
||||
if (hasRunningBackgroundTasks) {
|
||||
log(`[${HOOK_NAME}] Skipped: background tasks running`, { sessionID })
|
||||
return
|
||||
}
|
||||
|
||||
@@ -220,12 +218,12 @@ export function createRalphLoopEventHandler(
|
||||
}
|
||||
|
||||
if (event.type === "session.deleted") {
|
||||
if (!handleDeletedLoopSession(props, options.loopState, options.sessionRecovery)) return
|
||||
if (!handleDeletedLoopSession(props, options.loopState)) return
|
||||
return
|
||||
}
|
||||
|
||||
if (event.type === "session.error") {
|
||||
handleErroredLoopSession(props, options.loopState, options.sessionRecovery)
|
||||
handleErroredLoopSession(props, options.loopState)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { PluginInput } from "@opencode-ai/plugin"
|
||||
import type { RalphLoopOptions, RalphLoopState } from "./types"
|
||||
import { getTranscriptPath as getDefaultTranscriptPath } from "../claude-code-hooks/transcript"
|
||||
import { createLoopSessionRecovery } from "./loop-session-recovery"
|
||||
import { createLoopStateController } from "./loop-state-controller"
|
||||
import { createRalphLoopEventHandler } from "./ralph-loop-event-handler"
|
||||
|
||||
@@ -46,20 +45,20 @@ export function createRalphLoopHook(
|
||||
const getTranscriptPath = options?.getTranscriptPath ?? getDefaultTranscriptPath
|
||||
const apiTimeout = options?.apiTimeout ?? DEFAULT_API_TIMEOUT
|
||||
const checkSessionExists = options?.checkSessionExists
|
||||
const backgroundManager = options?.backgroundManager
|
||||
|
||||
const loopState = createLoopStateController({
|
||||
directory: ctx.directory,
|
||||
stateDir,
|
||||
config,
|
||||
})
|
||||
const sessionRecovery = createLoopSessionRecovery()
|
||||
|
||||
const event = createRalphLoopEventHandler(ctx, {
|
||||
directory: ctx.directory,
|
||||
apiTimeoutMs: apiTimeout,
|
||||
getTranscriptPath,
|
||||
checkSessionExists,
|
||||
sessionRecovery,
|
||||
backgroundManager,
|
||||
loopState,
|
||||
})
|
||||
|
||||
|
||||
@@ -7,15 +7,9 @@ type LoopStateController = {
|
||||
clear: () => boolean
|
||||
}
|
||||
|
||||
type SessionRecovery = {
|
||||
clear: (sessionID: string) => void
|
||||
markRecovering: (sessionID: string) => void
|
||||
}
|
||||
|
||||
export function handleDeletedLoopSession(
|
||||
props: Record<string, unknown> | undefined,
|
||||
loopState: LoopStateController,
|
||||
sessionRecovery: SessionRecovery,
|
||||
): boolean {
|
||||
const sessionInfo = props?.info as { id?: string } | undefined
|
||||
if (!sessionInfo?.id) return false
|
||||
@@ -25,14 +19,12 @@ export function handleDeletedLoopSession(
|
||||
loopState.clear()
|
||||
log(`[${HOOK_NAME}] Session deleted, loop cleared`, { sessionID: sessionInfo.id })
|
||||
}
|
||||
sessionRecovery.clear(sessionInfo.id)
|
||||
return true
|
||||
}
|
||||
|
||||
export function handleErroredLoopSession(
|
||||
props: Record<string, unknown> | undefined,
|
||||
loopState: LoopStateController,
|
||||
sessionRecovery: SessionRecovery,
|
||||
): boolean {
|
||||
const sessionID = props?.sessionID as string | undefined
|
||||
const error = props?.error as { name?: string } | undefined
|
||||
@@ -44,13 +36,12 @@ export function handleErroredLoopSession(
|
||||
loopState.clear()
|
||||
log(`[${HOOK_NAME}] User aborted, loop cleared`, { sessionID })
|
||||
}
|
||||
sessionRecovery.clear(sessionID)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
if (sessionID) {
|
||||
sessionRecovery.markRecovering(sessionID)
|
||||
log(`[${HOOK_NAME}] Session error ignored, loop remains active`, { sessionID })
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -22,4 +22,5 @@ export interface RalphLoopOptions {
|
||||
getTranscriptPath?: (sessionId: string) => string
|
||||
apiTimeout?: number
|
||||
checkSessionExists?: (sessionId: string) => Promise<boolean>
|
||||
backgroundManager?: { getTasksByParentSession: (sessionId: string) => Array<{ status: string }> }
|
||||
}
|
||||
|
||||
@@ -1053,7 +1053,6 @@ describe("todo-continuation-enforcer", () => {
|
||||
})
|
||||
|
||||
test("should show countdown toast updates", async () => {
|
||||
fakeTimers.restore()
|
||||
// given - session with incomplete todos
|
||||
const sessionID = "main-toast"
|
||||
setMainSession(sessionID)
|
||||
@@ -1066,7 +1065,7 @@ describe("todo-continuation-enforcer", () => {
|
||||
})
|
||||
|
||||
// then - multiple toast updates during countdown (2s countdown = 2 toasts: "2s" and "1s")
|
||||
await wait(2500)
|
||||
await fakeTimers.advanceBy(1500)
|
||||
expect(toastCalls.length).toBeGreaterThanOrEqual(2)
|
||||
expect(toastCalls[0].message).toContain("2s")
|
||||
}, { timeout: 15000 })
|
||||
|
||||
Reference in New Issue
Block a user