opencode-dev-framework 0.1.27 → 0.1.29

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
@@ -202,11 +202,15 @@ itself).
202
202
 
203
203
  ## Limitations
204
204
 
205
- - **The completion gate blocks only in newer OpenCode versions.** The
206
- `experimental.session.stopping` hook (PR #41811) lets the plugin keep the
207
- session running until checks pass. In older OpenCode versions the gate runs
208
- on `session.idle` and reports failures loudly but cannot force the agent to
209
- keep working.
205
+ - **The completion gate blocks only in newer OpenCode versions.** Newer
206
+ builds support the `session.stopping` hook (OpenCode PR #44712) and
207
+ the earlier `experimental.session.stopping` hook (PR #41811); either
208
+ lets the plugin keep the session running until checks pass. The new
209
+ hook uses a fail-closed `{ stop, message }` contract and applies only
210
+ to natural loop exits; OpenCode core also caps continuations at 3
211
+ regardless of `gate.max_blocks`. In older OpenCode versions the gate
212
+ runs on `session.idle` and reports failures loudly but cannot force
213
+ the agent to keep working.
210
214
  - **Guardrails run inside OpenCode.** The `tool.execute.before` hook runs
211
215
  after OpenCode's own permission system; it adds project rules on top, it
212
216
  does not replace OpenCode permissions.
package/dist/index.d.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  * - event (session.idle) -> completion gate fallback (advisory logging)
8
8
  * - experimental.chat.system.transform -> constitution injection + session mapping
9
9
  * - experimental.session.stopping -> blocking completion gate (OpenCode >= PR #41811)
10
+ * - session.stopping -> same blocking gate, new contract (OpenCode PR #44712)
10
11
  * - config hook -> registers /df-profile and /df-verify prompt commands
11
12
  * - command.execute.before -> handles /df-profile, /df-verify, and unknown /df-*
12
13
  */
@@ -16,10 +17,17 @@ import { type RunCommand } from "./host.js";
16
17
  import { type LogFn } from "./logger.js";
17
18
  import type { ResolvedConfig } from "./types.js";
18
19
  /**
19
- * The `experimental.session.stopping` hook was added in OpenCode PR #41811
20
- * and is not yet in the published `@opencode-ai/plugin` types. We define it
21
- * locally so the plugin compiles and automatically uses the hook when the
22
- * runtime supports it.
20
+ * OpenCode exposes two competing "loop continuation" hooks that are not yet in
21
+ * the published `@opencode-ai/plugin` types, so we declare both locally and use
22
+ * whichever the runtime supports:
23
+ *
24
+ * - `experimental.session.stopping` (OpenCode PR #41811): plugin pushes text
25
+ * into `output.context`; presence keeps the session running.
26
+ * - `session.stopping` (OpenCode PR #44712): fail-closed contract. The default
27
+ * `stop: true` lets the session end; setting `stop: false` with a non-empty
28
+ * `message` injects a synthetic user turn and continues the loop. The hook
29
+ * fires only on natural loop exit and OpenCode core enforces its own
30
+ * re-entry cap (3) regardless of `gate.max_blocks`.
23
31
  */
24
32
  export interface HooksWithStopping extends Hooks {
25
33
  "experimental.session.stopping"?: (input: {
@@ -27,6 +35,12 @@ export interface HooksWithStopping extends Hooks {
27
35
  }, output: {
28
36
  context: string[];
29
37
  }) => Promise<void>;
38
+ "session.stopping"?: (input: {
39
+ sessionID: string;
40
+ }, output: {
41
+ stop: boolean;
42
+ message?: string;
43
+ }) => Promise<void>;
30
44
  }
31
45
  /**
32
46
  * Build the plugin's hooks and custom tools. Exported (rather than inlined in
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@
7
7
  * - event (session.idle) -> completion gate fallback (advisory logging)
8
8
  * - experimental.chat.system.transform -> constitution injection + session mapping
9
9
  * - experimental.session.stopping -> blocking completion gate (OpenCode >= PR #41811)
10
+ * - session.stopping -> same blocking gate, new contract (OpenCode PR #44712)
10
11
  * - config hook -> registers /df-profile and /df-verify prompt commands
11
12
  * - command.execute.before -> handles /df-profile, /df-verify, and unknown /df-*
12
13
  */
@@ -21,6 +22,18 @@ import { checkToolCall } from "./protect.js";
21
22
  import { clearSessionDirectory, getHookState, getStateForSession, setBaseDirectory, setHookState, setSessionDirectory, } from "./registry.js";
22
23
  import { injectConstitution, loadConstitution } from "./rules.js";
23
24
  import { buildTools } from "./tools.js";
25
+ /**
26
+ * Module-level fallback logger, captured at plugin init. `safeLog` uses it when
27
+ * a hook's `HookState.log` is missing or was stripped, so a logging failure can
28
+ * never crash a hook. The original `state.log is not a function` error (seen when
29
+ * switching `off` -> `standard` at runtime) happened because a hook fired against
30
+ * a `HookState` whose `log` was never populated.
31
+ */
32
+ let fallbackLog = async () => { };
33
+ function safeLog(state, level, message, extra) {
34
+ const fn = typeof state.log === "function" ? state.log : fallbackLog;
35
+ return fn(level, message, extra);
36
+ }
24
37
  /**
25
38
  * Reload the in-memory config if the config file on disk changed since we last
26
39
  * loaded it. This makes out-of-process edits (e.g. a `/df-profile` change made
@@ -45,6 +58,47 @@ async function reloadConfigIfChanged(state) {
45
58
  // Config file missing/unreadable — keep the current state.
46
59
  }
47
60
  }
61
+ /**
62
+ * Shared completion-gate runner for the two loop-continuation hooks
63
+ * (`experimental.session.stopping` and `session.stopping`). The two hooks
64
+ * differ only in how they signal continuation to the runtime, so all gate and
65
+ * block-counting logic lives here and each hook translates the verdict into its
66
+ * own output contract. `state` must already be resolved and have had
67
+ * `reloadConfigIfChanged` applied by the caller.
68
+ */
69
+ async function runStoppingGate(state, sessionID) {
70
+ if (!state.config.gate || state.config.profile === "off") {
71
+ return { decision: "pass" };
72
+ }
73
+ const changedFiles = state.tracker.getChangedFiles();
74
+ const report = await runGate(state.run, state.config, changedFiles, { cwd: state.directory });
75
+ if (!report.ran || report.ok) {
76
+ state.tracker.clearChangedFiles();
77
+ state.blockCounts.delete(sessionID);
78
+ return { decision: "pass" };
79
+ }
80
+ const maxBlocks = state.config.gate.max_blocks ?? 3;
81
+ const blockCount = (state.blockCounts.get(sessionID) ?? 0) + 1;
82
+ state.blockCounts.set(sessionID, blockCount);
83
+ if (blockCount > maxBlocks) {
84
+ // Standing down: clear the tracker so the session.idle fallback does
85
+ // not re-run the same failing gate commands a second time.
86
+ state.tracker.clearChangedFiles();
87
+ await safeLog(state, "warn", `completion gate has blocked ${maxBlocks} times; standing down but checks are still failing`, { failedSteps: report.failedSteps.map((step) => step.name) });
88
+ return { decision: "standdown", failedSteps: report.failedSteps.map((step) => step.name) };
89
+ }
90
+ const summary = summarizeGate(report);
91
+ await safeLog(state, "error", summary, {
92
+ failedSteps: report.failedSteps.map((step) => step.name),
93
+ });
94
+ return { decision: "blocked", summary, blockCount, maxBlocks };
95
+ }
96
+ /** The continuation message both stopping hooks inject on a gate block. */
97
+ function stoppingMessage(verdict) {
98
+ return (`opencode-dev-framework completion gate blocked you from finishing (block ${verdict.blockCount}/${verdict.maxBlocks}). ` +
99
+ `The following checks failed:\n\n${verdict.summary}\n\n` +
100
+ `Fix the underlying cause and continue. Do NOT disable, skip, or weaken these checks to make them pass.`);
101
+ }
48
102
  /**
49
103
  * Build the plugin's hooks and custom tools. Exported (rather than inlined in
50
104
  * the plugin) so tests can inject a stubbed command runner and tracker.
@@ -104,9 +158,12 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
104
158
  if (input.sessionID) {
105
159
  setSessionDirectory(input.sessionID, state.directory);
106
160
  }
161
+ if (state.config.profile === "off") {
162
+ return;
163
+ }
107
164
  const next = injectConstitution(output.system, state.constitution);
108
165
  if (next !== output.system) {
109
- await state.log("info", "constitution injected into system prompt");
166
+ await safeLog(state, "info", "constitution injected into system prompt");
110
167
  output.system = next;
111
168
  }
112
169
  },
@@ -116,6 +173,9 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
116
173
  throw new Error("[opencode-dev-framework] plugin state is not available; guardrail cannot evaluate this tool call");
117
174
  }
118
175
  await reloadConfigIfChanged(state);
176
+ if (state.config.profile === "off") {
177
+ return;
178
+ }
119
179
  const result = checkToolCall(state.config, input.tool, output.args, state.directory, state.hostPermissions);
120
180
  if (result.decision === "allow") {
121
181
  return;
@@ -127,10 +187,10 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
127
187
  pattern: result.matchedPattern,
128
188
  };
129
189
  if (result.decision === "warn") {
130
- await state.log("warn", message, extra);
190
+ await safeLog(state, "warn", message, extra);
131
191
  return;
132
192
  }
133
- await state.log("error", message, extra);
193
+ await safeLog(state, "error", message, extra);
134
194
  throw new Error(`[opencode-dev-framework] ${message}`);
135
195
  },
136
196
  "experimental.session.stopping": async (input, output) => {
@@ -139,33 +199,26 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
139
199
  return;
140
200
  }
141
201
  await reloadConfigIfChanged(state);
142
- if (!state.config.gate || state.config.profile === "off") {
202
+ const verdict = await runStoppingGate(state, input.sessionID);
203
+ if (verdict.decision !== "blocked") {
143
204
  return;
144
205
  }
145
- const changedFiles = state.tracker.getChangedFiles();
146
- const report = await runGate(state.run, state.config, changedFiles, { cwd: state.directory });
147
- if (!report.ran || report.ok) {
148
- state.tracker.clearChangedFiles();
149
- state.blockCounts.delete(input.sessionID);
206
+ output.context.push(stoppingMessage(verdict));
207
+ },
208
+ "session.stopping": async (input, output) => {
209
+ const state = getStateForSession(input.sessionID);
210
+ if (!state) {
150
211
  return;
151
212
  }
152
- const maxBlocks = state.config.gate.max_blocks ?? 3;
153
- const blockCount = (state.blockCounts.get(input.sessionID) ?? 0) + 1;
154
- state.blockCounts.set(input.sessionID, blockCount);
155
- if (blockCount > maxBlocks) {
156
- // Standing down: clear the tracker so the session.idle fallback does
157
- // not re-run the same failing gate commands a second time.
158
- state.tracker.clearChangedFiles();
159
- await state.log("warn", `completion gate has blocked ${maxBlocks} times; standing down but checks are still failing`, { failedSteps: report.failedSteps.map((step) => step.name) });
213
+ await reloadConfigIfChanged(state);
214
+ const verdict = await runStoppingGate(state, input.sessionID);
215
+ if (verdict.decision !== "blocked") {
160
216
  return;
161
217
  }
162
- const summary = summarizeGate(report);
163
- await state.log("error", summary, {
164
- failedSteps: report.failedSteps.map((step) => step.name),
165
- });
166
- output.context.push(`opencode-dev-framework completion gate blocked you from finishing (block ${blockCount}/${maxBlocks}). ` +
167
- `The following checks failed:\n\n${summary}\n\n` +
168
- `Fix the underlying cause and continue. Do NOT disable, skip, or weaken these checks to make them pass.`);
218
+ // Fail-closed contract: leave `stop: true` on pass/standdown; only a
219
+ // real block sets `stop: false` with a continuation message.
220
+ output.stop = false;
221
+ output.message = stoppingMessage(verdict);
169
222
  },
170
223
  event: async ({ event }) => {
171
224
  // session.deleted must run even without hook state so the session map
@@ -182,6 +235,9 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
182
235
  return;
183
236
  }
184
237
  await reloadConfigIfChanged(state);
238
+ if (state.config.profile === "off") {
239
+ return;
240
+ }
185
241
  if (event.type === "file.edited") {
186
242
  const filePath = event.properties.file;
187
243
  state.tracker.add(filePath, state.directory);
@@ -197,15 +253,18 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
197
253
  precommitAvailable: state.precommitAvailable,
198
254
  });
199
255
  if (outcome.skipped) {
200
- await state.log("debug", summarizeLint(outcome), { filePath, reason: outcome.reason });
256
+ await safeLog(state, "debug", summarizeLint(outcome), {
257
+ filePath,
258
+ reason: outcome.reason,
259
+ });
201
260
  return;
202
261
  }
203
262
  if (!isLintFailure(outcome)) {
204
- await state.log("info", summarizeLint(outcome), { filePath });
263
+ await safeLog(state, "info", summarizeLint(outcome), { filePath });
205
264
  return;
206
265
  }
207
266
  const summary = summarizeLint(outcome);
208
- await state.log("error", summary, {
267
+ await safeLog(state, "error", summary, {
209
268
  filePath,
210
269
  command: outcome.command?.join(" "),
211
270
  stdout: outcome.result?.stdout,
@@ -220,11 +279,8 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
220
279
  return;
221
280
  }
222
281
  if (event.type === "session.idle") {
223
- if (state.config.profile === "off") {
224
- return;
225
- }
226
282
  if (!state.config.gate) {
227
- await state.log("warn", "plugin config is incomplete (missing gate section), skipping completion gate", { directory: state.directory });
283
+ await safeLog(state, "warn", "plugin config is incomplete (missing gate section), skipping completion gate", { directory: state.directory });
228
284
  return;
229
285
  }
230
286
  const changedFiles = state.tracker.getChangedFiles();
@@ -234,17 +290,17 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
234
290
  state.tracker.clearChangedFiles();
235
291
  const summary = summarizeGate(report);
236
292
  if (!report.ran) {
237
- await state.log("debug", summary);
293
+ await safeLog(state, "debug", summary);
238
294
  return;
239
295
  }
240
296
  if (report.ok) {
241
- await state.log("info", summary);
297
+ await safeLog(state, "info", summary);
242
298
  return;
243
299
  }
244
300
  // The gate cannot physically block on session.idle (the turn already
245
301
  // ended), so failure visibility is the enforcement mechanism.
246
302
  const level = state.config.gate.block_on_failure ? "error" : "warn";
247
- await state.log(level, summary, {
303
+ await safeLog(state, level, summary, {
248
304
  failedSteps: report.failedSteps.map((step) => ({
249
305
  name: step.name,
250
306
  command: step.command?.join(" "),
@@ -259,6 +315,7 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
259
315
  }
260
316
  export const devFramework = async (ctx) => {
261
317
  const log = createLogger(ctx.client);
318
+ fallbackLog = log;
262
319
  let config;
263
320
  try {
264
321
  config = loadConfig(ctx.directory);
@@ -278,10 +335,12 @@ export const devFramework = async (ctx) => {
278
335
  }
279
336
  return {};
280
337
  }
281
- // The off profile registers no hooks at all.
282
- if (config.profile === "off") {
283
- return {};
284
- }
338
+ // Hooks are now registered for every profile; each enforcement hook gates its
339
+ // own behavior by `state.config.profile` (off => no-op). Registering always
340
+ // guarantees HookState.log is populated at init, so a runtime `off` -> `standard`
341
+ // switch (via /df-profile) takes effect on the next hook call via
342
+ // reloadConfigIfChanged — no restart required — and a hook can never crash on a
343
+ // missing `log` (see safeLog).
285
344
  setBaseDirectory(ctx.directory);
286
345
  const { constitution, warning } = await loadConstitution(config, ctx.directory);
287
346
  if (warning) {
@@ -43,3 +43,7 @@ export declare function setSessionDirectory(sessionID: string, directory: string
43
43
  export declare function getDirectoryForSession(sessionID: string): string | null;
44
44
  /** Forget a session's directory mapping (called on `session.deleted`). */
45
45
  export declare function clearSessionDirectory(sessionID: string): void;
46
+ /** Reset all in-memory registries. Intended for test cleanup between
47
+ * test runs so stale session-to-directory mappings do not bleed
48
+ * `getStateForSession` into the next test. */
49
+ export declare function resetRegistry(): void;
package/dist/registry.js CHANGED
@@ -58,3 +58,11 @@ export function getDirectoryForSession(sessionID) {
58
58
  export function clearSessionDirectory(sessionID) {
59
59
  sessionToDirectory.delete(sessionID);
60
60
  }
61
+ /** Reset all in-memory registries. Intended for test cleanup between
62
+ * test runs so stale session-to-directory mappings do not bleed
63
+ * `getStateForSession` into the next test. */
64
+ export function resetRegistry() {
65
+ sessionToDirectory.clear();
66
+ hookRegistry.clear();
67
+ activeDirectory = null;
68
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-dev-framework",
3
- "version": "0.1.27",
3
+ "version": "0.1.29",
4
4
  "description": "OpenCode plugin that enforces project-specific quality gates during AI coding sessions",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -41,7 +41,12 @@
41
41
  "lint:fix": "biome lint --write .",
42
42
  "format:check": "biome format .",
43
43
  "format:fix": "biome format --write .",
44
- "lint:md": "markdownlint-cli2 \"**/*.md\""
44
+ "lint:md": "markdownlint-cli2 \"**/*.md\"",
45
+ "release": "./scripts/release.sh",
46
+ "release:patch": "./scripts/release.sh patch",
47
+ "release:minor": "./scripts/release.sh minor",
48
+ "release:major": "./scripts/release.sh major",
49
+ "dev:clean": "rm -rf ~/.cache/opencode/packages/opencode-dev-framework* && npm run build"
45
50
  },
46
51
  "keywords": [
47
52
  "opencode",