fixate-on 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,28 +1,14 @@
1
1
  # fixate-on
2
2
 
3
- A session-scoped goal-tracking plugin for [OpenCode](https://opencode.ai/). Run `/goal <objective>` to hold an objective in context, drive continuations when the assistant goes idle, enforce evidence-cited recovery against premature exits, and settle the goal only after a verifier has checked the completion claim.
3
+ A session-scoped goal-tracking plugin for [OpenCode](https://opencode.ai/). Run `/goal <objective>` in plain language (no flags required) to keep an objective in context, automatically continue the session when the assistant goes idle, check completion claims with a judge before settling, and stop when a brake is reached.
4
4
 
5
- A plugin that prevents premature exits must also prevent finished work from looping forever. `fixate-on` bounds both failure modes:
5
+ Completion claims require an attestation from a verifier (by default, a read-only judge subagent). Rejected claims trigger bounded recovery continuations listing the remaining issues, and operational verifier errors are recorded as faults and retried with backoff. Mechanical brakes (turn, stall, token, no-progress, no-tool-call, and prompt-failure limits) stop continuations without marking the goal complete or blocked.
6
6
 
7
- - **A goal never settles on narration.** Every completion claim requires an **attestation** naming the verifier that checked it. A judge's concurrence is weak evidence and its refusal is strong, making the policy asymmetric: easy to continue, hard to settle.
8
- - **A failure to obtain an attestation is a fault, not a verdict.** Operational verifier errors are retried with backoff and bounded by both a total recovery budget and a consecutive-unchanged threshold. When no verifier is available or faults exhaust the bound, the goal settles or pauses with an explicit receipt rather than looping indefinitely.
9
- - **Brakes are not verdicts.** Turn, token, duration, and API-cost ceilings stop a continuation; they never assert whether the objective is complete or blocked.
10
-
11
- **Core capabilities:**
12
-
13
- - **Claim ledger & judge-driven gate:** Every completion claim records the claim, verifier check, and outcome. Claims without an attestation are recorded as unattested — never `verified-complete`.
14
- - **Recovery escalation (r1–r4):** Rejected claims trigger a bounded pressure ladder citing failed evidence and outstanding requirements. Cited evidence later shown to be wrong receives a visible retraction.
15
- - **Artifact pointers (`--pointer <file>`):** Injects live file content into every continuation without mutating the goal contract. Contract-tier turn and token ceilings cannot be raised by agent tools mid-run.
16
- - **Brakes & crash-safe persistence:** Stall, context-token, turn, no-progress, and no-tool-call bounds backed by session-scoped state files (`0600`), an append-only WAL lifecycle ledger, and per-session single-writer leases.
17
- - **Handback & TUI companion:** Scoped reviewable diffs, known-risk enumeration, and an optional interactive TUI dashboard (`fixate-on/tui`).
18
-
19
- > **Compatibility note:** This plugin relies on experimental OpenCode hooks (`experimental.chat.system.transform` and related lifecycle hooks). Re-test against the exact OpenCode build and provider/backend stack you use for unattended runs.
20
-
21
- ---
7
+ Supports OpenCode 1.x (`opencode`) and OpenCode 2.x (`opencode2`). See [Compatibility](#compatibility) for runtime and experimental-hook requirements.
22
8
 
23
9
  ## Installation
24
10
 
25
- Register the plugin in `opencode.json`:
11
+ On OpenCode 1.x (`opencode`), register `fixate-on` in `opencode.json`:
26
12
 
27
13
  ```json
28
14
  {
@@ -30,30 +16,34 @@ Register the plugin in `opencode.json`:
30
16
  }
31
17
  ```
32
18
 
33
- On stock OpenCode v1 hosts, this single entry is the only required step. The plugin's `config` hook auto-registers the `/goal` slash command, the `goal` agent, and the read-only `goal-verify` subagent.
34
-
35
- <details>
36
- <summary>Optional: customize <code>command.goal</code> on OpenCode v1</summary>
19
+ On OpenCode 2.x (`opencode2`), run:
37
20
 
38
- ```json
39
- {
40
- "plugin": ["fixate-on"],
41
- "command": {
42
- "goal": {
43
- "description": "Set a session-scoped goal and auto-continue until complete.",
44
- "template": "$ARGUMENTS"
45
- }
46
- }
47
- }
21
+ ```sh
22
+ opencode2 plugin add fixate-on
48
23
  ```
49
24
 
50
- A user-defined `command.goal` is preserved via `??=` semantics, except for its `agent` field, which the plugin deletes. OpenCode routes to a command's `agent` *after* `command.execute.before` fires, so keeping `agent` on v1 would override the hook's output; the continuation loop uses the session's default agent instead.
25
+ That writes `"plugins": ["fixate-on"]` to your global `opencode.json`, and also loads the TUI companion. Either way, the plugin registers the `/goal` command, the `goal` agent, and the read-only `goal-verify` subagent automatically. On 1.x the [TUI companion](#tui-companion) is one further, optional entry.
26
+
27
+ ### OpenCode 1.x vs 2.x
28
+
29
+ One `fixate-on` package supports both OpenCode 1.x (`opencode`) and OpenCode 2.x (`opencode2`), with these config differences:
30
+
31
+ | Setting | OpenCode 1.x (`opencode`) | OpenCode 2.x (`opencode2`) |
32
+ |:---|:---|:---|
33
+ | Server plugin key | `plugin` (string or `[spec, options]`) | `plugins` (string or `{ "package", "options" }`) |
34
+ | Local checkout target | File path to the built bundle (`.../plugin/fixate-on/plugin.js`) | The repository directory (file paths fail with `configured plugin path must be a directory`) |
35
+ | `/goal` command | Auto-registered and intercepted via `command.execute.before` | Registered via `command.transform` (overrides built-in `opencode.goal`); explicit `command.goal` is the fallback for older builds |
36
+ | Agents (`goal`, `goal-verify`) | Registered by the `config` hook | Registered by `agent.transform` |
37
+ | TUI companion | `tui.json` `plugin` array (`fixate-on`) | Loaded automatically with the server plugin |
38
+ | Permission key (shared config) | `permission` (map) | `permissions` (also accepts 1.x `permission`) |
39
+
40
+ If you share one `opencode.json` across both versions, keep the 1.x singular keys (`plugin` and `permission`). OpenCode 2.x accepts and migrates them, whereas checked 1.18.x releases silently drop `plugins` and `permissions`.
51
41
 
52
- </details>
42
+ ### `/goal` on OpenCode 2.x
53
43
 
54
- ### `/goal` on OpenCode v2 hosts
44
+ OpenCode 2.x does not expose `command.execute.before`. Instead, the plugin registers `/goal` through `command.transform` (overriding the built-in `opencode.goal`), so `/goal` works without extra command configuration on current 2.x builds.
55
45
 
56
- On OpenCode v2 hosts (`opencode2`), plugins cannot intercept slash-command execution via `command.execute.before`, and a command template without `$ARGUMENTS` appends raw arguments as chat text. For `/goal` submissions to reach goal state rather than plain chat, configure `command.goal` to route through the plugin's `goal-command` bridge tool:
46
+ On older 2.x builds where `command.transform` is unavailable, add `command.goal` to `opencode.json` to route arguments through the `goal-command` tool:
57
47
 
58
48
  ```json
59
49
  {
@@ -67,64 +57,96 @@ On OpenCode v2 hosts (`opencode2`), plugins cannot intercept slash-command execu
67
57
  }
68
58
  ```
69
59
 
70
- With this template wired, `/goal <objective> --pointer SPEC.md --max-turns 10` creates the goal with artifact pointers on disk, drives continuations, and settles through the claim ledger. On stock OpenCode 1.x this template is unnecessary because the plugin intercepts the auto-registered command directly.
60
+ On OpenCode 1.x this template is unnecessary because `command.execute.before` intercepts `/goal` first, though keeping it in a shared config is harmless.
61
+
62
+ On 2.x, reporting commands and lifecycle receipts use the host's passive event channel so they do not enter the model inbox or start a turn, including while the model is busy. The 2.x TUI companion displays receipts in a dialog for the current session and as session-scoped toasts for other sessions or notices (see [passive command receipts](docs/tui-integration.md#passive-command-receipts-on-2x)). Older hosts without passive RPC require a configured `goalMessenger` option, or the command returns an output-delivery error containing its result. Calls through the `goal-command` tool return output through the standard tool channel.
71
63
 
72
- ### TUI companion setup
64
+ ### TUI companion
73
65
 
74
- The optional TUI companion (`fixate-on/tui`) provides an interactive dashboard, command palette actions (`ctrl+p` → `fixate:`), keyboard chords, and lifecycle toasts. Because `TuiPluginModule` and the server `PluginModule` are mutually exclusive, stock OpenCode v1 loads the server plugin from `opencode.json` and the TUI companion **only** from `tui.json` (`~/.config/opencode/tui.json` or `$OPENCODE_TUI_CONFIG`):
66
+ The optional TUI companion adds an interactive dashboard, command palette actions (`ctrl+p` → `fixate:`), keyboard shortcuts, and lifecycle toasts.
75
67
 
76
- `opencode.json`:
68
+ On OpenCode 2.x the companion loads automatically with the server plugin; nothing else needs configuring. The host does not pass the server entry's options to the companion, so the companion asks the server plugin which state directory it uses. Add an entry to `cli.json` (`~/.config/opencode/cli.json`) in two cases only: to set companion options such as `logLevel`, or when the TUI connects to a server on another machine or with a different package cache. The host does not install a server's plugins for the TUI in that second case:
77
69
 
78
70
  ```json
79
71
  {
80
- "plugin": ["fixate-on"]
72
+ "plugins": [
73
+ { "package": "fixate-on", "options": { "logLevel": "info" } }
74
+ ]
81
75
  }
82
76
  ```
83
77
 
84
- `tui.json`:
78
+ On OpenCode 1.x, add the same package name to `tui.json` (`~/.config/opencode/tui.json` or `$OPENCODE_TUI_CONFIG`), separate from `opencode.json`:
85
79
 
86
80
  ```json
87
81
  {
88
82
  "plugin": [
89
- ["fixate-on/tui", { "logLevel": "info" }]
83
+ ["fixate-on", { "logLevel": "info" }]
90
84
  ]
91
85
  }
92
86
  ```
93
87
 
94
- **State root alignment:** Both the server plugin and the TUI companion resolve the persisted state directory independently and reject goal files whose embedded session ID does not match their parent directory. If you override the default state directory, either set the `FIXATE_ON_STATE_ROOT` environment variable (read by both) or pass the identical `stateRoot` option to both entries:
88
+ Use the bare package name in both files. Both hosts parse a subpath such as `fixate-on/tui` as GitHub shorthand and try to clone a repository.
89
+
90
+ If you change the persisted state directory, see [Persistence and state root](#persistence-and-state-root). See [`docs/tui-integration.md`](docs/tui-integration.md) for dashboard usage and keyboard shortcuts.
91
+
92
+ ### Local source
93
+
94
+ Build the bundles first with `bun run bundle` (`plugin/fixate-on/` is generated, gitignored output; keep test files out of OpenCode's auto-loaded plugin directory).
95
+
96
+ On OpenCode 1.x, point `plugin` in `opencode.json` at the built server bundle, and `plugin` in `tui.json` at `tui.js` beside it:
95
97
 
96
98
  ```json
97
99
  {
98
- "plugin": [
99
- ["fixate-on/tui", { "stateRoot": "my/state/root", "logLevel": "info" }]
100
- ]
100
+ "plugin": ["file:///absolute/path/to/fixate-on/plugin/fixate-on/plugin.js"]
101
101
  }
102
102
  ```
103
103
 
104
- See [`docs/tui-integration.md`](docs/tui-integration.md) for the dual-mode output headers, v1 disk-refresh vs v2 `Result.metadata` transport architecture, toast coalescing rules, and keyboard shortcut tables.
105
-
106
- ### Loading from local source
107
-
108
- To test a local checkout without packing, point OpenCode directly at `src/plugin.ts` (keep test files out of OpenCode's auto-loaded plugin directory):
104
+ On OpenCode 2.x (2.2.0 and later), point `plugins` in `opencode.json` at the repository directory. The host resolves the server and companion through `package.json`, as it does for an npm install:
109
105
 
110
106
  ```json
111
107
  {
112
- "plugin": ["file:///absolute/path/to/fixate-on/src/plugin.ts"]
108
+ "plugins": [
109
+ {
110
+ "package": "file:///absolute/path/to/fixate-on",
111
+ "options": {}
112
+ }
113
+ ]
113
114
  }
114
115
  ```
115
116
 
116
- **Quick smoke test:**
117
+ Earlier 2.x builds ignore `exports` in a local directory. There, use a directory with a `server.js` that re-exports `plugin/fixate-on/plugin.js` and a `tui.js` that re-exports `plugin/fixate-on/tui.js`.
118
+
119
+ ## Examples
120
+
121
+ Start with a plain-language objective and add flags only when you want explicit overrides:
122
+
123
+ ```sh
124
+ # Plain-language goal using default brakes
125
+ /goal fix the failing tests and confirm the suite passes
126
+
127
+ # Override turn, stall-duration, and context-token brakes
128
+ /goal "migrate class components to functional" --max-turns=20 --max-minutes 60 --budget 400k
129
+
130
+ # Add success criteria, constraints, and a live file pointer
131
+ /goal "ship the release" --success "tests pass, changelog updated" --constraints "do not modify the public API" --pointer SPEC.md
132
+
133
+ # Queue an ordered multi-goal pipeline
134
+ /goal sequence build the parser; write unit tests; update docs
135
+ ```
117
136
 
118
- 1. Load the plugin in a scratch OpenCode config and configure `command.goal` if running on a v2 host.
119
- 2. Run `/goal status` and confirm no active goal is reported.
120
- 3. Run `/goal inspect this repo and call update_goal with status "blocked" if you need user input`.
121
- 4. Verify `/goal status`, `/goal pause`, `/goal resume`, and `/goal clear` transition state as expected.
137
+ Inspect or manage goals while a session is running:
122
138
 
123
- ---
139
+ ```sh
140
+ /goal status # State summary, remaining brakes, and next step
141
+ /goal status --full # Usage breakdown, recovery counters, and recorded claims
142
+ /goal pause # Pause the focused goal
143
+ /goal resume # Resume with a fresh per-run limit window
144
+ /goal handback # Scoped diff, known risks, recorded claims, and review payload
145
+ ```
124
146
 
125
147
  ## `/goal` Command Reference
126
148
 
127
- Natural language is the primary interface: `/goal <objective>` works with zero flags. Subcommands and per-goal flags provide lifecycle control and optional overrides.
149
+ Plain language is the primary interface (`/goal <objective>` works without flags). Subcommands and per-goal flags provide lifecycle control and optional overrides.
128
150
 
129
151
  ### Subcommands
130
152
 
@@ -132,208 +154,141 @@ Natural language is the primary interface: `/goal <objective>` works with zero f
132
154
  |:---|:---|
133
155
  | `/goal <objective> [flags]` | Sets or replaces the focused goal in the current session. |
134
156
  | `/goal add <objective> [flags]` | Creates and focuses a new goal while leaving existing unfinished goals active. |
135
- | `/goal sequence <obj1>; <obj2>` | Queues multiple objectives (separated by `;` or newlines) as an ordered pipeline. Focuses the first and keeps successors paused (`queued`) until auto-promoted on completion. |
136
- | `/goal status [--full \| --verbose]` | Shows a plain-language state headline, remaining brakes, and next duty. `--full` / `--verbose` prints the full usage breakdown, recovery counters, and raw evidentiary claim ledger. |
137
- | `/goal list [all]` | Lists numbered live goals and settled goals in the per-session archive, with state markers (`focused` = driven now, `idle` = active between turns, `background` = waiting). |
138
- | `/goal focus <number \| goalId>` | Switches which goal the dashboard and bare commands target. Persisted on disk. Does not alter goal status (focusing a paused goal leaves it paused; unfocused active goals keep running). |
139
- | `/goal pause [<goalId>]` | Pauses the focused (or named) goal while retaining its state and history. |
140
- | `/goal resume [<goalId>]` | Resumes a paused, blocked, or brake-stopped goal with a fresh local budget window and reset turn count, preserving the objective and history. |
141
- | `/goal edit <new objective>` | Revises the focused goal's objective in place, preserving budgets and history and clearing any paused/blocked state. If the goal already hit a hard brake, run `/goal resume` for a fresh budget window. |
157
+ | `/goal sequence <obj1>; <obj2>` | Queues multiple objectives (separated by `;` or newlines) as an ordered pipeline. Focuses the first and keeps successors paused (`queued`) until auto-promoted when the active goal settles as `complete`. |
158
+ | `/goal status [--full \| --verbose]` | Shows a plain-language state summary, remaining brakes, and next step. `--full` or `--verbose` adds the usage breakdown, recovery counters, and recorded claims. Alias: `info`. |
159
+ | `/goal list [all]` | Lists numbered live goals and settled goals in the per-session archive, with state markers (`focused` = driven now, `idle` = active between turns, `background` = waiting). Alias: `ls`. |
160
+ | `/goal focus <number \| goalId>` | Switches which goal bare commands and the TUI target. Persisted on disk without altering goal status; unfocused active goals keep running. |
161
+ | `/goal pause [<goalId>]` | Pauses the focused or named goal while retaining its state and history. |
162
+ | `/goal resume [<goalId>]` | Resumes a paused, blocked, or brake-stopped goal, resets the turn count, and starts a fresh window for configured per-run limits while preserving the objective and history. |
163
+ | `/goal edit <new objective>` | Revises the focused goal's objective in place, preserving limits and history and clearing paused or blocked state. If a hard brake already triggered, run `/goal resume` to reset limits. |
142
164
  | `/goal checkpoint <note>` | Records a progress note on the focused goal. |
143
- | `/goal history [--verbose]` | Displays the lifecycle event trail and latest progress note. |
144
- | `/goal clear [<goalId>]` | Removes live goal state and saved status (aliases: `stop`, `off`, `reset`, `none`, `cancel`). Clears immediately when only one live goal exists; when several exist, bare `/goal clear` refuses and requires a `<goalId>` (or unique prefix). Terminal ledger tombstones remain on disk for crash-safe recovery. |
165
+ | `/goal history [--verbose \| --full]` | Displays the lifecycle event trail and latest progress note. `--verbose` and `--full` include bookkeeping entries. Alias: `log`. |
166
+ | `/goal accept [proposalId]` | Applies the focused goal's pending proposal from `propose_goal_change` (objective, success criteria, constraints, and artifact pointers) and clears it. If `proposalId` is supplied, it must match. Alias: `accept-proposal`. |
167
+ | `/goal reject [proposalId]` | Discards the focused goal's pending proposal without changing the goal. If `proposalId` is supplied, it must match. Alias: `reject-proposal`. |
168
+ | `/goal handback` | Returns the handback deliverable for the focused goal: scoped reviewable diff (files, stat, patch), known risks, recorded claims, and external review payload. |
169
+ | `/goal review` | Returns only the external review payload from the focused goal's handback deliverable. Alias: `review-payload`. |
170
+ | `/goal clear [<goalId>]` | Removes live goal state and saved status. Clears immediately when one live goal exists; when multiple live goals exist, requires `<goalId>` (or a unique prefix). Aliases: `stop`, `off`, `reset`, `none`, `cancel`. |
145
171
 
146
- Every action that accepts a `<goalId>` (`pause`, `resume`, `focus`, `clear`) matches either the full ID or a unique prefix, rejecting ambiguous prefixes with an error instead of guessing.
172
+ Commands that accept `<goalId>` (`pause`, `resume`, `focus`, `clear`) match a full ID or a unique prefix. Ambiguous prefixes return an error.
147
173
 
148
174
  ### Per-goal flags
149
175
 
150
- Flags accept `--flag value` or `--flag=value`. Quote multi-word values. Unknown flags, missing values, non-positive integers, or invalid `--mode` values reject the command with an explicit error instead of folding malformed flags into the objective.
176
+ Flags accept `--flag value` or `--flag=value`. Quote multi-word values. Unknown flags, missing values, non-positive integers, or invalid `--mode` values fail with an explicit error instead of being folded into the objective.
151
177
 
152
178
  | Flag | Description |
153
179
  |:---|:---|
154
- | `--success <text>` | Success criteria injected alongside the objective (alias: `--success-criteria`). |
155
- | `--constraints <text>` | Constraints or non-goals to respect (alias: `--non-goals`). |
156
- | `--pointer <file>` | Artifact pointer; injects live file content into every continuation without editing the contract. |
180
+ | `--success <text>` | Success criteria injected alongside the objective. Alias: `--success-criteria`. |
181
+ | `--constraints <text>` | Constraints or non-goals to respect. Alias: `--non-goals`. |
182
+ | `--pointer <file>` | Artifact pointer; injects live file content into every continuation without editing the goal text. Repeatable and comma-separated. Aliases: `--pointers`, `--artifact-pointer`, `--artifact-pointers`. |
157
183
  | `--mode <normal\|ordered>` | Prompt mode for a single goal (`default: normal`; `ordered` preserves step order within the objective). |
158
- | `--max-turns <n>` | Continuation turn ceiling (contract-tier). |
184
+ | `--max-turns <n>` | Continuation turn ceiling (cannot be raised by agent tools). |
159
185
  | `--max-minutes <n>` | Stall brake in minutes (time without progress). |
160
186
  | `--max-duration-ms <n>` | Stall brake in milliseconds (time without progress). |
161
- | `--max-tokens <n>` | Cumulative context token ceiling (contract-tier). |
162
- | `--budget <n>` | Shorthand for `--max-tokens`; accepts `k`/`m` suffixes (e.g. `100k`, `1.5m`). |
163
- | `--token-budget <n>` | Advisory API-cost token budget (`k`/`m` suffixes supported; `null` = unbounded). Triggers a one-time `budget_limit.md` prompt when crossed. |
187
+ | `--max-tokens <n>` | Cumulative context-token ceiling (cannot be raised by agent tools). |
188
+ | `--budget <n>` | Shorthand for `--max-tokens`; accepts `k` and `m` suffixes (for example, `100k`, `1.5m`). |
189
+ | `--token-budget <n>` | Advisory API-cost token budget (`k` and `m` suffixes supported; `null` = unbounded). Triggers a one-time advisory warning when crossed. |
164
190
  | `--cooldown-ms <n>` | Minimum delay between continuations in milliseconds (`0` = no delay). |
165
191
  | `--no-progress-threshold <n>` | Output-token floor for a stalled turn (`0` = disable no-progress heuristic). |
166
192
  | `--no-progress-turns <n>` | Consecutive stalled low-output turns before pausing (`0` = pause on first). |
167
193
  | `--no-tool-turns <n>` | Consecutive tool-free continuation turns before pausing (`0` = disabled). |
168
- | `--max-recovery-turns <n>` | Total bounded recovery turns before escalating (`default: 12`). |
169
- | `--max-unchanged-results <n>` | Consecutive unchanged verifier results (matching candidate + fingerprint) before escalating (`default: 3`). |
194
+ | `--max-recovery-turns <n>` | Total bounded recovery turns before pausing with `recovery exhausted` (`default: 12`). |
195
+ | `--max-unchanged-results <n>` | Consecutive unchanged verifier results before pausing with `recovery exhausted` (`default: 3`). |
170
196
  | `--max-blocked-turns <n>` | Consecutive `update_goal {status: "blocked"}` calls required before `blocked` is accepted (`default: 3`). |
171
- | `--verbose` | Renders verbose command output. |
172
-
173
- ### Examples
174
-
175
- ```sh
176
- # Plain-language goal using default brakes
177
- /goal fix the failing tests and confirm the suite passes
178
-
179
- # Override turn, duration, and context-token brakes
180
- /goal "migrate class components to functional" --max-turns=20 --max-minutes 60 --budget 400k
181
-
182
- # Attach explicit success criteria, constraints, and a live spec pointer
183
- /goal "ship the release" --success "tests pass, changelog updated" --constraints "do not modify the public API" --pointer SPEC.md
184
-
185
- # Queue an ordered multi-goal pipeline
186
- /goal sequence build the parser; write unit tests; update docs
187
- ```
188
-
189
- ---
190
-
191
- ## Multi-Goal & Session-Scoped Behavior
192
-
193
- ### Concurrent goals and focus
197
+ | `--verbose` | Renders verbose command output (alias for `--full` on `/goal status`). |
194
198
 
195
- A session can hold multiple goals simultaneously, and **every unfinished goal is driven**: each session-idle event continues every active (or re-armable) goal in the session, not only the focused one.
199
+ ## How It Works
196
200
 
197
- - `/goal <objective>` replaces the focused goal.
198
- - `/goal add <objective>` adds and focuses a new objective while leaving prior goals running.
199
- - `/goal focus <number | goalId>` changes which goal bare commands (`/goal pause`, `/goal resume`, `/goal edit`, `/goal checkpoint`) and the TUI cockpit target by default.
200
- - In an ordered sequence created via `/goal sequence`, only the head goal runs; queued successors stay paused until the active goal settles as `complete`, at which point the next queued goal is auto-promoted and focused.
201
+ ### Sessions, concurrent goals, and forks
201
202
 
202
- ### Forks and session deletion
203
+ Goals are **session-scoped**: each goal belongs to one session and is stored in that session's state file. Sharing a single goal across two sessions is rejected.
203
204
 
204
- Goals are **session-scoped**: each goal belongs to exactly one session and is stored in that session's state file. Sharing a single goal instance across two sessions is rejected.
205
+ A session can hold multiple goals at once, and every unfinished goal in the session is driven on session idle, including unfocused goals. `/goal <objective>` replaces the focused goal, `/goal add <objective>` adds and focuses a new goal while keeping prior goals active, and `/goal focus <number | goalId>` changes which goal bare commands and the TUI target. In an ordered pipeline created with `/goal sequence`, only the first goal runs; queued successors stay paused until the active goal settles as `complete`, at which point the next queued goal is promoted and focused automatically.
205
206
 
206
- When a session is forked, live goals are **copied** into the fork with newly minted `goalId` values while the parent session keeps its own goals:
207
+ When a session is forked, live goals are copied into the fork with new `goalId` values while the parent session keeps its own goals. Copies preserve the objective, success criteria, constraints, artifact pointers, mode, and brake settings; turn counts, token usage, recovery and fault counters, blocked streaks, claims, and pending intents start empty. Settled goals (`complete`, `budgetLimited`) are not copied. On OpenCode 2.x, a durable `session.forked` event carries `parentID` and the fork boundary, triggering the copy automatically. On OpenCode 1.x, forks are created as unrelated top-level sessions without a `parentID`; because the plugin does not guess ancestry from session titles, 1.x forks start without copied goals.
207
208
 
208
- - **Intent crosses over, work does not:** The copy preserves the objective, completion contract (`--success`, `--constraints`, artifact pointers), mode, and brake configuration. Turn counts, tokens used, recovery and fault counters, blocked streaks, claims, and pending intents start empty in the fork. Settled goals (`complete`, `budgetLimited`) are not copied.
209
- - **OpenCode v1 vs v2 fork detection:** Stock OpenCode v1 creates a fork as an unrelated top-level session without a `parentID` (leaving only a mutable `… (fork #1)` title); the plugin refuses to guess ancestry from titles, so v1 forks start without copied goals. OpenCode v2 emits a durable `session.forked` event carrying `parentID` and the fork boundary, which triggers the copy.
210
- - **Deleted sessions:** If a goal's owning session is deleted, the next continuation fails and pauses the goal with the status reason `session not found` so the cause is explicit rather than silently abandoning the goal or reporting completion.
209
+ If the host cannot read a session (for example, after deletion), failed reads never trigger continuations. After `maxPromptFailures` consecutive failures, the goal pauses with a receipt (`session not found` or `auto-continue failures`).
211
210
 
212
- ---
211
+ ### Continuation loop and user intervention
213
212
 
214
- ## Continuation Loop & Steering
213
+ Active goals are injected into the primary system prompt as user-provided task data, separate from system, developer, tool, and repository policies. When a goal is paused, the plugin omits the objective from the system prompt and requires an explicit `/goal resume`.
215
214
 
216
- 1. **System prompt injection & injection hardening:** Active goals are injected into the primary `system` message wrapped in XML-escaped `<goal_objective>` tags. The objective is explicitly framed as user-provided task data, never as elevated instructions capable of overriding system, developer, tool, or repository policies. When a goal is **paused**, the plugin injects a system guard that omits the objective and requires an explicit `/goal resume`, preventing command text routed through chat on v1 hosts from being mistaken for active work.
217
- 2. **Steering templates:**
218
- - `continuation.md` — Injected on every idle continuation. Carries the completion check, the 3-consecutive-turn blocked rule, verification pressure, fidelity constraints, and work-from-evidence instructions without re-quoting the standing system-prompt objective every turn.
219
- - `budget_limit.md` — Injected once per goal (advisory, not a hard interrupt) when the explicit API-cost `token_budget` is crossed. In-flight tokens continue accruing until the turn ends.
220
- - `objective_updated.md` — Injected when `/goal edit` revises the objective.
221
- 3. **Idle pre-flight & deduplication:** Continuations preserve the initiating turn's agent, provider/model, and variant. After `minDelayMs`, the plugin re-verifies that the session is still idle and that no human message, newer assistant turn, Plan-agent switch, rejected permission, abort, or provider error has intervened. A durable claim on the source assistant turn prevents duplicate continuations across distinct idle events. If the host reports itself busy, the continuation is *deferred* without consuming turn budget and retried on the next idle, bounded by `maxPromptFailures`.
222
- 4. **Yield, then re-arm:** Sending a human message while a goal is active aborts any in-flight continuation and pauses active goals for the duration of your turn. When your turn goes idle, goals paused by this conversational interjection re-arm automatically. Two cases remain paused:
223
- - Whole-message stop imperatives (`"stop"`, `"pause"`, `"hold off"` — matched conservatively so mixed instructions like `"stop the server then fix tests"` remain normal steering) pause with `explicit pause` and require `/goal resume`.
224
- - If a yielded turn never settles within 15 minutes, the goal stops claiming it will auto-resume, surfaces as waiting on you, and accepts `/goal resume`.
225
- 5. **OpenCode v1 kickoff & echo filtering:** Because slash commands on stock v1 do not launch an assistant turn on their own, the plugin schedules a one-shot kickoff probe (`kickoffDelayMs`, default `2500` ms) when a command activates a goal, sending the first continuation only if no turn started organically. It also fingerprints just-dispatched slash arguments so v1's chat echo of `/goal ...` does not trigger a human-interjection pause.
226
- 6. **Compaction survival:** When OpenCode compacts a session, the plugin injects a deterministic summary reconstructed from the persisted goal record (objective, status, budget usage, recent progress notes, and lifecycle trail) and disables OpenCode's generic post-compaction auto-continue so it cannot race the plugin's continuation.
227
- 7. **Host token accounting:** On v1, token usage is tracked via `message.updated` events (falling back to fetched session messages when per-message events are absent). On v2, usage is tracked via ephemeral `session.usage.updated` steps. Because session context is shared, token usage accrues to every non-terminal goal in the session.
215
+ When the session goes idle, the plugin waits `minDelayMs` and checks that the session is still idle and that no human message, newer assistant turn, Plan-agent switch, rejected permission, abort, or provider error intervened. Continuations preserve the initiating turn's agent, provider/model, and variant. If OpenCode reports itself busy, the plugin defers the continuation without consuming turn budget and retries on the next idle, bounded by `maxPromptFailures`.
228
216
 
229
- ---
217
+ Sending an ordinary message while a goal is active yields the turn to you. The goal stays **active**, with its objective in the system prompt. The plugin cancels pending continuations and invalidates outstanding completion decisions; OpenCode handles steering the running turn. The loop continues automatically on the next idle after the host has answered your latest message. Direct replies restart the consecutive no-progress and no-tool-call streaks without resetting accumulated turns or token usage.
230
218
 
231
- ## Agent Tools & Goal State Model
219
+ - Whole-message stop imperatives (`"stop"`, `"pause"`, `"hold off"`, matched conservatively so mixed instructions like `"stop the server then fix tests"` remain normal steering) pause with `explicit pause` and require `/goal resume`. An explicit stop also requests host interruption when a plugin prompt is in flight.
232
220
 
233
- Completion and blocking are driven exclusively through the canonical tool surface — never by parsing free-text markers. Six agent-facing tools are registered by default (`registerTools: true`), plus the `goal-command` bridge on OpenCode v2 hosts:
221
+ Messages queued by the host also leave the goal active. The plugin records a notice and history entry, and continues the loop once the turn settles.
234
222
 
235
- | Tool | Arguments | Behavior |
236
- |:---|:---|:---|
237
- | `get_goal` | _(none)_ | Returns the focused goal as a `ThreadGoal` (`{goalId, threadId, objective, status, tokenBudget, tokensUsed, timeUsedSeconds, createdAt, updatedAt, artifactPointers, pendingProposal}`) plus `remainingTokens` and `completionBudgetReport`, or `null` if none exists. |
238
- | `create_goal` | `objective` (string), `token_budget` (optional positive int) | Creates an active user-requested goal (`token_budget` sets the advisory API-cost ceiling; `null` = unbounded). **Fails if an unfinished goal already exists** in the session; terminal goals (`complete`, `budgetLimited`) do not block creation. |
239
- | `update_goal` | `status` (`"complete"` \| `"blocked"`) | Transitions the focused goal. Accepts **only** `status` (no free-text `evidence` or `blocker` parameters; pause, resume, and brake limits are user/plugin-controlled). See below for `complete` and `blocked` gates. |
240
- | `list_goals` | _(none)_ | Lists all goals in the current session. |
241
- | `focus_goal` | `goal_id` (string) | Changes the focused goal in the current session. |
242
- | `propose_goal_change` | proposal fields | Records a `pendingProposal` on the goal for human review (agents cannot raise contract-tier turn or token ceilings directly). |
243
- | `goal-command` | `subcommand` (string) | *(OpenCode v2 only)* Routes `/goal` slash-command invocations into plugin state when wired via `command.goal`. |
244
-
245
- Tool schemas are defined with `zod` (a direct dependency). If `registerTools: false` is set or `zod` fails to load at runtime, active goals pause with a visible notice rather than looping on continuation prompts that reference unavailable tools. Legacy tool aliases (`goal_status`, `goal_set`, `goal_pause`, `goal_resume`, `goal_block`, `goal_complete`, `get_goal_history`, `set_goal`, `clear_goal`) are not registered.
223
+ > A goal persisted as `paused` with the legacy `user intervention` stop reason — from an older plugin version whose message handling paused goals — is not resumed automatically. Run `/goal resume` to continue it.
246
224
 
247
- **Goal statuses:** `active` · `paused` · `blocked` · `budgetLimited` · `finalizing` · `complete`
225
+ When OpenCode compacts a session, the plugin injects a summary reconstructed from persisted goal state (objective, status, budget usage, recent progress notes, and lifecycle trail) so the goal survives compaction. Because session context is shared, token usage accrues to every unfinished goal in the session.
248
226
 
249
- - `finalizing` is the transient state held while a settlement is being recorded.
250
- - `complete` and `budgetLimited` are **terminal**. A `budgetLimited` goal is frozen — it cannot be resumed, paused, or moved to `blocked`, and it does not block `create_goal`.
251
- - **Step barrier on `complete`:** Calling `update_goal {status: "complete"}` records a pending completion intent that is evaluated after the current step finishes, preventing the model from claiming completion and exiting before verification runs.
252
- - **Mechanical 3-consecutive-turn rule on `blocked`:** Calling `update_goal {status: "blocked"}` captures the blocker reason from the assistant's latest turn text and rejects the transition until the same blocker recurs `maxBlockedTurns` consecutive times (default `3`, configurable via `--max-blocked-turns`). The streak persists across the idle boundary when re-asserted and resets on `/goal resume` or any non-blocked turn.
227
+ When a brake is reached, the plugin sends one final wrap-up prompt asking the assistant to summarize what is done, what remains, and the next concrete step. The prompt instructs the assistant to call `update_goal {status: "complete"}` only if the objective is satisfied, and to avoid marking the goal `blocked` solely because a brake fired. Run `/goal resume` to continue with a fresh window for configured per-run limits.
253
228
 
254
- ---
229
+ ### Completion verification
255
230
 
256
- ## Completion Verification
231
+ The working agent runs workspace checks with its own tools. The plugin does not execute shell commands, Makefile targets, or test suites as verifiers. Every `update_goal {status: "complete"}` claim is evaluated by a judge. On OpenCode 2.x, when an active session stops naturally without calling `update_goal`, warm-cache idle triage (`languageTriage`, enabled by default) checks whether the final reply claims completion or a blocker and hands those claims to the same judge rather than pausing or settling directly.
257
232
 
258
- Every `update_goal {status: "complete"}` claim is checked by a **judge-driven completion gate**. All command execution is **agent-driven**: the plugin never executes external shell commands, Makefile targets, or test suites itself. The agent runs checks using its own tools and cites the evidence; the judge evaluates whether the claim holds.
233
+ The completion gate selects one verifier in this order:
259
234
 
260
- ### Verifier resolution and verdicts
235
+ 1. Custom `judge` callback: if configured (`async ({ goal, sessionID, latestText }) => ({ approved, reason })`), it takes precedence over the built-in judge.
236
+ 2. Built-in child-session judge (`childSessionJudge` enabled by default): spawns an isolated session running the hidden `goal-verify` subagent bound to the workspace directory, restricted to `read`, `glob`, and `grep` (`bash`, `edit`, and `write` are denied). On OpenCode 2.x, when session deletion is available, the verifier runs in a detached archived session that inherits the parent session's model (unless `goal-verify` configures its own), avoids `<background-result>` wakeups in the parent, and deletes itself on exit.
237
+ 3. No judge (`childSessionJudge: false` and no custom `judge`): after bounded attempts, the goal settles as unattested with stop reason `completed (no attestation could be obtained)` so queued sequence goals behind it can proceed.
261
238
 
262
- The completion gate consults one verifier in the following precedence order:
239
+ Verdicts and faults update goal state as follows:
263
240
 
264
- 1. **Custom `judge` callback:**
265
- `judge: async ({ goal, sessionID, latestText }) => ({ approved, reason })`
266
- When configured in plugin options, takes precedence over the built-in judge and uses the `{ approved, reason }` return contract.
267
- 2. **Built-in child-session judge (`childSessionJudge`, default `true`):**
268
- Spawns an isolated OpenCode child session running the hidden `goal-verify` subagent bound to the goal's workspace directory. The subagent has a default-deny tool policy: only `read`, `glob`, and `grep` are allowed (`bash`, `edit`, and `write` are denied). It emits a structured verdict conforming to `completion-verdict.schema.json` (`COMPLETE`, `WORKING`, `BLOCKED`, `NEEDS_INPUT`, or `CANCELLED`, plus `candidate`, `fingerprint`, `outstanding`, and `evidence`). The host stamps the candidate identity (git `HEAD` + worktree fingerprint) onto the attestation.
269
- 3. **No judge available (`childSessionJudge: false` and no custom `judge`):**
270
- The gate abstains (`unavailable`). To prevent an unendable loop, after a bounded number of attempts the claim is recorded on the `none` check path as `unverifiable-claim` with verdict `NONE` — **never** `verified-complete` — and settles with stop reason `completed (no attestation could be obtained)` so queued sequence goals behind it can proceed.
241
+ - `COMPLETE`: settles and archives the goal as `complete`.
242
+ - `WORKING`: drives bounded recovery continuations citing the failed evidence and remaining requirements. If cited evidence is later shown to be wrong, the plugin records a visible retraction.
243
+ - `BLOCKED` or `NEEDS_INPUT`: pauses the goal for user input with the judge's findings.
244
+ - `CANCELLED`: settles the goal as an authorized cancellation.
245
+ - Attestation fault (provider error, timeout, or missing child-session ID): recorded as a fault and retried with backoff as a forced continuation; it does not settle or reject the goal.
271
246
 
272
- **Verdict transitions:**
247
+ Recovery is bounded by both `--max-recovery-turns` (default `12`) and `--max-unchanged-results` (default `3`, counting consecutive unchanged verifier results for the same workspace state). New workspace changes reset the consecutive-unchanged counter while still counting toward the total recovery budget. Exhausting either bound pauses the goal with stop reason `recovery exhausted` and never synthesizes `COMPLETE`.
273
248
 
274
- - `COMPLETE` → settles and archives the goal as achieved (`complete`).
275
- - `WORKING` → enters bounded recovery, injecting a forced continuation with the outstanding gates and failed evidence.
276
- - `BLOCKED` / `NEEDS_INPUT` → settles with evidence (pauses for user input).
277
- - `CANCELLED` → settles as an authorized cancellation.
278
- - **Attestation fault** (provider error, timeout, missing child-session ID) → retried with backoff as a forced continuation; never treated as a verdict on the goal.
249
+ See [Plugin options](#plugin-options) to configure `childSessionJudge`, `judge`, and `judgeOptions`.
279
250
 
280
- **Recovery bounds:** Recovery is bounded by both a total recovery budget (`--max-recovery-turns`, default `12`) and a consecutive-unchanged threshold (`--max-unchanged-results`, default `3`, comparing `candidate` + `fingerprint`). A new candidate resets the consecutive-unchanged counter but not the total budget. Exhausting either bound pauses the goal with stop reason `recovery exhausted` and **never** fabricates `COMPLETE`.
251
+ ### Agent tools and goal statuses
281
252
 
282
- ### Tuning the built-in judge (`judgeOptions`)
253
+ Completion and blocking use structured agent tools (`registerTools: true`). If `registerTools` is `false`, active goals pause with a visible notice instead of continuing without tools.
283
254
 
284
- ```ts
285
- await GoalsPlugin(
286
- { client, directory },
287
- {
288
- childSessionJudge: true,
289
- judgeOptions: {
290
- timeoutMs: 60_000,
291
- failurePolicy: "reject" as const,
292
- },
293
- },
294
- );
295
- ```
296
-
297
- - `timeoutMs` (default `120000` ms): Maximum time to wait for the child-session judge to return a verdict.
298
- - `failurePolicy` (default `"reject"`): Fails closed on attestation faults. Setting `"approve"` acts solely as a compatibility escape hatch that synthesizes a `WORKING` verdict (never `COMPLETE`) so bounded recovery continues. `judgeOptions` is ignored when a custom `judge` callback is provided.
255
+ | Tool | Arguments | Behavior |
256
+ |:---|:---|:---|
257
+ | `get_goal` | _(none)_ | Returns the focused goal, remaining token and completion-budget details, or `null` if no goal is focused. |
258
+ | `create_goal` | `objective` (string), `token_budget` (optional positive integer) | Creates an active goal (`token_budget` sets the advisory API-cost ceiling; `null` = unbounded). Fails if an unfinished goal already exists in the session; terminal goals do not block creation. |
259
+ | `update_goal` | `status` (`"complete"` \| `"blocked"`) | Transitions the focused goal. Accepts only `status`. |
260
+ | `list_goals` | _(none)_ | Lists all goals in the current session. |
261
+ | `focus_goal` | `goal_id` (string) | Changes the focused goal in the current session. |
262
+ | `propose_goal_change` | proposal fields | Records a pending proposal for user review via `/goal accept` or `/goal reject`. Agents cannot raise turn or token ceilings directly. |
263
+ | `goal-command` | `subcommand` (string) | *(OpenCode 2.x)* Routes `/goal` invocations into plugin state when wired through `command.goal`. |
299
264
 
300
- ### Advisory phrase triage
265
+ Goal statuses are `active`, `paused`, `blocked`, `budgetLimited`, and `complete`:
301
266
 
302
- `src/stop-guard.ts` scans the assistant's final message across 22 word-boundary-anchored patterns for unfinished work, deferral, permission-seeking, and session-length excuses. When the verifier returns `WORKING`, any matched pattern appends its diagnostic reason to the recovery prompt. Phrase triage is strictly advisory and **cannot block or override** an attested `COMPLETE` verdict (the 16-case adversarial corpus in `test/fixtures/guard-corpus.tsv` locks a stated product boundary of `tp=6 fp=4 fn=2 tn=4`).
267
+ - `complete` and `budgetLimited` are terminal. A `budgetLimited` goal cannot be resumed, paused, or moved to `blocked`, and does not block `create_goal`.
268
+ - Calling `update_goal {status: "complete"}` records a pending completion claim that the completion gate evaluates after the current step finishes.
269
+ - Calling `update_goal {status: "blocked"}` captures the blocker reason from the assistant's latest turn text and rejects the transition until the same blocker recurs `maxBlockedTurns` consecutive times (default `3`, configurable via `--max-blocked-turns`). The streak persists across idle turns when re-asserted and resets on `/goal resume` or any non-blocked turn.
303
270
 
304
- ---
271
+ ## Configuration & Persistence
305
272
 
306
- ## Brakes, Persistence, and Configuration
273
+ ### Persistence and state root
307
274
 
308
- ### Default brakes
275
+ By default (`persistState: true`), each session persists its goals to `.opencode/goals/sessions/<sessionID>/state.json` and a lifecycle ledger to `state.json.ledger.jsonl` (mode `0600` inside an owner-only directory). Add `.opencode/goals/` to `.gitignore`.
309
276
 
310
- | Brake | Default | Notes |
311
- |:---|:---|:---|
312
- | Auto-continue turns (`maxTurns`) | `0` (`unlimited`) | Off by default; turn count alone cannot distinguish productive work from a stall. Disabled limits always render as `unlimited`, never `/ 0`. |
313
- | Stall brake (`maxDurationMs`) | `30 minutes` (`1800000` ms) | Time since last evidence of progress (a completed assistant turn or output-token increase, measured from goal creation before first progress — never suppressed by a hung tool call). |
314
- | Context tokens (`maxTokens`) | `1,000,000` | Cumulative provider-reported context tokens (`input + output + reasoning + cache read + cache write`). |
315
- | Continuation cooldown (`minDelayMs`) | `1.5 s` (`1500` ms) | Minimum delay before sending a continuation after idle. |
316
- | No-progress pause | `< 50` output tokens × `3` turns | Pauses after `noProgressTurnsBeforePause` consecutive low-output turns with no meaningful progress-note change. |
317
- | No-tool-call pause | `3` consecutive turns | Pauses after `noToolCallTurnsBeforePause` consecutive tool-free continuation turns (anti self-chat loop). |
318
- | Budget wrap-up threshold (`budgetWrapupRatio`) | `80%` (`0.8`) | Sends a wrap-up warning when context tokens reach 80% of `maxTokens`. |
319
- | Prompt failure pause (`maxPromptFailures`) | `3` consecutive failures | Pauses when host prompt dispatch fails or defers 3 times in a row. |
277
+ State root resolution follows this precedence order:
320
278
 
321
- **Wrap-up vs. hard stop:** When a brake is reached, the plugin sends one final prompt asking the assistant to summarize what is done, what remains, and the next concrete step. Because a brake is a budget rather than a verdict, the prompt instructs the assistant to call `update_goal {status: "complete"}` only if the objective is genuinely satisfied, and not to mark it `blocked` merely because a brake fired. Run `/goal resume` to continue with a fresh budget window.
279
+ 1. `stateRoot` plugin option
280
+ 2. `FIXATE_ON_STATE_ROOT` environment variable
281
+ 3. `<cwd>/.opencode/goals`
322
282
 
323
- ### Persistence and state root
283
+ On OpenCode 2.x the companion asks the server plugin for its resolved state root, so `stateRoot` needs setting only on the server entry in `opencode.json`. A `stateRoot` on the companion's own `cli.json` entry overrides that answer. If the server plugin does not answer, the companion falls back to `FIXATE_ON_STATE_ROOT`, then the default. On OpenCode 1.x the two entries resolve the root independently: pass the identical `stateRoot` to both, or set `FIXATE_ON_STATE_ROOT`.
324
284
 
325
- By default (`persistState: true`), each session's goals are persisted to `.opencode/goals/sessions/<sessionID>/state.json` (mode `0600`, inside an owner-only directory) alongside an append-only WAL lifecycle ledger (`state.json.ledger.jsonl`, mode `0600`). Add `.opencode/goals/` to `.gitignore`.
285
+ Active goals loaded from disk after a restart open in a `paused` state with a recovery note so unattended continuations do not resume automatically.
326
286
 
327
- - **State root precedence:**
328
- 1. `stateRoot` plugin option
329
- 2. `FIXATE_ON_STATE_ROOT` environment variable
330
- 3. `<cwd>/.opencode/goals`
331
- - **Restart safety:** Active goals recovered from disk load in a **paused** state with a recovery note so unattended continuations never resume blindly after a restart.
332
- - **Multi-process worktree sharing:** Processes hold single-writer leases per session file rather than locking the workspace. If another live process already owns a session's lease, the plugin still loads normally with all tools enabled and declines only to write that session's state file, logging the conflict on the hook surface.
287
+ Because each session persists to its own file, multiple OpenCode processes can share one worktree without locking each other out. If another live process already holds a session's write lease, the plugin still loads with all tools enabled and skips writing that session's state file.
333
288
 
334
289
  ### Plugin options
335
290
 
336
- Pass plugin-level defaults in `opencode.json`:
291
+ Example option overrides in `opencode.json` (on OpenCode 2.x, pass them under `plugins: [{ "package": ..., "options": { ... } }]`):
337
292
 
338
293
  ```json
339
294
  {
@@ -341,77 +296,101 @@ Pass plugin-level defaults in `opencode.json`:
341
296
  [
342
297
  "fixate-on",
343
298
  {
344
- "maxTurns": 0,
345
- "maxDurationMs": 1800000,
346
- "maxTokens": 1000000,
347
- "minDelayMs": 1500,
348
- "maxRecentMessages": 50,
349
- "noProgressTokenThreshold": 50,
350
- "noProgressTurnsBeforePause": 3,
351
- "noToolCallTurnsBeforePause": 3,
352
- "budgetWrapupRatio": 0.8,
353
- "maxPromptFailures": 3,
354
- "persistState": true,
355
- "stateRoot": ".opencode/goals",
356
- "resultRetentionMs": 604800000,
357
- "maxStoredResults": 10
299
+ "maxTurns": 20,
300
+ "maxTokens": 400000
358
301
  }
359
302
  ]
360
303
  ]
361
304
  }
362
305
  ```
363
306
 
364
- **Additional plugin options:**
365
-
366
- - `maxRecentMessages` (default `50`) — Number of recent session messages scanned to locate the latest assistant turn before continuing.
367
- - `noProgressTurnsBeforePause` (default `3`) — Consecutive stalled low-output turns required before pausing.
368
- - `noToolCallTurnsBeforePause` (default `3`) — Consecutive tool-free continuation turns before pausing; set to `0` for legitimate prose-only workflows.
369
- - `kickoffDelayMs` (default `2500`) — Delay in milliseconds before the one-shot v1 kickoff probe fires after `/goal` activates a goal.
370
- - `warnTurnsRemaining` / `warnDurationMsRemaining` / `warnTokensRemaining` (defaults: `3` turns, `60000` ms, `25000` tokens) — Thresholds at which `continuation.md` appends a "limits are near" warning.
371
- - `commandName` (default `"goal"`) — Slash command name owned by the plugin (e.g. `"objective"` for `/objective`; leading slash tolerated). All user-facing hints follow the configured name.
372
- - `registerCommand` (default `true`) — Whether to install the `command.execute.before` hook.
373
- - `registerTools` (default `true`) — Whether to register the canonical agent-facing goal tools.
374
- - `registerAgents` (default `true`) — Whether the config hook registers the native `goal` and `goal-verify` agents (existing agents with those names are preserved; default agent is unchanged).
375
- - `goalAgentName` / `verifierAgentName` (defaults: `"goal"` and `"goal-verify"`) — Custom names for the auto-registered native agents.
376
- - `sdkShape` (`"legacy"` | `"flat"`, default `"legacy"`) — Session-client argument shape (`{ path, body, query }` vs `{ sessionID, ... }`). Read-only calls probe the alternate shape on schema `TypeError`; mutating calls are never replayed.
377
- - `ledgerMaxBytes` / `ledgerRetentionFiles` (defaults: `2 MiB` and `3` rotated generations) — Bounds the per-session `.ledger.jsonl` files (`ledgerRetentionFiles: 0` discards the active ledger at the size ceiling).
378
- - `resultRetentionMs` (default `604800000` / 7 days) & `maxStoredResults` (default `10`) — How long settled goal summaries remain visible in `/goal status` and how many are retained in memory.
379
- - `goalMessages` (default `true`) & `goalMessenger(sessionID, text)` — Controls user-visible announcements for verdicts, attestation faults, pauses, recovery turns, and unattested settlements (routed to structured logs and TUI toasts by default).
307
+ When `maxTurns` or `maxTokens` is `0`, the limit is disabled and renders as `unlimited`.
308
+
309
+ | Option | Default | Description |
310
+ |:---|:---|:---|
311
+ | `maxTurns` | `0` | Continuation turn ceiling (`0` = unlimited). |
312
+ | `maxDurationMs` | `1800000` | Stall brake in ms (30 minutes): time since last progress (completed assistant turn or output-token increase, measured from goal creation before first progress). |
313
+ | `maxTokens` | `0` | Cumulative provider-reported context-token ceiling (`input + output + reasoning + cache read + cache write`; `0` = unlimited). |
314
+ | `minDelayMs` | `1500` | Minimum delay in ms before sending a continuation after idle. |
315
+ | `maxRecentMessages` | `50` | Number of recent session messages scanned to locate the latest assistant turn before continuing. |
316
+ | `noProgressTokenThreshold` | `50` | Output-token floor for treating a turn as stalled. |
317
+ | `noProgressTurnsBeforePause` | `3` | Consecutive stalled low-output turns (with no meaningful progress-note change) before pausing. |
318
+ | `noToolCallTurnsBeforePause` | `3` | Consecutive tool-free continuation turns before pausing. Set to `0` for prose-only workflows. |
319
+ | `budgetWrapupRatio` | `0.8` | Fraction of a positive `maxTokens` ceiling at which to send a wrap-up warning (disabled when `maxTokens` is `0`). |
320
+ | `maxPromptFailures` | `3` | Consecutive prompt dispatch failures, deferrals, or host state read failures before pausing. |
321
+ | `kickoffDelayMs` | `2500` | Delay in ms before the one-shot OpenCode 1.x kickoff probe fires after `/goal` activates a goal. |
322
+ | `warnTurnsRemaining` | `3` | Remaining turns threshold for appending a low-limit warning to continuation prompts. |
323
+ | `warnDurationMsRemaining` | `60000` | Remaining stall-brake ms threshold for appending a low-limit warning. |
324
+ | `warnTokensRemaining` | `25000` | Remaining context-token threshold for appending a low-limit warning. |
325
+ | `childSessionJudge` | `true` | Enables the built-in read-only `goal-verify` child-session judge. |
326
+ | `judge` | _(none)_ | Custom callback `async ({ goal, sessionID, latestText }) => ({ approved, reason })` that takes precedence over `childSessionJudge`. |
327
+ | `judgeOptions.timeoutMs` | `1800000` | Maximum wait in ms (30 minutes) for the built-in judge. Set to `0` to disable the plugin timer (host and provider timeouts still apply). On timeout, the child session is aborted and deleted and an attestation fault is recorded. |
328
+ | `judgeOptions.failurePolicy` | `"reject"` | Fault handling for the built-in judge. `"reject"` fails closed on attestation faults; `"approve"` synthesizes a `WORKING` verdict (never `COMPLETE`) so bounded recovery continues. Ignored when a custom `judge` is set. |
329
+ | `persistState` | `true` | Persists session goals and ledgers to disk. |
330
+ | `stateRoot` | `".opencode/goals"` | Directory for persisted goal state (see [Persistence and state root](#persistence-and-state-root)). |
331
+ | `ledgerMaxBytes` | `2 MiB` | Size limit for each per-session `.ledger.jsonl` file before rotation. |
332
+ | `ledgerRetentionFiles` | `3` | Rotated `.ledger.jsonl` generations retained (`0` discards the active ledger at the size limit). |
333
+ | `resultRetentionMs` | `604800000` | Duration in ms (7 days) that settled goal summaries remain visible in `/goal status`. |
334
+ | `maxStoredResults` | `10` | Maximum number of settled goal summaries retained in memory. |
335
+ | `commandName` | `"goal"` | Slash command name owned by the plugin (leading slash tolerated; user-facing hints follow this name). |
336
+ | `registerCommand` | `true` | Registers the slash command (`command.execute.before` on 1.x, `command.transform` on 2.x). |
337
+ | `registerTools` | `true` | Registers the agent-facing goal tools. |
338
+ | `registerAgents` | `true` | Registers the `goal` and `goal-verify` agents (`config` hook on 1.x, `agent.transform` on 2.x), preserving existing agents with those names and leaving the default agent unchanged. |
339
+ | `goalAgentName` | `"goal"` | Name for the auto-registered goal agent. |
340
+ | `verifierAgentName` | `"goal-verify"` | Name for the auto-registered read-only verifier subagent. |
341
+ | `goalMessages` | `true` | Enables user-visible announcements for verdicts, attestation faults, pauses, recovery turns, and unattested settlements (routed to structured logs and TUI toasts by default). |
342
+ | `goalMessenger` | _(none)_ | Custom `(sessionID, text)` callback for routing announcements and command receipts. |
343
+ | `sdkShape` | `"legacy"` | Session-client argument shape: `"legacy"` (`{ path, body, query }`) or `"flat"` (`{ sessionID, ... }`). |
380
344
 
381
345
  ### Environment variables
382
346
 
383
347
  | Variable | Effect |
384
348
  |:---|:---|
385
- | `FIXATE_ON_STATE_ROOT` | Overrides the goal state root directory (precedence: `stateRoot` option → `FIXATE_ON_STATE_ROOT` → `<cwd>/.opencode/goals`). Read by both the server plugin and the TUI companion. |
386
- | `FIXATE_ON_EVENT_LOG` | Opt-in v2 host diagnostic log (unset by default). When set to a writable file path, appends one space-delimited line per v2 adapter event (`<epoch-ms> <event-type> <session-id> <message-id>`) plus `tool-registration-<stage> <error>` on registration failure. Contains live session/message IDs; treat as sensitive and delete after debugging. |
349
+ | `FIXATE_ON_STATE_ROOT` | Overrides the persisted state root directory when `stateRoot` is not set (see [Persistence and state root](#persistence-and-state-root)). |
350
+ | `FIXATE_ON_EVENT_LOG` | Optional OpenCode 2.x diagnostic log path (unset by default). When set to a writable file path, appends space-delimited event lines for 2.x adapter events and tool-registration failures. Contains live session and message IDs; treat as sensitive and delete after debugging. |
387
351
 
388
- ---
352
+ ## Compatibility
389
353
 
390
- ## Compatibility & Known Limits
391
-
392
- | Area | Status |
354
+ | Area | Details |
393
355
  |:---|:---|
394
- | Runtime & OS | Declared support in `package.json` `engines`: Bun `>=1.0.0`, OpenCode `>=1.17.18`. Tested across Linux, macOS, and Windows. |
395
- | Package subpaths | `.`, `./server`, and `./tui` load standalone; `./tui-v2` depends on host-supplied modules. TypeScript declarations support `NodeNext` and `Bundler`. |
396
- | Provider templates | Strict-template backends require the goal block to merge into the primary `system` message (covered by regression tests). |
397
- | Static built-in verifier | The built-in `goal-verify` subagent is read-only (`read`, `glob`, `grep`); it cannot run shell commands itself and relies on workspace inspection plus evidence cited by the primary agent. |
398
- | OpenCode v2 TUI plugins | Stock released v2 binaries do not load external TUI plugins; v2 TUI e2e campaigns under `hack/e2e-harness/` run against a from-source host. |
356
+ | Runtime and OS | Bun `>=1.0.0`, OpenCode 1.x (`>=1.17.18`), and OpenCode 2.x. Tested on Linux, macOS, and Windows. The npm install of 0.2.0 was exercised on OpenCode 1.19.6 and 2.4.5; earlier versions in range were compared with host source only (plugin loaders and OpenTUI imports). |
357
+ | Package exports | `.` and `./server` load the server plugin and `./tui` loads the companion, each on both 1.x and 2.x. |
358
+ | Experimental hooks | Relies on `experimental.chat.system.transform` and related lifecycle hooks. Re-test against your exact OpenCode build and provider stack before unattended runs. |
359
+ | Read-only built-in judge | The built-in `goal-verify` subagent only uses `read`, `glob`, and `grep`. It cannot run shell commands and relies on workspace inspection plus evidence cited by the working agent. |
399
360
 
400
- ---
361
+ For TUI host API requirements, see [`docs/tui-integration.md#host-api-requirements`](docs/tui-integration.md#host-api-requirements).
401
362
 
402
363
  ## Troubleshooting
403
364
 
404
- Start with `/goal status --verbose` and `/goal history --verbose` to inspect the active state, stop reason, brake usage, and recent lifecycle trail.
405
-
406
- If a goal does not continue:
365
+ Start by inspecting the current state, stop reason, brake usage, recorded claims, and lifecycle trail:
407
366
 
408
- 1. **Distinguish self-resolving pauses from stops that wait on you:** Goals paused for `user intervention`, `recovery`, or `queued` sequence ordering resume automatically (unless a `user intervention` yield exceeds 15 minutes without settling, at which point `/goal status` flags that it did not re-arm and offers `/goal resume`). Deliberate pauses (`explicit pause`), hard brakes, no-progress/no-tool-call pauses, prompt failures, and `recovery exhausted` require human action.
409
- 2. **Resume after resolving the cause:** Run `/goal resume` to start a fresh local budget window and reset the turn count without losing the objective or history.
410
- 3. **Check structured logs and paths:** Inspect OpenCode's structured logs for persistence, `sdkShape`, prompt dispatch, or verifier faults, and verify that the working directory and `stateRoot` / `FIXATE_ON_STATE_ROOT` match between server and TUI entries.
367
+ ```sh
368
+ /goal status --full
369
+ /goal list all
370
+ /goal history --verbose
371
+ ```
411
372
 
412
- **Privacy note:** Do not paste raw `state.json` files, `.ledger.jsonl` transcripts, or `FIXATE_ON_EVENT_LOG` output into public issues without redacting them first — they contain goal text, progress notes, local paths, and session identifiers.
373
+ ### Install and host issues
413
374
 
414
- ---
375
+ | Symptom | Cause | Fix |
376
+ |:---|:---|:---|
377
+ | `configured plugin path must be a directory` | OpenCode 2.x was given a plugin file path | Point `plugins[].package` at the repository directory (see [Local source](#local-source)). |
378
+ | OpenCode 1.x loads no plugins (no error) | `plugins` (plural) was used in a config read by 1.x | Use `plugin` (singular); OpenCode 2.x accepts it too. |
379
+ | OpenCode 1.x ignores permissions | `permissions` (plural) was used in a shared config | Use `permission` (singular); OpenCode 2.x accepts it too. |
380
+ | OpenCode 2.x sends `/goal ...` as plain chat | Host does not expose `command.transform` and no `command.goal` bridge is configured | Add the `command.goal` template from [`/goal` on OpenCode 2.x](#goal-on-opencode-2x). |
381
+ | OpenCode 2.x reports `Invalid V2 TUI plugin module: fixate-on` | `fixate-on` 0.1.0 is installed; its `./tui` was 1.x only | Run `opencode2 plugin update` to move to 0.2.0 or later. |
382
+ | `NpmInstallFailedError`, or an SSH passphrase prompt, at startup | A subpath such as `fixate-on/tui` was configured | Use the bare name `fixate-on` (see [TUI companion](#tui-companion)). |
383
+ | OpenCode 2.x has no `Fixate:` palette entries when connected to a remote server | The TUI's own package cache does not hold the plugin | Add `fixate-on` to `cli.json` on the TUI's machine (see [TUI companion](#tui-companion)). |
384
+ | OpenCode 1.x TUI companion does not appear | `fixate-on` is in `opencode.json` only | Add it to `tui.json` as well (see [TUI companion](#tui-companion)). |
385
+ | Dashboard state differs from `/goal status` | Server plugin and TUI companion resolved different state directories | On 1.x, set the same `stateRoot` on both entries or set `FIXATE_ON_STATE_ROOT`. On 2.x, remove any `stateRoot` from the `cli.json` entry so the companion follows the server (see [Persistence and state root](#persistence-and-state-root)). |
386
+
387
+ ### When a goal does not continue
388
+
389
+ 1. Check whether the pause is self-resolving. Goals paused for `recovery` or `queued` sequence ordering resume automatically. Goals stopped by `explicit pause`, brakes, no-progress or no-tool-call limits, prompt failures, `recovery exhausted`, or a legacy `user intervention` pause from an older version wait for user action.
390
+ 2. Run `/goal resume` after addressing the cause. This resets the turn count and starts a fresh window for configured per-run limits while keeping the objective and history.
391
+ 3. Inspect OpenCode's structured logs for persistence, prompt dispatch, or verifier faults, and verify that the working directory and state root match across server and TUI entries.
392
+
393
+ **Privacy note:** Redact `state.json`, `.ledger.jsonl`, and `FIXATE_ON_EVENT_LOG` files before attaching them to public issues. They contain goal text, progress notes, local paths, and session identifiers.
415
394
 
416
395
  ## License
417
396