diff --git a/AGENTS.md b/AGENTS.md index 38d65e94..5517915a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,7 +78,7 @@ The V1 loader calls the function directly; the V2 loader reads `.id` and `.setup - **`src/core/sdk-compat.ts`** — Single import seam for the `@opencode-ai/plugin` SDK (V1 types, values). - **`src/core/context.ts`** — Builds the shared `PluginContext` from V1 `PluginInput`. -- **`src/tools/`** — All 30 tool factories in `src/tools/index.ts` (`createTools()`). +- **`src/tools/`** — All 38 tool factories in `src/tools/index.ts` (`createTools()`). The count is pinned by `src/tools/index.test.ts` and `src/core/tools-v2.test.ts`; treat the emitted schema as the authority on each tool's arguments, not this file. - **`src/hooks/`** — All 10 hook factories in `DEFAULT_HOOK_FACTORIES`, assembled by `createHooks()`. - **`src/core/types.ts`** — `PluginContext`, `SdkEssentials`, `ToolContext`, etc. @@ -368,45 +368,15 @@ The config watcher (`src/features/setup/config-watcher.ts`) watches the project- ## Structural Code Tools -Three MCP tools wrapping external CLIs for AST-aware code analysis and transformation. Each resolves its binary via `PATH` or the optional `binaryPaths` config in `goopspec.json` (keys: `ast-grep`, `difft`, `scip`, `scip-typescript`). When a binary is missing, the tool degrades gracefully with an install hint. - -### `ast_grep` — structural code search and rewrite -- **Args:** `pattern` (required), `language`/`lang` (required), `paths` (optional, default `["."]`), `rewrite` (optional replacement → rewrite mode), `apply` (optional bool, default false; dry-run unless true) -- **When to use:** Finding or refactoring code by AST pattern rather than fragile regex. Use for renaming, restructuring, or bulk edits where line-level patterns are unreliable. - -### `difftastic` — AST-aware structural diff -- **Args:** `old`/`oldPath` (required), `new`/`newPath` (required), `checkOnly` (optional bool) -- **Returns:** Structural diff summary + `meaningfully_changed` boolean (from `--exit-code`) -- **When to use:** Deciding whether a change is substantive vs. pure formatting/whitespace. Use in verification gates to skip re-review of cosmetic-only diffs. - -### `scip` — code intelligence over a SCIP index -- **Args:** `action` (`index | definitions | references | implementations`), `symbol` (for queries), `index_path` (optional, default `index.scip`) -- **Generates** an index via `scip-typescript` and answers defs/refs/impls for a symbol. -- **When to use:** Navigating code semantically — who calls a function, where is a type defined/implemented. Use for cross-file impact analysis and refactoring discovery. +Three MCP tools wrap external CLIs for AST-aware code analysis and transformation: `ast_grep` (structural search/rewrite), `difftastic` (AST-aware diff), and `scip` (SCIP-index code intelligence). Each resolves its binary via `PATH` or the optional `binaryPaths` config in `goopspec.json` (keys: `ast-grep`, `difft`, `scip`, `scip-typescript`) and degrades to an install hint when the binary is missing. The emitted tool schema is the authority on each tool's arguments, modes, defaults, and returns — read it at call time; `references/tool-reference.md` carries the maintained cheat sheet. Do not restate the args here: a copy silently goes stale (a prior version of this section fabricated arguments the tools never accepted). ## Image Generation Tool -### `generate_image` — generate images via ChatGPT OAuth - -- **Args:** `prompt` (required), `out`, `images[]`, `size`, `quality`, `outputFormat`, `background`, `count`, `timeout`, `dryRun`, `authFile`, `action`, `moderation`, `outputCompression`, `detail`, `mask`, `allowRefresh` -- **When to use:** Generating images using the user's existing ChatGPT subscription OAuth credentials — no API key required. Uses `gpt-image-2`. Images default to `.goopspec/generated-images/`; pass an explicit `out` path to place an asset elsewhere. For prompting technique, see `goop_reference({ name: "image-prompting" })`. -- **Transparency:** `background: "transparent"` is delivered via green-screen prompt injection plus a local chromakey step that always encodes PNG — transparent output is therefore PNG only, and a non-`.png` `out` extension is rejected at validation. The chromakey codec is `pngjs`, a runtime dependency isolated behind `png-codec.ts`. +`generate_image` generates images via the user's ChatGPT subscription OAuth credentials (no API key) using `gpt-image-2`. The emitted tool schema owns the full argument surface, the transparent-background png-only contract (rendered on green screen, keyed to alpha locally via the `pngjs` codec in `png-codec.ts`), and the two declared-but-ignored arguments (`mask`, `outputCompression`) — read it at call time rather than relying on a restatement here. For prompting technique, load the `image-prompting` reference via `goop_reference`. ## Background Command Tools -Three tools for launching, monitoring, and cancelling detached background jobs. Jobs are scoped to the plugin process lifetime and expire after 30 minutes (1800 seconds) by default. Logs are written to `.goopspec/background-jobs//stdout.log` and `stderr.log`. - -### `background_command` — start a detached background job -- **Args:** `command` (required, string), `cwd` (optional, string — defaults to the plugin working directory), `timeout_seconds` (optional, number — default 1800, range 1–86400) -- **When to use:** Launching long-running processes (dev servers, test suites, watchers) that should not block the agent's response. Returns the job id, pid, cwd, and deadline immediately. - -### `background_status` — poll one job or list all -- **Args:** `job_id` (optional, string — omit to list all jobs), `tail_bytes` (optional, number — default 4096, controls how many bytes of stdout/stderr to show) -- **When to use:** Checking whether a background job is still running, reading its output tail, or listing all registered jobs. Runs a lazy expiry sweep that marks deadline-past jobs as `timed-out` without killing them. - -### `background_cancel` — terminate a job and its process group -- **Args:** `job_id` (required, string) -- **When to use:** Stopping a background job that is stuck, no longer needed, or consuming resources. Sends SIGTERM to the entire process group, escalating to SIGKILL after 2 seconds. Returns a no-op message if the job is already terminal. +Three tools manage detached background jobs: `background_command` (start), `background_status` (poll one or list all), and `background_cancel` (terminate). Jobs are scoped to the plugin process lifetime, expire after 30 minutes (1800 seconds) by default, and write logs to `.goopspec/background-jobs//stdout.log` and `stderr.log`. The emitted tool schemas own the arguments, defaults, ranges, and return shapes. ## Gotchas (Auto) @@ -441,3 +411,5 @@ Three tools for launching, monitoring, and cancelling detached background jobs. - **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. - **System prompt composition: one state block, separate phase enforcement.** `src/hooks/system-transform.ts` injects exactly one `` block per LLM call. Phase enforcement (`## PHASE ENFORCEMENT`) is a separate block built by `src/features/enforcement/phase-context.ts` — it returns rules only, not a second state block. The `` block carries only the workflow doc inventory and a pointer to tool schemas; DB tool descriptions are no longer restated in the system prompt. Shared prompt-authoring strategy (precedence, absolutes, outcome-first, one autonomy policy per role, batching) lives once in `packages/opencode-plugin/references/core-protocol.md` §Prompt Authoring Rules — every other prompt surface points to it, not restates it. + +- **The host loads a built bundle, once per session — source edits in a worktree do not affect the running session.** `package.json` points `main`/`exports` at the source entry (`src/index.ts`), but the `build` script compiles that entry to a `dist/index.js` bundle (`bun build ./src/index.ts --outdir ./dist --target bun`), and the host loads the plugin from the built bundle at its configured install path, once per session. That install path is outside this git worktree, so editing tool behavior here — even after a commit or a passing test run — changes nothing the current session actually executes. An agent that just changed a tool cannot observe the change in its own tool calls, and a clean call must not be treated as evidence the fix works. Validating a plugin behavior change requires rebuilding the bundle at the install path and restarting the host; the only evidence available inside a session is the unit test suite. diff --git a/packages/opencode-plugin/references/tool-reference.md b/packages/opencode-plugin/references/tool-reference.md index 62a64eac..615dd7df 100644 --- a/packages/opencode-plugin/references/tool-reference.md +++ b/packages/opencode-plugin/references/tool-reference.md @@ -65,6 +65,28 @@ Runtime errors for invalid argument combinations name the tool, the offending fi Executors and wave verifiers own reporting tool friction. Every executor and verifier return must include a `FRICTION` section reporting every instance where a GoopSpec tool call failed, behaved unexpectedly, required a retry, or where a tool's schema or description misled the caller — including the exact argument involved and what the schema should have said. If no friction occurred, write "none". Incidents are logged to ADL and Field Notes and mapped to traced amendments through the deviation protocol. **This is the single authoritative statement of friction-reporting ownership; other documents point here.** +### Empty-string argument coalescing + +Tool-call serialization in some hosts injects empty strings (`""`) into argument payloads the caller never authored — most often into status and mode-selecting fields, including inside nested `task_updates[]` entries. An empty string is never a legitimate value for those fields, but it arrives as a *present* value and defeats the caller's intent: a mode conflict the caller never created, an "invalid status" rejection, or `""` stored as a real value. This was confirmed in the field: rewriting descriptions to say "omit, do not pass an empty string" did not stop the next agent from failing the same way, because the empty string is injected below the level any description can reach. + +At the single shared tool-input boundary (`createTools` in `src/tools/index.ts`, which both the V1 and V2 registration paths consume), an exact empty string is treated as absent (omitted) for every field where empty has no legitimate meaning, recursively through arrays and nested objects, before any tool logic runs. Only exact `""` is affected — `null`, `undefined`, `0`, `false`, `[]`, `{}`, and whitespace-only strings pass through untouched (a whitespace-only string may be intentional content). A non-empty value is never dropped. + +A small, explicit set of **tool-field pairs** is exempt, because for those pairs an empty string is a documented, intentional operation and coalescing it would convert that operation into a silent no-op — the same failure class the boundary exists to eliminate. The policy lives in `EMPTY_STRING_LOAD_BEARING_FIELDS_BY_TOOL` in `packages/opencode-plugin/src/shared/coalesce.ts`; it is keyed by canonical tool name first, then field name: + +| Field | Tools | Meaning of empty | +|-------|-------|------------------| +| `new_string` | `goop_write_db`, `goop_write_section`, `goop_save_note` | Delete the matched text. | +| `old_string` | `goop_write_db`, `goop_write_section`, `goop_save_note` | Activate patch mode on presence alone (documented in `shared/write-mode.ts`). | +| `pr_url` | `goop_write_wave` (top-level and `items[]`) | Clear the stored PR URL. | +| `pr_branch` | `goop_write_wave` (top-level and `items[]`) | Clear the stored PR branch. | +| `title` | `goop_write_wave` (top-level and `items[]`) | Clear the stored wave title (same overwrite-with-empty contract as `pr_url`/`pr_branch`). | + +Tool scoping is deliberate: a field name alone never grants an exemption. For example, `title:""` is protected for `goop_write_wave` but coalesces to absent for `memory_save`, `goop_save_note`, and `goop_create_pr`. A new tool receives no exemption by default; add a tool-field pair only after confirming that empty is a documented, load-bearing operation and testing that behavior. + +`content` is deliberately **not** exempt: an empty content has no legitimate meaning in a single-mode write, and exempting it would let an injected `content:""` silently destroy a document. Coalescing it to absent produces a loud `none`-mode error instead of a destructive wipe; in batch mode an empty `content` is already a neutral placeholder and is unaffected. + +Callers should still omit fields they do not intend rather than rely on coalescing — the boundary exists to neutralize injected artifacts a caller cannot prevent, not to license passing empty strings deliberately. + ## Batching cheat sheet The fastest mental model is: if the tool has a plural/batch argument (`doc_types`, `wave_numbers`, `section_keys`, `items`, `entries`, `task_updates`), use it. Preferring batch/plural forms over repeated single calls is the single biggest tool-call efficiency win available. @@ -107,7 +129,7 @@ The fastest mental model is: if the tool has a plural/batch argument (`doc_types | `goop_blocker` | `action: "open" \| "resolve" \| "list"`, `description?`, `severity?`, `wave_id?`, `id?`, `resolution?`, `status?`, `workflow_id?`, `items?: {action, description?, severity?, wave_id?, id?, resolution?, status?, workflow_id?}[]` | `goop_blocker({ action: "open", description: "CI token expired", severity: "high", wave_id: 2 })` | | `goop_acceptance_audit` | `workflow_id?`, `wave_ids?: number[]`, `include_all_blockers?: boolean` | `goop_acceptance_audit({ wave_ids: [1, 2], include_all_blockers: true })` | -`goop_write_wave`'s `verifications`/`traceability` fields replace the retired standalone `goop_record_verification` and `goop_write_traceability` tools — their behavior is fully absorbed as inline args. Available alongside `task_updates` (processed atomically in one transaction; if any task update fails, verifications and traceability are rolled back too). Not available alongside `items` batch mode. +`goop_write_wave`'s `verifications`/`traceability` fields replace the retired standalone `goop_record_verification` and `goop_write_traceability` tools — their behavior is fully absorbed as inline args. Available alongside `task_updates` (processed atomically in one transaction; if any task update fails, verifications and traceability are rolled back too). With `items[]` they are supplied **per-item** inside each item, not at the top level — supplying top-level `verifications`/`traceability` alongside `items[]` is rejected, because those payloads would otherwise be silently dropped. `goop_acceptance_audit` replaces the retired `goop_read_verifications` and `goop_read_waves` tools at the accept gate, plus blockers. Returns combined `{blockers, verifications, waves}` in a JSON comment. @@ -200,7 +222,9 @@ When `false` or absent, only `memory.db` results are returned, identical to the | Tool | Arguments | Example | |------|-----------|---------| -| `generate_image` | `prompt` (required), `out`, `images[]`, `model`, `size`, `quality`, `outputFormat`, `background`, `count`, `inputFidelity`, `timeout`, `dryRun`, `authFile`, `action`, `moderation`, `outputCompression`, `detail`, `mask`, `allowRefresh` | `generate_image({ prompt: "A serene mountain landscape at sunset", out: "docs/hero.png", count: 2 })` | +| `generate_image` | `prompt` (required), `out`, `images[]`, `size`, `quality`, `outputFormat`, `background`, `count`, `timeout`, `dryRun`, `authFile`, `action`, `moderation`, `outputCompression`, `detail`, `mask`, `allowRefresh` | `generate_image({ prompt: "A serene mountain landscape at sunset", out: "docs/hero.png", count: 2 })` | + +`mask` and `outputCompression` are declared but not read by the tool — supplying them has no effect (documented in the emitted schema, the authority on this tool's arguments). Generates images using the user's existing ChatGPT subscription OAuth credentials — no API key required. Images default to `.goopspec/generated-images/`; pass an explicit `out` path to place an asset elsewhere. For prompting technique, see `goop_reference({ name: "image-prompting" })`. @@ -211,7 +235,7 @@ The following tools and extended arguments reduce multi-call sequences to single | Pattern | Replaces | How | |---------|----------|------| | `goop_boot` | 4-5-call agent boot (read docs + search notes + search memory + load references) | Single call returns all requested blocks. Documents require explicit `doc_types` — no default. Wave context is fetched separately via `goop_read_wave`. | -| `goop_write_wave` + `verifications`/`traceability` | Retired `goop_record_verification`/`goop_write_traceability` | Side-payloads run sequentially inside the same `execute()`. Available alongside `task_updates` (atomic transaction); not available in `items` batch mode. | +| `goop_write_wave` + `verifications`/`traceability` | Retired `goop_record_verification`/`goop_write_traceability` | Side-payloads run sequentially inside the same `execute()`. Available alongside `task_updates` (atomic transaction); with `items[]` they are supplied per-item inside each item, not at the top level (top-level side payloads alongside `items[]` are rejected, not dropped). | | `goop_infer_intent` + `autoApply` | Manual infer-then-act two-call flow for `create-workflow`/`transition` | Opt-in (`autoApply: true`), confidence-gated (threshold `0.9`, minimum `0.85`), non-destructive-only. Returns `mutation` in result. | | `goop_append_chronicle` + `alsoLogAdl`/`alsoSaveMemory` | Separate `goop_adl`/`memory_save` calls alongside a chronicle entry | Best-effort sequential writes with partial-failure reporting. Not available in `entries` batch mode. | | `goop_acceptance_audit` | Retired `goop_read_verifications`/`goop_read_waves` + blockers at the accept gate | Single read-only call returns combined `{blockers, verifications, waves}`. | diff --git a/packages/opencode-plugin/src/core/tools-v2.test.ts b/packages/opencode-plugin/src/core/tools-v2.test.ts index 54787135..a9bfafe9 100644 --- a/packages/opencode-plugin/src/core/tools-v2.test.ts +++ b/packages/opencode-plugin/src/core/tools-v2.test.ts @@ -103,7 +103,10 @@ describe("registerToolsV2()", () => { expect(schema.type).toBe("object"); expect(schema.properties).toEqual({ - verbose: { type: "boolean" }, + verbose: { + type: "boolean", + description: expect.any(String), + }, }); }); diff --git a/packages/opencode-plugin/src/features/memory/index.test.ts b/packages/opencode-plugin/src/features/memory/index.test.ts index a117bd41..2597b3d9 100644 --- a/packages/opencode-plugin/src/features/memory/index.test.ts +++ b/packages/opencode-plugin/src/features/memory/index.test.ts @@ -111,15 +111,15 @@ describe("SqliteMemoryManager", () => { expect(high.importance).toBe(10); }); - it("appends reasoning and alternatives to content for decision type", async () => { + it("appends each decision rationale field to content exactly once", async () => { const entry = await mgr.save({ ...baseSaveInput, type: "decision", reasoning: "Better performance", alternatives: ["Option A", "Option B"], }); - expect(entry.content).toContain("Reasoning: Better performance"); - expect(entry.content).toContain("Alternatives considered: Option A, Option B"); + expect(entry.content.match(/Reasoning: Better performance/g)).toHaveLength(1); + expect(entry.content.match(/Alternatives considered: Option A, Option B/g)).toHaveLength(1); }); it("handles missing optional fields gracefully", async () => { @@ -461,6 +461,56 @@ describe("SqliteMemoryManager", () => { expect(results[0].memory.type).toBe("decision"); expect(results[0].memory.importance).toBeGreaterThanOrEqual(5); }); + + // MH11/MH20 investigation: "query plus tag misses results that query + // alone finds." Confirmed as intended AND-combination behavior, not a + // ranking bug: a memory that matches the query text but does not carry + // the filtered concept is excluded by design. A memory that carries the + // concept is retained even when the concept tag is a substring of the + // stored JSON value (the real filter is LIKE '%concept%'). Documented + // in tool-reference.md and the memory_search description; no algorithm + // change made or warranted. + it("a concept filter excludes a query match lacking the concept, under real FTS5", async () => { + await mgr.save({ + ...baseSaveInput, + title: "Gateway router", + content: "the gateway service handles inbound routing", + concepts: ["networking"], + importance: 7, + }); + await mgr.save({ + ...baseSaveInput, + title: "Gateway logging", + content: "the gateway service logs inbound routing", + concepts: ["observability"], + importance: 7, + }); + + const unfiltered = await mgr.search({ query: "gateway routing" }); + expect(unfiltered.length).toBe(2); + + const filtered = await mgr.search({ query: "gateway routing", concepts: ["networking"] }); + expect(filtered.length).toBe(1); + expect(filtered[0].memory.title).toBe("Gateway router"); + }); + + it("a concept filter matches stored tags by substring (real LIKE semantics)", async () => { + // The stored concepts JSON is matched with LIKE '%tag%'. A concept + // stored as "observability" is matched by a "serv" filter fragment, + // and an exact-case stored tag matches a lowercase filter (ASCII + // case-insensitivity). This is the real-manager semantic the mock + // cannot exercise (it uses exact, case-sensitive Array.includes). + await mgr.save({ + ...baseSaveInput, + title: "Telemetry pipeline", + content: "telemetry collection pipeline", + concepts: ["Observability"], + importance: 7, + }); + + const byLowercase = await mgr.search({ query: "telemetry", concepts: ["observability"] }); + expect(byLowercase.length).toBe(1); + }); }); // ----------------------------------------------------------------------- @@ -543,6 +593,39 @@ describe("SqliteMemoryManager", () => { const count = await mgr.forgetByQuery(" "); expect(count).toBe(0); }); + + // Pins the documented memory_forget divergence: the tool's preview path + // caps at limit 20, but confirmed deletion calls forgetByQuery, which + // searches with limit 100. A caller who reads "20 matches" in the + // preview and confirms can therefore delete up to 100 records. This + // test pins the 100-search ceiling at the manager level; the tool-level + // 20-preview limit is pinned in tools/memory-forget/index.test.ts. + it("deletes more than the 20-row preview ceiling when more than 20 match", async () => { + for (let i = 0; i < 30; i++) { + await mgr.save({ + ...baseSaveInput, + title: `Nebula orion match ${i}`, + content: "nebula orion deletable batch", + importance: 5, + }); + } + // One non-matching record whose title and content share no query + // tokens, to prove selectivity (FTS5 tokenizes on whitespace, so any + // shared token would otherwise pull it into the match set). + await mgr.save({ + ...baseSaveInput, + title: "Keeper record", + content: "this record must survive", + importance: 5, + }); + + const count = await mgr.forgetByQuery("nebula orion deletable batch"); + expect(count).toBe(30); + + const remaining = await mgr.search({ query: "survive" }); + expect(remaining.length).toBe(1); + expect(remaining[0].memory.title).toBe("Keeper record"); + }); }); // ----------------------------------------------------------------------- diff --git a/packages/opencode-plugin/src/features/memory/index.ts b/packages/opencode-plugin/src/features/memory/index.ts index 4bb53a00..885611b0 100644 --- a/packages/opencode-plugin/src/features/memory/index.ts +++ b/packages/opencode-plugin/src/features/memory/index.ts @@ -359,6 +359,14 @@ function clampImportance(raw: number | undefined): number { return Math.max(1, Math.min(10, Math.round(scaled))); } +// Decision note: records written before this function became the sole owner of +// composition (commit a8e85e6) contain reasoning/alternatives folded in twice. +// They were deliberately left unmigrated: the duplicated text carries no marker +// distinguishing content a caller genuinely wrote twice from content the two +// composition layers each contributed, so a cleanup pass could destroy +// legitimate content. Affected records stay correct and searchable but rank +// somewhat higher than they should, because content is indexed for FTS at +// weight 5. function buildContent(input: MemorySaveInput): string { let content = input.content; if (input.reasoning) { diff --git a/packages/opencode-plugin/src/features/prompt-audit/index.test.ts b/packages/opencode-plugin/src/features/prompt-audit/index.test.ts index ac0785f9..b948ace1 100644 --- a/packages/opencode-plugin/src/features/prompt-audit/index.test.ts +++ b/packages/opencode-plugin/src/features/prompt-audit/index.test.ts @@ -346,9 +346,39 @@ describe("auditPromptSurfaces (real tree)", () => { // exceed 700. Wording-only; the gate logic in src/tools/index.test.ts // and the allowlist membership are unchanged. tool-reference.md: // 23,329 -> 23,825 bytes (+496); references rollup 170,674 -> 171,170. + // + // The tool-definition-clarity workflow's Wave 3 Task 1 added the + // empty-string argument coalescing boundary (a behavior change, not a + // wording change): shared/coalesce.ts treats an exact "" as absent at + // the single createTools input boundary both V1 and V2 consume, with an + // explicit exclusion list (new_string/old_string delete+patch activation, + // pr_url/pr_branch/title clear). tool-reference.md gained a new + // "Empty-string argument coalescing" subsection under the House Tool- + // Description Standard documenting the boundary and the exclusion table. + // 23,825 -> 26,702 bytes (+2,877); references rollup 171,170 -> 174,047. + // A verifier-found remediation narrowed the exclusions to explicit + // tool-field pairs (rather than field names globally), so a new tool with + // title does not inherit goop_write_wave's clear-title behavior. The + // reference now states the protection-off default for new tools: + // 26,702 -> 27,161 bytes (+459); references 174,047 -> 174,506. + // + // The tool-definition-clarity workflow's Wave 6 Task 2 made the emitted + // tool schemas the sole usage-contract authority and reconciled the + // secondary surfaces against them. tool-reference.md had two real + // contradictions with current behavior, both fixed here: (1) the + // goop_write_wave prose and Combinator table said verifications/ + // traceability were "not available alongside items batch mode", which + // contradicts the per-item side-payload contract Wave 2 established + // (supply per-item inside items[]; top-level side payloads alongside + // items[] are rejected, not dropped); (2) the generate_image arg list + // carried phantom `model` and `inputFidelity` arguments the schema never + // declared, and did not note that `mask`/`outputCompression` are declared + // but ignored. Wording-only; no abs-language keywords added or removed. + // 27,161 -> 27,620 bytes (+459); references 174,506 -> 174,965. + // totalAbsoluteHits unchanged at 328. const references = report.directories.find((d) => d.directory === "references")!; expect(references.files).toBe(19); - expect(references.bytes).toBe(171_170); + expect(references.bytes).toBe(174_965); }); it("total absolute-language hits are 299 (Wave 1 role plumbing plus the Wave 3 execution gate)", () => { @@ -472,7 +502,18 @@ describe("auditPromptSurfaces (real tree)", () => { // never requires a description to exceed 700"), verified against the // audit regex (tool-reference.md 17 -> 18 hits) rather than assumed. // Total: 318 -> 319. - expect(report.totalAbsoluteHits).toBe(319); + // + // The tool-definition-clarity workflow's Wave 3 Task 1 added the + // "Empty-string argument coalescing" subsection to tool-reference.md. + // The +7 delta is the boundary's own contract language, verified against + // the audit regex (4x "never", 3x "only") rather than assumed. All are + // true invariants of the coalescing contract: an empty status is never a + // legitimate value, a non-empty value is never dropped, and only exact + // "" is affected. tool-reference.md 18 -> 25 hits; total 319 -> 326. + // The tool-scoping remediation adds two true boundary invariants (a field + // name never grants an exemption; a new tool receives no exemption by + // default), taking total absolute-language hits 326 -> 328. + expect(report.totalAbsoluteHits).toBe(328); }); it("per-file tokens are consistent with chars via estimateTokens", () => { diff --git a/packages/opencode-plugin/src/features/setup/index.ts b/packages/opencode-plugin/src/features/setup/index.ts index ccb3b118..9cd80709 100644 --- a/packages/opencode-plugin/src/features/setup/index.ts +++ b/packages/opencode-plugin/src/features/setup/index.ts @@ -882,7 +882,9 @@ export function reset( if (!opts.confirmed) { result.success = false; - result.errors.push("Reset requires confirmed: true"); + result.errors.push( + 'Reset requires `confirmed: true`. Retry with `{ action: "reset", confirmed: true }`.', + ); return result; } diff --git a/packages/opencode-plugin/src/shared/coalesce.test.ts b/packages/opencode-plugin/src/shared/coalesce.test.ts new file mode 100644 index 00000000..9146b494 --- /dev/null +++ b/packages/opencode-plugin/src/shared/coalesce.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, it } from "bun:test"; + +import { + EMPTY_STRING_LOAD_BEARING_FIELDS_BY_TOOL, + coalesceEmptyStrings, +} from "./coalesce.js"; + +/** Typed wrapper so object-shape assertions aren't fought by the generic `` return. */ +function coalesce( + input: Record, + toolName?: string, +): Record { + return coalesceEmptyStrings(input, toolName) as Record; +} + +describe("coalesceEmptyStrings", () => { + it("omits an exact empty string at the top level", () => { + const out = coalesce({ wave_number: 3, status: "" }); + expect(out).toEqual({ wave_number: 3 }); + expect(out.status).toBeUndefined(); + }); + + it("omits empty strings nested inside arrays of objects (task_updates shape)", () => { + const out = coalesce({ + wave_number: 3, + status: "", + task_updates: [{ task_index: 0, status: "" }], + verifications: [{ check_name: "test", status: "pass" }], + }); + expect(out).toEqual({ + wave_number: 3, + task_updates: [{ task_index: 0 }], + verifications: [{ check_name: "test", status: "pass" }], + }); + }); + + it("preserves array length and order, recursing into every element", () => { + const out = coalesce({ + items: [{ a: "", b: 1 }, { a: "x", b: "" }, { a: "", b: "" }], + }); + expect(out).toEqual({ + items: [{ b: 1 }, { a: "x" }, {}], + }); + }); + + it("does not touch null, undefined, 0, false, [], or {}", () => { + const out = coalesce({ + n: null, + u: undefined, + z: 0, + f: false, + emptyArr: [], + emptyObj: {}, + }); + expect(out).toEqual({ + n: null, + u: undefined, + z: 0, + f: false, + emptyArr: [], + emptyObj: {}, + }); + }); + + it("preserves whitespace-only strings (may be intentional content)", () => { + const out = coalesce({ a: " ", b: "\t\n", c: " x " }); + expect(out).toEqual({ a: " ", b: "\t\n", c: " x " }); + }); + + it("preserves non-empty strings unchanged", () => { + const out = coalesce({ branch: "feat/x", status: "done" }); + expect(out).toEqual({ branch: "feat/x", status: "done" }); + }); + + it("protects new_string and old_string only for patch-capable tools", () => { + for (const toolName of ["goop_write_db", "goop_write_section", "goop_save_note"]) { + expect( + coalesce({ old_string: "", new_string: "", items: [{ old_string: "", new_string: "" }] }, toolName), + ).toEqual({ + old_string: "", + new_string: "", + items: [{ old_string: "", new_string: "" }], + }); + } + expect(coalesce({ old_string: "", new_string: "" }, "goop_create_pr")).toEqual({}); + }); + + it("protects wave metadata clears only for goop_write_wave", () => { + const out = coalesce({ + pr_url: "", + pr_branch: "", + title: "", + items: [{ wave_number: 1, pr_url: "", pr_branch: "", title: "" }], + }, "goop_write_wave"); + expect(out).toEqual({ + pr_url: "", + pr_branch: "", + title: "", + items: [{ wave_number: 1, pr_url: "", pr_branch: "", title: "" }], + }); + }); + + it("uses protection-off as the safe default for tools sharing a field name", () => { + const out = coalesce({ status: "", pr_url: "" }, "memory_save"); + expect(out).toEqual({}); + expect(coalesce({ title: "" }, "memory_save")).toEqual({}); + expect(coalesce({ title: "" }, "goop_create_pr")).toEqual({}); + }); + + it("coalesces a non-protected sibling alongside a protected field", () => { + const out = coalesce({ status: "", pr_url: "" }, "goop_write_wave"); + expect(out).toEqual({ pr_url: "" }); + }); + + it("handles deeply nested structures", () => { + const out = coalesce({ + level1: { level2: [{ level3: { deep: "", kept: true } }] }, + }); + expect(out).toEqual({ + level1: { level2: [{ level3: { kept: true } }] }, + }); + }); + + it("returns primitives and null unchanged", () => { + expect(coalesceEmptyStrings("hello")).toBe("hello"); + expect(coalesceEmptyStrings(42)).toBe(42); + expect(coalesceEmptyStrings(null)).toBe(null); + expect(coalesceEmptyStrings(undefined)).toBe(undefined); + // An exact empty string at the root is not a keyed field; it is preserved. + expect(coalesceEmptyStrings("")).toBe(""); + }); + + it("uses no exemptions when no tool name is supplied", () => { + expect(coalesce({ title: "", new_string: "" })).toEqual({}); + }); +}); + +describe("EMPTY_STRING_LOAD_BEARING_FIELDS_BY_TOOL", () => { + it("contains exactly the audited tool-field exclusions", () => { + expect( + Object.fromEntries( + Object.entries(EMPTY_STRING_LOAD_BEARING_FIELDS_BY_TOOL).map(([toolName, fields]) => [ + toolName, + [...fields].sort(), + ]), + ), + ).toEqual({ + goop_save_note: ["new_string", "old_string"], + goop_write_db: ["new_string", "old_string"], + goop_write_section: ["new_string", "old_string"], + goop_write_wave: ["pr_branch", "pr_url", "title"], + }); + }); +}); diff --git a/packages/opencode-plugin/src/shared/coalesce.ts b/packages/opencode-plugin/src/shared/coalesce.ts new file mode 100644 index 00000000..09ea40ec --- /dev/null +++ b/packages/opencode-plugin/src/shared/coalesce.ts @@ -0,0 +1,115 @@ +/** + * Empty-string coalescing for tool arguments. + * + * Tool-call serialization in some hosts injects empty strings (`""`) into + * argument payloads the caller never authored — most visibly into status and + * mode-selecting fields, where an empty string is never a legitimate value but + * nevertheless arrives as a *present* value and defeats the caller's intent + * (mode conflicts, "invalid status" rejections, or treating `""` as a real + * value). Documentation cannot fix this: by the time the empty string is + * injected the caller's intent is already gone. + * + * This module treats an exact empty string as absent (omitted) for fields + * where empty carries no legitimate meaning, applied at the single shared + * tool-input boundary (`createTools` in `src/tools/index.ts`) so it runs on + * both the V1 and V2 registration paths from one source of truth. + * + * Contract (see `coalesce.test.ts`): + * - Only exact `""` is affected. `null`, `undefined`, `0`, `false`, `[]`, `{}`, + * and whitespace-only strings are preserved untouched — a whitespace-only + * string may be intentional content, and guessing is how this defect starts. + * - Recurses into arrays (preserving length and order) and nested objects, so + * empty strings inside `task_updates[]` entries are coalesced too. + * - Never silently drops a non-empty value, and never drops an array element or + * object that becomes empty after coalescing. + * - Fields listed for the receiving tool in + * {@link EMPTY_STRING_LOAD_BEARING_FIELDS_BY_TOOL} are exempt, because for + * those specific tool-field pairs an empty string is a documented, + * intentional operation (delete, clear, activate) that coalescing would turn + * into a silent no-op. A field name alone never grants an exemption. + * + * @module shared/coalesce + */ + +/** + * Tool-specific fields where an empty string (`""`) is a documented, + * intentional operation rather than an absent value. An unlisted tool gets no + * exemptions, even when it shares a field name with an allowlisted tool. + * + * Each entry exists because coalescing its empty value to absent would convert + * an intentional operation into a silent no-op — the exact failure class the + * coalescing exists to eliminate. + * + * Audit notes (fields considered but deliberately NOT protected): + * - `content` — coalescing empty content yields a loud `none`-mode error in + * single-mode writes (not a silent no-op), and in batch mode empty content is + * a documented neutral placeholder unaffected by coalescing. Protecting it + * would let an injected `content:""` silently wipe a document, which is the + * destructive case this boundary exists to prevent. + * - Status fields (`status`, `task_updates[].status`, etc.) — an empty status + * is never a valid value; coalescing to absent is the intended fix. + * - Free-text fields (`description`, `detail`, `body`, `entry`, …) — an empty + * value is not a documented operation; coalescing to absent is safe. + */ +export const EMPTY_STRING_LOAD_BEARING_FIELDS_BY_TOOL: Readonly< + Record> +> = { + // Patch-capable tools: an empty new_string deletes matched text; an empty + // old_string activates patch mode on presence alone. Both behaviors are + // documented and tested for every tool in this group. + goop_write_db: new Set(["new_string", "old_string"]), + goop_write_section: new Set(["new_string", "old_string"]), + goop_save_note: new Set(["new_string", "old_string"]), + // Wave metadata: empty values explicitly clear these stored fields. + goop_write_wave: new Set(["pr_url", "pr_branch", "title"]), +}; + +const NO_LOAD_BEARING_FIELDS: ReadonlySet = new Set(); + +/** + * Recursively treat exact empty strings as absent (omitted) for tool arguments + * where an empty string carries no legitimate meaning. + * + * @param value - The raw argument payload (object, array, or primitive). + * @param toolName - Canonical MCP tool name. Only its explicitly listed + * protected fields are exempt; unknown and omitted tool names get no + * exemptions by default. + * @returns A structurally equivalent value with exact empty strings omitted + * from non-protected keys, recursively. + */ +export function coalesceEmptyStrings( + value: T, + toolName?: string, +): T { + const protectedKeys = + toolName === undefined + ? NO_LOAD_BEARING_FIELDS + : (EMPTY_STRING_LOAD_BEARING_FIELDS_BY_TOOL[toolName] ?? NO_LOAD_BEARING_FIELDS); + return walk(value, protectedKeys) as T; +} + +function walk(value: unknown, skip: ReadonlySet): unknown { + if (Array.isArray(value)) { + // Recurse into every element but preserve length and order. An element + // that becomes an empty object after coalescing is NOT dropped — dropping + // would be a silent data change the contract forbids. + return value.map((item) => walk(item, skip)); + } + + if (value !== null && typeof value === "object") { + const source = value as Record; + const out: Record = {}; + for (const [key, val] of Object.entries(source)) { + // Exact empty string on a non-protected key → omit (treat as absent). + // Every other value (including whitespace-only strings) is preserved + // and recursed into. + if (val === "" && !skip.has(key)) { + continue; + } + out[key] = walk(val, skip); + } + return out; + } + + return value; +} diff --git a/packages/opencode-plugin/src/tools/ast-grep/index.ts b/packages/opencode-plugin/src/tools/ast-grep/index.ts index 1a4a24c9..84b46e07 100644 --- a/packages/opencode-plugin/src/tools/ast-grep/index.ts +++ b/packages/opencode-plugin/src/tools/ast-grep/index.ts @@ -105,29 +105,44 @@ function isMissingBinaryError(stderr: string): boolean { export function createAstGrepTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Structural code search and rewrite with ast-grep. " + - "Find matches for an AST pattern, optionally preview or apply rewrites.", + "Structural code search and rewrite via the external ast-grep CLI. " + + "WHEN TO USE: Find or refactor code by AST pattern where line-level regex is unreliable — renaming, restructuring, or bulk edits across files. " + + "WHEN NOT TO USE: difftastic for a structural diff between two files; scip for semantic symbol references and definitions; grep for literal text search. " + + "MODES: search — send pattern + language, omit rewrite; returns matches. rewrite dry-run — add rewrite, omit apply; previews replacements and modifies nothing. rewrite apply — add rewrite AND apply:true; rewrites files in place (-U). apply:true without rewrite is ignored: -U is only added when rewrite is present, so apply alone cannot turn a search into a mutation. " + + "RETURNS: Matches grouped by file, or a dry-run preview plus the exact apply call to issue next, or a count of files modified. " + + "CAVEATS: Resolves the ast-grep binary via PATH or binaryPaths.ast-grep in goopspec.json; a missing binary returns an install-hint string (not a throw), distinguishable from a real 'No matches found.' result. paths defaults to ['.']. language takes precedence over the lang alias when both are supplied.", args: { - pattern: tool.schema.string().describe("ast-grep pattern to search for"), - language: tool.schema + pattern: tool.schema .string() - .describe("Target language identifier (e.g. ts, js, python, rust)"), + .describe("ast-grep pattern to search for. Required in every mode."), + language: tool.schema.string().describe( + "Target language identifier for ast-grep (e.g. ts, js, python, rust). " + + "Takes precedence over the lang alias when both are supplied.", + ), lang: tool.schema .string() .optional() - .describe("Alias for language; language takes precedence"), + .describe( + "Optional alias for language; used only when language is absent. " + + "Prefer language for clarity.", + ), paths: tool.schema - .array(tool.schema.string()) + .array( + tool.schema.string().describe("A single search path, relative to the project directory."), + ) .optional() - .describe("Paths to search (default: current project directory)"), - rewrite: tool.schema - .string() - .optional() - .describe("Replacement string for rewrite mode (sets -r); omit for search mode"), - apply: tool.schema - .boolean() - .optional() - .describe("Apply rewrites in-place (adds -U); default false (dry-run)"), + .describe( + "Paths to search, relative to the project directory. Omit to default to ['.'] " + + "(the current project directory).", + ), + rewrite: tool.schema.string().optional().describe( + "Replacement string that activates rewrite mode (ast-grep -r). " + + "Omit for search mode; do not pass an empty string.", + ), + apply: tool.schema.boolean().optional().describe( + "Set to true alongside rewrite to apply the rewrite in place (ast-grep -U). " + + "Defaults to false (dry-run). Has no effect unless rewrite is also supplied.", + ), }, async execute( args: { diff --git a/packages/opencode-plugin/src/tools/background-cancel/index.ts b/packages/opencode-plugin/src/tools/background-cancel/index.ts index 2fc70504..70d3003e 100644 --- a/packages/opencode-plugin/src/tools/background-cancel/index.ts +++ b/packages/opencode-plugin/src/tools/background-cancel/index.ts @@ -28,11 +28,15 @@ const TERMINAL_STATES: ReadonlySet = new Set(["exited", "cancelled", " export function createBackgroundCancelTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Cancel a background job by terminating its entire process group " + - "(SIGTERM, escalating to SIGKILL after 2s). Returns a no-op message if " + - "the job is already terminal, and not-found for unknown ids. Never throws.", + "Terminate a background job and its entire process group. " + + "WHEN TO USE: Stop a job that is stuck, no longer needed, or consuming resources. " + + "WHEN NOT TO USE: background_status to inspect without stopping; background_command to start a job. " + + "RETURNS: A confirmation naming the job id and signalled process group, or a no-op message when the job is already terminal, or not-found for an unknown id. " + + "CAVEATS: Sends SIGTERM to the whole process group (signalled as the negated pgid) and escalates to SIGKILL after 2 seconds if the group does not exit. Marks the job cancelled before issuing the kill so a late exit code cannot overwrite the state. Never throws.", args: { - job_id: tool.schema.string(), + job_id: tool.schema + .string() + .describe("Id of the background job to cancel, as returned by background_command."), }, async execute(args: { job_id: string }, _context: ToolContext): Promise { try { diff --git a/packages/opencode-plugin/src/tools/background-command/index.ts b/packages/opencode-plugin/src/tools/background-command/index.ts index 522eaa1a..65c8af6d 100644 --- a/packages/opencode-plugin/src/tools/background-command/index.ts +++ b/packages/opencode-plugin/src/tools/background-command/index.ts @@ -48,13 +48,25 @@ function validateTimeoutSeconds(value: number | undefined): string | null { export function createBackgroundCommandTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Start a detached background job and return immediately with its job id, pid, cwd, and deadline. " + - "The default timeout is 30 minutes (1800 seconds); the command is killed automatically when the timeout expires. " + - "Pass a larger timeout_seconds for long-running work such as test suites or dev servers.", + "Start a detached background job and return immediately with its id, pid, cwd, and deadline. " + + "WHEN TO USE: Long-running work that should not block the response — dev servers, slow test suites. " + + "WHEN NOT TO USE: bash to wait on a command; background_status to poll a job; background_cancel to stop one. " + + "RETURNS: A block with the job id, pid, cwd, and ISO-8601 deadline. " + + "CAVEATS: The job outlives this call (detached, via sh -c). timeout_seconds defaults to 1800 (30 minutes); when the timeout expires the command is killed. Must be an integer in [1, 86400]; other values are rejected, not clamped. cwd defaults to the plugin working directory; logs land in .goopspec/background-jobs//.", args: { - command: tool.schema.string(), - cwd: tool.schema.string().optional(), - timeout_seconds: tool.schema.number().optional(), + command: tool.schema + .string() + .describe( + "Shell command to run detached. Must be a non-empty string; an empty command is rejected.", + ), + cwd: tool.schema.string().optional().describe( + "Working directory for the command. Defaults to the plugin working directory " + + "(ctx.sdk.directory) when omitted.", + ), + timeout_seconds: tool.schema.number().optional().describe( + "Maximum runtime in seconds before the job is killed. Defaults to 1800 (30 min). " + + "Must be an integer in [1, 86400]; non-integer or out-of-range values are rejected, not clamped.", + ), }, async execute( args: { command: string; cwd?: string; timeout_seconds?: number }, diff --git a/packages/opencode-plugin/src/tools/background-status/index.ts b/packages/opencode-plugin/src/tools/background-status/index.ts index 06da74b6..1838c756 100644 --- a/packages/opencode-plugin/src/tools/background-status/index.ts +++ b/packages/opencode-plugin/src/tools/background-status/index.ts @@ -180,13 +180,21 @@ function formatJobList(jobs: JobRecord[], now: number): string { export function createBackgroundStatusTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Poll one background job by id, or list all background jobs. Read-only apart from the lazy expiry sweep.", + "Poll one background job by id, or list all registered jobs. " + + "WHEN TO USE: Check whether a job is running, read its recent output, or enumerate every job. " + + "WHEN NOT TO USE: background_command to start a job; background_cancel to stop one. " + + "MODES: detail = send job_id; list = omit it to enumerate all jobs. " + + "RETURNS: With job_id, a detailed report (state, pid, exit code, started/deadline, command, stdout/stderr tails). Without job_id, a table of jobs. " + + "CAVEATS: Runs a lazy expiry sweep that marks any still-running job past its deadline as timed-out but does NOT kill it — the eager timer owns the kill, so timed-out does not mean the process is dead. tail_bytes (default 4096) bounds each output tail.", args: { - job_id: tool.schema.string().optional().describe("Job id to poll. Omit to list all jobs."), - tail_bytes: tool.schema - .number() - .optional() - .describe("Bytes of output tail to show (default 4096)."), + job_id: tool.schema.string().optional().describe( + "Job id to poll for a detailed report. Omit entirely to list all registered jobs; " + + "do not pass an empty string.", + ), + tail_bytes: tool.schema.number().optional().describe( + "Bytes of stdout/stderr tail to show in a single-job report. Defaults to 4096. " + + "Has no effect when listing all jobs.", + ), }, async execute( args: { job_id?: string; tail_bytes?: number }, diff --git a/packages/opencode-plugin/src/tools/difftastic/index.ts b/packages/opencode-plugin/src/tools/difftastic/index.ts index c23687e2..d16d0e8e 100644 --- a/packages/opencode-plugin/src/tools/difftastic/index.ts +++ b/packages/opencode-plugin/src/tools/difftastic/index.ts @@ -122,18 +122,37 @@ function safeParseFile(stdout: string): DifftasticFile | undefined { export function createDifftasticTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Structural (AST-aware) diff between two files using difftastic. " + - "Reports a `meaningfully_changed` boolean derived from difftastic's exit code.", + "Structural (AST-aware) diff between two files via the external difftastic CLI. " + + "WHEN TO USE: Decide whether a change is substantive vs. whitespace or formatting. " + + "WHEN NOT TO USE: git diff for line diffs; ast_grep to find or rewrite patterns across files. " + + "MODES: full diff (default) returns meaningfully_changed plus a per-chunk summary; checkOnly:true returns just the boolean. " + + "RETURNS: A meaningfully_changed line (from difftastic's exit code) and, unless checkOnly, the structural summary. " + + "CAVEATS: old/new alias oldPath/newPath and two paths are runtime-required though all four args are schema-optional (see per-arg details). A missing difft binary returns an install-hint string, not a throw and not a 'no differences' result; set binaryPaths.difft in goopspec.json to override PATH.", args: { - old: tool.schema.string().optional().describe("Original file path (alias for oldPath)"), - oldPath: tool.schema.string().optional().describe("Original file path"), - new: tool.schema.string().optional().describe("Changed file path (alias for newPath)"), - newPath: tool.schema.string().optional().describe("Changed file path"), + old: tool.schema.string().optional().describe( + "Original file path; alias for oldPath. old wins over oldPath when both are supplied. " + + "At least one of old/oldPath is runtime-required.", + ), + oldPath: tool.schema.string().optional().describe( + "Original file path; canonical name for old. " + + "At least one of old/oldPath is runtime-required.", + ), + new: tool.schema.string().optional().describe( + "Changed file path; alias for newPath. new wins over newPath when both are supplied. " + + "At least one of new/newPath is runtime-required.", + ), + newPath: tool.schema.string().optional().describe( + "Changed file path; canonical name for new. " + + "At least one of new/newPath is runtime-required.", + ), checkOnly: tool.schema .boolean() .optional() .default(false) - .describe("Fast boolean-only check; skips full diff output"), + .describe( + "Fast boolean-only check; skips the full diff output and returns just " + + "meaningfully_changed. Defaults to false.", + ), }, async execute( args: { diff --git a/packages/opencode-plugin/src/tools/generate-image/index.ts b/packages/opencode-plugin/src/tools/generate-image/index.ts index 522b9a50..1c79e022 100644 --- a/packages/opencode-plugin/src/tools/generate-image/index.ts +++ b/packages/opencode-plugin/src/tools/generate-image/index.ts @@ -155,25 +155,33 @@ function shapeDryRunOutput( export function createGenerateImageTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Generate images with ChatGPT image models from a text prompt. " + - "Use this when the user asks for a new image, an edit of an existing image, " + - "or a variation conditioned on reference images. Supports custom sizes, " + - "formats, quality, background, and moderation settings. Returns the absolute " + - "paths of files written to the project directory.", + "Generate images with the gpt-image-2 model from a text prompt, optionally conditioned on up to 5 reference images. " + + "WHEN TO USE: New image, image edit, or variation on reference images. " + + "WHEN NOT TO USE: To inspect an existing image (use the host Read tool); to preview without spending credits (use dryRun). " + + "MODES: dryRun returns the constructed request shape (bearer token redacted) and writes nothing; otherwise sends the request and writes files. " + + "RETURNS: On success, the model, absolute paths of written files, any revised prompt, and (for transparent requests) the green-screen note. On failure, a typed error. " + + "CAVEATS: Uses ChatGPT subscription OAuth (no API key); each non-dryRun call spends credits. " + + "Transparent output is png-only: gpt-image-2 has no native alpha, so it is rendered on green screen and keyed to png locally; non-.png out and jpeg/webp outputFormat with background:transparent are rejected at validation. " + + "Default path: /.goopspec/generated-images/-.; count > 1 adds -N before the extension. " + + "mask and outputCompression are declared but not read by the tool; supplying them has no effect.", args: { prompt: tool.schema.string().describe("Text prompt describing the desired image"), out: tool.schema .string() .optional() .describe( - "Output file path; relative paths are resolved against the project root. " + - "When count > 1, a '-1', '-2', ... suffix is inserted before the extension.", + "Output file path; relative paths resolve against the project root. " + + "When omitted, files land at /.goopspec/generated-images/-.. " + + "When count > 1, a '-1', '-2', ... suffix is inserted before the extension. " + + "Must end in .png when background is transparent (chromakey always encodes png).", ), images: tool.schema .array(tool.schema.string()) .max(MAX_INPUT_IMAGES) .optional() - .describe("Up to 5 reference image paths to condition or edit generation on"), + .describe( + "Up to 5 reference image paths to condition or edit generation on (use with action:edit).", + ), size: tool.schema .string() .optional() @@ -188,11 +196,17 @@ export function createGenerateImageTool(ctx: PluginContext): ToolDefinition { outputFormat: tool.schema .string() .optional() - .describe(`Output format. Allowed: ${OUTPUT_FORMATS.join(", ")}`), + .describe( + `Output format. Allowed: ${OUTPUT_FORMATS.join(", ")}. ` + + "jpeg and webp are rejected when background is transparent (png-only).", + ), background: tool.schema .string() .optional() - .describe(`Background treatment. Allowed: ${BACKGROUNDS.join(", ")}`), + .describe( + `Background treatment. Allowed: ${BACKGROUNDS.join(", ")}. ` + + "transparent is png-only and delivered via a local chromakey step.", + ), count: tool.schema .number() .int() @@ -229,7 +243,9 @@ export function createGenerateImageTool(ctx: PluginContext): ToolDefinition { .min(0) .max(100) .optional() - .describe("Output compression level (0-100) — currently unused by the backend"), + .describe( + "Declared but not read by the tool; supplying it has no effect.", + ), detail: tool.schema .string() .optional() @@ -237,7 +253,7 @@ export function createGenerateImageTool(ctx: PluginContext): ToolDefinition { mask: tool.schema .string() .optional() - .describe("Mask image path — currently unused by the backend"), + .describe("Declared but not read by the tool; supplying it has no effect."), allowRefresh: tool.schema .boolean() .optional() diff --git a/packages/opencode-plugin/src/tools/goop-append-chronicle/index.ts b/packages/opencode-plugin/src/tools/goop-append-chronicle/index.ts index 6070df90..e5ff5d28 100644 --- a/packages/opencode-plugin/src/tools/goop-append-chronicle/index.ts +++ b/packages/opencode-plugin/src/tools/goop-append-chronicle/index.ts @@ -228,35 +228,60 @@ function formatCombinedResult(result: CombinedResult): string { export function createGoopAppendChronicleTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Append a timestamped entry to the chronicle. Optionally log an ADL entry " + - "and/or save a memory in the same call. Cross-store atomicity is unavailable.", + "Append a timestamped chronicle entry; optionally log an ADL entry and/or save a memory in the same call. WHEN TO USE: Record progress, piggybacking a decision or memory when both describe one event. WHEN NOT TO USE: goop_write_db({doc_type:\"chronicle\"}) for full-document control; goop_adl or memory_save standalone. MODES: entry (single) or entries[] (batch); alsoLogAdl/alsoSaveMemory apply once, after the batch commits and only on full success. RETURNS: Per-store [OK]/[FAIL] lines for chronicle, ADL, memory. CAVEATS: Cross-store atomicity is unavailable — three separate stores written sequentially. If chronicle fails, aux writes are skipped (no orphans); if an aux write fails after chronicle success, the chronicle stays and the failure is reported — retry that store separately.", args: { - entry: tool.schema.string().optional().describe("Chronicle entry text"), - workflow_id: tool.schema.string().optional().describe("Workflow ID (defaults to active)"), + entry: tool.schema.string().optional().describe("Chronicle entry text (single mode)."), + workflow_id: tool.schema + .string() + .optional() + .describe("Workflow ID; omit to use the active workflow."), entries: tool.schema .array(tool.schema.string()) .optional() - .describe("Batch of chronicle entry strings"), + .describe("Batch of chronicle entry strings; preferred over repeated entry calls."), alsoLogAdl: tool.schema .object({ - type: tool.schema.enum(["decision", "deviation", "observation"] as const), - rule: tool.schema.number().optional(), - description: tool.schema.string(), - entry_action: tool.schema.string(), - files: tool.schema.array(tool.schema.string()).optional(), + type: tool.schema + .enum(["decision", "deviation", "observation"] as const) + .describe("ADL entry category."), + rule: tool.schema + .number() + .optional() + .describe("Optional deviation-rule number this entry relates to."), + description: tool.schema.string().describe("What was decided or observed."), + entry_action: tool.schema.string().describe("Short label for the action taken."), + files: tool.schema + .array(tool.schema.string()) + .optional() + .describe("Optional list of affected file paths."), }) .optional() - .describe("ADL entry to log alongside chronicle"), + .describe( + "ADL entry to log alongside the chronicle; applied once after a successful write, with no cross-store atomicity.", + ), alsoSaveMemory: tool.schema .object({ - title: tool.schema.string(), - content: tool.schema.string(), - type: tool.schema.enum(USER_MEMORY_TYPES).optional(), - importance: tool.schema.number().optional(), - concepts: tool.schema.array(tool.schema.string()).optional(), + title: tool.schema + .string() + .describe("Memory title (100 characters or fewer)."), + content: tool.schema.string().describe("Memory body content."), + type: tool.schema + .enum(USER_MEMORY_TYPES) + .optional() + .describe("Memory type; defaults to observation if omitted."), + importance: tool.schema + .number() + .optional() + .describe("Importance 1-10; defaults to 5 if omitted."), + concepts: tool.schema + .array(tool.schema.string()) + .optional() + .describe("Tags for categorization and search."), }) .optional() - .describe("Memory to save alongside chronicle"), + .describe( + "Memory to save alongside the chronicle; applied once after a successful write, with no cross-store atomicity.", + ), }, async execute( args: { diff --git a/packages/opencode-plugin/src/tools/goop-blocker/index.test.ts b/packages/opencode-plugin/src/tools/goop-blocker/index.test.ts index e78436d5..343bc395 100644 --- a/packages/opencode-plugin/src/tools/goop-blocker/index.test.ts +++ b/packages/opencode-plugin/src/tools/goop-blocker/index.test.ts @@ -563,7 +563,8 @@ describe("goop_blocker mode-selection contract", () => { const result = await tool.execute({ action: "open" }, toolCtx); expect(result).toContain("Error in goop_blocker"); - expect(result).toContain("'description' is required"); + expect(result).toContain('`description` is required for action "open"'); + expect(result).toContain('{ action: "open", description: "what is blocked" }'); expect(ctx.db.getBlockers("default")).toHaveLength(0); }); @@ -573,7 +574,8 @@ describe("goop_blocker mode-selection contract", () => { const result = await tool.execute({ action: "resolve", resolution: "no id" }, toolCtx); expect(result).toContain("Error in goop_blocker"); - expect(result).toContain("'id' is required"); + expect(result).toContain('`id` is required for action "resolve"'); + expect(result).toContain('{ action: "resolve", id: 123 }'); expect(ctx.db.getBlockers("default")).toHaveLength(0); }); diff --git a/packages/opencode-plugin/src/tools/goop-blocker/index.ts b/packages/opencode-plugin/src/tools/goop-blocker/index.ts index b1110a80..fb300a4d 100644 --- a/packages/opencode-plugin/src/tools/goop-blocker/index.ts +++ b/packages/opencode-plugin/src/tools/goop-blocker/index.ts @@ -71,7 +71,9 @@ function processBlockerItem( switch (item.action) { case "open": { if (!item.description) { - throw new Error("'description' is required for open action"); + throw new Error( + '`description` is required for action "open". Retry with `{ action: "open", description: "what is blocked" }`.', + ); } const blockerId = ctx.db.upsertBlocker(workflowId, { @@ -107,7 +109,9 @@ function processBlockerItem( case "resolve": { if (item.id === undefined) { - throw new Error("'id' is required for resolve action"); + throw new Error( + '`id` is required for action "resolve". Retry with `{ action: "resolve", id: 123 }` using the blocker row id.', + ); } const existing = ctx.db.getBlockers(workflowId).find((blocker) => blocker.id === item.id); diff --git a/packages/opencode-plugin/src/tools/goop-boot/index.ts b/packages/opencode-plugin/src/tools/goop-boot/index.ts index 16a524fa..c492a9a3 100644 --- a/packages/opencode-plugin/src/tools/goop-boot/index.ts +++ b/packages/opencode-plugin/src/tools/goop-boot/index.ts @@ -66,24 +66,64 @@ function formatReference(resource: ResolvedResource, section?: string): string { export function createGoopBootTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Load workflow state, documents, Field Notes, memory, and references in one call. " + - "Documents load only when doc_types is explicitly provided; otherwise, use goop_read_db or goop_read_section for explicit reads. " + - "Wave/task context is loaded separately via goop_read_wave.", + "Assemble workflow state, documents, Field Notes, memory, and references in one call. WHEN TO USE: At the start of a turn to orient on the active workflow and prime context in one round-trip. WHEN NOT TO USE: goop_read_wave for wave or task detail; goop_status for a compact status line; the granular tools when you need only one block. RETURNS: One markdown document with a section per requested block (State, Documents, Field Notes, Memory, References). CAVEATS: Every block is opt-in. Documents load ONLY when doc_types is explicitly passed — there is no default document set, so omitting it returns no documents. Wave/task context is never included; fetch it separately via goop_read_wave.", args: { - workflow_id: tool.schema.string().optional(), - doc_types: tool.schema.array(tool.schema.string()).optional(), - include_state: tool.schema.boolean().optional(), - note_query: tool.schema.string().optional(), - note_tags: tool.schema.array(tool.schema.string()).optional(), - note_limit: tool.schema.number().optional(), - note_full: tool.schema.boolean().optional(), - memory_query: tool.schema.string().optional(), - memory_limit: tool.schema.number().optional(), - memory_types: tool.schema.array(tool.schema.enum(MEMORY_TYPES)).optional(), - memory_concepts: tool.schema.array(tool.schema.string()).optional(), - memory_min_importance: tool.schema.number().optional(), - references: tool.schema.array(tool.schema.string()).optional(), - reference_section: tool.schema.string().optional(), + workflow_id: tool.schema + .string() + .optional() + .describe("Target workflow id; omit to use the active workflow."), + doc_types: tool.schema + .array(tool.schema.string()) + .optional() + .describe("Document types to load (opt-in); omit to load NO documents — there is no default set."), + include_state: tool.schema + .boolean() + .optional() + .describe("Include the State block (defaults to true)."), + note_query: tool.schema + .string() + .optional() + .describe("Field Notes search query; supplies the Field Notes block when set."), + note_tags: tool.schema + .array(tool.schema.string()) + .optional() + .describe("Filter the Field Notes block to notes carrying these tags."), + note_limit: tool.schema + .number() + .optional() + .describe("Max Field Notes results (default 10, clamped to 50)."), + note_full: tool.schema + .boolean() + .optional() + .describe("Return full Field Note bodies instead of 200-char snippets."), + memory_query: tool.schema + .string() + .optional() + .describe("Memory search query; supplies the Memory block when set."), + memory_limit: tool.schema + .number() + .optional() + .describe("Max memory results (default 5, clamped to 20)."), + memory_types: tool.schema + .array(tool.schema.enum(MEMORY_TYPES)) + .optional() + .describe("Filter memory results by type (observation, decision, note, todo)."), + memory_concepts: tool.schema + .array(tool.schema.string()) + .optional() + .describe("Filter memory results by concept tags."), + memory_min_importance: tool.schema + .number() + .optional() + .describe("Minimum importance (1-10) for memory results."), + references: tool.schema + .array(tool.schema.string()) + .optional() + .describe("Reference names to load; supplies the References block."), + reference_section: tool.schema + .string() + .optional() + .describe("Heading text to extract from each loaded reference; must match exactly, case-insensitively."), }, async execute( args: { diff --git a/packages/opencode-plugin/src/tools/goop-checkpoint/index.ts b/packages/opencode-plugin/src/tools/goop-checkpoint/index.ts index bcc8923b..2e7e0171 100644 --- a/packages/opencode-plugin/src/tools/goop-checkpoint/index.ts +++ b/packages/opencode-plugin/src/tools/goop-checkpoint/index.ts @@ -17,11 +17,20 @@ import type { CheckpointData, GoopState, PluginContext } from "../../core/types. export function createGoopCheckpointTool(ctx: PluginContext): ToolDefinition { return tool({ - description: "Save, load, or list execution checkpoints.", + description: + "Save, load, or list execution checkpoints of GoopSpec workflow state. WHEN TO USE: To snapshot in-memory state before a risky operation, or restore it afterward. WHEN NOT TO USE: goop_state for a live state read or transition; goop_compact for session compaction. MODES: save = id plus optional context, snapshots the full GoopState; load = id, restores it; list = no other arguments. RETURNS: A confirmation with the checkpoint id; on load, the saved timestamp, workflow, phase, mode, and context. CAVEATS: id is required for save and load and ignored for list. The snapshot is a deep copy taken at save time, immune to later mutations.", args: { - action: tool.schema.enum(["save", "load", "list"]), - id: tool.schema.string().optional(), - context: tool.schema.record(tool.schema.string(), tool.schema.unknown()).optional(), + action: tool.schema + .enum(["save", "load", "list"]) + .describe("save snapshots state, load restores a snapshot, list enumerates saved ids."), + id: tool.schema + .string() + .optional() + .describe("Checkpoint id; required for save and load, ignored for list."), + context: tool.schema + .record(tool.schema.string(), tool.schema.unknown()) + .optional() + .describe("Optional free-form metadata to store alongside a save (e.g. branch, reason)."), }, async execute( args: { diff --git a/packages/opencode-plugin/src/tools/goop-compact/index.ts b/packages/opencode-plugin/src/tools/goop-compact/index.ts index bf335bf4..c24667a2 100644 --- a/packages/opencode-plugin/src/tools/goop-compact/index.ts +++ b/packages/opencode-plugin/src/tools/goop-compact/index.ts @@ -306,7 +306,8 @@ export function dispatchPendingCompaction(ctx: PluginContext, sessionID: string) export function createGoopCompactTool(ctx: PluginContext): ToolDefinition { return tool({ - description: "Trigger session compaction and record the immediate resume step.", + description: + "Trigger OpenCode session compaction and seed the post-compaction resume step. WHEN TO USE: When the orchestrator context is near its limit and a clean handoff is needed. WHEN NOT TO USE: goop_checkpoint for a reversible state snapshot; goop_status to orient without compacting. RETURNS: A directive to end the turn so compaction can occur, carrying the recorded next_step. CAVEATS: Orchestrator-only and V1-only. If the host lacks session compaction the tool returns 'unavailable', which is not an error. next_step is required and is replayed as the immediate resume action; a queued compaction cannot be doubled.", args: { next_step: tool.schema .string() diff --git a/packages/opencode-plugin/src/tools/goop-create-pr/index.ts b/packages/opencode-plugin/src/tools/goop-create-pr/index.ts index 68d41e39..1e084c8f 100644 --- a/packages/opencode-plugin/src/tools/goop-create-pr/index.ts +++ b/packages/opencode-plugin/src/tools/goop-create-pr/index.ts @@ -77,9 +77,14 @@ function formatWarnings(warnings: ReportViolation[]): string { export function createGoopCreatePrTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Create a GitHub PR with a mandatory GoopSpec terminology gate. " + - "Scans title, body, and branch for internal terms; blocks on violations. " + - "Merge method is applied at merge time and defaults to merge-commit.", + "Create a GitHub pull request via `gh pr create`, gated by a sanitizer that blocks public exposure of GoopSpec-internal terms. " + + "WHEN TO USE: Opening a PR from a GoopSpec feature branch once work is complete. " + + "WHEN NOT TO USE: For gh invocations that must bypass the gate, call gh directly — this tool is the only path that enforces it. " + + "MODES: draft omitted/false creates a ready-for-review PR; draft:true adds --draft and creates a draft PR. " + + "RETURNS: On success, a PR Created block with the GitHub URL. On violation, a PR Creation Blocked report listing each match with line/column and a replacement. On gh failure, the exit code and stderr. " + + "CAVEATS: The gate scans title, body, AND branch. Error-severity terms block; warn-severity terms proceed with a notice. " + + "Inline and fenced code spans in title/body are masked before scanning, but branch names are never masked. " + + "The fix is rewording, not retrying (e.g. wave to phase, ADL to decision log). No merge-method argument; merge method is a repo setting on GitHub.", args: { title: tool.schema.string().describe("PR title"), body: tool.schema.string().describe("PR body/description"), diff --git a/packages/opencode-plugin/src/tools/goop-get-global-config/index.ts b/packages/opencode-plugin/src/tools/goop-get-global-config/index.ts index 0339c6df..fad5cd7d 100644 --- a/packages/opencode-plugin/src/tools/goop-get-global-config/index.ts +++ b/packages/opencode-plugin/src/tools/goop-get-global-config/index.ts @@ -59,7 +59,12 @@ export async function readGlobalConfig(): Promise { export function createGoopGetGlobalConfigTool(_ctx: PluginContext): ToolDefinition { return tool({ - description: "Read the global GoopSpec config. Returns {} if the file does not exist.", + description: + "Read the global GoopSpec config. " + + "WHEN TO USE: Inspect user-global defaults (defaultModel, agentModels, agentThinkingLevels) that apply across every project. " + + "WHEN NOT TO USE: goop_setup(action:\"status\") for the project-local config; memory_search for memory contents. " + + "RETURNS: A JSON object with success, config (the parsed object, or {} when the file is absent), and path. " + + "CAVEATS: Read-only; never writes or creates the file. A non-object or unparseable file returns success:false with an error message and the resolved path.", args: {}, async execute(_args: Record, _context: ToolContext): Promise { const result = await readGlobalConfig(); diff --git a/packages/opencode-plugin/src/tools/goop-infer-intent/index.ts b/packages/opencode-plugin/src/tools/goop-infer-intent/index.ts index f2f44a58..4219fb17 100644 --- a/packages/opencode-plugin/src/tools/goop-infer-intent/index.ts +++ b/packages/opencode-plugin/src/tools/goop-infer-intent/index.ts @@ -577,13 +577,41 @@ async function classifyTranscript( export function createGoopInferIntentTool(ctx: PluginContext): ToolDefinition { return tool({ - description: "Classify a raw voice transcript into a GoopSpec command intent.", + description: + "Classify a transcript into one of eight GoopSpec command intents. " + + "WHEN TO USE: Interpret natural-language or voice input into a structured command. " + + "WHEN NOT TO USE: Call slashcommand when the exact command is known; goop_state for explicit phase transitions without inference. " + + "MODES: classify-only is the default; autoApply:true additionally attempts only eligible non-destructive create-workflow/transition mutations when confidence clears both gates. " + + "RETURNS: Markdown with the command, confidence, extracted slots, autoRun hint, and JSON payload; a mutation object reports applied/result/error when autoApply or confidenceThreshold is supplied. " + + "CAVEATS: Prefers an SDK completion method, falling back to keyword matching. autoApply (default false) gates non-destructive create-workflow/transition mutations only; it requires confidence strictly above 0.85 AND at or above confidenceThreshold (default 0.9, clamped to 0-1). A below-threshold result is never an error — the classification is always returned and mutation.applied is false with an error. autoRun (the markdown hint) is separate from autoApply: it requires confidence >= 0.75 plus no active workflow or an idle-phase workflow.", args: { - transcript: tool.schema.string(), - workflowPhase: tool.schema.string().optional(), - hasActiveWorkflow: tool.schema.boolean().optional(), - autoApply: tool.schema.boolean().optional(), - confidenceThreshold: tool.schema.number().optional(), + transcript: tool.schema + .string() + .describe("Raw voice or text transcript to classify into a command intent."), + workflowPhase: tool.schema + .string() + .optional() + .describe( + "Phase of the active workflow (idle, discuss, plan, execute, accept). Affects only the autoRun hint: auto-run is suggested only when hasActiveWorkflow is false or this is idle.", + ), + hasActiveWorkflow: tool.schema + .boolean() + .optional() + .describe( + "Whether a workflow is currently active. Affects only the autoRun hint; has no effect on autoApply mutations.", + ), + autoApply: tool.schema + .boolean() + .optional() + .describe( + "When true, attempt to apply create-workflow or transition mutations server-side, gated by confidenceThreshold and a hard floor of 0.85. Default false; when false, no mutation is attempted.", + ), + confidenceThreshold: tool.schema + .number() + .optional() + .describe( + "Minimum confidence for autoApply, clamped to 0-1 (default 0.9). Confidence must also exceed a hard floor of 0.85. Read only when autoApply is true.", + ), }, async execute(args: IntentArgs, _context: ToolContext): Promise { try { diff --git a/packages/opencode-plugin/src/tools/goop-read-db/index.ts b/packages/opencode-plugin/src/tools/goop-read-db/index.ts index 6cb6f5a3..26b7ce9f 100644 --- a/packages/opencode-plugin/src/tools/goop-read-db/index.ts +++ b/packages/opencode-plugin/src/tools/goop-read-db/index.ts @@ -25,12 +25,24 @@ export function createGoopReadDbTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Read workflow documents from the GoopSpecDB. " + - "Provide doc_type (single) or doc_types (batch).", + "Read whole workflow documents from GoopSpecDB. WHEN TO USE: Load one doc_type or several doc_types[] in one call. WHEN NOT TO USE: goop_read_section for keyed sections; goop_adl({action:\"read\"}) for the ADL (an event log, not a document); goop_search_docs to find content across workflows. MODES: single = doc_type; batch = doc_types[] (preferred for multiple documents). If both are sent, doc_types[] wins. RETURNS: Raw markdown (single) or docs under \"## {doc_type}\" headings; a \"not found\" message names goop_write_db as the creator. CAVEATS: Valid doc_types: spec, blueprint, chronicle, adl, handoff, requirements, research; unknown types list the valid set.", args: { - doc_type: tool.schema.string().optional(), - doc_types: tool.schema.array(tool.schema.string()).optional(), - workflow_id: tool.schema.string().optional(), + doc_type: tool.schema + .string() + .optional() + .describe( + "Single document type to load; prefer doc_types[] when loading more than one.", + ), + doc_types: tool.schema + .array(tool.schema.string()) + .optional() + .describe( + "Batch of document types to load in one call; preferred over repeated doc_type calls.", + ), + workflow_id: tool.schema + .string() + .optional() + .describe("Target workflow id; omit to use the active workflow."), }, async execute( args: { diff --git a/packages/opencode-plugin/src/tools/goop-read-section/index.ts b/packages/opencode-plugin/src/tools/goop-read-section/index.ts index 5a906442..0053cfc4 100644 --- a/packages/opencode-plugin/src/tools/goop-read-section/index.ts +++ b/packages/opencode-plugin/src/tools/goop-read-section/index.ts @@ -20,13 +20,21 @@ import type { DocType } from "../../features/db/types.js"; export function createGoopReadSectionTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Read structured workflow document sections from GoopSpecDB. " + - "Section reads are separate from full-document goop_read_db reads.", + "Read keyed sections from GoopSpecDB. WHEN TO USE: Load one section_key, several section_keys[], or — with neither key — every section for a doc_type. WHEN NOT TO USE: goop_read_db for whole documents; goop_search_docs to find sections by content across workflows. MODES: single = section_key; batch = section_keys[]; all = omit both. If both keys are sent, section_keys[] wins. RETURNS: Section content (single) or sections under \"## {key}\" headings; a \"not found\" message names goop_write_section. CAVEATS: Sections and whole documents are separate stores — content written via goop_write_db is not returned here until goop_write_section creates a keyed section. doc_type is required.", args: { - doc_type: tool.schema.enum(DOC_TYPES), - section_key: tool.schema.string().optional(), - section_keys: tool.schema.array(tool.schema.string()).optional(), - workflow_id: tool.schema.string().optional(), + doc_type: tool.schema.enum(DOC_TYPES).describe("Document type to read sections from."), + section_key: tool.schema + .string() + .optional() + .describe("Single section key to read; omit both key fields to read every section."), + section_keys: tool.schema + .array(tool.schema.string()) + .optional() + .describe("Batch of section keys to read in one call."), + workflow_id: tool.schema + .string() + .optional() + .describe("Target workflow id; omit to use the active workflow."), }, async execute( args: { diff --git a/packages/opencode-plugin/src/tools/goop-read-wave/index.ts b/packages/opencode-plugin/src/tools/goop-read-wave/index.ts index 547ed7c4..de45dca3 100644 --- a/packages/opencode-plugin/src/tools/goop-read-wave/index.ts +++ b/packages/opencode-plugin/src/tools/goop-read-wave/index.ts @@ -21,11 +21,12 @@ import { formatWaves } from "../../features/db/wave-format.js"; export function createGoopReadWaveTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Read wave, task, PR, status, verification, and traceability rows for one workflow. " + + "Read wave, task, PR, verification, and traceability rows for one workflow. " + "WHEN TO USE: Inspect wave progress, task status, PR links, or recorded verification/traceability rows. " + "WHEN NOT TO USE: goop_read_db loads workflow DOCUMENTS (SPEC, BLUEPRINT) — this reads tracking rows only, and picking the wrong one is a common silent mistake. goop_acceptance_audit combines blockers, verifications, and waves at the accept gate. " + - "RETURNS: A markdown block of wave rows with tasks, progress, and any verification/traceability rows; a no-waves message when none exist. " + - "CAVEATS: workflow_id defaults to the active workflow. Omit wave_numbers to read every wave; supply an array to filter. Read-only.", + "MODES: all = omit wave_numbers; selected = send wave_numbers[] to filter. " + + "RETURNS: A markdown block of wave rows with tasks, progress, and any verification/traceability rows; a no-waves message when none exist. " + + "CAVEATS: workflow_id defaults to the active workflow. Read-only.", args: { workflow_id: tool.schema .string() diff --git a/packages/opencode-plugin/src/tools/goop-reference/index.ts b/packages/opencode-plugin/src/tools/goop-reference/index.ts index 4b6d8189..8dc17acf 100644 --- a/packages/opencode-plugin/src/tools/goop-reference/index.ts +++ b/packages/opencode-plugin/src/tools/goop-reference/index.ts @@ -68,22 +68,29 @@ function formatResource(resource: ResolvedResource, section?: string): string { export function createGoopReferenceTool(ctx: PluginContext): ToolDefinition { return tool({ - description: "Load reference documents or templates. Supports multi-load via `names` array.", + description: + "Load bundled reference documents or templates from disk. WHEN TO USE: To read a reference (e.g. core-protocol, tool-reference) or template, or list what is available. WHEN NOT TO USE: goop_read_db for workflow documents; goop_search_docs to search stored docs. MODES: single = name; multi = names[] (loads each, lists any not-found); list = list:true (optionally filtered by type). RETURNS: Rendered markdown per resource, or an inventory. CAVEATS: section extracts one heading and needs an EXACT, case-insensitive match of the full heading text (not a substring or prefix); a miss returns the whole resource with a 'not found' note, not an error. type defaults to 'reference' with template fallback.", args: { - name: tool.schema.string().optional().describe("Single reference name"), + name: tool.schema + .string() + .optional() + .describe("Single resource name; omit when using names[] or list."), names: tool.schema .array(tool.schema.string()) .optional() - .describe("Multiple reference names (multi-load)"), + .describe("Multiple resource names for a multi-load; takes precedence over name."), type: tool.schema .enum(RESOURCE_TYPES) .optional() - .describe("Filter by type: reference or template"), - list: tool.schema.boolean().optional().describe("List available references"), + .describe("Filter by type: 'reference' or 'template'; defaults to reference with template fallback."), + list: tool.schema + .boolean() + .optional() + .describe("List available resource names instead of loading; combine with type to filter."), section: tool.schema .string() .optional() - .describe("Extract a specific ## section from the resource"), + .describe("Heading text to extract; must match the full heading exactly, case-insensitively."), }, async execute(args): Promise { try { diff --git a/packages/opencode-plugin/src/tools/goop-save-note/index.ts b/packages/opencode-plugin/src/tools/goop-save-note/index.ts index f0882630..51c1d457 100644 --- a/packages/opencode-plugin/src/tools/goop-save-note/index.ts +++ b/packages/opencode-plugin/src/tools/goop-save-note/index.ts @@ -185,63 +185,100 @@ function normalizeTags(tags: unknown): string[] { export function createGoopSaveNoteTool(ctx: PluginContext): ToolDefinition { return tool({ - description: "Save a Field Note to the global knowledge base.", + description: + "Save or patch a Field Note in the global knowledge base. WHEN TO USE: To persist a reusable finding across projects, or patch an existing note by ID. WHEN NOT TO USE: memory_save for process memory; goop_search_notes to read notes back. MODES: create = title+body+tags+source_agent (importance defaults to 5); patch = note_id+old_string (+new_string/replace_all; an empty new_string deletes matched text); batch = items[] only. REJECTED: create fields with note_id; old_string/new_string/replace_all without note_id. RETURNS: The saved note id (fn_...) with char count, or a batch rollup. CAVEATS: items[] is atomic — a failure rolls back all items. Batch was historically non-atomic and could half-succeed, so retry logic built on partial failure no longer applies.", args: { - title: tool.schema.string().optional().describe("Note title (required for new notes)"), - body: tool.schema.string().optional().describe("Note body markdown (required for new notes)"), + title: tool.schema + .string() + .optional() + .describe("Note title; required for create, rejected alongside note_id."), + body: tool.schema + .string() + .optional() + .describe("Note body markdown; required for create, rejected alongside note_id."), tags: tool.schema .array(tool.schema.string()) .optional() - .describe("Categorization tags (required for new notes)"), + .describe("Categorization tags; required for create, rejected alongside note_id."), source_agent: tool.schema .string() .optional() - .describe("Agent saving the note (required for new notes)"), - importance: tool.schema.number().optional().describe("Importance 1-10 (default 5)"), - workflow_id: tool.schema.string().optional().describe("Originating workflow"), - project_id: tool.schema.string().optional().describe("Originating project"), + .describe("Agent saving the note; required for create, rejected alongside note_id."), + importance: tool.schema + .number() + .optional() + .describe("Importance 1-10 (defaults to 5); rejected alongside note_id."), + workflow_id: tool.schema + .string() + .optional() + .describe("Originating workflow; rejected alongside note_id."), + project_id: tool.schema + .string() + .optional() + .describe("Originating project; rejected alongside note_id."), note_id: tool.schema .string() .optional() - .describe("Existing note fn_... id to patch instead of creating a new note"), - old_string: tool.schema.string().optional().describe("Exact existing text to replace"), - new_string: tool.schema.string().optional().describe("Replacement text"), + .describe("Existing note fn_... id; presence activates patch mode — omit to create a new note."), + old_string: tool.schema + .string() + .optional() + .describe("Exact existing text to replace; required when note_id is present (presence activates patch)."), + new_string: tool.schema + .string() + .optional() + .describe("Replacement text; an empty new_string deletes the matched text."), replace_all: tool.schema .boolean() .optional() - .describe("Replace all occurrences instead of requiring a single match"), + .describe("Replace all occurrences instead of requiring a single match."), items: tool.schema .array( tool.schema.object({ - title: tool.schema.string().optional().describe("Note title (required for new notes)"), + title: tool.schema + .string() + .optional() + .describe("Note title for this item; required for create, rejected alongside note_id."), body: tool.schema .string() .optional() - .describe("Note body markdown (required for new notes)"), + .describe("Note body markdown for this item; required for create, rejected alongside note_id."), tags: tool.schema .array(tool.schema.string()) .optional() - .describe("Categorization tags (required for new notes)"), + .describe("Categorization tags for this item; required for create, rejected alongside note_id."), source_agent: tool.schema .string() .optional() - .describe("Agent saving the note (required for new notes)"), - importance: tool.schema.number().optional().describe("Importance 1-10 (default 5)"), - workflow_id: tool.schema.string().optional().describe("Originating workflow"), - project_id: tool.schema.string().optional().describe("Originating project"), + .describe("Agent saving this item; required for create, rejected alongside note_id."), + importance: tool.schema + .number() + .optional() + .describe("Importance 1-10 (defaults to 5) for this item."), + workflow_id: tool.schema.string().optional().describe("Originating workflow for this item."), + project_id: tool.schema.string().optional().describe("Originating project for this item."), note_id: tool.schema .string() .optional() - .describe("Existing note fn_... id to patch instead of creating a new note"), - old_string: tool.schema.string().optional().describe("Exact existing text to replace"), - new_string: tool.schema.string().optional().describe("Replacement text"), + .describe("Existing note fn_... id for this item; presence activates patch mode."), + old_string: tool.schema + .string() + .optional() + .describe("Exact existing text to replace; required when this item's note_id is present."), + new_string: tool.schema + .string() + .optional() + .describe("Replacement text for this item; an empty new_string deletes the matched text."), replace_all: tool.schema .boolean() .optional() - .describe("Replace all occurrences instead of requiring a single match"), + .describe("Replace all occurrences instead of requiring a single match for this item."), }), ) - .optional(), + .optional() + .describe( + "Atomic batch of note writes; each item is create or patch — cannot be supplied alongside top-level create or patch fields.", + ), }, async execute(args: SaveNoteArgs, _context: ToolContext): Promise { try { diff --git a/packages/opencode-plugin/src/tools/goop-search-docs/index.ts b/packages/opencode-plugin/src/tools/goop-search-docs/index.ts index 531396fb..33ca64fb 100644 --- a/packages/opencode-plugin/src/tools/goop-search-docs/index.ts +++ b/packages/opencode-plugin/src/tools/goop-search-docs/index.ts @@ -55,8 +55,7 @@ function formatResult(result: DocumentSearchResult, index: number): string { export function createGoopSearchDocsTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Search workflow documents and sections across all workflows. " + - "Plural filters (workflow_ids, doc_types, section_keys) use OR matching.", + "Search workflow documents and keyed sections by query text. WHEN TO USE: Find where a term appears before reading the whole doc; narrow by workflow, doc_type, section_key, or time window. WHEN NOT TO USE: goop_read_db / goop_read_section when you already know the doc or section key. RETURNS: Ranked results with source (document|section), workflow_id, doc_type, section_key, created_at, and a 160-char snippet; \"No ... found\" when empty. CAVEATS: Plural filters (workflow_ids, doc_types, section_keys) OR within each set — a result matching any value passes, widening not narrowing; filters AND across types. limit defaults to 20 (clamped 1-50); unknown doc_types list the valid set.", args: { query: tool.schema.string().describe("Search query"), workflow_id: tool.schema.string().optional().describe("Filter by workflow ID"), diff --git a/packages/opencode-plugin/src/tools/goop-search-notes/index.ts b/packages/opencode-plugin/src/tools/goop-search-notes/index.ts index 25a2e32f..3b740906 100644 --- a/packages/opencode-plugin/src/tools/goop-search-notes/index.ts +++ b/packages/opencode-plugin/src/tools/goop-search-notes/index.ts @@ -86,32 +86,41 @@ function formatNote( export function createGoopSearchNotesTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Search Field Notes with hybrid FTS5 + tag matching. " + - "Supports scoping by project, workflow, and tags. " + - "Optional body control via `full`, `body_offset`, and `body_limit`. " + - "Use `note_id` to fetch a specific note by ID (bypasses ranking, returns full body).", + "Search Field Notes with hybrid FTS5 plus tag matching. WHEN TO USE: To recall a reusable finding by keywords or tags, scoped to a project or workflow. WHEN NOT TO USE: memory_search for an agent's own process memory; goop_read_db for workflow documents. MODES: search = query and/or tags (default, up to 10 results, max 50); exact-fetch = note_id alone (bypasses ranking, ignores query, returns the full body). RETURNS: A markdown list of notes with tags, importance, agent, and a body slice. CAVEATS: The default body is a 200-char snippet; pass full:true for whole bodies, or body_offset/body_limit for a window (body_limit:0 means unbounded). note_id takes precedence over every other argument.", args: { query: tool.schema .string() .optional() - .describe("Search query (optional when note_id provided)"), - tags: tool.schema.array(tool.schema.string()).optional().describe("Filter by tags"), - project_id: tool.schema.string().optional().describe("Scope to project (omit for global)"), - workflow_id: tool.schema.string().optional().describe("Scope to workflow"), - limit: tool.schema.number().optional().describe("Max results (default 10, max 50)"), + .describe("Search query; optional when note_id is supplied."), + tags: tool.schema + .array(tool.schema.string()) + .optional() + .describe("Filter results to notes carrying all of these tags."), + project_id: tool.schema + .string() + .optional() + .describe("Scope to a project; omit for the global knowledge base."), + workflow_id: tool.schema.string().optional().describe("Scope to a workflow."), + limit: tool.schema + .number() + .optional() + .describe("Max results (default 10, clamped to 50)."), full: tool.schema .boolean() .optional() - .describe("Return full body instead of 200-char snippet"), - body_offset: tool.schema.number().optional().describe("Character offset into note body"), + .describe("Return the whole body instead of a 200-char snippet."), + body_offset: tool.schema + .number() + .optional() + .describe("Character offset into the body (default 0); ignored unless full or body_limit is set."), body_limit: tool.schema .number() .optional() - .describe("Max chars from body_offset (0 = unbounded)"), + .describe("Max chars returned from body_offset (0 means unbounded)."), note_id: tool.schema .string() .optional() - .describe("Fetch exact note by fn_... ID (bypasses search)"), + .describe("Exact fn_... id; when present, bypasses ranking and query and returns the full body."), }, async execute( args: { diff --git a/packages/opencode-plugin/src/tools/goop-setup/index.test.ts b/packages/opencode-plugin/src/tools/goop-setup/index.test.ts index a28eed8f..69ea18dc 100644 --- a/packages/opencode-plugin/src/tools/goop-setup/index.test.ts +++ b/packages/opencode-plugin/src/tools/goop-setup/index.test.ts @@ -239,9 +239,61 @@ describe("goop_setup tool", () => { }); // ========================================================================= - // gitignore side-effect + // action-to-argument legality (contract pinning) // ========================================================================= + describe("action-to-argument legality", () => { + it("scope is ignored by every action — supplying it has no observable effect", async () => { + await exec({ action: "init", projectName: "scope-test" }); + + // Run status with and without scope; output must be identical. + const withoutScope = await exec({ action: "status" }); + const withScope = await exec({ action: "status", scope: "global" }); + expect(withScope).toBe(withoutScope); + + // detect ignores scope too. + const detectPlain = await exec({ action: "detect" }); + const detectScoped = await exec({ action: "detect", scope: "both" }); + expect(detectScoped).toBe(detectPlain); + }); + + it("detect ignores all config args — projectName/defaultModel/agentModels have no effect", async () => { + const result = await exec({ + action: "detect", + projectName: "ignored-name", + defaultModel: "ignored-model", + agentModels: { orchestrator: "ignored/model" }, + }); + // detect reports the directory state, not config args. + expect(result).toContain("Environment Detection"); + expect(result).not.toContain("ignored-name"); + }); + + it("verify ignores all config args", async () => { + await exec({ action: "init", projectName: "verify-real" }); + const result = await exec({ + action: "verify", + projectName: "wrong-name", + defaultModel: "wrong-model", + }); + // verify checks directory/db health, not config args. + expect(result).toContain("All checks passed"); + expect(result).not.toContain("wrong-name"); + }); + + it("status ignores all config args", async () => { + await exec({ action: "init", projectName: "real-name" }); + const result = await exec({ + action: "status", + defaultModel: "ignored-model", + agentModels: { orchestrator: "ignored/model" }, + }); + expect(result).toContain("real-name"); + expect(result).not.toContain("ignored-model"); + }); + }); + + describe("gitignore handling", () => { it("adds .goopspec to .gitignore when gitignoreGoopspec is true", async () => { await exec({ action: "detect", gitignoreGoopspec: true }); diff --git a/packages/opencode-plugin/src/tools/goop-setup/index.ts b/packages/opencode-plugin/src/tools/goop-setup/index.ts index 46c2bc00..63b8d9fd 100644 --- a/packages/opencode-plugin/src/tools/goop-setup/index.ts +++ b/packages/opencode-plugin/src/tools/goop-setup/index.ts @@ -200,28 +200,66 @@ function formatStatus(result: ReturnType): string { export function createGoopSetupTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "GoopSpec configuration and setup. " + - "Actions: detect, init, models, verify, status, reset. " + - "plan/apply are aliases for init.", + "Configure or inspect the GoopSpec project setup. " + + "WHEN TO USE: Initialise a project, view or update per-role model routing, run a health check, show config, or reset. " + + "WHEN NOT TO USE: goop_status for live workflow/phase state; goop_get_global_config for user-global config; goop_state for workflow phase transitions. " + + "MODES: detect inspects the project and reads no other args. init/plan/apply (plan and apply alias init) create .goopspec and config, reading projectName, defaultModel, agentModels, memoryEnabled, gitignoreGoopspec. models reads defaultModel and agentModels to update config, then formats the routing table. verify runs health checks and reads no other args. status shows config and reads no other args. reset requires confirmed:true; preserveData (default true) keeps goopspec.db and checkpoints, false deletes them. " + + "RETURNS: Action-specific markdown (detection report, init summary, model routing table, verify checklist, config status, or reset result). " + + "CAVEATS: scope is declared but ignored by every action. gitignoreGoopspec is additionally applied as a cross-action side effect regardless of action. Confined to the project's .goopspec/ directory.", args: { - action: tool.schema.enum([ - "detect", - "init", - "plan", - "apply", - "verify", - "reset", - "models", - "status", - ]), - projectName: tool.schema.string().optional(), - defaultModel: tool.schema.string().optional(), - agentModels: tool.schema.record(tool.schema.string(), tool.schema.string()).optional(), - memoryEnabled: tool.schema.boolean().optional(), - gitignoreGoopspec: tool.schema.boolean().optional(), - preserveData: tool.schema.boolean().optional(), - confirmed: tool.schema.boolean().optional(), - scope: tool.schema.enum(["global", "project", "both"]).optional(), + action: tool.schema + .enum(["detect", "init", "plan", "apply", "verify", "reset", "models", "status"]) + .describe( + "Setup action: detect inspects; init/plan/apply create .goopspec (plan and apply alias init); models views or updates routing; verify health-checks; status shows config; reset resets config.", + ), + projectName: tool.schema + .string() + .optional() + .describe( + "Project name written to config.json. Read only by init/plan/apply; ignored by every other action.", + ), + defaultModel: tool.schema + .string() + .optional() + .describe( + 'Blanket default model id for all roles. Read by init/plan/apply (writes to config) and models (updates config when supplied); ignored by detect, verify, status, reset.', + ), + agentModels: tool.schema + .record(tool.schema.string(), tool.schema.string()) + .optional() + .describe( + 'Map of agent role to model id (e.g. {"executor-low":"anthropic/claude-sonnet-4-6"}). Read by init/plan/apply and models; ignored by detect, verify, status, reset.', + ), + memoryEnabled: tool.schema + .boolean() + .optional() + .describe( + "Whether the in-process memory system is active. Read only by init/plan/apply; ignored by every other action.", + ), + gitignoreGoopspec: tool.schema + .boolean() + .optional() + .describe( + "When true, adds .goopspec/ to .gitignore. Applied as a cross-action side effect regardless of action, and also written to config by init/plan/apply.", + ), + preserveData: tool.schema + .boolean() + .optional() + .describe( + "Controls reset scope only. Read by reset: true (default) preserves goopspec.db and checkpoints; false deletes them. Ignored by every other action.", + ), + confirmed: tool.schema + .boolean() + .optional() + .describe( + "Must be true to commit a reset; without it reset fails with an error. Read only by reset; ignored by every other action.", + ), + scope: tool.schema + .enum(["global", "project", "both"]) + .optional() + .describe( + "Declared but currently ignored by every action; supplying it has no effect.", + ), }, async execute( args: { diff --git a/packages/opencode-plugin/src/tools/goop-spec/index.test.ts b/packages/opencode-plugin/src/tools/goop-spec/index.test.ts index b24f538c..64213494 100644 --- a/packages/opencode-plugin/src/tools/goop-spec/index.test.ts +++ b/packages/opencode-plugin/src/tools/goop-spec/index.test.ts @@ -245,6 +245,39 @@ describe("goop_spec tool", () => { }); }); + // ----------------------------------------------------------------------- + // argument-to-nothing contract (phase is declared but ignored) + // ----------------------------------------------------------------------- + + describe("phase is ignored by every action", () => { + it("read produces identical output regardless of phase", async () => { + const docDir = join(testDir, GOOPSPEC_DIR); + writeFileSync(join(docDir, "SPEC.md"), "# Spec\nContent.", "utf-8"); + + const tool = createGoopSpecTool(ctx); + const withoutPhase = await tool.execute({ action: "read", file: "spec" }, toolCtx); + const withPhase = await tool.execute( + { action: "read", file: "spec", phase: "execute" }, + toolCtx, + ); + expect(withPhase).toBe(withoutPhase); + }); + + it("list produces identical output regardless of phase", async () => { + const tool = createGoopSpecTool(ctx); + const withoutPhase = await tool.execute({ action: "list" }, toolCtx); + const withPhase = await tool.execute({ action: "list", phase: "discuss" }, toolCtx); + expect(withPhase).toBe(withoutPhase); + }); + + it("validate produces identical output regardless of phase", async () => { + const tool = createGoopSpecTool(ctx); + const withoutPhase = await tool.execute({ action: "validate" }, toolCtx); + const withPhase = await tool.execute({ action: "validate", phase: "plan" }, toolCtx); + expect(withPhase).toBe(withoutPhase); + }); + }); + // ----------------------------------------------------------------------- // error handling // ----------------------------------------------------------------------- diff --git a/packages/opencode-plugin/src/tools/goop-spec/index.ts b/packages/opencode-plugin/src/tools/goop-spec/index.ts index 48f0213e..65282cfb 100644 --- a/packages/opencode-plugin/src/tools/goop-spec/index.ts +++ b/packages/opencode-plugin/src/tools/goop-spec/index.ts @@ -177,11 +177,31 @@ function validateDocs(ctx: PluginContext): string { export function createGoopSpecTool(ctx: PluginContext): ToolDefinition { return tool({ - description: "Read, list, or validate SPEC.md and BLUEPRINT.md files.", + description: + "Read, list, or validate the active workflow's SPEC.md and BLUEPRINT.md. " + + "WHEN TO USE: Inspect or validate spec/blueprint for the active workflow. " + + "WHEN NOT TO USE: goop_read_db for other docs or workflows; goop_read_section for keyed sections. " + + "MODES: read returns SPEC.md and/or BLUEPRINT.md (file picks which, default both); list enumerates each workflow's docs; validate checks SPEC.md sections and must-haves, BLUEPRINT.md sections, and wave plan. " + + "RETURNS: Markdown content (read), a doc inventory (list), or a pass/fail report (validate). " + + "CAVEATS: file is read only by read; phase is ignored by every action. Active workflow only.", args: { - action: tool.schema.enum(["read", "list", "validate"]), - file: tool.schema.enum(["spec", "plan", "both"]).optional(), - phase: tool.schema.string().optional(), + action: tool.schema + .enum(["read", "list", "validate"]) + .describe( + "Operation to perform: read returns doc content, list enumerates workflows and doc presence, validate checks required sections and wave-plan existence.", + ), + file: tool.schema + .enum(["spec", "plan", "both"]) + .optional() + .describe( + "Which file to return; only read by action:\"read\" (defaults to both). Ignored by list and validate.", + ), + phase: tool.schema + .string() + .optional() + .describe( + "Declared but currently ignored by every action; supplying it has no effect.", + ), }, async execute( args: { diff --git a/packages/opencode-plugin/src/tools/goop-state/index.ts b/packages/opencode-plugin/src/tools/goop-state/index.ts index ecb3092a..790e3abf 100644 --- a/packages/opencode-plugin/src/tools/goop-state/index.ts +++ b/packages/opencode-plugin/src/tools/goop-state/index.ts @@ -297,7 +297,9 @@ function executeAction( // -- Phase transition --------------------------------------------------- case "transition": { - if (!args.phase) return "**Error:** `phase` is required for transition."; + if (!args.phase) { + return '**Error (goop_state):** transition requires `phase`. Retry with `{ action: "transition", phase: "execute" }`, using one of idle, discuss, plan, execute, or accept.'; + } if (!isValidPhase(args.phase)) { return `**Error:** Invalid phase "${args.phase}". Valid: ${WORKFLOW_PHASES.join(", ")}`; } @@ -344,7 +346,9 @@ function executeAction( // -- Mode --------------------------------------------------------------- case "set-mode": { - if (!args.mode) return "**Error:** `mode` is required for set-mode."; + if (!args.mode) { + return '**Error (goop_state):** set-mode requires `mode`. Retry with `{ action: "set-mode", mode: "standard" }`, using one of quick, standard, comprehensive, or milestone.'; + } if (!isValidMode(args.mode)) { return `**Error:** Invalid mode "${args.mode}". Valid: ${TASK_MODES.join(", ")}`; } @@ -355,7 +359,9 @@ function executeAction( // -- Depth -------------------------------------------------------------- case "set-depth": { - if (!args.depth) return "**Error:** `depth` is required for set-depth."; + if (!args.depth) { + return '**Error (goop_state):** set-depth requires `depth`. Retry with `{ action: "set-depth", depth: "standard" }`, using one of shallow, standard, or deep.'; + } if (!isValidDepth(args.depth)) { return `**Error:** Invalid depth "${args.depth}". Valid: ${WORKFLOW_DEPTHS.join(", ")}`; } @@ -367,7 +373,7 @@ function executeAction( // -- Autopilot ---------------------------------------------------------- case "set-autopilot": { if (args.autopilot == null) { - return "**Error:** `autopilot` (boolean) is required for set-autopilot."; + return '**Error (goop_state):** set-autopilot requires boolean `autopilot`. Retry with `{ action: "set-autopilot", autopilot: true }` or `false`.'; } sm.updateWorkflow({ autopilot: args.autopilot, @@ -381,7 +387,7 @@ function executeAction( // -- Wave progress ------------------------------------------------------ case "update-wave": { if (args.currentWave == null || args.totalWaves == null) { - return "**Error:** `currentWave` and `totalWaves` are required for update-wave."; + return '**Error (goop_state):** update-wave requires both `currentWave` and `totalWaves`. Retry with `{ action: "update-wave", currentWave: 1, totalWaves: 3 }`.'; } sm.updateWaveProgress(args.currentWave, args.totalWaves); renderStatusAfterMutation(ctx); @@ -410,7 +416,7 @@ function executeAction( case "set-active-workflow": { if (!args.workflowId) { - return "**Error:** `workflowId` is required for set-active-workflow."; + return '**Error (goop_state):** set-active-workflow requires `workflowId`. Retry with `{ action: "set-active-workflow", workflowId: "my-workflow" }` using an existing workflow id.'; } sm.setActiveWorkflow(args.workflowId); renderStatusAfterMutation(ctx); @@ -419,7 +425,7 @@ function executeAction( case "create-workflow": { if (!args.workflowId) { - return "**Error:** `workflowId` is required for create-workflow."; + return '**Error (goop_state):** create-workflow requires `workflowId`. Retry with `{ action: "create-workflow", workflowId: "my-workflow" }`.'; } sm.createWorkflow(args.workflowId); if (args.activate) { diff --git a/packages/opencode-plugin/src/tools/goop-status/index.test.ts b/packages/opencode-plugin/src/tools/goop-status/index.test.ts index 7ae236d6..9744b381 100644 --- a/packages/opencode-plugin/src/tools/goop-status/index.test.ts +++ b/packages/opencode-plugin/src/tools/goop-status/index.test.ts @@ -124,6 +124,13 @@ describe("goop_status tool", () => { expect(result).toContain("No active workflow found"); }); + it("verbose is declared but ignored — output is identical whether set or omitted", async () => { + const tool = createGoopStatusTool(ctx); + const withoutVerbose = await tool.execute({}, createMockToolContext()); + const withVerbose = await tool.execute({ verbose: true }, createMockToolContext()); + expect(withVerbose).toBe(withoutVerbose); + }); + it("handles errors gracefully without throwing", async () => { // Create a context with a broken state manager const brokenCtx: PluginContext = { diff --git a/packages/opencode-plugin/src/tools/goop-status/index.ts b/packages/opencode-plugin/src/tools/goop-status/index.ts index 76f58e9f..17f25b2e 100644 --- a/packages/opencode-plugin/src/tools/goop-status/index.ts +++ b/packages/opencode-plugin/src/tools/goop-status/index.ts @@ -153,9 +153,19 @@ export function formatStatus( export function createGoopStatusTool(ctx: PluginContext): ToolDefinition { return tool({ - description: "Show current GoopSpec workflow state, phase, progress, and next steps.", + description: + "Show current GoopSpec workflow state, phase, progress, and next steps. " + + "WHEN TO USE: Orient at the start of any turn on the active workflow, current phase, flags, and the next conductor action. " + + "WHEN NOT TO USE: goop_read_wave for wave or task detail; goop_dashboard for cross-workflow views; goop_read_db to load SPEC or BLUEPRINT prose; goop_setup(action:\"status\") for setup and config status. " + + "RETURNS: A markdown status block with project, workflow id, phase, mode, flags, a wave progress bar, phase guidance, and the next slash command. " + + "CAVEATS: Read-only and side-effect free; safe to call any time. verbose is declared but currently ignored — output is identical whether it is set or omitted.", args: { - verbose: tool.schema.boolean().optional(), + verbose: tool.schema + .boolean() + .optional() + .describe( + "Declared but currently ignored; the output is identical whether this is set or omitted.", + ), }, async execute(_args: { verbose?: boolean }, _context: ToolContext): Promise { try { diff --git a/packages/opencode-plugin/src/tools/goop-write-db/index.test.ts b/packages/opencode-plugin/src/tools/goop-write-db/index.test.ts index 3a0bfa42..66f8fae3 100644 --- a/packages/opencode-plugin/src/tools/goop-write-db/index.test.ts +++ b/packages/opencode-plugin/src/tools/goop-write-db/index.test.ts @@ -10,6 +10,7 @@ import { } from "../../test-utils.js"; import { createGoopReadDbTool } from "../goop-read-db/index.js"; import { createGoopWriteSectionTool } from "../goop-write-section/index.js"; +import { createTools } from "../index.js"; import { createGoopWriteDbTool } from "./index.js"; describe("goop_write_db tool", () => { @@ -796,3 +797,71 @@ describe("goop_write_db tool", () => { }); }); }); + +// --------------------------------------------------------------------------- +// Empty-string boundary (via createTools) — Wave 3 Task 1 exclusions +// --------------------------------------------------------------------------- + +describe("goop_write_db empty-string boundary (via createTools)", () => { + let ctx: PluginContext; + let toolCtx: ToolContext; + let cleanup: () => void; + + beforeEach(() => { + const env = setupTestEnvironment("goop-write-db-coalesce"); + cleanup = env.cleanup; + ctx = createMockPluginContext({ testDir: env.testDir, db: env.db }); + toolCtx = createMockToolContext(); + }); + + afterEach(() => cleanup()); + + it("exclusion: an empty new_string still deletes the matched text", async () => { + const tools = createTools(ctx); + const dbTool = tools.goop_write_db; + await dbTool.execute({ doc_type: "spec", content: "keep this\nremove me\nkeep this too" }, toolCtx); + + // new_string:"" is protected from coalescing and must DELETE the matched + // text, not be treated as absent. + const result = (await dbTool.execute( + { doc_type: "spec", old_string: "remove me\n", new_string: "" }, + toolCtx, + )) as string; + expect(result).toContain("Patched"); + expect(ctx.db.getDocument("default", "spec")?.content).toBe("keep this\nkeep this too"); + }); + + it("exclusion: an empty old_string still activates patch mode (does not fall through)", async () => { + const tools = createTools(ctx); + const dbTool = tools.goop_write_db; + + // old_string:"" is protected. With new_string present it must resolve to + // patch mode (not coalesce to absent and trigger the "new_string without + // old_string" rule-2 error, nor fall through to a full write of ""). + const result = await dbTool.execute( + { doc_type: "spec", old_string: "", new_string: "# via empty old_string" }, + toolCtx, + ); + // Empty old_string activates patch mode; patchContent then reports the + // match outcome. The call must NOT be the rule-2 "new_string supplied + // without old_string" error — that would mean old_string was coalesced. + expect(result).not.toMatch(/new_string .* without old_string/); + }); + + it("coalescing: an injected single-mode content:\"\" does not wipe the document", async () => { + // content is deliberately NOT in the exclusion list: an empty content has + // no legitimate meaning in a single-mode write, and protecting it would + // let an injected content:"" silently destroy a document. Coalescing it to + // absent yields a loud none-mode error instead of a destructive wipe. + const tools = createTools(ctx); + const dbTool = tools.goop_write_db; + await dbTool.execute({ doc_type: "spec", content: "# original" }, toolCtx); + + const result = (await dbTool.execute({ doc_type: "spec", content: "" }, toolCtx)) as string; + // The coalesced payload has no operation fields → none-mode error, not a + // silent empty write. + expect(result).toMatch(/Error|Valid call shapes|cannot|did not/i); + // The document was NOT wiped. + expect(ctx.db.getDocument("default", "spec")?.content).toBe("# original"); + }); +}); diff --git a/packages/opencode-plugin/src/tools/goop-write-db/index.ts b/packages/opencode-plugin/src/tools/goop-write-db/index.ts index 3d222e98..a5c783f9 100644 --- a/packages/opencode-plugin/src/tools/goop-write-db/index.ts +++ b/packages/opencode-plugin/src/tools/goop-write-db/index.ts @@ -65,33 +65,71 @@ function patchExistingDocument( export function createGoopWriteDbTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Write or update a workflow document in GoopSpecDB. Renders a markdown sidecar file.", + "Write or update a whole workflow document. WHEN TO USE: Create, replace, append, patch, or batch a document. WHEN NOT TO USE: goop_write_section for keyed sections; goop_append_chronicle for chronicle entries. MODES: full = doc_type+content (+mode: replace default, append concatenates); patch = doc_type+old_string (+new_string/replace_all, in-place, new_string:\"\" deletes); batch = items[] only. REJECTED: content+old_string; new_string/replace_all without old_string; mode:\"append\"+old_string; op fields alongside items[]. RETURNS: Char count, mode, sidecar path; batch per-item rollup. CAVEATS: Batch is atomic. old_string presence activates patch; omit content when not writing (empty content coalesces to absent, not a wipe).", args: { - doc_type: tool.schema.enum(DOC_TYPES), - content: tool.schema.string().optional(), - workflow_id: tool.schema.string().optional(), - mode: tool.schema.enum(["replace", "append"] as const).optional(), - old_string: tool.schema.string().optional().describe("Exact existing text to replace"), - new_string: tool.schema.string().optional().describe("Replacement text"), + doc_type: tool.schema + .enum(DOC_TYPES) + .describe("Document type to write (one of the DOC_TYPES enum values)."), + content: tool.schema + .string() + .optional() + .describe( + "Full document content (full-write mode); omit for patch or batch mode — an empty content is coalesced to absent and produces a loud none-mode error rather than a wipe.", + ), + workflow_id: tool.schema + .string() + .optional() + .describe("Target workflow id; omit to use the active workflow."), + mode: tool.schema + .enum(["replace", "append"] as const) + .optional() + .describe( + "Full-write mode only: replace (default) overwrites, append concatenates; invalid alongside old_string.", + ), + old_string: tool.schema + .string() + .optional() + .describe("Exact existing text to replace; presence activates patch mode."), + new_string: tool.schema + .string() + .optional() + .describe("Replacement text; an empty new_string deletes the matched text."), replace_all: tool.schema .boolean() .optional() - .describe("Replace all occurrences instead of requiring a single match"), + .describe("Replace all occurrences instead of requiring a single match."), items: tool.schema .array( tool.schema.object({ - doc_type: tool.schema.enum(DOC_TYPES), - content: tool.schema.string().optional(), - mode: tool.schema.enum(["replace", "append"] as const).optional(), - old_string: tool.schema.string().optional().describe("Exact existing text to replace"), - new_string: tool.schema.string().optional().describe("Replacement text"), + doc_type: tool.schema + .enum(DOC_TYPES) + .describe("Document type for this batch item."), + content: tool.schema + .string() + .optional() + .describe("Full document content for this item."), + mode: tool.schema + .enum(["replace", "append"] as const) + .optional() + .describe("replace (default) or append for this item; invalid with old_string."), + old_string: tool.schema + .string() + .optional() + .describe("Exact existing text to replace; presence activates patch mode."), + new_string: tool.schema + .string() + .optional() + .describe("Replacement text; an empty new_string deletes the matched text."), replace_all: tool.schema .boolean() .optional() - .describe("Replace all occurrences instead of requiring a single match"), + .describe("Replace all occurrences instead of requiring a single match."), }), ) - .optional(), + .optional() + .describe( + "Batch of document writes; cannot be supplied alongside top-level content, old_string, new_string, replace_all, or mode.", + ), }, async execute( args: { diff --git a/packages/opencode-plugin/src/tools/goop-write-section/index.ts b/packages/opencode-plugin/src/tools/goop-write-section/index.ts index 71ff1426..765f29fd 100644 --- a/packages/opencode-plugin/src/tools/goop-write-section/index.ts +++ b/packages/opencode-plugin/src/tools/goop-write-section/index.ts @@ -103,37 +103,78 @@ export function createGoopWriteSectionTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Write, update, or delete a structured workflow document section in GoopSpecDB. " + - "Section writes are separate from full-document goop_write_db writes and render the assembled section sidecar.", + "Write, update, or delete a keyed document section. WHEN TO USE: Create, replace, patch, delete a section, or batch writes. WHEN NOT TO USE: goop_write_db for whole documents; goop_read_section to read. MODES: write (default) = content, or patch via old_string/new_string, or items[] batch (top-level op fields rejected); delete = action:\"delete\"+section_key, single only (items[] rejected). REJECTED (write): content+old_string; new_string/replace_all without old_string; mode:\"append\"+old_string. RETURNS: Section + assembled char counts and sidecar path; delete confirms removal or reports not-found. CAVEATS: Batch is atomic. First section write migrates any full-document content into reserved \"_migrated-legacy-content\". new_string:\"\" deletes matched text; omit content when not writing.", args: { - action: tool.schema.enum(["write", "delete"] as const).optional(), - doc_type: tool.schema.enum(DOC_TYPES), - section_key: tool.schema.string().optional(), - content: tool.schema.string().optional(), - position: tool.schema.number().optional(), - workflow_id: tool.schema.string().optional(), - old_string: tool.schema.string().optional().describe("Exact existing text to replace"), - new_string: tool.schema.string().optional().describe("Replacement text"), + action: tool.schema + .enum(["write", "delete"] as const) + .optional() + .describe( + "write (default) creates/updates a section; delete removes one section_key and does not support items[].", + ), + doc_type: tool.schema.enum(DOC_TYPES).describe("Document type the section belongs to."), + section_key: tool.schema + .string() + .optional() + .describe( + "Key identifying the section; required for delete and for single write, omit only in items[] batch mode.", + ), + content: tool.schema + .string() + .optional() + .describe( + "Full section content (write mode); omit for patch or batch — an empty content is coalesced to absent.", + ), + position: tool.schema + .number() + .optional() + .describe("Sort order of the section within the assembled document; omit to append."), + workflow_id: tool.schema + .string() + .optional() + .describe("Target workflow id; omit to use the active workflow."), + old_string: tool.schema + .string() + .optional() + .describe("Exact existing text to replace; presence activates patch mode."), + new_string: tool.schema + .string() + .optional() + .describe("Replacement text; an empty new_string deletes the matched text."), replace_all: tool.schema .boolean() .optional() - .describe("Replace all occurrences instead of requiring a single match"), + .describe("Replace all occurrences instead of requiring a single match."), items: tool.schema .array( tool.schema.object({ - doc_type: tool.schema.enum(DOC_TYPES), - section_key: tool.schema.string(), - content: tool.schema.string().optional(), - position: tool.schema.number().optional(), - old_string: tool.schema.string().optional().describe("Exact existing text to replace"), - new_string: tool.schema.string().optional().describe("Replacement text"), + doc_type: tool.schema.enum(DOC_TYPES).describe("Document type for this section."), + section_key: tool.schema.string().describe("Key identifying this section."), + content: tool.schema + .string() + .optional() + .describe("Full section content for this item."), + position: tool.schema + .number() + .optional() + .describe("Sort order within the assembled document; omit to append."), + old_string: tool.schema + .string() + .optional() + .describe("Exact existing text to replace; presence activates patch mode."), + new_string: tool.schema + .string() + .optional() + .describe("Replacement text; an empty new_string deletes the matched text."), replace_all: tool.schema .boolean() .optional() - .describe("Replace all occurrences instead of requiring a single match"), + .describe("Replace all occurrences instead of requiring a single match."), }), ) - .optional(), + .optional() + .describe( + "Batch of section writes; cannot be supplied alongside top-level content, old_string, new_string, replace_all, or action:'delete'.", + ), }, async execute( args: { diff --git a/packages/opencode-plugin/src/tools/goop-write-wave/index.test.ts b/packages/opencode-plugin/src/tools/goop-write-wave/index.test.ts index 444f7c9d..7aba40f8 100644 --- a/packages/opencode-plugin/src/tools/goop-write-wave/index.test.ts +++ b/packages/opencode-plugin/src/tools/goop-write-wave/index.test.ts @@ -15,6 +15,7 @@ import { } from "../../test-utils.js"; import { createGoopReadWaveTool } from "../goop-read-wave/index.js"; import { createGoopWriteWaveTool } from "./index.js"; +import { createTools } from "../index.js"; describe("goop_write_wave tool", () => { let ctx: PluginContext; @@ -2637,3 +2638,142 @@ describe("goop_write_wave rejection messages teach the correction", () => { expect(ctx.db.getWave("default", 1)).toBeNull(); }); }); + +// --------------------------------------------------------------------------- +// Empty-string boundary (via createTools) — Wave 3 Task 1 regression +// +// Tool-call serialization in some hosts injects empty strings the caller never +// authored. The coalescing boundary in createTools treats "" as absent for +// fields where empty has no legitimate meaning, so a call expressing clear +// intent is not defeated by a value its author never wrote. These tests go +// THROUGH createTools (the wrapped path agents actually use); the direct +// factory tests above remain strict by design. +// --------------------------------------------------------------------------- + +describe("goop_write_wave empty-string boundary (via createTools)", () => { + let ctx: PluginContext; + let toolCtx: ToolContext; + let cleanup: () => void; + + beforeEach(() => { + const env = setupTestEnvironment("goop-write-wave-coalesce"); + cleanup = env.cleanup; + ctx = createMockPluginContext({ testDir: env.testDir, db: env.db }); + toolCtx = createMockToolContext(); + }); + + afterEach(() => cleanup()); + + it("regression: the exact Wave 2 failure shape now succeeds and records verifications", async () => { + // This is the real shape that broke the Wave 2 verifier: a call intended + // as { wave_number, verifications } arrived with an injected top-level + // status:"" and an injected task_updates:[{task_index:0,status:""}]. The + // empty status triggered a mode conflict (status alongside task_updates), + // so the verifications were never recorded. After coalescing, status and + // the nested task_update status become absent, the spurious task_update is + // filtered as a no-op, and the verifications are recorded. + const tools = createTools(ctx); + const waveTool = tools.goop_write_wave; + + // Set up wave 3 with task 0 so the target exists. + await waveTool.execute( + { + wave_number: 3, + title: "Wave three", + status: "in_progress", + tasks: [{ task_index: 0, description: "seed task", status: "pending" }], + }, + toolCtx, + ); + + // The broken shape, exactly as observed in the field. + const result = await waveTool.execute( + { + wave_number: 3, + status: "", + task_updates: [{ task_index: 0, status: "" }], + verifications: [ + { check_name: "typecheck", status: "pass" }, + { check_name: "test", status: "pass", detail: "scoped run" }, + ], + }, + toolCtx, + ); + + // The call must succeed (not return an error) and record the verifications. + expect(result).not.toContain("Error in goop_write_wave"); + expect(result).toContain("Verifications:"); + expect(result).toContain("typecheck=pass"); + expect(result).toContain("test=pass"); + + // Both verification rows persisted. + const wave = ctx.db.getWave("default", 3); + if (wave === null) throw new Error("wave 3 should exist after setup"); + const rows = ctx.db.getVerifications("default", wave.id); + expect(rows.length).toBe(2); + expect(rows.some((r) => r.check_name === "typecheck" && r.status === "passed")).toBe(true); + expect(rows.some((r) => r.check_name === "test" && r.status === "passed")).toBe(true); + + // The wave status was NOT clobbered by the injected status:"". + expect(wave.status).toBe("in_progress"); + // Task 0 status was NOT clobbered by the injected task_update status:"". + const tasks = ctx.db.getWaveTasks(wave.id); + expect(tasks.find((t) => t.task_index === 0)?.status).toBe("pending"); + }); + + it("exclusion: an empty pr_url still clears the stored value", async () => { + const tools = createTools(ctx); + const waveTool = tools.goop_write_wave; + + await waveTool.execute( + { wave_number: 1, pr_url: "https://example.com/pr/1", status: "in_progress" }, + toolCtx, + ); + expect(ctx.db.getWave("default", 1)?.pr_url).toBe("https://example.com/pr/1"); + + // pr_url:"" is protected from coalescing and must overwrite (clear) the + // stored value, per the documented contract. + const result = await waveTool.execute({ wave_number: 1, pr_url: "" }, toolCtx); + expect(result).not.toContain("Error in goop_write_wave"); + expect(ctx.db.getWave("default", 1)?.pr_url).toBe(""); + }); + + it("exclusion: an empty pr_branch still clears the stored value", async () => { + const tools = createTools(ctx); + const waveTool = tools.goop_write_wave; + + await waveTool.execute( + { wave_number: 1, pr_branch: "feat/orig", status: "in_progress" }, + toolCtx, + ); + expect(ctx.db.getWave("default", 1)?.pr_branch).toBe("feat/orig"); + + const result = await waveTool.execute({ wave_number: 1, pr_branch: "" }, toolCtx); + expect(result).not.toContain("Error in goop_write_wave"); + expect(ctx.db.getWave("default", 1)?.pr_branch).toBe(""); + }); + + it("exclusion: an empty title still clears the stored value", async () => { + const tools = createTools(ctx); + const waveTool = tools.goop_write_wave; + + await waveTool.execute({ wave_number: 1, title: "Original", status: "in_progress" }, toolCtx); + expect(ctx.db.getWave("default", 1)?.title).toBe("Original"); + + const result = await waveTool.execute({ wave_number: 1, title: "" }, toolCtx); + expect(result).not.toContain("Error in goop_write_wave"); + expect(ctx.db.getWave("default", 1)?.title).toBe(""); + }); + + it("a spurious top-level status:\"\" does not clobber a real status in the same call", async () => { + // status:"" coalesces to absent, so the real intent (status: "in_progress" + // written moments before) is preserved rather than reset to "". + const tools = createTools(ctx); + const waveTool = tools.goop_write_wave; + await waveTool.execute({ wave_number: 2, status: "in_progress" }, toolCtx); + + const result = await waveTool.execute({ wave_number: 2, status: "" }, toolCtx); + expect(result).not.toContain("Error in goop_write_wave"); + expect(ctx.db.getWave("default", 2)?.status).toBe("in_progress"); + }); +}); diff --git a/packages/opencode-plugin/src/tools/goop-write-wave/index.ts b/packages/opencode-plugin/src/tools/goop-write-wave/index.ts index 02e35f16..5cc9e838 100644 --- a/packages/opencode-plugin/src/tools/goop-write-wave/index.ts +++ b/packages/opencode-plugin/src/tools/goop-write-wave/index.ts @@ -198,13 +198,17 @@ function validateAndNormalizeStatuses(args: { } } - if (args.task_update !== undefined) { + if (args.task_update !== undefined && args.task_update.status !== undefined) { const r = normalizeStatus(args.task_update.status, TASK_STATUSES); if (!r.ok) return `Error in goop_write_wave: ${r.error}`; args.task_update.status = r.status; } for (const update of args.task_updates ?? []) { + // A status coalesced to absent at the tool-input boundary (an injected + // empty string on a field the caller never authored) expresses no intent. + // Skip normalization; the entry is filtered out of processing downstream. + if (update.status === undefined) continue; const r = normalizeStatus(update.status, TASK_STATUSES); if (!r.ok) return `Error in goop_write_wave: ${r.error}`; update.status = r.status; @@ -705,7 +709,15 @@ export function createGoopWriteWaveTool(ctx: PluginContext): ToolDefinition { } const defaultWaveId = wave.id; - const taskUpdates = args.task_updates; + // Drop task_updates entries whose status was coalesced to absent at + // the tool-input boundary (an injected empty string the caller never + // authored). Such an entry expresses no status change and must not be + // applied — applying it would store an undefined status. If every + // entry is dropped, the loop below is a no-op and any verifications + // are still recorded, which is the caller's actual intent. + const taskUpdates = args.task_updates.filter( + (update): update is BulkTaskStatusUpdate => update.status !== undefined, + ); const successes: BatchItemResult[] = []; let verificationResults: string[] = []; let traceabilityResults: string[] = []; @@ -877,7 +889,10 @@ export function createGoopWriteWaveTool(ctx: PluginContext): ToolDefinition { }); } - if (args.task_update !== undefined) { + // A task_update whose status was coalesced to absent (injected empty + // string) expresses no status change; skip the lookup and write so we + // never store an undefined status. + if (args.task_update !== undefined && args.task_update.status !== undefined) { const task = ctx.db .getWaveTasks(wave.id) .find((candidate) => candidate.task_index === args.task_update?.task_index); @@ -928,7 +943,7 @@ export function createGoopWriteWaveTool(ctx: PluginContext): ToolDefinition { mainResult = `Written wave ${waveNumber} for workflow '${workflowId}'; existing tasks left unchanged.`; } } - if (args.task_update !== undefined) { + if (args.task_update !== undefined && args.task_update.status !== undefined) { const taskResult = `Updated task ${args.task_update.task_index} on wave ${waveNumber} to '${args.task_update.status}' for workflow '${workflowId}'.`; mainResult = mainResult.length > 0 ? `${mainResult}\n${taskResult}` : taskResult; } diff --git a/packages/opencode-plugin/src/tools/index.test.ts b/packages/opencode-plugin/src/tools/index.test.ts index b7dbd2bb..402042ad 100644 --- a/packages/opencode-plugin/src/tools/index.test.ts +++ b/packages/opencode-plugin/src/tools/index.test.ts @@ -79,7 +79,83 @@ const EXPECTED_TOOL_KEYS = [ * change; otherwise the length predicate fails it for exceeding the normal * ceiling. */ -const HIGH_FRICTION_TOOLS: readonly string[] = ["goop_write_wave", "goop_state", "goop_blocker"]; +const HIGH_FRICTION_TOOLS: readonly string[] = [ + "goop_write_wave", + "goop_state", + "goop_blocker", + // Wave 3 Task 2: multi-mode write tools whose rejection contracts cannot + // fit under 700 without dropping a rule a caller needs to avoid an error. + "goop_write_db", + "goop_write_section", + "goop_append_chronicle", + // Wave 3 Task 3: goop_save_note is structurally identical to goop_write_db + // — create / patch (by note_id) / batch modes with cross-field rejection + // (create fields rejected alongside note_id; patch fields rejected without + // it) plus a mandatory atomicity-history caveat. Parity with the existing + // allowlist, not a loosened bar; the description lands at 766 chars. + "goop_save_note", + // Wave 4 Task 1: memory_forget is destructive and irreversible, with two + // mutually exclusive modes (id vs query) gated by different rules: id + // deletes immediately and ignores confirm; query needs confirm:true to + // commit. The mandatory content includes the confirm-gates-query-only + // rule, the preview-vs-commit workflow, AND the footgun that the preview + // caps at 20 rows while confirmed deletion searches up to 100 — a caller + // cannot use this safely first-try without all three, and together they + // cannot fit under 700. Description lands at 1074 chars. + "memory_forget", + // Wave 4 Task 2: action-dispatch tools whose action-to-argument legality + // matrix cannot fit under 700 without dropping a rule a caller needs. + // goop_setup: 8 actions, each reading a different subset of 9 args, plus + // a cross-action gitignoreGoopspec side effect and a scope arg that is + // silently ignored — caller cannot first-try know which fields apply. + // goop_infer_intent: autoApply vs autoRun are separate mechanisms with + // different gates (hard floor 0.85, threshold default 0.9, autoRun floor + // 0.75), and a below-threshold result is never an error — the precise + // confidence contract is load-bearing for safe use. + "goop_setup", + "goop_infer_intent", + // Wave 5 Task 1: utility tools that shell out to external binaries. + // ast_grep: three mutually exclusive modes (search / rewrite dry-run / + // rewrite apply) plus a conditional argument — apply:true without rewrite + // is a documented no-op (the -U flag is only appended inside the rewrite + // branch). The mode contract and the apply-without-rewrite rule together + // cannot fit under 700 without dropping a rule a caller needs to avoid an + // accidental mutation, or to achieve one on purpose. + // scip: action-dependent required fields — symbol is required for + // definitions/references/implementations and ignored by index, and each + // action resolves a different binary (scip vs scip-typescript). The + // action-to-argument and action-to-binary matrix is mandatory content. + "ast_grep", + "scip", + // Wave 5 Task 1: difftastic has two modes (full diff / checkOnly) plus an + // alias-pair cross-field contract (old/oldPath and new/newPath — all four + // schema-optional, two runtime-required). The load-bearing content that + // pushes it past 700 is the missing-binary distinction the workflow + // dispatch flags as mandatory: a missing difft binary returns an + // install-hint string that a caller MUST be able to distinguish from a real + // "no differences" result. Dropping that sentence to fit 700 would violate + // the dispatch; every other sentence is also load-bearing. Description + // lands at 787 chars — no padding, each section earns its place. + "difftastic", + // Wave 5 Task 2: generate_image has the largest argument surface in the + // registry (17 args) plus a non-trivial cross-field contract: transparent + // background is png-only (rendered on green screen, keyed locally via + // chromakey), non-.png out and jpeg/webp outputFormat with transparent are + // rejected at validation, default output path and count-suffix behavior, + // and two dead arguments (mask, outputCompression) that must be documented + // as ignored. This cannot fit under 700 without dropping contract a caller + // needs to avoid a wasted credit spend or a validation rejection. + // Description lands at 1136 chars. + "generate_image", + // Wave 5 Task 2: goop_create_pr has a terminology gate that scans title, + // body, AND branch with different masking rules (code spans masked in + // title/body, never in branch), two severity levels with different + // behavior (error blocks, warn proceeds), and the reword-not-retry + // contract. The mandatory gate contract cannot fit under 700 without + // dropping a rule a caller needs to avoid repeated rejections. + // Description lands at 904 chars. + "goop_create_pr", +]; /** * Tools that do NOT yet meet the house standard and so skip the content @@ -99,38 +175,12 @@ const HIGH_FRICTION_TOOLS: readonly string[] = ["goop_write_wave", "goop_state", * is a tracked TODO, never a permanent exemption. An over-broad list silently * disables the gate, which is the worst outcome here, so the safety-net test * below rejects typos and duplicates in this list. + * + * Wave 5 Task 2 brought the final two tools (generate_image, goop_create_pr) + * into conformance. This list is now EMPTY: every tool in the registry is + * subject to every predicate. */ -const PENDING_CONFORMANCE: readonly string[] = [ - "ast_grep", - "background_cancel", - "background_command", - "background_status", - "difftastic", - "generate_image", - "goop_append_chronicle", - "goop_boot", - "goop_checkpoint", - "goop_compact", - "goop_create_pr", - "goop_get_global_config", - "goop_infer_intent", - "goop_read_db", - "goop_read_section", - "goop_reference", - "goop_save_note", - "goop_search_docs", - "goop_search_notes", - "goop_setup", - "goop_spec", - "goop_status", - "goop_write_db", - "goop_write_section", - "memory_forget", - "memory_save", - "memory_search", - "scip", - "slashcommand", -]; +const PENDING_CONFORMANCE: readonly string[] = []; // ---- Predicates (pure; shared with the bad-fixture proofs) --------------- @@ -138,10 +188,8 @@ const PENDING_CONFORMANCE: readonly string[] = [ * Section labels that are unconditionally mandatory for every tool * description, per `tool-reference.md`. * - * `MODES:` and `CAVEATS:` are intentionally NOT in this list: the standard - * makes them conditional ("mandatory when the tool has more than one mode" - * / "mandatory when applicable"), and the condition cannot be detected - * mechanically without a per-tool mode inventory. The `Purpose` section has + * `MODES:` and `CAVEATS:` are intentionally NOT in this list because their + * applicability is enforced by the explicit per-tool inventory below. The `Purpose` section has * no label (it is the opening sentence), so it is proxied by the * 120-character length floor rather than a label match. These scope * decisions are deliberate and documented; do not "strengthen" the gate by @@ -154,11 +202,79 @@ const MANDATORY_SECTION_LABELS = [ "RETURNS:", ] as const; +type ConditionalSectionRequirements = Readonly<{ + modes: boolean; + caveats: boolean; +}>; + +/** + * Implementation-based conditional-section inventory. Every registered tool + * must be classified here: new tools never inherit an exemption by default. + * + * `modes` is true for tools with action dispatch, distinct single/batch or + * selected/all read forms, mutually exclusive payloads, or an opt-in path + * that changes execution. `caveats` is true where the implementation has + * side effects, defaults, precedence, atomicity, or other non-obvious rules. + */ +const CONDITIONAL_SECTION_REQUIREMENTS: Readonly< + Record<(typeof EXPECTED_TOOL_KEYS)[number], ConditionalSectionRequirements> +> = { + goop_status: { modes: false, caveats: true }, + goop_state: { modes: true, caveats: true }, + goop_spec: { modes: true, caveats: true }, + goop_adl: { modes: true, caveats: true }, + goop_checkpoint: { modes: true, caveats: true }, + goop_compact: { modes: false, caveats: true }, + goop_setup: { modes: true, caveats: true }, + goop_get_global_config: { modes: false, caveats: true }, + goop_reference: { modes: true, caveats: true }, + goop_read_db: { modes: true, caveats: true }, + goop_write_db: { modes: true, caveats: true }, + goop_save_note: { modes: true, caveats: true }, + goop_search_notes: { modes: true, caveats: true }, + goop_acceptance_audit: { modes: false, caveats: true }, + goop_append_chronicle: { modes: true, caveats: true }, + goop_boot: { modes: false, caveats: true }, + goop_create_pr: { modes: true, caveats: true }, + goop_write_section: { modes: true, caveats: true }, + goop_read_section: { modes: true, caveats: true }, + goop_write_wave: { modes: true, caveats: true }, + goop_read_wave: { modes: true, caveats: true }, + goop_query_decisions: { modes: false, caveats: true }, + goop_blocker: { modes: true, caveats: true }, + goop_search_docs: { modes: false, caveats: true }, + goop_timeline: { modes: false, caveats: true }, + goop_dashboard: { modes: false, caveats: true }, + goop_infer_intent: { modes: true, caveats: true }, + memory_save: { modes: true, caveats: true }, + memory_search: { modes: true, caveats: true }, + memory_forget: { modes: true, caveats: true }, + slashcommand: { modes: false, caveats: true }, + ast_grep: { modes: true, caveats: true }, + difftastic: { modes: true, caveats: true }, + scip: { modes: true, caveats: true }, + generate_image: { modes: true, caveats: true }, + background_command: { modes: false, caveats: true }, + background_status: { modes: true, caveats: true }, + background_cancel: { modes: false, caveats: true }, +}; + /** Returns the mandatory section labels absent from a tool description. */ function missingMandatorySections(description: string): string[] { return MANDATORY_SECTION_LABELS.filter((label) => !description.includes(label)); } +/** Returns applicable conditional section labels absent from a description. */ +function missingConditionalSections( + description: string, + requirements: ConditionalSectionRequirements, +): string[] { + const missing: string[] = []; + if (requirements.modes && !description.includes("MODES:")) missing.push("MODES:"); + if (requirements.caveats && !description.includes("CAVEATS:")) missing.push("CAVEATS:"); + return missing; +} + interface DescriptionLengthViolation { actual: number; min: number; @@ -338,6 +454,11 @@ describe("tool-description standard conformance gate", () => { } }); + it("classifies every registered tool for conditional sections", () => { + const tools = createTools(ctx); + expect(Object.keys(CONDITIONAL_SECTION_REQUIREMENTS).sort()).toEqual(Object.keys(tools).sort()); + }); + // The live gate. Non-pending tools must satisfy every predicate; pending // tools must still exist in the registry. All violations are collected and // reported in one shot so a wave fixing a tool sees every problem at once. @@ -359,6 +480,18 @@ describe("tool-description standard conformance gate", () => { violations.push(`${name}: missing mandatory sections — ${missing.join(", ")}`); } + if (!(name in CONDITIONAL_SECTION_REQUIREMENTS)) { + violations.push(`${name}: missing conditional-section classification`); + continue; + } + const conditionalMissing = missingConditionalSections( + desc, + CONDITIONAL_SECTION_REQUIREMENTS[name as keyof typeof CONDITIONAL_SECTION_REQUIREMENTS], + ); + if (conditionalMissing.length > 0) { + violations.push(`${name}: missing applicable conditional sections — ${conditionalMissing.join(", ")}`); + } + const allowlisted = HIGH_FRICTION_TOOLS.includes(name); const lengthViolation = descriptionLengthViolation(desc, allowlisted); if (lengthViolation) { @@ -438,6 +571,18 @@ describe("conformance predicates reject non-conformant fixtures", () => { expect(collectEmptyStringEndorsements(CLEAN_SCHEMA)).toEqual([]); }); + it("a classified tool missing an applicable conditional section is flagged", () => { + expect(missingConditionalSections(CONFORMANT_DESCRIPTION, { modes: true, caveats: true })).toEqual([ + "MODES:", + ]); + expect( + missingConditionalSections(CONFORMANT_DESCRIPTION.replace("CAVEATS:", "DETAILS:"), { + modes: false, + caveats: true, + }), + ).toEqual(["CAVEATS:"]); + }); + it("a description missing a mandatory section is flagged", () => { const missingWhenNotToUse = CONFORMANT_DESCRIPTION.replace("WHEN NOT TO USE:", "DETAIL:"); expect(missingMandatorySections(missingWhenNotToUse)).toEqual(["WHEN NOT TO USE:"]); diff --git a/packages/opencode-plugin/src/tools/index.ts b/packages/opencode-plugin/src/tools/index.ts index edf0e98e..44329b83 100644 --- a/packages/opencode-plugin/src/tools/index.ts +++ b/packages/opencode-plugin/src/tools/index.ts @@ -9,6 +9,7 @@ import type { ToolDefinition } from "../core/sdk-compat.js"; import type { PluginContext } from "../core/types.js"; +import { coalesceEmptyStrings } from "../shared/coalesce.js"; import { createGoopAcceptanceAuditTool } from "./goop-acceptance-audit/index.js"; import { createGoopAdlTool } from "./goop-adl/index.js"; import { createGoopAppendChronicleTool } from "./goop-append-chronicle/index.js"; @@ -93,7 +94,7 @@ export { }; export function createTools(ctx: PluginContext): Record { - return { + const tools: Record = { goop_status: createGoopStatusTool(ctx), goop_state: createGoopStateTool(ctx), goop_spec: createGoopSpecTool(ctx), @@ -136,4 +137,31 @@ export function createTools(ctx: PluginContext): Record background_status: createBackgroundStatusTool(ctx), background_cancel: createBackgroundCancelTool(ctx), }; + + // Coalesce empty-string arguments to absent at this single shared boundary, + // before any tool logic runs. Tool-call serialization in some hosts injects + // empty strings into payloads the caller never authored (status fields, mode + // selectors, nested task_updates[] entries); for fields where empty has no + // legitimate meaning, treating "" as absent restores the caller's intent. + // Both registration paths consume this map — V1 (src/index.ts returns it as + // `tool:`) and V2 (src/core/tools-v2.ts reads each definition's execute) — + // so the coalescing applies on both hosts from one source of truth. Fields + // where empty is a documented operation are exempt only for their owning + // tool; see shared/coalesce.ts. + return Object.fromEntries( + Object.entries(tools).map(([name, definition]) => [name, wrapWithCoalescing(name, definition)]), + ); +} + +/** + * Wrap a tool's `execute` so its arguments pass through empty-string coalescing + * first. Preserves `description` and `args` (the schema) verbatim — only the + * runtime argument payload is normalized. + */ +function wrapWithCoalescing(name: string, definition: ToolDefinition): ToolDefinition { + const { execute: originalExecute, ...rest } = definition; + return { + ...rest, + execute: async (args, context) => originalExecute(coalesceEmptyStrings(args, name), context), + }; } diff --git a/packages/opencode-plugin/src/tools/memory-forget/index.test.ts b/packages/opencode-plugin/src/tools/memory-forget/index.test.ts index 695c8484..97d85d55 100644 --- a/packages/opencode-plugin/src/tools/memory-forget/index.test.ts +++ b/packages/opencode-plugin/src/tools/memory-forget/index.test.ts @@ -122,7 +122,76 @@ describe("memory_forget tool", () => { const tool = createMemoryForgetTool(ctx); const result = await tool.execute({}, toolCtx); - expect(result).toContain("Error: Must provide either 'id' or 'query'"); + expect(result).toBe( + 'Error in memory_forget: neither `id` nor `query` was supplied. Retry with `{ id: 42 }` to delete one memory, or `{ query: "topic", confirm: true }` to delete query matches.', + ); + }); + + // ------------------------------------------------------------------------- + // Confirm gate and mode precedence — the destructive contract pinned. + // These tests exist because memory_forget is irreversible: a caller must + // be able to read the description alone and know which invocation deletes + // one record, which can delete many, and what confirm gates. The assertions + // below fix that contract so a future refactor cannot silently change it. + // ------------------------------------------------------------------------- + + it("id mode deletes immediately without confirm and ignores confirm:false", async () => { + const tool = createMemoryForgetTool(ctx); + // confirm:false must NOT protect an id-mode deletion. + const result = await tool.execute({ id: 1, confirm: false }, toolCtx); + + expect(result).toBe("Memory 1 deleted successfully."); + expect(await ctx.memory.getById(1)).toBeNull(); + }); + + it("id mode takes precedence over query + confirm (no bulk deletion occurs)", async () => { + const tool = createMemoryForgetTool(ctx); + // Supplying both id and a confirmed query must delete only the id record. + // forgetByQuery must NOT run, so the other auth-related memory survives. + const result = await tool.execute({ id: 2, query: "auth", confirm: true }, toolCtx); + + expect(result).toBe("Memory 2 deleted successfully."); + // Memory 3 ("Use auth tokens") matches the query but must survive because + // id mode short-circuits before the query path runs. + const surviving = await ctx.memory.search({ query: "auth" }); + expect(surviving.some((r) => r.memory.id === 3)).toBe(true); + }); + + it("query mode without confirm returns a read-only preview and deletes nothing", async () => { + const tool = createMemoryForgetTool(ctx); + const result = await tool.execute({ query: "auth" }, toolCtx); + + expect(result).toContain("Will delete:"); + expect(result).toContain("confirm=true"); + // Nothing was actually deleted. + const stillPresent = await ctx.memory.search({ query: "auth" }); + expect(stillPresent.length).toBeGreaterThan(0); + }); + + it("query-mode preview searches with a limit of 20", async () => { + // The preview path passes limit:20 to memory.search. This pins the + // documented "preview caps at 20 rows" contract; the confirmed-delete + // path (limit 100) is pinned at the manager level in features/memory. + const realSearch = ctx.memory.search; + let capturedLimit: number | undefined; + ctx.memory.search = async (options) => { + capturedLimit = options.limit; + return realSearch(options); + }; + + const tool = createMemoryForgetTool(ctx); + await tool.execute({ query: "auth" }, toolCtx); + + expect(capturedLimit).toBe(20); + }); + + it("query mode with confirm:true commits the deletion via forgetByQuery", async () => { + const tool = createMemoryForgetTool(ctx); + const result = await tool.execute({ query: "auth", confirm: true }, toolCtx); + + expect(result).toContain("Deleted"); + const remaining = await ctx.memory.search({ query: "auth" }); + expect(remaining.length).toBe(0); }); // ------------------------------------------------------------------------- diff --git a/packages/opencode-plugin/src/tools/memory-forget/index.ts b/packages/opencode-plugin/src/tools/memory-forget/index.ts index 785ca4fb..4c93e323 100644 --- a/packages/opencode-plugin/src/tools/memory-forget/index.ts +++ b/packages/opencode-plugin/src/tools/memory-forget/index.ts @@ -18,15 +18,35 @@ import type { PluginContext } from "../../core/types.js"; export function createMemoryForgetTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Delete memories from persistent storage by ID or query. " + - "Query-based deletes require confirm=true. WARNING: irreversible.", + "Delete one memory by id, or every memory matching a query. Irreversible: no undo, " + + "no recycle bin, no soft delete. " + + "WHEN TO USE: Remove a single wrong record via id; bulk-remove a topic via query. " + + "WHEN NOT TO USE: memory_search to inspect without deleting; goop_search_notes targets " + + "Field Notes (a separate store this tool never touches). " + + "MODES: id mode — send only id; deletes that one record immediately; query and confirm " + + "are ignored. query mode — send only query; without confirm returns a read-only preview " + + "(up to 20 matches) plus the exact confirm=true call to repeat; with confirm:true deletes " + + "every match. Supplying neither id nor query is rejected. " + + "RETURNS: The deletion outcome (count or not-found), or in query mode without confirm the " + + "preview plus the confirmation call to issue next. " + + "CAVEATS: confirm gates ONLY query-mode deletion; it does not protect id mode, which needs " + + "no confirm. The preview caps at 20 rows but confirmed deletion searches up to 100, so the " + + "count deleted can exceed the count previewed. A missing id returns 'not found' and deletes nothing.", args: { - id: tool.schema.number().optional().describe("Memory ID to delete"), - query: tool.schema - .string() - .optional() - .describe("Search query to delete matching memories (requires confirm=true)"), - confirm: tool.schema.boolean().optional().describe("Confirm deletion when using query"), + id: tool.schema.number().optional().describe( + "Numeric id of the single memory to delete. When supplied, takes precedence over query " + + "and confirm: that one record is deleted immediately and confirm is not required. " + + "Omit when using query mode.", + ), + query: tool.schema.string().optional().describe( + "Search query whose matches to delete, after confirmation. Without confirm, returns a " + + "read-only preview; with confirm:true, deletes every match. Omit entirely when using " + + "id mode; do not pass an empty string.", + ), + confirm: tool.schema.boolean().optional().describe( + "Set to true to commit a query-mode deletion. Has no effect in id mode, which deletes " + + "without confirmation regardless. Omit when using id mode.", + ), }, async execute( args: { @@ -39,7 +59,7 @@ export function createMemoryForgetTool(ctx: PluginContext): ToolDefinition { try { // Must provide either id or query if (args.id === undefined && !args.query) { - return "Error: Must provide either 'id' or 'query' to delete memories."; + return 'Error in memory_forget: neither `id` nor `query` was supplied. Retry with `{ id: 42 }` to delete one memory, or `{ query: "topic", confirm: true }` to delete query matches.'; } // Delete by ID — immediate, no confirmation needed diff --git a/packages/opencode-plugin/src/tools/memory-save/index.test.ts b/packages/opencode-plugin/src/tools/memory-save/index.test.ts index e19aac85..563dce67 100644 --- a/packages/opencode-plugin/src/tools/memory-save/index.test.ts +++ b/packages/opencode-plugin/src/tools/memory-save/index.test.ts @@ -6,6 +6,7 @@ import { createMockToolContext, setupTestEnvironment, } from "../../test-utils.js"; +import { createTools } from "../index.js"; import { createMemorySaveTool } from "./index.js"; describe("memory_save tool", () => { @@ -39,6 +40,21 @@ describe("memory_save tool", () => { expect(result).toContain("**Importance:** 5/10"); }); + it("coalesces an injected empty title to absent at the shared tool boundary", async () => { + const tools = createTools(ctx); + const save = ctx.memory.save; + let saveCalled = false; + ctx.memory.save = async (input) => { + saveCalled = true; + return save(input); + }; + + const result = await tools.memory_save.execute({ title: "", content: "must not persist" }, toolCtx); + + expect(result).toContain("Error saving memory"); + expect(saveCalled).toBe(false); + }); + it("saves with explicit type, concepts, facts, sourceFiles", async () => { const tool = createMemorySaveTool(ctx); const result = await tool.execute( @@ -112,6 +128,12 @@ describe("memory_save tool", () => { it("saves a decision with reasoning and alternatives folded into content", async () => { const tool = createMemorySaveTool(ctx); + const save = ctx.memory.save; + let receivedContent: string | undefined; + ctx.memory.save = async (input) => { + receivedContent = input.content; + return save(input); + }; const result = await tool.execute( { title: "Use PostgreSQL for storage", @@ -130,6 +152,7 @@ describe("memory_save tool", () => { expect(result).toContain("**Importance:** 7/10"); expect(result).toContain("**Reasoning:** included"); expect(result).toContain("**Alternatives:** 3 considered"); + expect(receivedContent).toBe("Chose PostgreSQL as the primary database."); }); it("auto-generates facts for decisions when none supplied", async () => { @@ -147,9 +170,9 @@ describe("memory_save tool", () => { // Verify the mock memory received auto-generated facts const searchResults = await ctx.memory.search({ query: "jose" }); expect(searchResults.length).toBe(1); - // The stored content should include the alternatives section - expect(searchResults[0].memory.content).toContain("## Alternatives Considered"); - expect(searchResults[0].memory.content).toContain("- jsonwebtoken"); + // The lightweight test manager stores the raw tool payload; composition is + // covered by the concrete manager test. + expect(searchResults[0].memory.content).toBe("Selected jose library."); }); it("preserves explicit facts for decisions", async () => { @@ -258,6 +281,38 @@ describe("memory_save tool", () => { expect(result).toContain("Error: Title must be 100 characters or less"); }); + // ------------------------------------------------------------------------- + // Graceful degradation: a failed write surfaces as id -1, not a throw. + // The memory manager degrades to a synthetic fallbackEntry (id: -1) when + // the DB write fails, so the tool still returns a success-shaped message. + // A caller must check the returned id to know whether the record persisted. + // ------------------------------------------------------------------------- + + it("surfaces a failed write as id -1 rather than throwing", async () => { + const degradedCtx = createMockPluginContext({ testDir: "/tmp/broken" }); + // Mimic the real manager's graceful-degradation return (fallbackEntry). + degradedCtx.memory.save = async (input) => ({ + id: -1, + type: input.type, + title: input.title, + content: input.content, + facts: input.facts, + concepts: input.concepts, + sourceFiles: input.sourceFiles, + importance: input.importance ?? 5, + createdAt: Date.now(), + }); + + const tool = createMemorySaveTool(degradedCtx); + const result = await tool.execute( + { title: "Fails to persist", content: "Should degrade gracefully." }, + toolCtx, + ); + + // The tool still reports success-shaped output, but the id signals failure. + expect(result).toContain("**ID:** -1"); + }); + // ------------------------------------------------------------------------- // Error handling // ------------------------------------------------------------------------- diff --git a/packages/opencode-plugin/src/tools/memory-save/index.ts b/packages/opencode-plugin/src/tools/memory-save/index.ts index f32a9117..97ed44f7 100644 --- a/packages/opencode-plugin/src/tools/memory-save/index.ts +++ b/packages/opencode-plugin/src/tools/memory-save/index.ts @@ -36,27 +36,6 @@ function normalizeImportance(raw: number | undefined, memoryType: MemoryType): n return raw; } -/** - * When type=decision, fold reasoning/alternatives into the stored content - * so a single tool covers what `memory_decision` used to do. - */ -function buildDecisionContent( - baseContent: string, - reasoning: string | undefined, - alternatives: string[] | undefined, -): string { - const sections: string[] = [baseContent]; - - if (reasoning) { - sections.push("", "## Reasoning", reasoning); - } - if (alternatives?.length) { - sections.push("", "## Alternatives Considered", ...alternatives.map((a) => `- ${a}`)); - } - - return sections.join("\n"); -} - /** * For decisions, auto-generate facts from the reasoning/alternatives if the * caller didn't supply explicit facts. @@ -87,41 +66,56 @@ const USER_MEMORY_TYPES = MEMORY_TYPES.filter( export function createMemorySaveTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Save structured information to persistent memory. " + - "Supports observation, decision, note, and todo types.", + "Persist a memory record. " + + "WHEN TO USE: Capture an observation, decision, note, or todo. " + + "WHEN NOT TO USE: goop_save_note for curated, tagged knowledge. " + + "MODES: insert = omit deduplicate or send false; creates a row. deduplicate = true: a near-duplicate (token F1 >=0.85) keeps its id, sets importance=max(old,new), refreshes created_at, and leaves content unchanged; no match inserts. " + + "RETURNS: A confirmation with id, type, title, importance; failures return id -1. " + + "CAVEATS: importance defaults by type (decision 7, note 4, else 5), must be 1-10 (0-1 scales x10). type=decision folds reasoning/alternatives into content and auto-generates facts from the title if omitted; both are ignored otherwise.", args: { - title: tool.schema.string().describe("Memory title (max 100 chars)"), - content: tool.schema.string().describe("Memory content"), - type: tool.schema - .enum(USER_MEMORY_TYPES) - .optional() - .describe("Type: observation (default), decision, note, or todo"), + title: tool.schema + .string() + .describe("Memory title; max 100 characters. Required."), + content: tool.schema.string().describe( + "Memory body text. Required. Stored verbatim for non-decision types; for type=decision " + + "the reasoning and alternatives are appended into the stored content.", + ), + type: tool.schema.enum(USER_MEMORY_TYPES).optional().describe( + "Record type. Defaults to observation. decision folds reasoning/alternatives into " + + "content and auto-generates facts; note lowers the default importance; todo tracks " + + "an action item.", + ), concepts: tool.schema .array(tool.schema.string()) .optional() - .describe("Tags for categorization and search"), - facts: tool.schema - .array(tool.schema.string()) - .optional() - .describe("Atomic facts extracted from this memory"), - importance: tool.schema - .number() - .optional() - .describe("Importance 1-10 (default varies by type)"), + .describe( + "Tags for categorization and retrieval; stored verbatim and full-text-indexed.", + ), + facts: tool.schema.array(tool.schema.string()).optional().describe( + "Atomic facts extracted from this memory; stored verbatim and full-text-indexed. For " + + "type=decision, auto-generated from the title when omitted.", + ), + importance: tool.schema.number().optional().describe( + "Priority 1-10. Defaults vary by type: decision 7, note 4, observation/todo 5. Values " + + "in (0, 1) are scaled x10 for backward compatibility.", + ), sourceFiles: tool.schema .array(tool.schema.string()) .optional() - .describe("Related file paths"), - // Decision-specific fields (only meaningful when type=decision) - reasoning: tool.schema.string().optional().describe("Why this decision was made"), - alternatives: tool.schema - .array(tool.schema.string()) - .optional() - .describe("Alternatives considered"), - deduplicate: tool.schema - .boolean() - .optional() - .describe("Consolidate a near-duplicate memory instead of inserting a new entry"), + .describe("Related file paths; stored verbatim."), + reasoning: tool.schema.string().optional().describe( + "Why a decision was made. Only applied for type=decision (folded into content); " + + "ignored for other types. Omit for non-decision memories.", + ), + alternatives: tool.schema.array(tool.schema.string()).optional().describe( + "Alternatives considered. Only applied for type=decision (folded into content); " + + "ignored for other types. Omit for non-decision memories.", + ), + deduplicate: tool.schema.boolean().optional().describe( + "When true, reinforce a near-duplicate existing record instead of inserting a new row " + + "(importance becomes max of old and new, created_at refreshed, content unchanged). " + + "When absent or false, always insert. No-op when FTS5 is unavailable.", + ), }, async execute( args: { @@ -152,12 +146,6 @@ export function createMemorySaveTool(ctx: PluginContext): ToolDefinition { return "Error: Importance must be between 1 and 10."; } - // Build content — decisions get reasoning/alternatives folded in - const content = - memoryType === "decision" - ? buildDecisionContent(args.content, args.reasoning, args.alternatives) - : args.content; - // Build facts — decisions auto-generate if none supplied const facts = memoryType === "decision" @@ -167,7 +155,7 @@ export function createMemorySaveTool(ctx: PluginContext): ToolDefinition { const entry = await ctx.memory.save({ type: memoryType, title: args.title, - content, + content: args.content, facts, concepts: args.concepts, sourceFiles: args.sourceFiles, diff --git a/packages/opencode-plugin/src/tools/memory-search/index.test.ts b/packages/opencode-plugin/src/tools/memory-search/index.test.ts index 9f740055..f4322271 100644 --- a/packages/opencode-plugin/src/tools/memory-search/index.test.ts +++ b/packages/opencode-plugin/src/tools/memory-search/index.test.ts @@ -254,6 +254,44 @@ describe("memory_search tool", () => { expect(result).toContain("Memory Search Results"); }); + it("clamps a sub-1 limit up to 1 rather than rejecting it", async () => { + const tool = createMemorySearchTool(ctx); + const result = await tool.execute({ query: "auth", limit: 0 }, toolCtx); + + expect(result).toContain("Memory Search Results"); + }); + + it("returns no results for an empty or whitespace query", async () => { + const tool = createMemorySearchTool(ctx); + const result = await tool.execute({ query: " " }, toolCtx); + + expect(result).toContain('No memories found matching: " "'); + }); + + // ------------------------------------------------------------------------- + // MH11/MH20: filters narrow by design. + // A record that matches the query text but lacks the filter is excluded. + // This is the intended AND-combination contract, not a ranking bug. Pinned + // here at the tool level against the mock, and at the real-manager level + // (with FTS5) in features/memory/index.test.ts so both semantics agree. + // ------------------------------------------------------------------------- + + it("a concept filter excludes a query match that lacks the concept (tool level)", async () => { + const tool = createMemorySearchTool(ctx); + // "Refactor auth middleware" matches the "auth" query but its concepts + // are ["auth","refactor"]; "Auth tests flaky on CI" also matches "auth" + // but its concepts are ["testing","ci"]. + const unfiltered = await tool.execute({ query: "auth" }, toolCtx); + expect(unfiltered).toContain("Refactor auth middleware"); + expect(unfiltered).toContain("Auth tests flaky"); + + // Restricting to the "refactor" concept drops the flaky-tests record even + // though it still matches the query text. + const filtered = await tool.execute({ query: "auth", concepts: ["refactor"] }, toolCtx); + expect(filtered).toContain("Refactor auth middleware"); + expect(filtered).not.toContain("Auth tests flaky"); + }); + // ------------------------------------------------------------------------- // Output formatting // ------------------------------------------------------------------------- diff --git a/packages/opencode-plugin/src/tools/memory-search/index.ts b/packages/opencode-plugin/src/tools/memory-search/index.ts index e18c3b4d..3a8bccb7 100644 --- a/packages/opencode-plugin/src/tools/memory-search/index.ts +++ b/packages/opencode-plugin/src/tools/memory-search/index.ts @@ -81,23 +81,45 @@ function formatCrossStoreResult(result: CrossStoreSearchResult, index: number): export function createMemorySearchTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Search persistent memory using keyword and semantic matching with optional filters.", + "Search persistent memory. " + + "WHEN TO USE: Recall saved memories by keyword. " + + "WHEN NOT TO USE: goop_search_notes for Field Notes; memory_forget with a query to " + + "preview a deletion without committing it. " + + "MODES: memory-only = omit includeFieldNotes or send false. cross-store = true; searches Field Notes in parallel and fuses both rankings via reciprocal-rank fusion, while filters apply only to memories. " + + "RETURNS: Ranked results or a no-matches tip. " + + "CAVEATS: limit defaults to 5, clamped to 1-20. Filters AND together: types (membership), concepts (OR within, substring on stored tags), minImportance (>=). Empty query returns nothing; a query match lacking a filter is excluded.", args: { - query: tool.schema.string().describe("Search query"), - limit: tool.schema.number().optional().describe("Max results (default 5, max 20)"), + query: tool.schema.string().describe( + "Search query over title, content, facts, and concepts. Required; an empty or " + + "whitespace-only query returns no results.", + ), + limit: tool.schema + .number() + .optional() + .describe("Max results to return. Defaults to 5; clamped to the 1-20 range."), types: tool.schema .array(tool.schema.enum(MEMORY_TYPES)) .optional() - .describe("Filter by memory types"), - concepts: tool.schema - .array(tool.schema.string()) - .optional() - .describe("Filter by concept tags"), - minImportance: tool.schema.number().optional().describe("Minimum importance (1-10)"), - includeFieldNotes: tool.schema - .boolean() + .describe( + "Restrict to memories whose type is in this list " + + "(observation, decision, note, todo, session_summary). AND-combined with other filters.", + ), + concepts: tool.schema.array(tool.schema.string()).optional().describe( + "Restrict to memories tagged with any of these concepts. Multiple concepts are OR'd " + + "within this list (a memory need only match one), then AND'd with other filters. " + + "Matched as a case-insensitive substring against stored tags.", + ), + minImportance: tool.schema + .number() .optional() - .describe("Include matching Field Notes, fused with memories using reciprocal-rank fusion"), + .describe( + "Exclude memories with importance below this value (>= comparison). AND-combined with other filters.", + ), + includeFieldNotes: tool.schema.boolean().optional().describe( + "When true, also search Field Notes and fuse both ranked lists via reciprocal-rank " + + "fusion (k=60), tagging each result's origin. Re-ranks every result. Filters apply to " + + "the memory side only; Field Notes are searched by query alone. Absent and false are identical.", + ), }, async execute( args: { diff --git a/packages/opencode-plugin/src/tools/scip/index.ts b/packages/opencode-plugin/src/tools/scip/index.ts index 2c6062ec..57244c66 100644 --- a/packages/opencode-plugin/src/tools/scip/index.ts +++ b/packages/opencode-plugin/src/tools/scip/index.ts @@ -54,18 +54,24 @@ interface ScipLocation { export function createScipTool(ctx: PluginContext): ToolDefinition { return tool({ description: - "Query a SCIP index for symbol definitions, references, or implementations. " + - "Use the exact SCIP symbol string; index generation is available through the index action.", + "Query a SCIP code-intelligence index for symbol definitions, references, or implementations; or generate the index. " + + "WHEN TO USE: Navigate code semantically — who calls a function, where a type is defined or implemented. " + + "WHEN NOT TO USE: ast_grep for pattern-based structural search; grep for literal text. " + + "MODES: index — generates index.scip via the scip-typescript binary; symbol and index_path are ignored. definitions/references/implementations — require symbol and query an existing index via the scip binary. " + + "RETURNS: For index, the generated index path. For queries, a list of file:line:column locations (UTF-16 columns) or a no-results message. " + + "CAVEATS: index resolves the scip-typescript binary; queries resolve the scip binary — each via PATH or the matching binaryPaths key (scip-typescript / scip) in goopspec.json, and a missing binary returns an install-hint string, not a throw. Query actions also require an existing index file (run index first) or they return guidance instead of spawning. index_path defaults to index.scip in the project root and is ignored by index.", args: { - action: tool.schema.enum(SCIP_ACTIONS).describe("SCIP action to perform"), - symbol: tool.schema - .string() - .optional() - .describe("Exact SCIP symbol string; required for query actions"), - index_path: tool.schema - .string() - .optional() - .describe("Path to the SCIP index (default: index.scip in the project root)"), + action: tool.schema + .enum(SCIP_ACTIONS) + .describe("SCIP action to perform. index generates the index; the other three query it."), + symbol: tool.schema.string().optional().describe( + "Exact SCIP symbol string to look up. Required for definitions, references, and " + + "implementations; ignored by index. Omit entirely for index; do not pass an empty string.", + ), + index_path: tool.schema.string().optional().describe( + "Path to the SCIP index file. Defaults to index.scip in the project root. " + + "Used only by query actions; ignored by index.", + ), }, async execute( args: { action: ScipAction; symbol?: string; index_path?: string }, diff --git a/packages/opencode-plugin/src/tools/slashcommand/index.ts b/packages/opencode-plugin/src/tools/slashcommand/index.ts index 4f7127ac..4e73aabd 100644 --- a/packages/opencode-plugin/src/tools/slashcommand/index.ts +++ b/packages/opencode-plugin/src/tools/slashcommand/index.ts @@ -120,9 +120,13 @@ function listAvailableCommands(commandsDir: string): string[] { // --------------------------------------------------------------------------- export function createSlashcommandTool(ctx: PluginContext): ToolDefinition { - const availableList = KEPT_COMMANDS.map((c) => `/${c}`).join(", "); return tool({ - description: `Execute a GoopSpec slash command. Available commands: ${availableList}`, + description: + "Resolve a GoopSpec slash command name to its markdown definition. " + + "WHEN TO USE: Load workflow instructions for a kept command (goop-discuss, goop-plan, goop-execute, goop-accept, goop-quick, goop-status, goop-setup, goop-help, goop-amend). " + + "WHEN NOT TO USE: goop_status for live state; goop_reference for reference documents. " + + "RETURNS: The command's raw markdown body, or an error string listing available commands when the name is unknown. " + + "CAVEATS: Side-effect free — resolves and returns markdown only; never creates sessions, binds workflows, or mutates state. Leading slash and the goop- prefix are both optional; only the first whitespace-delimited token is used.", args: { command: tool.schema .string()