opencode-dev-framework 0.2.4 → 0.3.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
@@ -36,20 +36,16 @@ reimplemented as an OpenCode-native plugin.
36
36
  - **Custom tools.** `dev_framework_init` scaffolds project-level agents,
37
37
  skills, local rules directory, and config; `dev_framework_set_profile` changes the profile
38
38
  in-session without restarting; `dev_framework_status` reports the current
39
- profile, guardrails, gate, and tracked changed files.
39
+ profile, guardrails, gate, and tracked changed files; `dev_framework_verify`
40
+ runs the completion gate on demand and returns the summary to the agent.
40
41
  - **CLI installer.** `df init` auto-detects your language and writes a config
41
42
  with sensible commands; `df profile <name>` changes the profile from the
42
43
  shell; `df status` / `df version` report template state and the version.
43
- - **Slash commands.** The plugin registers four commands. None of them feed
44
- anything to the LLM:
45
- - `/df-status` and `/df-help` are TUI commands (bundled `./tui` companion module)
46
- that open an instant modal dialog.
47
- - `/df-profile <profile>` and `/df-verify` are server-side commands. They are
48
- registered with an empty template so the argument (e.g. `standard`) is
49
- captured by the plugin and the model never sees it; the result is shown as a
50
- toast and the user turn is suppressed.
51
- - The `dev_framework_init` and `dev_framework_set_profile` custom *tools* remain
52
- available for in-agent use.
44
+ - **Slash commands.** The plugin registers four TUI commands that open instant
45
+ modal dialogs and never feed anything to the LLM: `/df-status`, `/df-help`,
46
+ `/df-profile` (bare for a picker, or with an argument), and `/df-verify`
47
+ (runs the gate manually). The `dev_framework_*` custom *tools* above remain
48
+ available for in-agent use.
53
49
 
54
50
  ## Profiles
55
51
 
@@ -58,7 +54,18 @@ reimplemented as an OpenCode-native plugin.
58
54
  | `off` | disabled | not reported | no | no | no | Plugin registers no hooks at all. |
59
55
  | `advisory` | warn | warn | yes | warn only | warned, not blocked | Nothing blocks; everything is logged. |
60
56
  | `standard` | deny | error | yes | deny edits | blocks completion | The default when a config file exists. |
61
- | `strict` | deny | error | yes | deny edits | blocks completion | Also lints changed files in the gate and throws on per-edit lint failures. |
57
+ | `strict` | deny | error | yes | deny edits | blocks completion | Also lints changed files in the gate; per-edit lint failures are reported loudly (error level — the edit already landed, so nothing throws there). |
58
+
59
+ ## Enforcement layers
60
+
61
+ How each mechanism is enforced on OpenCode `v2` (verified on `v2.0.26`):
62
+
63
+ | Mechanism | Primary layer | Backstop / fallback | Strength |
64
+ | --------- | ------------- | ------------------- | -------- |
65
+ | Pre-flight gate | `tool.execute.before` deny | — | **Hard block** on every build: the edit never lands. |
66
+ | 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
+ | 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. |
62
69
 
63
70
  ## Install
64
71
 
@@ -74,7 +81,7 @@ Then add the plugin to your project's `opencode.json`:
74
81
  }
75
82
  ```
76
83
 
77
- Requires OpenCode `v2.0.0+` (`@opencode/plugin` `^2`). On `v1.18.18–1.18.31` use the `v1` branch
84
+ Requires OpenCode `v2.x` (`@opencode/plugin` `^2`) — tested on `v2.0.26`. On `v1.18.18–1.18.31` use the `v1` branch
78
85
  of this plugin (`plugin` key). The `./tui` companion (`/df-status` and `/df-help`
79
86
  modals) is auto-discovered from the npm entry on `v2` — no separate `tui.json` needed.
80
87
 
@@ -107,12 +114,17 @@ config. OpenCode reads `tui.json` from the global config dir
107
114
 
108
115
  ```json
109
116
  {
110
- "plugins": ["/home/jerome/opencode-dev-framework"]
117
+ "plugins": [{ "package": "/home/jerome/opencode-dev-framework/dist" }]
111
118
  }
112
119
  ```
113
120
 
114
- The path must be the **repository root** (where `package.json` lives). OpenCode
115
- loads the plugin from `dist/index.js` (TUI from `tui.tsx`), so rebuild after every source change:
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:
116
128
 
117
129
  ```bash
118
130
  npm run build
@@ -200,8 +212,8 @@ They open instantly and **never** feed text back to the LLM:
200
212
  - `/df-help` — lists the available dev-framework commands in a modal dialog.
201
213
  - `/df-profile` — opens a profile picker (off / advisory / standard / strict) in
202
214
  a modal dialog; selecting one switches the active profile immediately (written
203
- to the config file). Run it **bare** — the argument form
204
- (`/df-profile standard`) is not wired up in this build.
215
+ to the config file). With an argument (`/df-profile standard`) it switches
216
+ directly with a toast instead of the picker.
205
217
  - `/df-verify` — runs the configured verification suite (the completion gate)
206
218
  manually and shows a pass/fail summary in a modal dialog.
207
219
 
@@ -250,6 +262,17 @@ For persistent debug traces, set `OPENCODE_DEV_FRAMEWORK_LOG_FILE`:
250
262
  OPENCODE_DEV_FRAMEWORK_LOG_FILE=/tmp/odf.log opencode run
