opencode-dev-framework 0.4.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,18 +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 — and on builds with the V2 `experimental.stopping` hook the failure continues
31
- the turn with steer text instead; `/df-status` shows which mode is active
32
- (idle-fallback → legacy probe → new hook).
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.
33
35
  - **Pre-flight gate (optional).** When a `preflight:` task list is configured, edit
34
36
  tools are **denied** (standard/strict) until the agent writes its pre-flight findings
35
37
  to `.opencode/opencode-dev-framework/preflight.md`. Use it for work that requires
@@ -60,14 +62,15 @@ reimplemented as an OpenCode-native plugin.
60
62
 
61
63
  ## Enforcement layers
62
64
 
63
- 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)):
64
67
 
65
68
  | Mechanism | Primary layer | Backstop / fallback | Strength |
66
69
  | --------- | ------------- | ------------------- | -------- |
67
70
  | Pre-flight gate | `tool.execute.before` deny | — | **Hard block** on every build: the edit never lands. |
68
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). |
69
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. |
70
- | Completion gate | `session.idle` re-prompt via `session.prompt` | `session.stopping` hard-stop veto / `experimental.stopping` turn-continuation, if the core dispatches either | **Async, bounded** by `gate.max_blocks` (re-prompt, not a veto); hard stop / continuation 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. |
71
74
 
72
75
  ## Install
73
76
 
@@ -106,27 +109,19 @@ profile from the shell; `df version` prints the plugin version.
106
109
  ## Local development and testing
107
110
 
108
111
  To test the plugin from source without publishing to npm, point OpenCode at the
109
- local repository path in your project's `opencode.jsonc` **and** in a `tui.json`.
110
- The TUI module (`/df-status`, `/df-help` modals) is **not** auto-discovered for
111
- local filesystem paths — it only loads when the package is listed in the TUI
112
- config. OpenCode reads `tui.json` from the global config dir
113
- (`~/.config/opencode/tui.json`) and the project dir (`.opencode/tui.json`).
114
-
115
- `opencode.jsonc`:
112
+ local repository **root** in your project's `opencode.jsonc`:
116
113
 
117
114
  ```json
118
115
  {
119
- "plugins": [{ "package": "/home/jerome/opencode-dev-framework/dist" }]
116
+ "plugins": [{ "package": "/home/jerome/opencode-dev-framework" }]
120
117
  }
121
118
  ```
122
119
 
123
- The path must be the package's **`dist/` directory**, not the repository
124
- root. Verified on OpenCode `v2.0.26`: for local directory entries the server
125
- resolves the entrypoint as `<dir>/index.js` and ignores `package.json`
126
- `main`, so a repo-root path fails silently with `Plugin entrypoint not
127
- found` (visible only via `/plugins` or server logs) and no hook runs at
128
- all. Rebuild after every source change (`npm run build`) since OpenCode
129
- 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:
130
125
 
