Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
3a2ea67
feat(tools): coalesce empty-string args to absent at the input boundary
hffmnnj Aug 4, 2026
015d4ce
docs(tool-reference): document the empty-string coalescing boundary
hffmnnj Aug 4, 2026
5e83a01
feat(goop-read): make document/section/search selection first-try cor…
hffmnnj Aug 4, 2026
d4abc78
feat(goop-write): make document/section/chronicle write contracts fir…
hffmnnj Aug 4, 2026
8ac682d
feat(goop-knowledge): make six knowledge/workflow tool contracts firs…
hffmnnj Aug 4, 2026
213988c
fix(tools): scope empty-string exclusions by tool
hffmnnj Aug 4, 2026
57dc31b
feat(memory): make save/search/forget contracts first-try correct
hffmnnj Aug 4, 2026
816801a
feat(tools): make six action-dispatch tool contracts first-try correct
hffmnnj Aug 4, 2026
3f38a5f
feat(tools): make six utility/external-binary tool contracts first-tr…
hffmnnj Aug 5, 2026
66dc6c7
feat(tools): bring final two tools to conformance; empty PENDING_CONF…
hffmnnj Aug 5, 2026
a8e85e6
fix(memory): compose decision content once
hffmnnj Aug 5, 2026
b61219e
fix(tools): make rejected calls self-correcting
hffmnnj Aug 5, 2026
78d4adf
docs(tools): make emitted schemas the sole usage-contract authority
hffmnnj Aug 5, 2026
c11d2a6
docs(memory): record decision to leave pre-fix records unmigrated
hffmnnj Aug 5, 2026
a9a9f36
test(tools): enforce conditional description sections
hffmnnj Aug 5, 2026
c750e4e
test(tools): classify opt-in execution modes
hffmnnj Aug 5, 2026
acd8b4c
Merge pull request #295 from hffmnnj/feat/tool-contract-integration
hffmnnj Aug 5, 2026
861514a
Merge pull request #294 from hffmnnj/feat/utility-tool-contracts
hffmnnj Aug 5, 2026
3e5d0cc
Merge pull request #293 from hffmnnj/feat/workflow-memory-contracts
hffmnnj Aug 5, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 6 additions & 34 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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/<jobId>/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/<jobId>/stdout.log` and `stderr.log`. The emitted tool schemas own the arguments, defaults, ranges, and return shapes.

## Gotchas (Auto)

Expand Down Expand Up @@ -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 `<goopspec_state>` 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 `<goopspec_db>` 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.
30 changes: 27 additions & 3 deletions packages/opencode-plugin/references/tool-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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" })`.

Expand All @@ -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}`. |
Expand Down
5 changes: 4 additions & 1 deletion packages/opencode-plugin/src/core/tools-v2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
},
});
});

Expand Down
Loading