251
263
  ```
252
264
 
265
+ Plugin code runs in the `opencode serve` backend, not in your terminal
266
+ process — a variable exported only in the TUI shell never reaches it. For
267
+ full server logs plus the plugin trace, run a private server:
268
+
269
+ ```bash
270
+ OPENCODE_DEV_FRAMEWORK_LOG_FILE=/tmp/odf.log opencode run --standalone --print-logs
271
+ ```
272
+
273
+ (There is no `cli.json` interaction: the plugin never reads or writes CLI
274
+ config; the flags above are stock OpenCode CLI options.)
275
+
253
276
  See `AGENTS.md` and `docs/plans/` for the architecture and implementation
254
277
  plan.
255
278
 
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Persistent per-session completion-gate block counts.
3
+ *
4
+ * Counts live in `ctx.storage` (survives plugin reload / `session_move` /
5
+ * server restart) with a caller-provided `Map` as the write-through L1
6
+ * cache (keeps `/df-status` rendering and the synchronous status paths
7
+ * working off live data). Every storage call is best-effort: on failure the
8
+ * store falls back to memory, records `isDegraded()`, and never throws — so
9
+ * a broken storage backend degrades to pre-Phase-23 behavior instead of
10
+ * breaking the gate.
11
+ *
12
+ * Stored values are only block counts (`number`) and one `boolean` flag.
13
+ * Never store secrets, prompts, or file contents here.
14
+ *
15
+ * Key namespacing: counts are keyed `df:blocks:<sessionID>` (OpenCode
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`.
18
+ */
19
+ import type { Context } from "@opencode/plugin/promise/plugin";
20
+ /** Minimal storage surface we need (subset of `Context["storage"]`). */
21
+ export type StorageLike = Pick<Context["storage"], "get" | "set" | "remove">;
22
+ export declare const BLOCK_COUNT_KEY_PREFIX = "df:blocks:";
23
+ export declare const STOP_SUPPORTED_KEY = "df:stopSupported";
24
+ export interface BlockStore {
25
+ get(sessionID: string): Promise<number>;
26
+ /** Read, add one, persist, and return the new count. */
27
+ increment(sessionID: string): Promise<number>;
28
+ clear(sessionID: string): Promise<void>;
29
+ /** Live entries (mirrors the L1 map; used by tests). */
30
+ readonly size: number;
31
+ getStopSupported(): Promise<boolean>;
32
+ setStopSupported(): Promise<void>;
33
+ /** True once any storage call has failed (in-memory fallback in use). */
34
+ isDegraded(): boolean;
35
+ }
36
+ export declare function createBlockStore(storage: StorageLike | undefined | null, memory?: Map<string, number>): BlockStore;
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Persistent per-session completion-gate block counts.
3
+ *
4
+ * Counts live in `ctx.storage` (survives plugin reload / `session_move` /
5
+ * server restart) with a caller-provided `Map` as the write-through L1
6
+ * cache (keeps `/df-status` rendering and the synchronous status paths
7
+ * working off live data). Every storage call is best-effort: on failure the
8
+ * store falls back to memory, records `isDegraded()`, and never throws — so
9
+ * a broken storage backend degrades to pre-Phase-23 behavior instead of
10
+ * breaking the gate.
11
+ *
12
+ * Stored values are only block counts (`number`) and one `boolean` flag.
13
+ * Never store secrets, prompts, or file contents here.
14
+ *
15
+ * Key namespacing: counts are keyed `df:blocks:<sessionID>` (OpenCode
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`.
18
+ */
19
+ export const BLOCK_COUNT_KEY_PREFIX = "df:blocks:";
20
+ export const STOP_SUPPORTED_KEY = "df:stopSupported";
21
+ function blockKey(sessionID) {
22
+ return `${BLOCK_COUNT_KEY_PREFIX}${sessionID}`;
23
+ }
24
+ /** Accept only sane counts; anything else (foreign/corrupt value) is treated as missing. */
25
+ function asCount(value) {
26
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
27
+ return undefined;
28
+ return Math.floor(value);
29
+ }
30
+ export function createBlockStore(storage, memory) {
31
+ const counts = memory ?? new Map();
32
+ let stopMemory = false;
33
+ let degraded = false;
34
+ async function readCount(sessionID) {
35
+ if (storage == null)
36
+ return counts.get(sessionID) ?? 0;
37
+ try {
38
+ const stored = asCount(await storage.get(blockKey(sessionID)));
39
+ if (stored !== undefined) {
40
+ counts.set(sessionID, stored);
41
+ return stored;
42
+ }
43
+ return counts.get(sessionID) ?? 0;
44
+ }
45
+ catch {
46
+ degraded = true;
47
+ return counts.get(sessionID) ?? 0;
48
+ }
49
+ }
50
+ async function writeCount(sessionID, count) {
51
+ counts.set(sessionID, count);
52
+ if (storage == null)
53
+ return;
54
+ try {
55
+ await storage.set(blockKey(sessionID), count);
56
+ }
57
+ catch {
58
+ degraded = true;
59
+ }
60
+ }
61
+ return {
62
+ get(sessionID) {
63
+ return readCount(sessionID);
64
+ },
65
+ async increment(sessionID) {
66
+ const next = (await readCount(sessionID)) + 1;
67
+ await writeCount(sessionID, next);
68
+ return next;
69
+ },
70
+ async clear(sessionID) {
71
+ counts.delete(sessionID);
72
+ if (storage == null)
73
+ return;
74
+ try {
75
+ await storage.remove(blockKey(sessionID));
76
+ }
77
+ catch {
78
+ degraded = true;
79
+ }
80
+ },
81
+ get size() {
82
+ return counts.size;
83
+ },
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
+ isDegraded() {
114
+ return degraded;
115
+ },
116
+ };
117
+ }
package/dist/gate.d.ts CHANGED
@@ -15,6 +15,8 @@ export declare const DEFAULT_GATE_TIMEOUT_SECONDS = 300;
15
15
  /** Tracks files edited during a session so the gate can scope work. */
16
16
  export interface ChangedFileTracker {
17
17
  add: (filePath: string, directory?: string) => void;
18
+ /** True when the (normalized) path is already tracked. */
19
+ has: (filePath: string, directory?: string) => boolean;
18
20
  getChangedFiles: () => string[];
19
21
  clearChangedFiles: () => void;
20
22
  }
package/dist/gate.js CHANGED
@@ -13,6 +13,13 @@ import { splitCommand } from "./command-utils.js";
13
13
  import { lintFile } from "./lint.js";
14
14
  /** Fallback per-command timeout (seconds) when `gate.timeout` is unset. */
15
15
  export const DEFAULT_GATE_TIMEOUT_SECONDS = 300;
16
+ function normalizeTrackedPath(filePath, directory) {
17
+ let candidate = filePath;
18
+ if (directory !== undefined && isAbsolute(filePath)) {
19
+ candidate = relative(directory, filePath);
20
+ }
21
+ return candidate.replace(/^\.\//, "");
22
+ }
16
23
  /**
17
24
  * Create a changed-file tracker. Paths are deduplicated and stored relative
18
25
  * to the project directory when one is provided.
@@ -21,11 +28,10 @@ export function createChangedFileTracker() {
21
28
  const files = new Set();
22
29
  return {
23
30
  add(filePath, directory) {
24
- let candidate = filePath;
25
- if (directory !== undefined && isAbsolute(filePath)) {
26
- candidate = relative(directory, filePath);
27
- }
28
- files.add(candidate.replace(/^\.\//, ""));
31
+ files.add(normalizeTrackedPath(filePath, directory));
32
+ },
33
+ has(filePath, directory) {
34
+ return files.has(normalizeTrackedPath(filePath, directory));
29
35
  },
30
36
  getChangedFiles() {
31
37
  return [...files];
package/dist/harness.d.ts CHANGED
@@ -18,6 +18,7 @@
18
18
  * when the OpenCode build supports it) and the `session.idle` fallback
19
19
  * (re-prompt).
20
20
  */
21
+ import type { BlockStore } from "./block-store.js";
21
22
  import { type ChangedFileTracker } from "./gate.js";
22
23
  import type { RunCommand } from "./host.js";
23
24
  import type { LogFn } from "./logger.js";
@@ -78,7 +79,7 @@ export interface CompletionDeps {
78
79
  directory: string;
79
80
  sessionID: string;
80
81
  tracker: ChangedFileTracker;
81
- blockCounts: Map<string, number>;
82
+ blockCounts: BlockStore;
82
83
  log: LogFn;
83
84
  }
84
85
  /**
package/dist/harness.js CHANGED
@@ -150,7 +150,7 @@ export async function evaluateCompletion(deps) {
150
150
  const reviewMissing = reviewRequired && reviewState !== "present";
151
151
  if (!gateFailed && !reviewMissing) {
152
152
  tracker.clearChangedFiles();
153
- blockCounts.delete(sessionID);
153
+ await blockCounts.clear(sessionID);
154
154
  return {
155
155
  decision: "pass",
156
156
  changedFiles,
@@ -170,17 +170,16 @@ export async function evaluateCompletion(deps) {
170
170
  const reason = gateFailed ? "gate" : "review";
171
171
  const summary = gateFailed ? summarizeGate(report) : reviewMissingMessage(changedFiles);
172
172
  const maxBlocks = config.gate.max_blocks ?? 3;
173
- const blockCount = (blockCounts.get(sessionID) ?? 0) + 1;
173
+ const blockCount = await blockCounts.increment(sessionID);
174
174
  if (blockCount > maxBlocks) {
175
175
  tracker.clearChangedFiles();
176
- blockCounts.delete(sessionID);
176
+ await blockCounts.clear(sessionID);
177
177
  const standdownSummary = `opencode-dev-framework completion gate has blocked ${maxBlocks} times and is standing ` +
178
178
  `down to avoid trapping you. The requirement is STILL unmet:\n\n${summary}\n\n` +
179
179
  `Do not claim the work is complete. Tell the user plainly what remains unmet and why.`;
180
180
  await deps.log("error", standdownSummary, { reason, sessionID });
181
181
  return { decision: "standdown", reason, summary: standdownSummary, changedFiles };
182
182
  }
183
- blockCounts.set(sessionID, blockCount);
184
183
  await deps.log("error", summary, { reason, sessionID, blockCount, maxBlocks });
185
184
  return {
186
185
  decision: "blocked",
package/dist/index.d.ts CHANGED
@@ -2,11 +2,14 @@
2
2
  * opencode-dev-framework V2 plugin entry point.
3
3
  *
4
4
  * V2 framework (opencode v2): Plugin.define({ id, setup(ctx) })
5
- * - ctx.session.hook("context", ...) -> constitution injection
6
- * - ctx.tool.hook("execute.before", ...) -> guardrails
5
+ * - ctx.session.hook("context"/"generate"/"compaction"/"title", ...) -> constitution injection
6
+ * - ctx.permission.hook("evaluate", ...) -> native permission layer (Phase 25;
7
+ * observe-only spike in 25.1, enforcing mapper from 25.2)
8
+ * - ctx.tool.hook("execute.before", ...) -> guardrails (backstop from Phase 25)
9
+ * - ctx.tool.hook("execute.after", ...) -> per-edit lint + change tracking
10
+ * (`filesystem.changed` stays as a fallback this release; see Phase 24)
7
11
  * - ctx.event.subscribe() -> file tracking + gate enforcement via re-prompt
8
12
  * - ctx.tool.transform(...) -> custom tools
9
- * - ctx.command.transform(...) -> slash commands (optional)
10
13
  *
11
14
  * Gate enforcement: no synchronous `session.stopping`. On `session.idle`
12
15
  * / `session.status:idle` we run the gate and if it fails inside budget we
@@ -14,6 +17,7 @@
14
17
  * agent — async re-injection preserving the enforcement intent (see docs/plans/08-notes).
15
18
  */
16
19
  import { Plugin } from "@opencode/plugin";
20
+ import { type BlockStore } from "./block-store.js";
17
21
  import { type ChangedFileTracker } from "./gate.js";
18
22
  import { type RunCommand } from "./host.js";
19
23
  import { type LogFn } from "./logger.js";
@@ -26,6 +30,16 @@ export interface HookState {
26
30
  tracker: ChangedFileTracker;
27
31
  constitution: string | null;
28
32
  blockCounts: Map<string, number>;
33
+ /**
34
+ * Persistent block-count store over `ctx.storage`, write-through into
35
+ * `blockCounts` (which stays the live L1 cache for status rendering).
36
+ * Survives plugin reload / session_move / server restart.
37
+ * Note: this `HookState` is intentionally forked from `registry.ts`
38
+ * `HookState` (module state is per-location here, not registry-keyed);
39
+ * `format-status.ts` reads the `blockCounts` Map projection, which the
40
+ * store keeps live on every get/increment/clear.
41
+ */
42
+ blocks: BlockStore;
29
43
  precommitAvailable?: boolean;
30
44
  configMtime?: number;
31
45
  /**
package/dist/index.js CHANGED
@@ -2,11 +2,14 @@
2
2
  * opencode-dev-framework V2 plugin entry point.
3
3
  *
4
4
  * V2 framework (opencode v2): Plugin.define({ id, setup(ctx) })
5
- * - ctx.session.hook("context", ...) -> constitution injection
6
- * - ctx.tool.hook("execute.before", ...) -> guardrails
5
+ * - ctx.session.hook("context"/"generate"/"compaction"/"title", ...) -> constitution injection
6
+ * - ctx.permission.hook("evaluate", ...) -> native permission layer (Phase 25;
7
+ * observe-only spike in 25.1, enforcing mapper from 25.2)
8
+ * - ctx.tool.hook("execute.before", ...) -> guardrails (backstop from Phase 25)
9
+ * - ctx.tool.hook("execute.after", ...) -> per-edit lint + change tracking
10
+ * (`filesystem.changed` stays as a fallback this release; see Phase 24)
7
11
  * - ctx.event.subscribe() -> file tracking + gate enforcement via re-prompt
8
12
  * - ctx.tool.transform(...) -> custom tools
9
- * - ctx.command.transform(...) -> slash commands (optional)
10
13
  *
11
14
  * Gate enforcement: no synchronous `session.stopping`. On `session.idle`
12
15
  * / `session.status:idle` we run the gate and if it fails inside budget we
@@ -16,13 +19,14 @@
16
19
  import { Plugin } from "@opencode/plugin";
17
20
  import { stat } from "node:fs/promises";
18
21
  import { join } from "node:path";
22
+ import { createBlockStore } from "./block-store.js";
19
23
  import { clearConfigCache, loadConfig } from "./config.js";
20
24
  import { createChangedFileTracker } from "./gate.js";
21
25
  import { artifactState, evaluateCompletion, PREFLIGHT_ARTIFACT_REL, preflightBlockReason, } from "./harness.js";
22
26
  import { runCommand } from "./host.js";
23
27
  import { lintFile, detectPreCommitAvailability, isLintFailure, summarizeLint } from "./lint.js";
24
28
  import { createLogger } from "./logger.js";
25
- import { checkToolCall, extractFilePath } from "./protect.js";
29
+ import { checkToolCall, extractFilePath, FILE_TOOLS, toPermissionGuard } from "./protect.js";
26
30
  import { loadConstitution } from "./rules.js";
27
31
  let activeState = null;
28
32
  let fallbackLog = async () => { };
@@ -95,6 +99,41 @@ async function actOnVerdict(state, verdict) {
95
99
  }
96
100
  return continuationMessage(verdict);
97
101
  }
102
+ /**
103
+ * Per-edit lint flow, shared by the `execute.after` hook (primary) and the
104
+ * `filesystem.changed` fallback. Skipped files log at debug; passes at info;
105
+ * failures log loudly at error (the edit already landed, so unlike
106
+ * `execute.before` this never throws — it only reports).
107
+ */
108
+ async function runPerEditLint(state, filePath) {
109
+ if (!state.config.on_edit.lint)
110
+ return;
111
+ if (state.config.precommit === "auto" && state.precommitAvailable === undefined) {
112
+ state.precommitAvailable = await detectPreCommitAvailability(state.run, state.directory);
113
+ }
114
+ const outcome = await lintFile(state.run, state.config, filePath, {
115
+ cwd: state.directory,
116
+ timeout: state.config.gate?.timeout,
117
+ precommitAvailable: state.precommitAvailable,
118
+ });
119
+ if (outcome.skipped) {
120
+ await safeLog(state, "debug", summarizeLint(outcome), {
121
+ filePath,
122
+ reason: outcome.reason,
123
+ });
124
+ return;
125
+ }
126
+ if (!isLintFailure(outcome)) {
127
+ await safeLog(state, "info", summarizeLint(outcome), { filePath });
128
+ return;
129
+ }
130
+ await safeLog(state, "error", summarizeLint(outcome), {
131
+ filePath,
132
+ command: outcome.command?.join(" "),
133
+ stdout: outcome.result?.stdout,
134
+ stderr: outcome.result?.stderr,
135
+ });
136
+ }
98
137
  /** Assemble the completion verdict with the state's live dependencies. */
99
138
  function runCompletion(state, sessionID) {
100
139
  return evaluateCompletion({
@@ -103,7 +142,7 @@ function runCompletion(state, sessionID) {
103
142
  directory: state.directory,
104
143
  sessionID,
105
144
  tracker: state.tracker,
106
- blockCounts: state.blockCounts,
145
+ blockCounts: state.blocks,
107
146
  log: (level, message, extra) => safeLog(state, level, message, extra),
108
147
  });
109
148
  }
@@ -194,6 +233,8 @@ const plugin = Plugin.define({
194
233
  }
195
234
  }
196
235
  const tracker = createChangedFileTracker();
236
+ const blockCounts = new Map();
237
+ const blocks = createBlockStore(ctx.storage, blockCounts);
197
238
  const state = {
198
239
  directory,
199
240
  config,
@@ -201,10 +242,18 @@ const plugin = Plugin.define({
201
242
  run: runCommand,
202
243
  tracker,
203
244
  constitution,
204
- blockCounts: new Map(),
245
+ blockCounts,
246
+ blocks,
205
247
  configMtime,
206
248
  };
207
249
  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();
254
+ if (blocks.isDegraded()) {
255
+ await log("warn", "ctx.storage is unavailable; gate block counts are in-memory only and reset on reload", { directory });
256
+ }
208
257
  const registrations = [];
209
258
  function trackRegistration(value) {
210
259
  if (value !== null &&
@@ -223,41 +272,40 @@ const plugin = Plugin.define({
223
272
  // an in-flight handler between awaits (captured `state` stays valid
224
273
  // while the global may be cleared). See issue #1 follow-up.
225
274
  // 1) Constitution injection — per model request (V1: experimental.chat.system.transform -> V2: session.hook("context", ...))
226
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
227
275
  trackRegistration(await ctx.session.hook("context", async (event) => {
228
276
  if (activeState !== state)
229
277
  return;
230
278
  await reloadConfigIfChanged(state);
231
279
  if (state.config.profile === "off")
232
280
  return;
233
- if (!state.constitution)
281
+ const constitution = state.constitution;
282
+ if (!constitution)
234
283
  return;
235
284
  // V2 system is Array<SystemPart> {type:"text", text:string}
236
- const already = event.system.some((part) => part.text.includes(state.constitution));
285
+ const already = event.system.some((part) => part.text.includes(constitution));
237
286
  if (already)
238
287
  return;
239
288
  event.system.push({
240
289
  type: "text",
241
- text: state.constitution,
290
+ text: constitution,
242
291
  });
243
292
  await safeLog(state, "info", "constitution injected into system prompt");
244
293
  }));
245
294
  // Also hook other request kinds so the reminder is not missed on title/generate
246
295
  // (no-op if model doesn't need it; cheap)
247
- for (const kind of ["generate", "compaction"]) {
248
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
296
+ for (const kind of ["generate", "compaction", "title"]) {
249
297
  trackRegistration(await ctx.session.hook(kind, async (event) => {
250
298
  if (activeState !== state)
251
299
  return;
252
- if (state.config.profile === "off" || !state.constitution)
300
+ const constitution = state.constitution;
301
+ if (state.config.profile === "off" || !constitution)
253
302
  return;
254
- // generate/compaction also have system — inject similarly if present
255
- const ev = event;
256
- if (!ev.system)
303
+ // generate/compaction/title also have system — inject similarly if present
304
+ if (!event.system)
257
305
  return;
258
- const already = ev.system.some((p) => p.text.includes(state.constitution));
306
+ const already = event.system.some((p) => p.text.includes(constitution));
259
307
  if (!already)
260
- ev.system.push({ type: "text", text: state.constitution });
308
+ event.system.push({ type: "text", text: constitution });
261
309
  }));
262
310
  }
263
311
  // 1b) Hard-stop completion gate — `session.stopping` (OpenCode PR #44712).
@@ -268,9 +316,13 @@ const plugin = Plugin.define({
268
316
  // session.idle fallback below provides re-prompt enforcement instead.
269
317
  // The first invocation flips `stopHookSupported` so /df-status can show
270
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.
271
323
  try {
272
324
  trackRegistration(
273
- // biome-ignore lint/suspicious/noExplicitAny: V2 hook names are not yet typed for session.stopping
325
+ // biome-ignore lint/suspicious/noExplicitAny: defensive stopping probe, not in SessionHooks (PR #44712)
274
326
  await ctx.session.hook("stopping",
275
327
  // biome-ignore lint/suspicious/noExplicitAny: core may dispatch (input, output) or a single mutable event
276
328
  async (input, output) => {
@@ -282,6 +334,7 @@ const plugin = Plugin.define({
282
334
  getEventSessionID(input) ??
283
335
  "unknown";
284
336
  state.stopHookSupported = true;
337
+ await state.blocks.setStopSupported();
285
338
  await reloadConfigIfChanged(state);
286
339
  if (state.config.profile === "off")
287
340
  return;
@@ -297,6 +350,88 @@ const plugin = Plugin.define({
297
350
  catch {
298
351
  await safeLog(state, "warn", "could not register session.stopping hook; using session.idle re-prompt fallback only");
299
352
  }
353
+ // 2a) Native permission layer (Phase 25): `permission.evaluate` fires
354
+ // with `{action, resources, effect}` (shapes recorded in the 25.1 spike,
355
+ // docs/plans/08-notes.md — never guessed: action "edit" covers
356
+ // edit/write/patch with resources[0] = file path; action "shell" covers
357
+ // bash/shell with resources[0] = command).
358
+ // The mapper only ever denies or abstains (never allows), so it can
359
+ // never weaken host/engine enforcement. `execute.before` below stays as
360
+ // the backstop — and is the load-bearing layer: the firing investigation
361
+ // (08-notes) proved the pipeline runs before-hooks FIRST, so evaluate
362
+ // only ever sees calls the backstop already passed. The native layer is
363
+ // defense-in-depth (it still matters if core ever reorders the pipeline
364
+ // or adds paths bypassing tool hooks). Quiet paths log at debug — in
365
+ // particular advisory warns stay debug here because execute.before
366
+ // already warned for the same call.
367
+ try {
368
+ trackRegistration(await ctx.permission.hook("evaluate", async (event) => {
369
+ if (activeState !== state)
370
+ return;
371
+ await reloadConfigIfChanged(state);
372
+ if (state.config.profile === "off")
373
+ return;
374
+ const action = event.action;
375
+ const target = event.resources[0];
376
+ const baseExtra = {
377
+ action,
378
+ resources: [...event.resources],
379
+ sessionID: event.sessionID,
380
+ };
381
+ // Already denied by the host/engine: abstain so its verdict and
382
+ // message survive untouched (mirrors the backstop's hostDenies
383
+ // stand-down; the mapper must never overwrite a denial).
384
+ if (event.effect === "deny") {
385
+ await safeLog(state, "debug", `permission.evaluate action=${action} already denied; leaving host/engine verdict untouched`, { ...baseExtra, message: event.message });
386
+ return;
387
+ }
388
+ // Pre-flight (mirrors execute.before; the artifact itself stays
389
+ // writable). Deny/warn per profile, exactly like the backstop.
390
+ if (state.config.preflight.length > 0 && action === "edit") {
391
+ const artifact = await artifactState(state.directory, PREFLIGHT_ARTIFACT_REL);
392
+ const reason = preflightBlockReason(state.config, "edit", target, artifact);
393
+ if (reason !== null) {
394
+ if (state.config.profile === "advisory") {
395
+ // Debug, not warn: execute.before runs first and already
396
+ // warned for this exact call (same double-noise rule as the
397
+ // guardrail warn path below).
398
+ await safeLog(state, "debug", reason, {
399
+ ...baseExtra,
400
+ artifact: PREFLIGHT_ARTIFACT_REL,
401
+ });
402
+ return;
403
+ }
404
+ event.effect = "deny";
405
+ event.message = reason;
406
+ await safeLog(state, "error", reason, {
407
+ ...baseExtra,
408
+ artifact: PREFLIGHT_ARTIFACT_REL,
409
+ });
410
+ return;
411
+ }
412
+ }
413
+ const verdict = toPermissionGuard(state.config, action, event.resources, state.directory);
414
+ if (verdict === null) {
415
+ await safeLog(state, "debug", `permission.evaluate action=${action} effect=${event.effect} (no guardrail verdict; engine default wins)`, { ...baseExtra, effect: event.effect });
416
+ return;
417
+ }
418
+ const message = verdict.reason ?? "blocked by guardrails";
419
+ const extra = { ...baseExtra, pattern: verdict.matchedPattern };
420
+ if (verdict.decision === "warn") {
421
+ // Advisory: stay silent at warn level — `execute.before` runs
422
+ // first in the pipeline and already warned for this exact call.
423
+ // A debug trace keeps the layer observable without double noise.
424
+ await safeLog(state, "debug", message, extra);
425
+ return; // leave the engine verdict untouched
426
+ }
427
+ event.effect = "deny";
428
+ event.message = message;
429
+ await safeLog(state, "error", message, extra);
430
+ }));
431
+ }
432
+ catch {
433
+ await safeLog(state, "warn", "could not register permission.evaluate hook; guardrails use execute.before only");
434
+ }
300
435
  // 2) Guardrails — tool execution blocking (V1: tool.execute.before -> V2: ctx.tool.hook("execute.before", ...))
301
436
  // Stale-hook fail-open: the closure captures its own `state` and allows
302
437
  // the call whenever it is no longer live — torn down (activeState null)
@@ -304,10 +439,9 @@ const plugin = Plugin.define({
304
439
  // whose own hook enforces; this one must not double-enforce). Using the
305
440
  // captured `state` throughout also closes the teardown race where the
306
441
  // global is cleared between awaits. See issue #1.
307
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
308
442
  trackRegistration(await ctx.tool.hook("execute.before", async (event) => {
309
443
  if (activeState !== state) {
310
- if (activeState == null) {
444
+ if (activeState === null) {
311
445
  await safeLog(null, "warn", "[opencode-dev-framework] plugin state is not available; allowing tool call (fail-open after teardown)", { tool: event.tool });
312
446
  }
313
447
  return;
@@ -349,8 +483,31 @@ const plugin = Plugin.define({
349
483
  await safeLog(state, "error", message, extra);
350
484
  throw new Error(`[opencode-dev-framework] ${message}`);
351
485
  }));
486
+ // 2b) Per-edit lint — `tool.execute.after` (primary; the
487
+ // `filesystem.changed` branch below stays as a fallback this release).
488
+ // Edit tools with `completed` status are tracked + linted via the shared
489
+ // flow; `error` status tracks without linting (the tool failed, so there
490
+ // is nothing reliable to lint); read-only tools never touch the tracker.
491
+ // The edit already landed, so this hook only reports — it never throws.
492
+ trackRegistration(await ctx.tool.hook("execute.after", async (event) => {
493
+ if (activeState !== state)
494
+ return;
495
+ await reloadConfigIfChanged(state);
496
+ if (state.config.profile === "off")
497
+ return;
498
+ const filePath = extractFilePath(event.input);
499
+ if (!filePath)
500
+ return;
501
+ if (!FILE_TOOLS.has(event.tool))
502
+ return;
503
+ state.tracker.add(filePath, state.directory);
504
+ if (event.status !== "completed") {
505
+ await safeLog(state, "debug", `tracked ${filePath} from failed ${event.tool} call (lint skipped)`, { tool: event.tool, sessionID: event.sessionID, filePath });
506
+ return;
507
+ }
508
+ await runPerEditLint(state, filePath);
509
+ }));
352
510
  // 3) Custom tools — V2: ctx.tool.transform(editor => editor.add(...))
353
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
354
511
  trackRegistration(await ctx.tool.transform((editor) => {
355
512
  editor.add({
356
513
  name: "dev_framework_init",
@@ -441,6 +598,34 @@ const plugin = Plugin.define({
441
598
  return { content: `${message} Change applied immediately.` };
442
599
  },
443
600
  });
601
+ editor.add({
602
+ name: "dev_framework_verify",
603
+ description: "Run the opencode-dev-framework completion gate now (typecheck, tests, changed-file lint) and return the summary. Use for a mid-session gate check without waiting for session idle; unlike the idle gate this never re-prompts, it only reports.",
604
+ input: {
605
+ type: "object",
606
+ properties: {
607
+ directory: {
608
+ type: "string",
609
+ description: "Project directory (defaults to current project)",
610
+ },
611
+ },
612
+ additionalProperties: false,
613
+ },
614
+ async execute(input) {
615
+ const { verifyGate } = await import("./commands.js");
616
+ const args = input;
617
+ const targetDir = args.directory ?? directory;
618
+ const live = activeState && activeState.directory === targetDir ? activeState : null;
619
+ const own = state.directory === targetDir ? state : null;
620
+ const holder = live ?? own;
621
+ // Live tracker's changed files beat the TUI's empty default: a
622
+ // mid-session verify scopes `changed` steps to real edits.
623
+ const cfg = holder?.config ?? loadConfig(targetDir);
624
+ const changed = holder ? holder.tracker.getChangedFiles() : [];
625
+ const { summary } = await verifyGate(state.run, targetDir, cfg, changed);
626
+ return { content: summary };
627
+ },
628
+ });
444
629
  editor.add({
445
630
  name: "dev_framework_status",
446
631
  description: "Show the current opencode-dev-framework state for the project: active profile, guardrails, completion gate, on-edit behavior, tracked changed files, and block counts.",
@@ -482,10 +667,11 @@ const plugin = Plugin.define({
482
667
  const event = rawEvent;
483
668
  const type = event.type;
484
669
  if (isSessionDeletedEvent(type)) {
485
- // session.deleted: cleanup blockCounts (and tracker if needed)
670
+ // session.deleted: cleanup block counts (memory + storage) and
671
+ // forget the session's directory mapping if present.
486
672
  const sid = getEventSessionID(event);
487
673
  if (sid)
488
- state.blockCounts.delete(sid);
674
+ await state.blocks.clear(sid);
489
675
  continue;
490
676
  }
491
677
  if (isFilesystemChangedEvent(type)) {
@@ -497,40 +683,15 @@ const plugin = Plugin.define({
497
683
  const filePath = getEventFilePath(event);
498
684
  if (!filePath)
499
685
  continue;
500
- state.tracker.add(filePath, state.directory);
501
- // per-edit lint (V1: event file.edited -> lintFile)
502
- if (!state.config.on_edit.lint)
503
- continue;
504
- if (state.config.precommit === "auto" && state.precommitAvailable === undefined) {
505
- state.precommitAvailable = await detectPreCommitAvailability(state.run, state.directory);
506
- }
507
- const outcome = await lintFile(state.run, state.config, filePath, {
508
- cwd: state.directory,
509
- timeout: state.config.gate?.timeout,
510
- precommitAvailable: state.precommitAvailable,
511
- });
512
- if (outcome.skipped) {
513
- await safeLog(state, "debug", summarizeLint(outcome), {
514
- filePath,
515
- reason: outcome.reason,
516
- });
686
+ // Fallback path (primary is `execute.after` since Phase 24): the
687
+ // tracker is add-idempotent, so a file already seen via
688
+ // `execute.after` just logs at debug instead of linting twice.
689
+ if (state.tracker.has(filePath, state.directory)) {
690
+ await safeLog(state, "debug", `already tracked ${filePath} (skipping fallback lint; execute.after is primary)`, { filePath });
517
691
  continue;
518
692
  }
519
- if (!isLintFailure(outcome)) {
520
- await safeLog(state, "info", summarizeLint(outcome), { filePath });
521
- continue;
522
- }
523
- const summary = summarizeLint(outcome);
524
- await safeLog(state, "error", summary, {
525
- filePath,
526
- command: outcome.command?.join(" "),
527
- stdout: outcome.result?.stdout,
528
- stderr: outcome.result?.stderr,
529
- });
530
- if (state.config.profile === "strict") {
531
- // Event handlers cannot throw to block the edit (edit already happened), but we log loudly.
532
- // In V2 we also have the tool hook to block before; this is advisory.
533
- }
693
+ state.tracker.add(filePath, state.directory);
694
+ await runPerEditLint(state, filePath);
534
695
  continue;
535
696
  }
536
697
  if (isIdleEvent(event)) {
package/dist/protect.d.ts CHANGED
@@ -42,3 +42,19 @@ export declare function matchDangerousCommand(command: string): DangerousCommand
42
42
  * matched. Otherwise returns `deny` or `warn` per `protect_mode`.
43
43
  */
44
44
  export declare function checkToolCall(config: ResolvedConfig, tool: string, args: unknown, directory?: string, hostPermissions?: OpenCodePermission): GuardResult;
45
+ /**
46
+ * Phase 25: adapt a native `permission.evaluate` event to the guardrail
47
+ * verdict. Maps the observed engine shapes (spike 25.1, OpenCode v2.0.26 —
48
+ * recorded in docs/plans/08-notes.md, never guessed):
49
+ * - action `"edit"` (covers edit/write/patch tools) with `resources[0]` =
50
+ * the target file path (repo-relative).
51
+ * - action `"shell"` (covers bash/shell tools) with `resources[0]` = the
52
+ * shell command string.
53
+ *
54
+ * Returns the guardrail verdict (`deny`/`warn`) or `null` when the mapper
55
+ * abstains (unknown action, empty resources, protection off, or no match) —
56
+ * `null` leaves the engine verdict untouched so the engine default wins.
57
+ * Never returns `allow`: the mapper can only deny, warn, or abstain, so it
58
+ * can never weaken host/engine enforcement.
59
+ */
60
+ export declare function toPermissionGuard(config: ResolvedConfig, action: string, resources: ReadonlyArray<string>, directory?: string): GuardResult | null;
package/dist/protect.js CHANGED
@@ -157,3 +157,35 @@ export function checkToolCall(config, tool, args, directory, hostPermissions) {
157
157
  }
158
158
  return { decision: "allow" };
159
159
  }
160
+ /**
161
+ * Phase 25: adapt a native `permission.evaluate` event to the guardrail
162
+ * verdict. Maps the observed engine shapes (spike 25.1, OpenCode v2.0.26 —
163
+ * recorded in docs/plans/08-notes.md, never guessed):
164
+ * - action `"edit"` (covers edit/write/patch tools) with `resources[0]` =
165
+ * the target file path (repo-relative).
166
+ * - action `"shell"` (covers bash/shell tools) with `resources[0]` = the
167
+ * shell command string.
168
+ *
169
+ * Returns the guardrail verdict (`deny`/`warn`) or `null` when the mapper
170
+ * abstains (unknown action, empty resources, protection off, or no match) —
171
+ * `null` leaves the engine verdict untouched so the engine default wins.
172
+ * Never returns `allow`: the mapper can only deny, warn, or abstain, so it
173
+ * can never weaken host/engine enforcement.
174
+ */
175
+ export function toPermissionGuard(config, action, resources, directory) {
176
+ if (config.profile === "off" || config.protect_off) {
177
+ return null;
178
+ }
179
+ if (resources.length === 0) {
180
+ return null;
181
+ }
182
+ if (action === "edit") {
183
+ const result = checkToolCall(config, "edit", { filePath: resources[0] }, directory, undefined);
184
+ return result.decision === "allow" ? null : result;
185
+ }
186
+ if (action === "shell") {
187
+ const result = checkToolCall(config, "bash", { command: resources[0] }, directory, undefined);
188
+ return result.decision === "allow" ? null : result;
189
+ }
190
+ return null;
191
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-dev-framework",
3
- "version": "0.2.4",
3
+ "version": "0.3.0",
4
4
  "description": "OpenCode plugin that enforces project-specific quality gates during AI coding sessions",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -56,16 +56,16 @@
56
56
  "guardrails"
57
57
  ],
58
58
  "dependencies": {
59
- "@opencode/plugin": "^2.0.11",
59
+ "@opencode/plugin": "^2.0.26",
60
60
  "picomatch": "^4.0.5",
61
61
  "yaml": "^2.9.0",
62
62
  "zod": "^4.4.3"
63
63
  },
64
64
  "devDependencies": {
65
65
  "@biomejs/biome": "^2.5.8",
66
- "@opentui/core": "^0.5.10",
67
- "@opentui/keymap": "^0.5.11",
68
- "@opentui/solid": "^0.5.11",
66
+ "@opentui/core": "^0.5.17",
67
+ "@opentui/keymap": "^0.5.17",
68
+ "@opentui/solid": "^0.5.17",
69
69
  "@types/node": "^26.2.0",
70
70
  "@types/picomatch": "^4.0.3",
71
71
  "markdownlint-cli2": "^0.23.2",