131
126
  ```bash
132
127
  npm run build
@@ -134,10 +129,22 @@ npm run build
134
129
 
135
130
  ### Important caveats
136
131
 
137
- - Plugin arrays **merge** across config files (global `opencode.jsonc`,
138
- project `./opencode.jsonc`, `./.opencode/opencode.jsonc`), so a stale entry
139
- in another file adds to — never replaces — the registration above. If a
140
- session loads an unexpected plugin source, check all three locations.
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.)
141
148
  - OpenCode caches downloaded plugins in
142
149
  `~/.cache/opencode/packages/opencode-dev-framework*/`. If you previously
143
150
  loaded a published version and then switch to a local source, clear that
@@ -227,14 +234,16 @@ itself).
227
234
 
228
235
  ## Limitations
229
236
 
230
- - **Post-flight enforcement depends on core support.** OpenCode v2.0.12 has no
231
- `session.stopping` veto (PR #44712 is open; the earlier PR #41811 was never merged),
232
- so on failure inside `gate.max_blocks` the plugin re-prompts via
233
- `ctx.session.prompt()` from the `session.idle` event. The plugin still registers the
234
- `session.stopping` hook defensively — and the V2 `experimental.stopping` hook
235
- alongside it: on builds that dispatch either, the same verdict
236
- vetoes loop exit / continues the turn before the agent stops. `/df-status` shows which
237
- 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
238
247
  as the strongest available enforcement, not an unbreakable lock. The **pre-flight**
239
248
  gate, by contrast, is a genuine hard block on every build: it denies edit tools in
240
249
  `tool.execute.before`, before the edit lands.
@@ -9,27 +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 stop-level flag
13
- * (`"stopping"` for the legacy probe, `"experimental.stopping"` for the V2
14
- * hook; pre-Phase-27 `true` reads back as the legacy level).
15
- * 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.
16
14
  *
17
15
  * Key namespacing: counts are keyed `df:blocks:<sessionID>` (OpenCode
18
16
  * session IDs are globally unique, so this is safe even if storage is
19
- * 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.
20
22
  */
21
23
  import type { Context } from "@opencode/plugin/promise/plugin";
22
24
  /** Minimal storage surface we need (subset of `Context["storage"]`). */
23
25
  export type StorageLike = Pick<Context["storage"], "get" | "set" | "remove">;
24
26
  export declare const BLOCK_COUNT_KEY_PREFIX = "df:blocks:";
25
- export declare const STOP_SUPPORTED_KEY = "df:stopSupported";
26
- /**
27
- * Which pre-terminal hook fired. `stopping` is the legacy V1-shape probe
28
- * (PR #44712); `experimental.stopping` is the V2 contract (single mutable
29
- * event, `decision` grant). The new hook outranks the old: once it has
30
- * fired, the level never downgrades back to the legacy probe.
31
- */
32
- export type StopHookKind = "stopping" | "experimental.stopping";
33
27
  export interface BlockStore {
34
28
  get(sessionID: string): Promise<number>;
35
29
  /** Read, add one, persist, and return the new count. */
@@ -37,16 +31,6 @@ export interface BlockStore {
37
31
  clear(sessionID: string): Promise<void>;
38
32
  /** Live entries (mirrors the L1 map; used by tests). */
39
33
  readonly size: number;
40
- getStopSupported(): Promise<boolean>;
41
- /**
42
- * Record that a stopping hook fired. Defaults to the legacy `stopping`
43
- * probe (preserves pre-Phase-27 call sites); pass
44
- * `"experimental.stopping"` for the V2 hook. Monotonic: a stored new-hook
45
- * level is never downgraded by a later legacy-probe call.
46
- */
47
- setStopSupported(kind?: StopHookKind): Promise<void>;
48
- /** Which hook fired, or null when neither has (legacy `true` reads as the old probe). */
49
- getStopKind(): Promise<StopHookKind | null>;
50
34
  /** True once any storage call has failed (in-memory fallback in use). */
51
35
  isDegraded(): boolean;
52
36
  }
@@ -9,39 +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 stop-level flag
13
- * (`"stopping"` for the legacy probe, `"experimental.stopping"` for the V2
14
- * hook; pre-Phase-27 `true` reads back as the legacy level).
15
- * 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.
16
14
  *
17
15
  * Key namespacing: counts are keyed `df:blocks:<sessionID>` (OpenCode
18
16
  * session IDs are globally unique, so this is safe even if storage is
19
- * 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.
20
22
  */
21
23
  export const BLOCK_COUNT_KEY_PREFIX = "df:blocks:";
22
- export const STOP_SUPPORTED_KEY = "df:stopSupported";
23
24
  function blockKey(sessionID) {
24
25
  return `${BLOCK_COUNT_KEY_PREFIX}${sessionID}`;
25
26
  }
26
- function asStopKind(value) {
27
- if (value === "experimental.stopping")
28
- return "experimental.stopping";
29
- // Legacy boolean flag (pre-Phase-27) means the old probe fired.
30
- if (value === true || value === "stopping")
31
- return "stopping";
32
- return null;
33
- }
34
- function stopKindRank(kind) {
35
- return kind === "experimental.stopping" ? 1 : 0;
36
- }
37
- /** Monotonic max: a third hook level later only touches this function. */
38
- function maxStopKind(current, next) {
39
- if (current === null)
40
- return next;
41
- if (next === null)
42
- return current;
43
- return stopKindRank(next) > stopKindRank(current) ? next : current;
44
- }
45
27
  /** Accept only sane counts; anything else (foreign/corrupt value) is treated as missing. */
46
28
  function asCount(value) {
47
29
  if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
@@ -50,7 +32,6 @@ function asCount(value) {
50
32
  }
51
33
  export function createBlockStore(storage, memory) {
52
34
  const counts = memory ?? new Map();
53
- let stopMemory = null;
54
35
  let degraded = false;
55
36
  async function readCount(sessionID) {
56
37
  if (storage == null)
@@ -68,19 +49,6 @@ export function createBlockStore(storage, memory) {
68
49
  return counts.get(sessionID) ?? 0;
69
50
  }
70
51
  }
71
- async function readStopKind() {
72
- // Single read-through: memory holds a level, but storage may hold a
73
- // higher one written by a newer setup sharing the backend — take the max.
74
- if (storage != null) {
75
- try {
76
- stopMemory = maxStopKind(stopMemory, asStopKind(await storage.get(STOP_SUPPORTED_KEY)));
77
- }
78
- catch {
79
- degraded = true;
80
- }
81
- }
82
- return stopMemory;
83
- }
84
52
  async function writeCount(sessionID, count) {
85
53
  counts.set(sessionID, count);
86
54
  if (storage == null)
@@ -115,28 +83,6 @@ export function createBlockStore(storage, memory) {
115
83
  get size() {
116
84
  return counts.size;
117
85
  },
118
- async getStopSupported() {
119
- return (await readStopKind()) !== null;
120
- },
121
- getStopKind() {
122
- return readStopKind();
123
- },
124
- async setStopSupported(kind = "stopping") {
125
- // Monotonic: never downgrade a recorded new-hook level. The storage
126
- // read is required, not redundant — without it a fresh process would
127
- // blind-write its own (possibly lower) level over a stored higher one.
128
- stopMemory = maxStopKind(stopMemory, kind) ?? kind;
129
- if (storage == null)
130
- return;
131
- try {
132
- const next = maxStopKind(asStopKind(await storage.get(STOP_SUPPORTED_KEY)), stopMemory) ?? kind;
133
- stopMemory = next;
134
- await storage.set(STOP_SUPPORTED_KEY, next);
135
- }
136
- catch {
137
- degraded = true;
138
- }
139
- },
140
86
  isDegraded() {
141
87
  return degraded;
142
88
  },
@@ -122,19 +122,15 @@ export function renderHelp() {
122
122
  export function renderStatus(config, state) {
123
123
  const lines = [renderConfigStatus(config)];
124
124
  if (state) {
125
- // Enforcement level: none (no live state — config-only rendering) →
126
- // idle-fallback (no hook dispatched yet) → legacy `stopping` probe →
127
- // V2 `experimental.stopping` hook. The kind is monotonic: once the new
128
- // hook has fired, a late legacy dispatch never downgrades the level.
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.
129
128
  lines.push("");
130
- if (!state.stopHookSupported) {
131
- lines.push(`Hard stop (stopping / experimental.stopping): not dispatched by this OpenCode build — idle re-prompt fallback`);
132
- }
133
- else if (state.stopHookKind === "experimental.stopping") {
134
- lines.push(`Hard stop (experimental.stopping): active — gate failures continue the turn with steer text`);
129
+ if (state.continuationLevel === "idle") {
130
+ lines.push(`Continuation (idle): active — gate failures continue the same execution via synthetic`);
135
131
  }
136
132
  else {
137
- lines.push(`Hard stop (stopping): active — gate vetoes loop exit (legacy probe)`);
133
+ lines.push(`Continuation (idle): not dispatched — event-subscribe fallback`);
138
134
  }
139
135
  if (config.precommit === "auto") {
140
136
  lines.push(` pre-commit binary available: ${state.precommitAvailable === true ? "yes" : state.precommitAvailable === false ? "no" : "not checked yet"}`);
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,13 +11,15 @@
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
- import { type BlockStore, type StopHookKind } from "./block-store.js";
22
+ import { type BlockStore } from "./block-store.js";
21
23
  import { type ChangedFileTracker } from "./gate.js";
22
24
  import { type RunCommand } from "./host.js";
23
25
  import { type LogFn } from "./logger.js";
@@ -43,15 +45,22 @@ export interface HookState {
43
45
  precommitAvailable?: boolean;
44
46
  configMtime?: number;
45
47
  /**
46
- * Set once a stopping hook has actually been invoked by core — i.e. this
47
- * OpenCode build supports pre-break gate vetoes (hard stops). Until then
48
- * the idle re-prompt fallback is the only post-flight lever.
49
- * `stopHookKind` records WHICH hook fired (`stopping` legacy probe vs
50
- * `experimental.stopping` V2 contract); the new hook outranks the old and
51
- * the level never downgrades. `/df-status` renders the active level.
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.
52
54
  */
53
- stopHookSupported?: boolean;
54
- stopHookKind?: StopHookKind;
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>;
55
64
  }
56
65
  declare const plugin: Plugin.Plugin;
57
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,10 +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, the
75
- * `experimental.stopping` continuation vote, and the `session.idle`
76
- * re-prompt fallback so wording (and block counting) is identical on every
77
- * 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.
78
80
  */
79
81
  function continuationMessage(verdict) {
80
82
  const why = verdict.reason === "review"
@@ -148,17 +150,22 @@ function runCompletion(state, sessionID) {
148
150
  });
149
151
  }
150
152
  /**
151
- * Record that a stopping hook fired at `kind`. Monotonic: the V2
152
- * `experimental.stopping` level outranks the legacy `stopping` probe, so a
153
- * late legacy dispatch never downgrades an already-recorded new-hook level
154
- * (both the in-memory flag and the persisted store upgrade only).
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.
155
156
  */
156
- async function recordStopLevel(state, kind) {
157
- if (state.stopHookKind !== "experimental.stopping") {
158
- state.stopHookKind = kind;
159
- }
160
- state.stopHookSupported = true;
161
- await state.blocks.setStopSupported(kind);
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;
162
169
  }
163
170
  // Helpers to normalize V2 event shapes (data vs properties vs direct)
164
171
  function getEventSessionID(event) {
@@ -259,14 +266,13 @@ const plugin = Plugin.define({
259
266
  blockCounts,
260
267
  blocks,
261
268
  configMtime,
269
+ lastIdleHandled: new Map(),
262
270
  };
263
271
  activeState = state;
264
- // Hydrate the hard-stop probe level: a previous setup may have seen core
265
- // dispatch `stopping` or `experimental.stopping`. A storage failure
266
- // degrades to in-memory counts (pre-Phase-23 behavior) and is logged,
267
- // never thrown.
268
- state.stopHookKind = (await blocks.getStopKind()) ?? undefined;
269
- state.stopHookSupported = state.stopHookKind !== undefined;
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().
270
276
  if (blocks.isDegraded()) {
271
277
  await log("warn", "ctx.storage is unavailable; gate block counts are in-memory only and reset on reload", { directory });
272
278
  }
@@ -324,122 +330,100 @@ const plugin = Plugin.define({
324
330
  event.system.push({ type: "text", text: constitution });
325
331
  }));
326
332
  }
327
- // 1b) Hard-stop completion gate — `session.stopping` (OpenCode PR #44712).
328
- // Fires before the agent loop breaks on natural exit: a blocked verdict
329
- // sets stop=false + message and the loop re-enters, so gate failures
330
- // physically prevent completion. Registered defensively: on builds
331
- // without core support the hook is simply never dispatched, and the
332
- // session.idle fallback below provides re-prompt enforcement instead.
333
- // The first invocation flips `stopHookSupported` so /df-status can show
334
- // which enforcement level is active.
335
- // DEFENSIVE: "stopping" is not in SessionHooks as of 2.0.x; fires only
336
- // if a future core dispatches it (see PR #44712). One of two any-casts
337
- // in src/ (this probe + the `experimental.stopping` probe in §1c) —
338
- // all other hooks are fully typed so the compiler guards future SDK
339
- // upgrades.
340
- try {
341
- trackRegistration(
342
- // biome-ignore lint/suspicious/noExplicitAny: defensive stopping probe, not in SessionHooks (PR #44712)
343
- await ctx.session.hook("stopping",
344
- // biome-ignore lint/suspicious/noExplicitAny: core may dispatch (input, output) or a single mutable event
345
- async (input, output) => {
346
- 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)
347
364
  return;
348
- const out = output ?? input ?? {};
349
- const sessionID = input?.sessionID ??
350
- out.sessionID ??
351
- getEventSessionID(input) ??
352
- "unknown";
353
- await recordStopLevel(state, "stopping");
354
365
  await reloadConfigIfChanged(state);
355
366
  if (state.config.profile === "off")
356
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;
357
378
  const verdict = await runCompletion(state, sessionID);
358
379
  const message = await actOnVerdict(state, verdict);
359
- if (message !== null) {
360
- out.stop = false;
361
- out.message = message;
362
- }
363
- }));
364
- await safeLog(state, "info", "registered session.stopping hook; if this OpenCode build dispatches it, gate failures become hard stops before loop exit");
365
- }
366
- catch {
367
- await safeLog(state, "warn", "could not register session.stopping hook; using session.idle re-prompt fallback only");
368
- }
369
- // 1c) V2 pre-terminal continuation vote — `experimental.stopping`.
370
- // Same verdict mapping as §1b, in the new contract shape: gate fail →
371
- // `decision = { shouldContinue: true, text: message }` (core admits it
372
- // as a synthetic steer and continues the turn); gate pass/stand-down →
373
- // leave the fail-closed default (abstain). Registered ALONGSIDE the
374
- // legacy probe, not replacing it — the same dist keeps working on
375
- // mainline builds that lack the new core. No provider scoping: the
376
- // event carries no model, so a providerID option would never fire.
377
- // `event.continuations` is the pre-increment grant count (core caps at
378
- // 2 and goes silent past it without calling voters); local policy stays
379
- // tighter-or-equal via the verdict runner's own max_blocks/stand-down,
380
- // never fighting the core cap — expect silence after 2 grants.
381
- // DEFENSIVE: "experimental.stopping" is not in SessionHooks on released
382
- // cores; fires only on builds dispatching it. Same any-cast pattern as
383
- // §1b (the only two in src/).
384
- try {
385
- trackRegistration(
386
- // biome-ignore lint/suspicious/noExplicitAny: defensive stopping probe, not in SessionHooks on released cores
387
- await ctx.session.hook("experimental.stopping",
388
- // biome-ignore lint/suspicious/noExplicitAny: core dispatches a single mutable event
389
- async (event) => {
390
- if (activeState !== state)
380
+ if (message === null || verdict.decision !== "blocked") {
381
+ // Pass/stand-down: completed evaluation, nothing to admit.
382
+ stampIdleHandled(state, sessionID);
383
+ state.continuationLevel = "idle";
391
384
  return;
392
- // Core always dispatches a single mutable event object; a
393
- // non-object would leave the grant with nowhere to land, so bail
394
- // (fail-closed is the core's job on malformed dispatch).
395
- if (event === null || typeof event !== "object")
385
+ }
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
+ });
396
393
  return;
397
- const vote = event;
398
- const sessionID = (typeof vote.sessionID === "string" && vote.sessionID) ||
399
- getEventSessionID(event) ||
400
- "unknown";
401
- // Never let a voter failure escape into core: on any error
402
- // abstain (leave the fail-closed default) instead of losing the
403
- // turn to an undefined core reaction. A throwing voter stops the
404
- // turn per the contract — that decision belongs to core, not to
405
- // a logging or gate-backend failure inside this probe.
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) {
406
405
  try {
407
- await recordStopLevel(state, "experimental.stopping");
408
- await reloadConfigIfChanged(state);
409
- if (state.config.profile === "off")
410
- return;
411
- const verdict = await runCompletion(state, sessionID);
412
- const message = await actOnVerdict(state, verdict);
413
- await safeLog(state, "info", "experimental.stopping vote", {
406
+ await safeLog(state, "warn", "idle continuation failed; abstaining (subscriber net retries)", {
414
407
  sessionID,
415
- step: vote.step,
416
- continuations: vote.continuations,
417
- decision: verdict.decision,
408
+ error: error instanceof Error ? error.message : String(error),
418
409
  });
419
- if (message !== null) {
420
- event.decision = {
421
- shouldContinue: true,
422
- text: message,
423
- };
424
- }
425
410
  }
426
- catch (error) {
427
- try {
428
- await safeLog(state, "warn", "experimental.stopping vote failed; abstaining", {
429
- sessionID,
430
- error: error instanceof Error ? error.message : String(error),
431
- });
432
- }
433
- catch {
434
- // best-effort only — the abstain itself must not throw
435
- }
411
+ catch {
412
+ // best-effort only — the abstain itself must not throw
436
413
  }
437
- }));
438
- await safeLog(state, "info", "registered experimental.stopping hook; if this OpenCode build dispatches it, gate failures continue the turn with steer text");
439
- }
440
- catch {
441
- await safeLog(state, "warn", "could not register experimental.stopping hook; legacy stopping probe and session.idle re-prompt remain");
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
+ }
442
425
  }
426
+ await safeLog(state, "info", "registered experimental.idle hook (+ idle alias); gate failures continue the same execution via synthetic");
443
427
  // 2a) Native permission layer (Phase 25): `permission.evaluate` fires
444
428
  // with `{action, resources, effect}` (shapes recorded in the 25.1 spike,
445
429
  // docs/plans/08-notes.md — never guessed: action "edit" covers
@@ -743,9 +727,12 @@ const plugin = Plugin.define({
743
727
  },
744
728
  });
745
729
  }));
746
- // 4) Event subscription — file tracking + gate enforcement (V1: event hook)
747
- // Keeps the completion gate intent without session.stopping: on idle, run gate;
748
- // 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.
749
736
  const controller = new AbortController();
750
737
  const eventLoop = (async () => {
751
738
  try {
@@ -758,10 +745,12 @@ const plugin = Plugin.define({
758
745
  const type = event.type;
759
746
  if (isSessionDeletedEvent(type)) {
760
747
  // session.deleted: cleanup block counts (memory + storage) and
761
- // forget the session's directory mapping if present.
748
+ // the idle dedup stamp for the session.
762
749
  const sid = getEventSessionID(event);
763
- if (sid)
750
+ if (sid) {
764
751
  await state.blocks.clear(sid);
752
+ state.lastIdleHandled.delete(sid);
753
+ }
765
754
  continue;
766
755
  }
767
756
  if (isFilesystemChangedEvent(type)) {
@@ -799,23 +788,31 @@ const plugin = Plugin.define({
799
788
  const sessionID = getEventSessionID(event);
800
789
  if (!sessionID)
801
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;
802
797
  const verdict = await runCompletion(state, sessionID);
798
+ if (state.continuationLevel === undefined)
799
+ state.continuationLevel = "fallback";
803
800
  const message = await actOnVerdict(state, verdict);
804
801
  if (message === null)
805
802
  continue;
806
803
  const blockInfo = verdict.decision === "blocked"
807
804
  ? ` (block ${verdict.blockCount}/${verdict.maxBlocks})`
808
805
  : "";
809
- // blocked -> re-prompt the session (fallback when session.stopping
810
- // 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).
811
808
  try {
812
- // Prefer prompt (creates a user turn and wakes the agent); fallback to synthetic if prompt not available
813
- if (typeof ctx.session.prompt === "function") {
814
- await ctx.session.prompt({ sessionID, text: message });
815
- }
816
- 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") {
817
811
  await ctx.session.synthetic({ sessionID, text: message });
818
812
  }
813
+ else if (typeof ctx.session.prompt === "function") {
814
+ await ctx.session.prompt({ sessionID, text: message });
815
+ }
819
816
  else {
820
817
  await safeLog(state, "error", `gate blocked but no session prompt API available: ${message}`);
821
818
  }
@@ -1,4 +1,3 @@
1
- import type { StopHookKind } from "./block-store.js";
2
1
  import type { ChangedFileTracker } from "./gate.js";
3
2
  import type { RunCommand } from "./host.js";
4
3
  import type { LogFn } from "./logger.js";
@@ -33,14 +32,12 @@ export interface HookState {
33
32
  /** mtime (ms) of the config file at last load; used to detect out-of-process
34
33
  * edits (e.g. a `/df-profile` change made from the TUI module). */
35
34
  configMtime?: number;
36
- /** True once core has actually dispatched a stopping hook (hard stops active). */
37
- stopHookSupported?: boolean;
38
- /**
39
- * Which hook fired: the legacy `stopping` probe or the V2
40
- * `experimental.stopping` contract. The new hook outranks the old; absent
41
- * until either fires (idle re-prompt fallback is the active level).
42
- */
43
- stopHookKind?: StopHookKind;
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";
44
41
  }
45
42
  export declare function setBaseDirectory(directory: string): void;
46
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.4.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",