Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -428,3 +428,5 @@ Three tools for launching, monitoring, and cancelling detached background jobs.
- **`goop_write_wave` accepts `verifications[]` and `traceability[]` in two forms, and the distinction matters.** With `task_updates[]` (the common case), supply them as top-level fields — they are processed atomically alongside task updates. With `items[]`, supply them **per-item** — each `items[]` entry can carry its own `verifications[]` and `traceability[]`. A traceability row omitting `wave_number` inherits the enclosing item's wave; an explicit value overrides. A verification omitting `wave_id` defaults to the enclosing item's resolved wave row; an explicit id wins. Everything is written in one transaction — any failure rolls back rows *and* events, so no orphan events survive. Supplying top-level `verifications`/`traceability` **alongside** `items[]` is rejected deliberately, because those payloads would otherwise be silently dropped.

- **Compaction hook replaces `output.prompt`, does not append to `output.context`.** The `experimental.session.compacting` hook (V1-only) overwrites `output.prompt` with a bounded continuation prompt from the shared formatter (`src/shared/continuation-prompt.ts`). `output.prompt` is last-writer-wins — earlier prompt content is not preserved or merged. `output.context` is never touched by the hook; if the host does not read `output.context` after compaction, context entries from other hooks are silently discarded. The hook stands down without mutating either field when no valid workflow can be resolved.

- **Live V2 catalogs can publish `reasoning_options` instead of `variants`.** Real OpenCode host catalogs (e.g. `openai/gpt-5.6-sol`) publish `reasoning: true` plus `reasoning_options: [{type:"effort", values:[...]}]` with **no** `variants` array — only supported ids, no request encoding. `resolveCapabilities` (`src/features/thinking/capability.ts`) extracts these into an id-only supported set; `resolveThinkingValue` returns the honest string id (no fabricated headers/body); and the V2 adapter applies it through `agent.model.variant` alone (`src/core/hooks-v2.ts`). The same shape is classified as `raw.source === "v2"` on the V1 path, where `getVerifiedV1RequestOption` returns `undefined` and the provider default is preserved with a diagnostic — V1 never fabricates a request option.
36 changes: 36 additions & 0 deletions packages/opencode-plugin/src/core/dual-contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,42 @@ describe("dual-contract parity", () => {
expect(v1Resolution.warning).toBeUndefined();
});

it("produces the same supported thinking-level set for equivalent V1 and real-shape V2 host payloads", () => {
// Redacted from the observed live OpenCode host catalog shape: the host
// publishes `reasoning:true` + `reasoning_options:[{type:"effort",...}]`
// with no `variants`. The V1 SDK contract publishes the same conceptual
// effort ladder under `capabilities.reasoning:true` + `options.<key>:[...]`.
// Both shapes flow through the shared `resolveCapabilities` extractor; this
// parity assertion guarantees V1 and V2 agents on the same provider see
// the same supported set, regardless of which contract surfaced the data.
const REAL_LEVELS = ["none", "low", "medium", "high", "xhigh", "max"] as const;

const realShapeV2HostPayload = {
reasoning: true,
reasoning_options: [{ type: "effort", values: [...REAL_LEVELS] }],
};

const equivalentV1HostPayload = {
capabilities: { reasoning: true },
options: { reasoningEffort: [...REAL_LEVELS] },
};

const v2Capabilities = resolveCapabilities(realShapeV2HostPayload);
const v1Capabilities = resolveCapabilities(equivalentV1HostPayload);

expect(v2Capabilities.supported).toEqual([...REAL_LEVELS]);
expect(v1Capabilities.supported).toEqual([...REAL_LEVELS]);
// Set equality is the parity contract: order may differ between sources,
// but the supported set must not.
expect(new Set(v2Capabilities.supported)).toEqual(new Set(v1Capabilities.supported));

// Every canonical GoopSpec label resolves on both contracts.
for (const label of ["none", "low", "medium", "high", "xhigh"] as const) {
expect(resolveThinkingValue(label, v2Capabilities).apply).not.toBeNull();
expect(resolveThinkingValue(label, v1Capabilities).apply).not.toBeNull();
}
});

