opencode-dev-framework 0.3.0 → 0.5.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
@@ -18,16 +18,20 @@ reimplemented as an OpenCode-native plugin.
18
18
  - **Per-edit lint.** Runs your configured linter on each file the agent edits
19
19
  and reports failures loudly. Optionally delegates per-file linting to
20
20
  `pre-commit run --files` when `precommit: auto` is set.
21
- - **Completion gate.** When the session goes idle (`session.idle`/`session.status:idle`),
22
- runs typecheck, tests, and (optionally) lint on changed files — changed files are
21
+ - **Completion gate.** At the would-go-idle boundary (`session.hook("experimental.idle")`,
22
+ with an `idle` alias registered for a future rename), runs typecheck, tests,
23
+ and (optionally) lint on changed files — changed files are
23
24
  tracked from edit events and cross-checked against `git status`, so the gate cannot
24
25
  silently skip due to an event-shape mismatch. In `standard`/`strict`, sessions that
25
26
  changed files must also produce a **peer-review artifact**
26
27
  (`.opencode/opencode-dev-framework/review.md`) covering the delegation rule's review
27
- cadence. On failure inside `gate.max_blocks` the plugin re-prompts the session with
28
- the failure summary. On OpenCode builds that dispatch the `session.stopping` hook
29
- (PR #44712) the same verdict vetoes loop exit *before* the agent stops — a true hard
30
- stop; `/df-status` shows which mode is active.
28
+ cadence. On failure inside `gate.max_blocks` the plugin admits a synthetic
29
+ continuation in the same execution with the failure summary. The
30
+ `event.subscribe` idle net catches the boundaries the hook skips
31
+ (interruption, failure, steer-parked drains) — deduped so one boundary never
32
+ runs the gate twice, synthetic-first with `prompt` only as fallback.
33
+ `/df-status` shows `Continuation (idle): active` once the hook has completed
34
+ an evaluation, else the event-subscribe fallback.
31
35
  - **Pre-flight gate (optional).** When a `preflight:` task list is configured, edit
32
36
  tools are **denied** (standard/strict) until the agent writes its pre-flight findings
33
37
  to `.opencode/opencode-dev-framework/preflight.md`. Use it for work that requires
@@ -58,14 +62,15 @@ reimplemented as an OpenCode-native plugin.
58
62
 
59
63
  ## Enforcement layers
60
64
 
61
- How each mechanism is enforced on OpenCode `v2` (verified on `v2.0.26`):
65
+ How each mechanism is enforced on OpenCode `v2` (idle hook landed via
66
+ [`anomalyco/opencode#59437`](https://github.com/anomalyco/opencode/pull/59437)):
62
67
 
63
68
  | Mechanism | Primary layer | Backstop / fallback | Strength |
64
69
  | --------- | ------------- | ------------------- | -------- |
65
70
  | Pre-flight gate | `tool.execute.before` deny | — | **Hard block** on every build: the edit never lands. |
66
71
  | Protected paths + dangerous commands | `tool.execute.before` deny/throw | `permission.evaluate` native layer (deny) | **Hard block** via the backstop; the native layer is defense-in-depth (the pipeline runs before-hooks first, so it only sees calls the backstop passed). |
67
72
  | Per-edit lint | `tool.execute.after` track + lint | `filesystem.changed` event (this release) | Report-only: the edit already landed, so failures log loudly but never throw. |
68
- | Completion gate | `session.idle` re-prompt via `session.prompt` | `session.stopping` hard-stop veto, if the core dispatches it | **Async, bounded** by `gate.max_blocks` (re-prompt, not a veto); hard stop only on builds with core support. `/df-status` shows which mode is active. |
73
+ | Completion gate | `session.hook("experimental.idle")` (+ `idle` alias) → `session.synthetic` (same execution) | `event.subscribe` idle net for the boundaries the hook skips (deduped; synthetic-first, `prompt` fallback) | **Async, bounded** by `gate.max_blocks`. `/df-status` shows `Continuation (idle): active` vs the event-subscribe fallback. `execute.before` stays the only true hard wall. |
69
74
 
70
75
  ## Install
71
76
 
@@ -73,7 +78,7 @@ How each mechanism is enforced on OpenCode `v2` (verified on `v2.0.26`):
73
78
  npm install opencode-dev-framework
74
79
  ```
75
80
 
76
- Then add the plugin to your project's `opencode.json`:
81
+ Then add the plugin to your project's `opencode.jsonc`:
77
82
 
78
83
  ```json
79
84
  {
@@ -104,27 +109,19 @@ profile from the shell; `df version` prints the plugin version.
104
109
  ## Local development and testing
105
110
 
106
111
  To test the plugin from source without publishing to npm, point OpenCode at the
107
- local repository path in your project's `opencode.json` **and** in a `tui.json`.
108
- The TUI module (`/df-status`, `/df-help` modals) is **not** auto-discovered for
109
- local filesystem paths — it only loads when the package is listed in the TUI
110
- config. OpenCode reads `tui.json` from the global config dir
111
- (`~/.config/opencode/tui.json`) and the project dir (`.opencode/tui.json`).
112
-
113
- `opencode.json` (V2):
112
+ local repository **root** in your project's `opencode.jsonc`:
114
113
 
115
114
  ```json
116
115
  {
117
- "plugins": [{ "package": "/home/jerome/opencode-dev-framework/dist" }]
116
+ "plugins": [{ "package": "/home/jerome/opencode-dev-framework" }]
118
117
  }
119
118
  ```
120
119
 
121
- The path must be the package's **`dist/` directory**, not the repository
122
- root. Verified on OpenCode `v2.0.26`: for local directory entries the server
123
- resolves the entrypoint as `<dir>/index.js` and ignores `package.json`
124
- `main`, so a repo-root path fails silently with `Plugin entrypoint not
125
- found` (visible only via `/plugins` or server logs) and no hook runs at
126
- all. Rebuild after every source change (`npm run build`) since OpenCode
127
- loads `dist/index.js` directly:
120
+ The root path resolves through the package's `exports` map, so one entry
121
+ loads **both** parts: the server (`dist/index.js` — hooks, guardrails, gate,
122
+ custom tools) and the TUI (`tui.tsx` — `/df-status`, `/df-help` modals).
123
+ Rebuild after every source change (`npm run build`) since OpenCode loads the
124
+ compiled `dist/` output:
128
125
 
129
126
  ```bash
130
127
  npm run build
@@ -132,10 +129,22 @@ npm run build
132
129
 
133
130
  ### Important caveats
134
131
 
135
- - The `opencode plugin <module>` command creates a `.opencode/opencode.json`
136
- file in the project directory that takes precedence over the project-level
137
- `opencode.json`. If you used that command while testing, either delete
138
- `.opencode/opencode.json` or make sure it also points to the local path.
132
+ - Register the plugin **exactly once** per project. Plugin arrays **merge**
133
+ across config files (global `opencode.jsonc`, project `./opencode.jsonc`,
134
+ `./.opencode/opencode.json[c]`), so a second entry in another file —
135
+ even one pointing at a different path of the same repo such as `dist/`
136
+ — loads the same plugin ID twice and the duplicate fails with
137
+ `Duplicate plugin ID: opencode-dev-framework` (check
138
+ `opencode api get "/api/plugin?location[directory]=/path/to/project"`).
139
+ If a session loads an unexpected plugin source, check all three locations.
140
+ - Do **not** point the entry at `dist/` directly: a bare directory without
141
+ `package.json`/`exports` resolves only the server part, so the TUI
142
+ commands (`/df-status`, `/df-help`) never load. (On OpenCode `v2.0.x` the
143
+ entrypoint resolved as `<dir>/index.js` and ignored `package.json`, which
144
+ is why older revisions of this section recommended `dist/` — verified on
145
+ `v2.2.0` that the root path resolves correctly through `exports`. The
146
+ `.opencode/tui.json` listing from that era is likewise no longer needed:
147
+ one `plugins` entry loads every part.)
139
148
  - OpenCode caches downloaded plugins in
140
149
  `~/.cache/opencode/packages/opencode-dev-framework*/`. If you previously
141
150
  loaded a published version and then switch to a local source, clear that
@@ -219,19 +228,22 @@ They open instantly and **never** feed text back to the LLM:
219
228
 
220
229
  You can still run `df init` to install the bundled agents, skills, and default
221
230
  config; the commands themselves are provided by the plugin. The
222
- `dev_framework_init` and `dev_framework_set_profile` custom *tools* remain
231
+ `dev_framework_*` custom *tools* remain
223
232
  available for in-agent use (e.g. when the model wants to change the profile
224
233
  itself).
225
234
 
226
235
  ## Limitations
227
236
 
228
- - **Post-flight enforcement depends on core support.** OpenCode v2.0.12 has no
229
- `session.stopping` veto (PR #44712 is open; the earlier PR #41811 was never merged),
230
- so on failure inside `gate.max_blocks` the plugin re-prompts via
231
- `ctx.session.prompt()` from the `session.idle` event. The plugin still registers the
232
- `session.stopping` hook defensively: on builds that dispatch it, the same verdict
233
- vetoes loop exit before the agent stops — a true hard stop. `/df-status` shows which
234
- mode is active. Until then, the user can always close the session, so treat the gate
237
+ - **Post-flight enforcement is a same-execution continuation, not a veto.**
238
+ At the would-go-idle boundary the `experimental.idle` hook (landed via
239
+ [`anomalyco/opencode#59437`](https://github.com/anomalyco/opencode/pull/59437))
240
+ runs the gate, and on failure inside `gate.max_blocks` admits a synthetic
241
+ continuation in the same execution. The `event.subscribe` idle net covers
242
+ the boundaries the hook skips (interruption, failure, steer-parked drains),
243
+ deduped so one boundary never runs the gate twice. On builds without the
244
+ hook only the net applies. `/df-status` shows which lever completed an
245
+ evaluation (`Continuation (idle): active` vs the event-subscribe fallback).
246
+ The user can always close the session, so treat the gate
235
247
  as the strongest available enforcement, not an unbreakable lock. The **pre-flight**
236
248
  gate, by contrast, is a genuine hard block on every build: it denies edit tools in
237
249
  `tool.execute.before`, before the edit lands.
@@ -9,18 +9,21 @@
9
9
  * a broken storage backend degrades to pre-Phase-23 behavior instead of
10
10
  * breaking the gate.
11
11
  *
12
- * Stored values are only block counts (`number`) and one `boolean` flag.
13
- * Never store secrets, prompts, or file contents here.
12
+ * Stored values are only block counts (`number`). Never store secrets,
13
+ * prompts, or file contents here.
14
14
  *
15
15
  * Key namespacing: counts are keyed `df:blocks:<sessionID>` (OpenCode
16
16
  * session IDs are globally unique, so this is safe even if storage is
17
- * shared across projects); the hard-stop probe flag is `df:stopSupported`.
17
+ * shared across projects).
18
+ *
19
+ * Historical note: pre-cutover builds persisted a `df:stopSupported` flag
20
+ * recording which stopping probe fired. The idle-first cutover removed
21
+ * that API; a stale key left by an older install is simply never read.
18
22
  */
19
23
  import type { Context } from "@opencode/plugin/promise/plugin";
20
24
  /** Minimal storage surface we need (subset of `Context["storage"]`). */
21
25
  export type StorageLike = Pick<Context["storage"], "get" | "set" | "remove">;
22
26
  export declare const BLOCK_COUNT_KEY_PREFIX = "df:blocks:";
23
- export declare const STOP_SUPPORTED_KEY = "df:stopSupported";
24
27
  export interface BlockStore {
25
28
  get(sessionID: string): Promise<number>;
26
29
  /** Read, add one, persist, and return the new count. */
@@ -28,8 +31,6 @@ export interface BlockStore {
28
31
  clear(sessionID: string): Promise<void>;
29
32
  /** Live entries (mirrors the L1 map; used by tests). */
30
33
  readonly size: number;
31
- getStopSupported(): Promise<boolean>;
32
- setStopSupported(): Promise<void>;
33
34
  /** True once any storage call has failed (in-memory fallback in use). */
34
35
  isDegraded(): boolean;
35
36
  }
@@ -9,15 +9,18 @@
9
9
  * a broken storage backend degrades to pre-Phase-23 behavior instead of
10
10
  * breaking the gate.
11
11
  *
12
- * Stored values are only block counts (`number`) and one `boolean` flag.
13
- * Never store secrets, prompts, or file contents here.
12
+ * Stored values are only block counts (`number`). Never store secrets,
13
+ * prompts, or file contents here.
14
14
  *
15
15
  * Key namespacing: counts are keyed `df:blocks:<sessionID>` (OpenCode
16
16
  * session IDs are globally unique, so this is safe even if storage is
17
- * shared across projects); the hard-stop probe flag is `df:stopSupported`.
17
+ * shared across projects).
18
+ *
19
+ * Historical note: pre-cutover builds persisted a `df:stopSupported` flag
20
+ * recording which stopping probe fired. The idle-first cutover removed
21
+ * that API; a stale key left by an older install is simply never read.
18
22
  */
19
23
  export const BLOCK_COUNT_KEY_PREFIX = "df:blocks:";
20
- export const STOP_SUPPORTED_KEY = "df:stopSupported";
21
24
  function blockKey(sessionID) {
22
25
  return `${BLOCK_COUNT_KEY_PREFIX}${sessionID}`;
23
26
  }
@@ -29,7 +32,6 @@ function asCount(value) {
29
32
  }
30
33
  export function createBlockStore(storage, memory) {
31
34
  const counts = memory ?? new Map();
32
- let stopMemory = false;
33
35
  let degraded = false;
34
36
  async function readCount(sessionID) {
35
37
  if (storage == null)
@@ -81,35 +83,6 @@ export function createBlockStore(storage, memory) {
81
83
  get size() {
82
84
  return counts.size;
83
85
  },
84
- async getStopSupported() {
85
- if (stopMemory)
86
- return true;
87
- if (storage == null)
88
- return false;
89
- try {
90
- const stored = await storage.get(STOP_SUPPORTED_KEY);
91
- if (stored === true) {
92
- stopMemory = true;
93
- return true;
94
- }
95
- return false;
96
- }
97
- catch {
98
- degraded = true;
99
- return false;
100
- }
101
- },
102
- async setStopSupported() {
103
- stopMemory = true;
104
- if (storage == null)
105
- return;
106
- try {
107
- await storage.set(STOP_SUPPORTED_KEY, true);
108
- }
109
- catch {
110
- degraded = true;
111
- }
112
- },
113
86
  isDegraded() {
114
87
  return degraded;
115
88
  },
@@ -122,8 +122,16 @@ export function renderHelp() {
122
122
  export function renderStatus(config, state) {
123
123
  const lines = [renderConfigStatus(config)];
124
124
  if (state) {
125
+ // Enforcement level: the `experimental.idle` hook (same-execution
126
+ // synthetic continuation) once it has completed an evaluation, else
127
+ // the `event.subscribe` idle re-prompt net.
125
128
  lines.push("");
126
- lines.push(`Hard stop (session.stopping): ${state.stopHookSupported ? "active — gate vetoes loop exit" : "not dispatched by this OpenCode build — idle re-prompt fallback"}`);
129
+ if (state.continuationLevel === "idle") {
130
+ lines.push(`Continuation (idle): active — gate failures continue the same execution via synthetic`);
131
+ }
132
+ else {
133
+ lines.push(`Continuation (idle): not dispatched — event-subscribe fallback`);
134
+ }
127
135
  if (config.precommit === "auto") {
128
136
  lines.push(` pre-commit binary available: ${state.precommitAvailable === true ? "yes" : state.precommitAvailable === false ? "no" : "not checked yet"}`);
129
137
  }
package/dist/gate.d.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  /**
2
2
  * Completion gate: run typecheck / test / lint-changed commands when the
3
- * session tries to stop, plus the changed-file tracking that feeds it.
3
+ * session goes idle, plus the changed-file tracking that feeds it.
4
4
  *
5
5
  * The gate runs from two call sites:
6
- * - `session.stopping` (OpenCode PR #44712): on failure, the adapter sets
7
- * `stop: false` with a continuation message, up to `gate.max_blocks`.
8
- * - `session.idle` (fallback on older OpenCode): advisory logging only — by
9
- * then the agent's turn has already finished, so failures cannot block.
6
+ * - `experimental.idle` hook: same-execution synthetic continuation on
7
+ * failure, up to `gate.max_blocks`.
8
+ * - `session.idle` event net: re-prompt fallback for the boundaries the
9
+ * hook skips.
10
10
  */
11
11
  import type { CommandResult, RunCommand } from "./host.js";
12
12
  import type { ResolvedConfig } from "./types.js";
package/dist/gate.js CHANGED
@@ -1,12 +1,12 @@
1
1
  /**
2
2
  * Completion gate: run typecheck / test / lint-changed commands when the
3
- * session tries to stop, plus the changed-file tracking that feeds it.
3
+ * session goes idle, plus the changed-file tracking that feeds it.
4
4
  *
5
5
  * The gate runs from two call sites:
6
- * - `session.stopping` (OpenCode PR #44712): on failure, the adapter sets
7
- * `stop: false` with a continuation message, up to `gate.max_blocks`.
8
- * - `session.idle` (fallback on older OpenCode): advisory logging only — by
9
- * then the agent's turn has already finished, so failures cannot block.
6
+ * - `experimental.idle` hook: same-execution synthetic continuation on
7
+ * failure, up to `gate.max_blocks`.
8
+ * - `session.idle` event net: re-prompt fallback for the boundaries the
9
+ * hook skips.
10
10
  */
11
11
  import { isAbsolute, relative } from "node:path";
12
12
  import { splitCommand } from "./command-utils.js";
package/dist/harness.d.ts CHANGED
@@ -8,15 +8,13 @@
8
8
  * configured, edit tools are denied (standard/strict) until the agent has
9
9
  * written the pre-flight artifact. This is a true hard gate: it runs in
10
10
  * `tool.execute.before`, before the edit lands. This is the only fully hard
11
- * enforcement available on OpenCode builds without a `session.stopping`
12
- * hook.
11
+ * enforcement — the idle continuation can only steer, never deny.
13
12
  * - **Post-flight**: the completion verdict runner. It unions event-tracked
14
13
  * changed files with `git status --porcelain` (robust against event-shape
15
14
  * mismatches), runs the command gate, and — when `gate.require_review` is
16
15
  * set — requires a peer-review artifact for sessions that changed files.
17
- * The verdict is consumed by both the `session.stopping` hook (hard stop,
18
- * when the OpenCode build supports it) and the `session.idle` fallback
19
- * (re-prompt).
16
+ * The verdict is consumed by the `experimental.idle` hook (same-execution
17
+ * synthetic continuation) and the `session.idle` event net (re-prompt).
20
18
  */
21
19
  import type { BlockStore } from "./block-store.js";
22
20
  import { type ChangedFileTracker } from "./gate.js";
@@ -84,8 +82,8 @@ export interface CompletionDeps {
84
82
  }
85
83
  /**
86
84
  * Evaluate the completion gate + review requirement and update block state.
87
- * Pure orchestration: both the `session.stopping` and `session.idle` call
88
- * sites feed their outcome from here so one session's block count applies to
89
- * either hook.
85
+ * Pure orchestration: both the `experimental.idle` hook and the
86
+ * `session.idle` event net feed their outcome from here so one session's
87
+ * block count applies to either lever.
90
88
  */
91
89
  export declare function evaluateCompletion(deps: CompletionDeps): Promise<CompletionVerdict>;
package/dist/harness.js CHANGED
@@ -8,15 +8,13 @@
8
8
  * configured, edit tools are denied (standard/strict) until the agent has
9
9
  * written the pre-flight artifact. This is a true hard gate: it runs in
10
10
  * `tool.execute.before`, before the edit lands. This is the only fully hard
11
- * enforcement available on OpenCode builds without a `session.stopping`
12
- * hook.
11
+ * enforcement — the idle continuation can only steer, never deny.
13
12
  * - **Post-flight**: the completion verdict runner. It unions event-tracked
14
13
  * changed files with `git status --porcelain` (robust against event-shape
15
14
  * mismatches), runs the command gate, and — when `gate.require_review` is
16
15
  * set — requires a peer-review artifact for sessions that changed files.
17
- * The verdict is consumed by both the `session.stopping` hook (hard stop,
18
- * when the OpenCode build supports it) and the `session.idle` fallback
19
- * (re-prompt).
16
+ * The verdict is consumed by the `experimental.idle` hook (same-execution
17
+ * synthetic continuation) and the `session.idle` event net (re-prompt).
20
18
  */
21
19
  import { readFile } from "node:fs/promises";
22
20
  import { join } from "node:path";
@@ -126,9 +124,9 @@ function reviewMissingMessage(changedFiles) {
126
124
  }
127
125
  /**
128
126
  * Evaluate the completion gate + review requirement and update block state.
129
- * Pure orchestration: both the `session.stopping` and `session.idle` call
130
- * sites feed their outcome from here so one session's block count applies to
131
- * either hook.
127
+ * Pure orchestration: both the `experimental.idle` hook and the
128
+ * `session.idle` event net feed their outcome from here so one session's
129
+ * block count applies to either lever.
132
130
  */
133
131
  export async function evaluateCompletion(deps) {
134
132
  const { run, config, directory, sessionID, tracker, blockCounts } = deps;
package/dist/index.d.ts CHANGED
@@ -11,10 +11,12 @@
11
11
  * - ctx.event.subscribe() -> file tracking + gate enforcement via re-prompt
12
12
  * - ctx.tool.transform(...) -> custom tools
13
13
  *
14
- * Gate enforcement: no synchronous `session.stopping`. On `session.idle`
15
- * / `session.status:idle` we run the gate and if it fails inside budget we
16
- * call `ctx.session.prompt({ sessionID, text: stoppingMessage })` to wake the
17
- * agent — async re-injection preserving the enforcement intent (see docs/plans/08-notes).
14
+ * Gate enforcement: no synchronous pre-stop veto. On `experimental.idle`
15
+ * (same execution) we run the gate and if it fails inside budget we admit
16
+ * `ctx.session.synthetic({ sessionID, text: stoppingMessage })` — the
17
+ * continuation runs before the session goes idle (see
18
+ * docs/plans/12-idle-hook-cutover.md). The `event.subscribe` idle net
19
+ * stays as a deduped fallback for the boundaries the hook skips.
18
20
  */
19
21
  import { Plugin } from "@opencode/plugin";
20
22
  import { type BlockStore } from "./block-store.js";
@@ -43,11 +45,22 @@ export interface HookState {
43
45
  precommitAvailable?: boolean;
44
46
  configMtime?: number;
45
47
  /**
46
- * Set once the `session.stopping` hook has actually been invoked by core —
47
- * i.e. this OpenCode build supports pre-break gate vetoes (hard stops).
48
- * Until then the idle re-prompt fallback is the only post-flight lever.
48
+ * Which lever completed a gate evaluation most recently in this process:
49
+ * `"idle"` once the `experimental.idle` hook has (same-execution
50
+ * continuation active), `"fallback"` when only the `event.subscribe`
51
+ * idle re-prompt net has. Absent until either fires. Memory-only: a
52
+ * reload re-derives it on the next idle boundary. `/df-status` renders
53
+ * the active level.
49
54
  */
50
- stopHookSupported?: boolean;
55
+ continuationLevel?: "idle" | "fallback";
56
+ /**
57
+ * Dedup map for the idle-first cutover: sessionID → `Date.now()` at the
58
+ * last COMPLETED hook evaluation (pass, blocked-admitted, and standdown
59
+ * all stamp; throw/early-return do not). The `event.subscribe` idle net
60
+ * skips when the stamp is fresh so one boundary never runs the gate
61
+ * twice. Memory-only; worst case on reload is one extra suite run.
62
+ */
63
+ lastIdleHandled: Map<string, number>;
51
64
  }
52
65
  declare const plugin: Plugin.Plugin;
53
66
  export default plugin;
package/dist/index.js CHANGED
@@ -11,10 +11,12 @@
11
11
  * - ctx.event.subscribe() -> file tracking + gate enforcement via re-prompt
12
12
  * - ctx.tool.transform(...) -> custom tools
13
13
  *
14
- * Gate enforcement: no synchronous `session.stopping`. On `session.idle`
15
- * / `session.status:idle` we run the gate and if it fails inside budget we
16
- * call `ctx.session.prompt({ sessionID, text: stoppingMessage })` to wake the
17
- * agent — async re-injection preserving the enforcement intent (see docs/plans/08-notes).
14
+ * Gate enforcement: no synchronous pre-stop veto. On `experimental.idle`
15
+ * (same execution) we run the gate and if it fails inside budget we admit
16
+ * `ctx.session.synthetic({ sessionID, text: stoppingMessage })` — the
17
+ * continuation runs before the session goes idle (see
18
+ * docs/plans/12-idle-hook-cutover.md). The `event.subscribe` idle net
19
+ * stays as a deduped fallback for the boundaries the hook skips.
18
20
  */
19
21
  import { Plugin } from "@opencode/plugin";
20
22
  import { stat } from "node:fs/promises";
@@ -71,9 +73,10 @@ async function reloadConfigIfChanged(state) {
71
73
  }
72
74
  /**
73
75
  * Turn a completion verdict into the continuation message fed back to the
74
- * agent when blocked. Shared by the `session.stopping` hard-stop path and
75
- * the `session.idle` re-prompt fallback so wording (and block counting) is
76
- * identical on either core support level.
76
+ * agent when blocked. Shared by the `experimental.idle` hook (same
77
+ * execution, via synthetic) and the `event.subscribe` idle re-prompt
78
+ * fallback so wording (and block counting) is identical on every
79
+ * enforcement level.
77
80
  */
78
81
  function continuationMessage(verdict) {
79
82
  const why = verdict.reason === "review"
@@ -146,6 +149,24 @@ function runCompletion(state, sessionID) {
146
149
  log: (level, message, extra) => safeLog(state, level, message, extra),
147
150
  });
148
151
  }
152
+ /**
153
+ * Record a completed idle-hook evaluation for the dedup map. Stamp ONLY on
154
+ * the completed-evaluation paths (pass, blocked-admitted, standdown);
155
+ * throw/early-return paths must not stamp so the subscriber net retries.
156
+ */
157
+ function stampIdleHandled(state, sessionID) {
158
+ state.lastIdleHandled.set(sessionID, Date.now());
159
+ }
160
+ /**
161
+ * True when the idle hook completed an evaluation for this session inside
162
+ * `windowMs`. The hook itself uses a short window (same-boundary
163
+ * double-fire guard for the dual key registration below); the subscriber
164
+ * net uses the full window (one boundary, one gate run).
165
+ */
166
+ function wasIdleHandledRecently(state, sessionID, windowMs = 5_000) {
167
+ const at = state.lastIdleHandled.get(sessionID);
168
+ return at !== undefined && Date.now() - at < windowMs;
169
+ }
149
170
  // Helpers to normalize V2 event shapes (data vs properties vs direct)
150
171
  function getEventSessionID(event) {
151
172
  const e = event;
@@ -245,12 +266,13 @@ const plugin = Plugin.define({
245
266
  blockCounts,
246
267
  blocks,
247
268
  configMtime,
269
+ lastIdleHandled: new Map(),
248
270
  };
249
271
  activeState = state;
250
- // Hydrate the hard-stop probe flag: a previous setup may have seen core
251
- // dispatch `session.stopping`. A storage failure degrades to in-memory
252
- // counts (pre-Phase-23 behavior) and is logged, never thrown.
253
- state.stopHookSupported = await blocks.getStopSupported();
272
+ // Surface a broken storage backend early (best-effort, never thrown).
273
+ // With the stop-level hydration gone there is no setup-time storage
274
+ // read left, so this rarely fires here — the store still degrades
275
+ // lazily on first use and reports via isDegraded().
254
276
  if (blocks.isDegraded()) {
255
277
  await log("warn", "ctx.storage is unavailable; gate block counts are in-memory only and reset on reload", { directory });
256
278
  }
@@ -308,48 +330,100 @@ const plugin = Plugin.define({
308
330
  event.system.push({ type: "text", text: constitution });
309
331
  }));
310
332
  }
311
- // 1b) Hard-stop completion gate — `session.stopping` (OpenCode PR #44712).
312
- // Fires before the agent loop breaks on natural exit: a blocked verdict
313
- // sets stop=false + message and the loop re-enters, so gate failures
314
- // physically prevent completion. Registered defensively: on builds
315
- // without core support the hook is simply never dispatched, and the
316
- // session.idle fallback below provides re-prompt enforcement instead.
317
- // The first invocation flips `stopHookSupported` so /df-status can show
318
- // which enforcement level is active.
319
- // DEFENSIVE: "stopping" is not in SessionHooks as of 2.0.x; fires only
320
- // if a future core dispatches it (see PR #44712). This is the ONLY
321
- // remaining any-cast in src/ — all other hooks are fully typed so the
322
- // compiler guards future SDK upgrades.
323
- try {
324
- trackRegistration(
325
- // biome-ignore lint/suspicious/noExplicitAny: defensive stopping probe, not in SessionHooks (PR #44712)
326
- await ctx.session.hook("stopping",
327
- // biome-ignore lint/suspicious/noExplicitAny: core may dispatch (input, output) or a single mutable event
328
- async (input, output) => {
329
- if (activeState !== state)
333
+ // 1b) Idle-first completion gate — `experimental.idle` (landed upstream
334
+ // via anomalyco/opencode#59437; see docs/plans/12-idle-hook-cutover.md).
335
+ // Fires where a session would otherwise go idle, inside the same
336
+ // execution: a blocked verdict admits a synthetic continuation and the
337
+ // runner re-checks the inbox instead of idling. Pass/stand-down admit
338
+ // nothing. Registered defensively: on builds without core support the
339
+ // hook is simply never dispatched, and the session.idle event net below
340
+ // provides re-prompt enforcement instead (deduped via lastIdleHandled).
341
+ // Both the current `experimental.idle` key and the unprefixed `idle`
342
+ // alias are registered so a future stabilization rename is a non-event;
343
+ // the same-boundary double-fire guard below makes that safe. Never
344
+ // `prompt` here — only `synthetic` keeps the same execution.
345
+ // DEFENSIVE: any-cast because the installed @opencode/plugin may predate
346
+ // the hook; fires only on builds dispatching it.
347
+ const handleIdleContinuation = async (event) => {
348
+ if (activeState !== state)
349
+ return;
350
+ if (event === null || typeof event !== "object")
351
+ return;
352
+ // Never let a gate failure escape into core: an uncaught throw fails
353
+ // the drain (Failed terminal), it does NOT fail open to idle. So on
354
+ // any error — including a hostile event shape blowing up sessionID
355
+ // resolution — abstain (admit nothing) and leave unstamped; the
356
+ // subscriber net retries at the next idle.
357
+ let sessionID;
358
+ try {
359
+ sessionID =
360
+ (typeof event.sessionID === "string" &&
361
+ event.sessionID) ||
362
+ getEventSessionID(event);
363
+ if (!sessionID)
330
364
  return;
331
- const out = output ?? input ?? {};
332
- const sessionID = input?.sessionID ??
333
- out.sessionID ??
334
- getEventSessionID(input) ??
335
- "unknown";
336
- state.stopHookSupported = true;
337
- await state.blocks.setStopSupported();
338
365
  await reloadConfigIfChanged(state);
339
366
  if (state.config.profile === "off")
340
367
  return;
368
+ if (!state.config.gate) {
369
+ await safeLog(state, "warn", "plugin config is incomplete (missing gate section), skipping completion gate", { directory: state.directory });
370
+ return;
371
+ }
372
+ // Same-boundary double-fire guard for the dual key registration
373
+ // above (a future core dispatching both names for one boundary).
374
+ // Short window on purpose: any legitimate re-fire needs a full
375
+ // model round-trip first, which never lands inside a second.
376
+ if (wasIdleHandledRecently(state, sessionID, 1_000))
377
+ return;
341
378
  const verdict = await runCompletion(state, sessionID);
342
379
  const message = await actOnVerdict(state, verdict);
343
- if (message !== null) {
344
- out.stop = false;
345
- out.message = message;
380
+ if (message === null || verdict.decision !== "blocked") {
381
+ // Pass/stand-down: completed evaluation, nothing to admit.
382
+ stampIdleHandled(state, sessionID);
383
+ state.continuationLevel = "idle";
384
+ return;
346
385
  }
347
- }));
348
- await safeLog(state, "info", "registered session.stopping hook; if this OpenCode build dispatches it, gate failures become hard stops before loop exit");
349
- }
350
- catch {
351
- await safeLog(state, "warn", "could not register session.stopping hook; using session.idle re-prompt fallback only");
386
+ // Blocked: admit a synthetic continuation (same execution).
387
+ // `background` is intentionally ignored — the gate evaluates the
388
+ // working tree, it never waits on running work.
389
+ if (typeof ctx.session.synthetic !== "function") {
390
+ await safeLog(state, "warn", "gate blocked but no session.synthetic API available", {
391
+ sessionID,
392
+ });
393
+ return;
394
+ }
395
+ await ctx.session.synthetic({ sessionID, text: message });
396
+ stampIdleHandled(state, sessionID);
397
+ state.continuationLevel = "idle";
398
+ await safeLog(state, "info", `completion gate continued session ${sessionID} via idle hook`, {
399
+ sessionID,
400
+ blockCount: verdict.blockCount,
401
+ maxBlocks: verdict.maxBlocks,
402
+ });
403
+ }
404
+ catch (error) {
405
+ try {
406
+ await safeLog(state, "warn", "idle continuation failed; abstaining (subscriber net retries)", {
407
+ sessionID,
408
+ error: error instanceof Error ? error.message : String(error),
409
+ });
410
+ }
411
+ catch {
412
+ // best-effort only — the abstain itself must not throw
413
+ }
414
+ }
415
+ };
416
+ for (const name of ["experimental.idle", "idle"]) {
417
+ try {
418
+ trackRegistration(
419
+ // biome-ignore lint/suspicious/noExplicitAny: defensive idle hook, absent from SessionHooks on older cores
420
+ await ctx.session.hook(name, handleIdleContinuation));
421
+ }
422
+ catch {
423
+ await safeLog(state, "warn", `could not register session hook ${name}`, { hook: name });
424
+ }
352
425
  }
426
+ await safeLog(state, "info", "registered experimental.idle hook (+ idle alias); gate failures continue the same execution via synthetic");
353
427
  // 2a) Native permission layer (Phase 25): `permission.evaluate` fires
354
428
  // with `{action, resources, effect}` (shapes recorded in the 25.1 spike,
355
429
  // docs/plans/08-notes.md — never guessed: action "edit" covers
@@ -653,9 +727,12 @@ const plugin = Plugin.define({
653
727
  },
654
728
  });
655
729
  }));
656
- // 4) Event subscription — file tracking + gate enforcement (V1: event hook)
657
- // Keeps the completion gate intent without session.stopping: on idle, run gate;
658
- // on failure inside budget, re-prompt the session (async block).
730
+ // 4) Event subscription — file tracking + gate enforcement net.
731
+ // Runs the gate on `session.idle` for the boundaries the §1b hook
732
+ // skipped (interruption, failure, steer-parked drains) or for builds
733
+ // without the hook. Skips when the hook just handled the same boundary
734
+ // (dedup map). Synthetic-first admit: after the execution ended, a
735
+ // synthetic message is the quietest wake; prompt is the fallback.
659
736
  const controller = new AbortController();
660
737
  const eventLoop = (async () => {
661
738
  try {
@@ -668,10 +745,12 @@ const plugin = Plugin.define({
668
745
  const type = event.type;
669
746
  if (isSessionDeletedEvent(type)) {
670
747
  // session.deleted: cleanup block counts (memory + storage) and
671
- // forget the session's directory mapping if present.
748
+ // the idle dedup stamp for the session.
672
749
  const sid = getEventSessionID(event);
673
- if (sid)
750
+ if (sid) {
674
751
  await state.blocks.clear(sid);
752
+ state.lastIdleHandled.delete(sid);
753
+ }
675
754
  continue;
676
755
  }
677
756
  if (isFilesystemChangedEvent(type)) {
@@ -709,23 +788,31 @@ const plugin = Plugin.define({
709
788
  const sessionID = getEventSessionID(event);
710
789
  if (!sessionID)
711
790
  continue;
791
+ // The §1b hook completed an evaluation for this boundary — one
792
+ // boundary, one gate run. (Deliberately not stamped here: only
793
+ // the hook stamps, so a hook that never fires can never be
794
+ // starved by the net.)
795
+ if (wasIdleHandledRecently(state, sessionID))
796
+ continue;
712
797
  const verdict = await runCompletion(state, sessionID);
798
+ if (state.continuationLevel === undefined)
799
+ state.continuationLevel = "fallback";
713
800
  const message = await actOnVerdict(state, verdict);
714
801
  if (message === null)
715
802
  continue;
716
803
  const blockInfo = verdict.decision === "blocked"
717
804
  ? ` (block ${verdict.blockCount}/${verdict.maxBlocks})`
718
805
  : "";
719
- // blocked -> re-prompt the session (fallback when session.stopping
720
- // is not dispatched by this OpenCode build)
806
+ // blocked -> admit a continuation (net for the boundaries the
807
+ // hook skipped: interruption, failure, steer-parked drains).
721
808
  try {
722
- // Prefer prompt (creates a user turn and wakes the agent); fallback to synthetic if prompt not available
723
- if (typeof ctx.session.prompt === "function") {
724
- await ctx.session.prompt({ sessionID, text: message });
725
- }
726
- else if (typeof ctx.session.synthetic === "function") {
809
+ // Prefer synthetic (quiet wake, no user turn); fallback to prompt if synthetic not available
810
+ if (typeof ctx.session.synthetic === "function") {
727
811
  await ctx.session.synthetic({ sessionID, text: message });
728
812
  }
813
+ else if (typeof ctx.session.prompt === "function") {
814
+ await ctx.session.prompt({ sessionID, text: message });
815
+ }
729
816
  else {
730
817
  await safeLog(state, "error", `gate blocked but no session prompt API available: ${message}`);
731
818
  }
@@ -32,8 +32,12 @@ export interface HookState {
32
32
  /** mtime (ms) of the config file at last load; used to detect out-of-process
33
33
  * edits (e.g. a `/df-profile` change made from the TUI module). */
34
34
  configMtime?: number;
35
- /** True once core has actually dispatched `session.stopping` (hard stops active). */
36
- stopHookSupported?: boolean;
35
+ /** Which lever completed a gate evaluation most recently in this process:
36
+ * `"idle"` once the `experimental.idle` hook has (same-execution
37
+ * continuation active), `"fallback"` when only the `event.subscribe`
38
+ * idle re-prompt net has. Absent until either fires. Memory-only: a
39
+ * reload re-derives it on the next idle boundary. */
40
+ continuationLevel?: "idle" | "fallback";
37
41
  }
38
42
  export declare function setBaseDirectory(directory: string): void;
39
43
  export declare function getBaseDirectory(): string | null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-dev-framework",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "OpenCode plugin that enforces project-specific quality gates during AI coding sessions",
5
5
  "license": "MIT",
6
6
  "type": "module",