it("produces equivalent applied values for the same thinking config and compatible model", async () => {
const env = setupTestEnvironment("dual-thinking-parity");
const globalConfigPath = process.env.GOOPSPEC_GLOBAL_CONFIG_PATH;
Expand Down
298 changes: 298 additions & 0 deletions packages/opencode-plugin/src/core/hooks-v2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type {
V2AgentDraft,
V2AgentInfo,
V2CatalogDraft,
V2CatalogModel,
V2RuntimeContext,
V2SessionRequestEvent,
V2ToolExecuteAfterEvent,
Expand All @@ -32,6 +33,17 @@ interface Registrations {
catalogReloads: number;
}

/**
* Casts host catalog test data through a single, explicit boundary. Real V2
* hosts publish fields (`reasoning`, `reasoning_options`) that the minimal
* `V2CatalogModel` type does not declare (see fn_20260803_pia9pfxi); this
* keeps that documented gap from forcing excess-property errors on realistic
* fixtures while still routing every fixture through the real type.
*/
function catalogModel(fields: Record<string, unknown>): V2CatalogModel {
return fields as V2CatalogModel;
}

function createRuntimeContext(
registrations: Registrations,
drafts: { agent?: V2AgentDraft; catalog?: V2CatalogDraft } = {},
Expand Down Expand Up @@ -444,4 +456,290 @@ describe("registerHooksV2()", () => {
else process.env.GOOPSPEC_DEBUG = originalDebug;
}
});

it("sets agent.model.variant from an id-only reasoning_options catalog model without fabricating headers or body", async () => {
const env = setupTestEnvironment("v2-thinking-id-only-apply");
const ctx = createMockPluginContext({ testDir: env.testDir, db: env.db });
contexts.push(ctx);
writeFileSync(
join(ctx.sdk.directory, "goopspec.json"),
JSON.stringify({ agentThinkingLevels: { "executor-high": "medium" } }),
);
const agent: V2AgentInfo = {
id: "goop-executor-high",
model: { providerID: "openai", id: "gpt-5.6-sol" },
request: { headers: { "x-existing": "keep" }, body: { existing: true } },
};
// Real host shape (fn_20260803_pia9pfxi): reasoning:true + reasoning_options,
// no `variants` field at all — the host publishes no request encoding.
const catalog: V2CatalogDraft = {
provider: {
list: () => [
{
provider: { id: "openai" },
models: new Map([
[
"gpt-5.6-sol",
catalogModel({
reasoning: true,
reasoning_options: [
{ type: "effort", values: ["none", "low", "medium", "high", "xhigh", "max"] },
],
}),
],
]),
},
],
},
};
const agents: V2AgentDraft = {
list: () => [agent],
update: (_id, update) => update(agent),
};
const registrations: Registrations = {
agentTransforms: 0,
catalogTransforms: 0,
agentReloads: 0,
catalogReloads: 0,
};

await registerHooksV2(createRuntimeContext(registrations, { agent: agents, catalog }), ctx);

expect(agent.model?.variant).toBe("medium");
expect(agent.request.headers).toEqual({ "x-existing": "keep" });
expect(agent.request.body).toEqual({ existing: true });
env.cleanup();
});

it("applies a configured goop-* thinking level end-to-end via a real-shape reasoning_options catalog and changes the variant when the config changes (wiring Pattern 4)", async () => {
// End-to-end wiring proof for the live host capability shape that caused
// the original defect (fn_20260803_pia9pfxi): the catalog publishes
// `reasoning:true` + `reasoning_options:[{type:"effort",values:[...]}]`
// with no `variants` field. A configured `agentThinkingLevels` value for a
// `goop-*` role must reach the V2 consumer and set `agent.model.variant`
// WITHOUT a preserve-default warning, and changing the configured level
// must change the applied variant. No headers/body are fabricated.
const env = setupTestEnvironment("v2-thinking-wiring-real-shape");
const ctx = createMockPluginContext({ testDir: env.testDir, db: env.db });
contexts.push(ctx);
writeFileSync(
join(ctx.sdk.directory, "goopspec.json"),
JSON.stringify({ agentThinkingLevels: { "executor-medium": "medium" } }),
);
const agent: V2AgentInfo = {
id: "goop-executor-medium",
model: { providerID: "openai", id: "gpt-5.6-sol" },
request: { headers: { "x-existing": "keep" }, body: { existing: true } },
};
const catalog: V2CatalogDraft = {
provider: {
list: () => [
{
provider: { id: "openai" },
models: new Map([
[
"gpt-5.6-sol",
catalogModel({
reasoning: true,
reasoning_options: [
{ type: "effort", values: ["none", "low", "medium", "high", "xhigh", "max"] },
],
}),
],
]),
},
],
},
};
const agents: V2AgentDraft = {
list: () => [agent],
update: (_id, update) => update(agent),
};
const registrations: Registrations = {
agentTransforms: 0,
catalogTransforms: 0,
agentReloads: 0,
catalogReloads: 0,
};
const errorSpy = spyOn(console, "error").mockImplementation(() => {});

const hooks = await registerHooksV2(
createRuntimeContext(registrations, { agent: agents, catalog }),
ctx,
);

// (a) The configured "medium" reaches the consumer and sets the variant,
// with no preserve-default warning and no fabricated headers/body.
expect(agent.model?.variant).toBe("medium");
expect(agent.request.headers).toEqual({ "x-existing": "keep" });
expect(agent.request.body).toEqual({ existing: true });
expect(
errorSpy.mock.calls
.map((c) => String(c[0] ?? ""))
.some((m) => m.includes("preserving the provider default")),
).toBe(false);

// (b) Changing the configured level to "high" changes the applied variant
// (both levels are in the supported set), still with no warning and no
// fabricated headers/body.
writeFileSync(
join(ctx.sdk.directory, "goopspec.json"),
JSON.stringify({ agentThinkingLevels: { "executor-medium": "high" } }),
);
await hooks.reloadThinkingLevels();

expect(agent.model?.variant).toBe("high");
expect(registrations.catalogTransforms).toBe(2);
expect(registrations.agentTransforms).toBe(2);
expect(agent.request.headers).toEqual({ "x-existing": "keep" });
expect(agent.request.body).toEqual({ existing: true });
expect(
errorSpy.mock.calls
.map((c) => String(c[0] ?? ""))
.some((m) => m.includes("preserving the provider default")),
).toBe(false);

errorSpy.mockRestore();
env.cleanup();
});

it("emits the preserve-default warning and leaves the agent unchanged for an unsupported level", async () => {
const env = setupTestEnvironment("v2-thinking-unsupported");
const ctx = createMockPluginContext({ testDir: env.testDir, db: env.db });
contexts.push(ctx);
writeFileSync(
join(ctx.sdk.directory, "goopspec.json"),
JSON.stringify({ agentThinkingLevels: { "executor-high": "xhigh" } }),
);
const agent: V2AgentInfo = {
id: "goop-executor-high",
model: { providerID: "openai", id: "gpt-test" },
request: { headers: { "x-existing": "keep" }, body: { existing: true } },
};
const catalog: V2CatalogDraft = {
provider: {
list: () => [
{
provider: { id: "openai" },
models: new Map([
[
"gpt-test",
catalogModel({
variants: [{ id: "medium", headers: {}, body: { reasoning_effort: "medium" } }],
}),
],
]),
},
],
},
};
const agents: V2AgentDraft = {
list: () => [agent],
update: (_id, update) => update(agent),
};
const registrations: Registrations = {
agentTransforms: 0,
catalogTransforms: 0,
agentReloads: 0,
catalogReloads: 0,
};
const errorSpy = spyOn(console, "error").mockImplementation(() => {});

await registerHooksV2(createRuntimeContext(registrations, { agent: agents, catalog }), ctx);

expect(agent.model?.variant).toBeUndefined();
expect(agent.request.headers).toEqual({ "x-existing": "keep" });
expect(agent.request.body).toEqual({ existing: true });
const logged = errorSpy.mock.calls.map((c) => String(c[0] ?? ""));
expect(
logged.some(
(m) => m.includes("goop-executor-high") && m.includes("preserving the provider default"),
),
).toBe(true);

errorSpy.mockRestore();
env.cleanup();
});

it("does not expose a transiently emptied capabilities map to a reentrant agent transform racing catalog capture", async () => {
const env = setupTestEnvironment("v2-thinking-reentrancy");
const ctx = createMockPluginContext({ testDir: env.testDir, db: env.db });
contexts.push(ctx);
writeFileSync(
join(ctx.sdk.directory, "goopspec.json"),
JSON.stringify({ agentThinkingLevels: { "executor-high": "medium" } }),
);

const agent: V2AgentInfo = {
id: "goop-executor-high",
model: { providerID: "openai", id: "gpt-test" },
request: { headers: {}, body: {} },
};
const reentrantAgent: V2AgentInfo = {
id: "goop-executor-high",
model: { providerID: "openai", id: "gpt-test" },
request: { headers: {}, body: {} },
};
const catalogRecords = [
{
provider: { id: "openai" },
models: new Map([
[
"gpt-test",
catalogModel({
variants: [{ id: "medium", headers: {}, body: { reasoning_effort: "medium" } }],
}),
],
]),
},
];
const registrations: Registrations = {
agentTransforms: 0,
catalogTransforms: 0,
agentReloads: 0,
catalogReloads: 0,
};

// A host that reenters the already-registered agent transform WHILE this
// catalog capture is still enumerating providers — before this refresh's
// new capability snapshot has been captured. Guards against firing on the
// very first registration, when no agent transform is registered yet.
let reentered = false;
const catalog: V2CatalogDraft = {
provider: {
list: () => {
if (!reentered && registrations.agentTransform) {
reentered = true;
void registrations.agentTransform({
list: () => [reentrantAgent],
update: (_id, update) => update(reentrantAgent),
});
}
return catalogRecords;
},
},
};
const agents: V2AgentDraft = {
list: () => [agent],
update: (_id, update) => update(agent),
};

const hooks = await registerHooksV2(
createRuntimeContext(registrations, { agent: agents, catalog }),
ctx,
);
expect(agent.model?.variant).toBe("medium");

// The second refresh is where the reentrant call fires: by now
// `registrations.agentTransform` is already set from the first pass.
await hooks.reloadThinkingLevels();

expect(reentered).toBe(true);
// The reentrant call must resolve against the last-known-good, fully
// populated snapshot — never a transiently emptied map from an in-place
// clear() that runs before the new snapshot is captured.
expect(reentrantAgent.model?.variant).toBe("medium");
expect(reentrantAgent.request.body.reasoning_effort).toBe("medium");
env.cleanup();
});
});
Loading