opencode-dev-framework 0.1.28 → 0.2.2

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/dist/index.js CHANGED
@@ -1,15 +1,19 @@
1
1
  /**
2
- * opencode-dev-framework plugin entry point.
2
+ * opencode-dev-framework V2 plugin entry point.
3
3
  *
4
- * Wired so far:
5
- * - tool.execute.before -> protected-path / dangerous-command guardrails
6
- * - event (file.edited) -> per-edit lint + changed-file tracking
7
- * - event (session.idle) -> completion gate fallback (advisory logging)
8
- * - experimental.chat.system.transform -> constitution injection + session mapping
9
- * - experimental.session.stopping -> blocking completion gate (OpenCode >= PR #41811)
10
- * - config hook -> registers /df-profile and /df-verify prompt commands
11
- * - command.execute.before -> handles /df-profile, /df-verify, and unknown /df-*
4
+ * V2 framework (opencode v2): Plugin.define({ id, setup(ctx) })
5
+ * - ctx.session.hook("context", ...) -> constitution injection
6
+ * - ctx.tool.hook("execute.before", ...) -> guardrails
7
+ * - ctx.event.subscribe() -> file tracking + gate enforcement via re-prompt
8
+ * - ctx.tool.transform(...) -> custom tools
9
+ * - ctx.command.transform(...) -> slash commands (optional)
10
+ *
11
+ * Gate enforcement: no synchronous `session.stopping`. On `session.idle`
12
+ * / `session.status:idle` we run the gate and if it fails inside budget we
13
+ * call `ctx.session.prompt({ sessionID, text: stoppingMessage })` to wake the
14
+ * agent — async re-injection preserving the enforcement intent (see docs/plans/08-notes).
12
15
  */
16
+ import { Plugin } from "@opencode/plugin";
13
17
  import { stat } from "node:fs/promises";
14
18
  import { join } from "node:path";
15
19
  import { clearConfigCache, loadConfig } from "./config.js";
@@ -18,306 +22,474 @@ import { runCommand } from "./host.js";
18
22
  import { detectPreCommitAvailability, isLintFailure, lintFile, summarizeLint } from "./lint.js";
19
23
  import { createLogger } from "./logger.js";
20
24
  import { checkToolCall } from "./protect.js";
21
- import { clearSessionDirectory, getHookState, getStateForSession, setBaseDirectory, setHookState, setSessionDirectory, } from "./registry.js";
22
- import { injectConstitution, loadConstitution } from "./rules.js";
23
- import { buildTools } from "./tools.js";
24
- /**
25
- * Module-level fallback logger, captured at plugin init. `safeLog` uses it when
26
- * a hook's `HookState.log` is missing or was stripped, so a logging failure can
27
- * never crash a hook. The original `state.log is not a function` error (seen when
28
- * switching `off` -> `standard` at runtime) happened because a hook fired against
29
- * a `HookState` whose `log` was never populated.
30
- */
25
+ import { loadConstitution } from "./rules.js";
26
+ let activeState = null;
31
27
  let fallbackLog = async () => { };
32
28
  function safeLog(state, level, message, extra) {
33
- const fn = typeof state.log === "function" ? state.log : fallbackLog;
29
+ const fn = state && typeof state.log === "function" ? state.log : fallbackLog;
34
30
  return fn(level, message, extra);
35
31
  }
36
- /**
37
- * Reload the in-memory config if the config file on disk changed since we last
38
- * loaded it. This makes out-of-process edits (e.g. a `/df-profile` change made
39
- * from the TUI module, which writes the file directly) take effect on the next
40
- * enforcement hook without restarting OpenCode.
41
- */
42
32
  async function reloadConfigIfChanged(state) {
43
- const configPath = join(state.directory, ".opencode-dev-framework.yml");
44
- try {
45
- const stats = await stat(configPath);
46
- if (state.configMtime !== undefined && state.configMtime === stats.mtimeMs) {
47
- return;
33
+ const primary = join(state.directory, ".opencode-dev-framework.yml");
34
+ const fallback = join(state.directory, ".dev-framework.yml");
35
+ // check both names; stat whichever exists
36
+ let configPath = null;
37
+ let mtime;
38
+ for (const p of [primary, fallback]) {
39
+ try {
40
+ const s = await stat(p);
41
+ configPath = p;
42
+ mtime = s.mtimeMs;
43
+ break;
44
+ }
45
+ catch {
46
+ // continue
48
47
  }
48
+ }
49
+ if (!configPath || mtime === undefined) {
50
+ return;
51
+ }
52
+ if (state.configMtime !== undefined && state.configMtime === mtime) {
53
+ return;
54
+ }
55
+ try {
49
56
  clearConfigCache();
50
57
  const next = loadConfig(state.directory);
51
58
  const { constitution } = await loadConstitution(next, state.directory);
52
59
  state.config = next;
53
60
  state.constitution = constitution;
54
- state.configMtime = stats.mtimeMs;
61
+ state.configMtime = mtime;
55
62
  }
56
63
  catch {
57
- // Config file missing/unreadable — keep the current state.
64
+ // keep current state on read failure
58
65
  }
59
66
  }
60
- /**
61
- * Build the plugin's hooks and custom tools. Exported (rather than inlined in
62
- * the plugin) so tests can inject a stubbed command runner and tracker.
63
- */
64
- export function buildHooks(ctx, config, log, run = runCommand, tracker = createChangedFileTracker(), constitution = null, configMtime) {
65
- // All hook state — including the project directory — lives in the registry
66
- // and is looked up at call time. OpenCode's Effect runtime stripped closure
67
- // captures in production (config/log/run came back undefined), so hooks must
68
- // not rely on variables from this scope.
69
- const showToast = (message, variant = "info") => {
67
+ async function runGateVerdict(state, _sessionID) {
68
+ if (!state.config.gate || state.config.profile === "off") {
69
+ return { decision: "pass" };
70
+ }
71
+ const changedFiles = state.tracker.getChangedFiles();
72
+ const report = await runGate(state.run, state.config, changedFiles, { cwd: state.directory });
73
+ if (!report.ran || report.ok) {
74
+ state.tracker.clearChangedFiles();
75
+ state.blockCounts.delete(_sessionID);
76
+ return { decision: "pass" };
77
+ }
78
+ const maxBlocks = state.config.gate.max_blocks ?? 3;
79
+ const blockCount = (state.blockCounts.get(_sessionID) ?? 0) + 1;
80
+ state.blockCounts.set(_sessionID, blockCount);
81
+ if (blockCount > maxBlocks) {
82
+ state.tracker.clearChangedFiles();
83
+ await safeLog(state, "warn", `completion gate has blocked ${maxBlocks} times; standing down but checks are still failing`, {
84
+ failedSteps: report.failedSteps.map((s) => s.name),
85
+ });
86
+ return { decision: "standdown", failedSteps: report.failedSteps.map((s) => s.name) };
87
+ }
88
+ const summary = summarizeGate(report);
89
+ await safeLog(state, "error", summary, { failedSteps: report.failedSteps.map((s) => s.name) });
90
+ return { decision: "blocked", summary, blockCount, maxBlocks };
91
+ }
92
+ function stoppingMessage(verdict) {
93
+ return (`opencode-dev-framework completion gate blocked you from finishing (block ${verdict.blockCount}/${verdict.maxBlocks}). ` +
94
+ `The following checks failed:\n\n${verdict.summary}\n\n` +
95
+ `Fix the underlying cause and continue. Do NOT disable, skip, or weaken these checks to make them pass.`);
96
+ }
97
+ // Helpers to normalize V2 event shapes (data vs properties vs direct)
98
+ function getEventSessionID(event) {
99
+ const e = event;
100
+ // try common locations
101
+ if (typeof e.sessionID === "string")
102
+ return e.sessionID;
103
+ const data = (e.data ?? e.properties ?? e.payload);
104
+ if (data && typeof data.sessionID === "string")
105
+ return data.sessionID;
106
+ if (data && typeof data.session_id === "string")
107
+ return data.session_id;
108
+ // session.status carries sessionID at data.sessionID
109
+ if (e.properties && typeof e.properties.sessionID === "string") {
110
+ return e.properties.sessionID;
111
+ }
112
+ return undefined;
113
+ }
114
+ function getEventFilePath(event) {
115
+ const e = event;
116
+ const data = (e.data ?? e.properties ?? e.payload);
117
+ if (data && typeof data.file === "string")
118
+ return data.file;
119
+ if (data && typeof data.filePath === "string")
120
+ return data.filePath;
121
+ if (typeof e.file === "string")
122
+ return e.file;
123
+ return undefined;
124
+ }
125
+ function isIdleEvent(event) {
126
+ if (event.type === "session.idle")
127
+ return true;
128
+ if (event.type === "session.status") {
129
+ const d = event.data;
130
+ const p = event.properties;
131
+ const statusType = d?.status?.type ??
132
+ p?.status?.type ??
133
+ event.status?.type;
134
+ return statusType === "idle";
135
+ }
136
+ if (event.type === "session.status") {
137
+ // also handle flattened shape where data is {status: "idle"}? check
138
+ const d2 = event.data;
139
+ if (d2?.status === "idle")
140
+ return true;
141
+ }
142
+ return false;
143
+ }
144
+ function isFilesystemChangedEvent(type) {
145
+ return type === "filesystem.changed" || type === "file.edited" || type === "file.changed";
146
+ }
147
+ function isSessionDeletedEvent(type) {
148
+ return type === "session.deleted";
149
+ }
150
+ // ---------------------------------------------------------------------------
151
+ // V2 Plugin definition
152
+ // ---------------------------------------------------------------------------
153
+ const plugin = Plugin.define({
154
+ id: "opencode-dev-framework",
155
+ async setup(ctx) {
156
+ const log = createLogger();
157
+ fallbackLog = log;
158
+ const directory = ctx.location.directory;
159
+ let config;
70
160
  try {
71
- const tui = ctx.client.tui;
72
- tui?.showToast?.({ title: "opencode-dev-framework", message, variant });
161
+ config = loadConfig(directory);
73
162
  }
74
- catch {
75
- // TUI may be unavailable; the log line is enough.
163
+ catch (error) {
164
+ const message = error instanceof Error ? error.message : String(error);
165
+ await log("error", message, { directory });
166
+ // No client.app.log in V2 — stderr is enough
167
+ return;
76
168
  }
77
- };
78
- setHookState(ctx.directory, {
79
- directory: ctx.directory,
80
- config,
81
- log,
82
- run,
83
- tracker,
84
- constitution,
85
- blockCounts: new Map(),
86
- showToast,
87
- configMtime,
88
- });
89
- return {
90
- tool: buildTools(ctx),
91
- config: async (opencodeConfig) => {
92
- const typedConfig = opencodeConfig;
93
- const state = getHookState(ctx.directory);
94
- if (state) {
95
- // OpenCode's native `permission` is a per-agent tool-to-mode object
96
- // (e.g. `{ edit: "deny", bash: "deny" }`), not an array. Adopt it when
97
- // it is a plain object; anything else (array, string, undefined) is
98
- // ignored so the guardrail falls back to its own evaluation. See
99
- // hostDenies in protect.ts.
100
- const perm = typedConfig.permission;
101
- state.hostPermissions =
102
- perm !== undefined && typeof perm === "object" && !Array.isArray(perm) ? perm : undefined;
103
- }
104
- // `df-profile`, `df-verify`, `df-status`, and `df-help` are all registered
105
- // as TUI commands (keymap layer with `slashName`) in `tui.tsx`. TUI
106
- // commands never insert text into the chat stream, so they cannot leak
107
- // into a model turn. No server prompt command is registered here — such
108
- // commands always produce a model turn, which is exactly what we avoid.
109
- },
110
- "experimental.chat.system.transform": async (input, output) => {
111
- const state = getStateForSession(input.sessionID);
112
- if (!state) {
113
- return;
169
+ const { constitution, warning } = await loadConstitution(config, directory);
170
+ if (warning) {
171
+ await log("warn", warning);
172
+ }
173
+ let configMtime;
174
+ for (const name of [".opencode-dev-framework.yml", ".dev-framework.yml"]) {
175
+ try {
176
+ configMtime = (await stat(join(directory, name))).mtimeMs;
177
+ break;
114
178
  }
115
- await reloadConfigIfChanged(state);
116
- if (input.sessionID) {
117
- setSessionDirectory(input.sessionID, state.directory);
179
+ catch {
180
+ // continue
118
181
  }
119
- if (state.config.profile === "off") {
182
+ }
183
+ const tracker = createChangedFileTracker();
184
+ const state = {
185
+ directory,
186
+ config,
187
+ log,
188
+ run: runCommand,
189
+ tracker,
190
+ constitution,
191
+ blockCounts: new Map(),
192
+ configMtime,
193
+ };
194
+ activeState = state;
195
+ // 1) Constitution injection — per model request (V1: experimental.chat.system.transform -> V2: session.hook("context", ...))
196
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
197
+ await ctx.session.hook("context", async (event) => {
198
+ if (!activeState)
120
199
  return;
121
- }
122
- const next = injectConstitution(output.system, state.constitution);
123
- if (next !== output.system) {
124
- await safeLog(state, "info", "constitution injected into system prompt");
125
- output.system = next;
126
- }
127
- },
128
- "tool.execute.before": async (input, output) => {
129
- const state = getStateForSession(input.sessionID);
130
- if (!state) {
200
+ await reloadConfigIfChanged(activeState);
201
+ if (activeState.config.profile === "off")
202
+ return;
203
+ if (!activeState.constitution)
204
+ return;
205
+ // V2 system is Array<SystemPart> {type:"text", text:string}
206
+ const already = event.system.some((part) => part.text.includes(activeState.constitution));
207
+ if (already)
208
+ return;
209
+ event.system.push({
210
+ type: "text",
211
+ text: activeState.constitution,
212
+ });
213
+ await safeLog(activeState, "info", "constitution injected into system prompt");
214
+ });
215
+ // Also hook other request kinds so the reminder is not missed on title/generate
216
+ // (no-op if model doesn't need it; cheap)
217
+ for (const kind of ["generate", "compaction"]) {
218
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
219
+ await ctx.session.hook(kind, async (event) => {
220
+ if (!activeState || activeState.config.profile === "off" || !activeState.constitution)
221
+ return;
222
+ // generate/compaction also have system — inject similarly if present
223
+ const ev = event;
224
+ if (!ev.system)
225
+ return;
226
+ const already = ev.system.some((p) => p.text.includes(activeState.constitution));
227
+ if (!already)
228
+ ev.system.push({ type: "text", text: activeState.constitution });
229
+ });
230
+ }
231
+ // 2) Guardrails — tool execution blocking (V1: tool.execute.before -> V2: ctx.tool.hook("execute.before", ...))
232
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
233
+ await ctx.tool.hook("execute.before", async (event) => {
234
+ if (!activeState) {
131
235
  throw new Error("[opencode-dev-framework] plugin state is not available; guardrail cannot evaluate this tool call");
132
236
  }
133
- await reloadConfigIfChanged(state);
134
- if (state.config.profile === "off") {
237
+ await reloadConfigIfChanged(activeState);
238
+ if (activeState.config.profile === "off")
135
239
  return;
136
- }
137
- const result = checkToolCall(state.config, input.tool, output.args, state.directory, state.hostPermissions);
138
- if (result.decision === "allow") {
240
+ // V2 event shapes: { tool, sessionID, agent, messageID, id, input: unknown }
241
+ const toolName = event.tool;
242
+ const input = event.input;
243
+ const sessionID = event.sessionID;
244
+ // hostPermissions: not available in V2 permission model; pass undefined (conservative — still guard)
245
+ const result = checkToolCall(activeState.config, toolName, input, activeState.directory, undefined);
246
+ if (result.decision === "allow")
139
247
  return;
140
- }
141
248
  const message = result.reason ?? "blocked by guardrails";
142
- const extra = {
143
- tool: input.tool,
144
- sessionID: input.sessionID,
145
- pattern: result.matchedPattern,
146
- };
249
+ const extra = { tool: toolName, sessionID, pattern: result.matchedPattern };
147
250
  if (result.decision === "warn") {
148
- await safeLog(state, "warn", message, extra);
251
+ await safeLog(activeState, "warn", message, extra);
149
252
  return;
150
253
  }
151
- await safeLog(state, "error", message, extra);
254
+ await safeLog(activeState, "error", message, extra);
152
255
  throw new Error(`[opencode-dev-framework] ${message}`);
153
- },
154
- "experimental.session.stopping": async (input, output) => {
155
- const state = getStateForSession(input.sessionID);
156
- if (!state) {
157
- return;
158
- }
159
- await reloadConfigIfChanged(state);
160
- if (!state.config.gate || state.config.profile === "off") {
161
- return;
162
- }
163
- const changedFiles = state.tracker.getChangedFiles();
164
- const report = await runGate(state.run, state.config, changedFiles, { cwd: state.directory });
165
- if (!report.ran || report.ok) {
166
- state.tracker.clearChangedFiles();
167
- state.blockCounts.delete(input.sessionID);
168
- return;
169
- }
170
- const maxBlocks = state.config.gate.max_blocks ?? 3;
171
- const blockCount = (state.blockCounts.get(input.sessionID) ?? 0) + 1;
172
- state.blockCounts.set(input.sessionID, blockCount);
173
- if (blockCount > maxBlocks) {
174
- // Standing down: clear the tracker so the session.idle fallback does
175
- // not re-run the same failing gate commands a second time.
176
- state.tracker.clearChangedFiles();
177
- await safeLog(state, "warn", `completion gate has blocked ${maxBlocks} times; standing down but checks are still failing`, { failedSteps: report.failedSteps.map((step) => step.name) });
178
- return;
179
- }
180
- const summary = summarizeGate(report);
181
- await safeLog(state, "error", summary, {
182
- failedSteps: report.failedSteps.map((step) => step.name),
183
- });
184
- output.context.push(`opencode-dev-framework completion gate blocked you from finishing (block ${blockCount}/${maxBlocks}). ` +
185
- `The following checks failed:\n\n${summary}\n\n` +
186
- `Fix the underlying cause and continue. Do NOT disable, skip, or weaken these checks to make them pass.`);
187
- },
188
- event: async ({ event }) => {
189
- // session.deleted must run even without hook state so the session map
190
- // does not grow unboundedly.
191
- if (event.type === "session.deleted") {
192
- clearSessionDirectory(event.properties.info.id);
193
- return;
194
- }
195
- const sessionID = event.type === "session.idle"
196
- ? event.properties.sessionID
197
- : undefined;
198
- const state = getStateForSession(sessionID);
199
- if (!state) {
200
- return;
201
- }
202
- await reloadConfigIfChanged(state);
203
- if (state.config.profile === "off") {
204
- return;
205
- }
206
- if (event.type === "file.edited") {
207
- const filePath = event.properties.file;
208
- state.tracker.add(filePath, state.directory);
209
- if (!state.config.on_edit.lint) {
210
- return;
211
- }
212
- if (state.config.precommit === "auto" && state.precommitAvailable === undefined) {
213
- state.precommitAvailable = await detectPreCommitAvailability(state.run, state.directory);
214
- }
215
- const outcome = await lintFile(state.run, state.config, filePath, {
216
- cwd: state.directory,
217
- timeout: state.config.gate?.timeout,
218
- precommitAvailable: state.precommitAvailable,
219
- });
220
- if (outcome.skipped) {
221
- await safeLog(state, "debug", summarizeLint(outcome), {
222
- filePath,
223
- reason: outcome.reason,
256
+ });
257
+ // 3) Custom tools — V2: ctx.tool.transform(editor => editor.add(...))
258
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
259
+ await ctx.tool.transform((editor) => {
260
+ editor.add({
261
+ name: "dev_framework_init",
262
+ description: "Scaffold opencode-dev-framework project files (agents, skills, commands, default config) into the current project. Missing files are created; existing files are skipped unless overwrite is true.",
263
+ input: {
264
+ type: "object",
265
+ properties: {
266
+ directory: {
267
+ type: "string",
268
+ description: "Target project directory (defaults to current project)",
269
+ },
270
+ overwrite: {
271
+ type: "boolean",
272
+ description: "Overwrite existing files that differ from templates",
273
+ },
274
+ },
275
+ additionalProperties: false,
276
+ },
277
+ async execute(input) {
278
+ const { installTemplates, writeDetectedConfig } = await import("./installer.js");
279
+ const args = input;
280
+ const targetDir = args.directory ?? directory;
281
+ const result = await installTemplates(targetDir, {
282
+ overwriteExisting: args.overwrite ?? false,
283
+ skipExisting: !(args.overwrite ?? false),
224
284
  });
225
- return;
226
- }
227
- if (!isLintFailure(outcome)) {
228
- await safeLog(state, "info", summarizeLint(outcome), { filePath });
229
- return;
230
- }
231
- const summary = summarizeLint(outcome);
232
- await safeLog(state, "error", summary, {
233
- filePath,
234
- command: outcome.command?.join(" "),
235
- stdout: outcome.result?.stdout,
236
- stderr: outcome.result?.stderr,
237
- });
238
- // In strict mode lint failures throw. Note: file.edited is an event
239
- // notification (the edit already happened), so this cannot undo the
240
- // edit — it surfaces the failure loudly to the session.
241
- if (state.config.profile === "strict") {
242
- throw new Error(`[opencode-dev-framework] ${summary}`);
285
+ const configResult = await writeDetectedConfig(targetDir, {
286
+ overwriteExisting: args.overwrite ?? false,
287
+ skipExisting: !(args.overwrite ?? false),
288
+ });
289
+ const lines = [
290
+ `Installed opencode-dev-framework templates into ${targetDir}.`,
291
+ `Created: ${result.created.length} file(s)`,
292
+ `Overwritten: ${result.overwritten.length} file(s)`,
293
+ `Skipped: ${result.skipped.length} file(s)`,
294
+ `Config: ${configResult.action}`,
295
+ ];
296
+ if (result.created.length > 0)
297
+ lines.push("", "Created files:", ...result.created.map((f) => `- ${f}`));
298
+ if (result.overwritten.length > 0)
299
+ lines.push("", "Overwritten files:", ...result.overwritten.map((f) => `- ${f}`));
300
+ return { content: lines.join("\n") };
301
+ },
302
+ });
303
+ editor.add({
304
+ name: "dev_framework_set_profile",
305
+ description: "Change the opencode-dev-framework profile (off, advisory, standard, strict) for the current project and apply it immediately without restarting OpenCode.",
306
+ input: {
307
+ type: "object",
308
+ properties: {
309
+ profile: {
310
+ type: "string",
311
+ description: "New profile: off, advisory, standard, or strict",
312
+ },
313
+ directory: {
314
+ type: "string",
315
+ description: "Project directory (defaults to current project)",
316
+ },
317
+ },
318
+ required: ["profile"],
319
+ additionalProperties: false,
320
+ },
321
+ async execute(input) {
322
+ const { clearConfigCache: ccc, loadConfig: lc } = await import("./config.js");
323
+ const { changeProfile } = await import("./commands.js");
324
+ const { loadConstitution: lc2 } = await import("./rules.js");
325
+ const args = input;
326
+ const targetDir = args.directory ?? directory;
327
+ const profile = args.profile.trim().toLowerCase();
328
+ const valid = ["off", "advisory", "standard", "strict"];
329
+ if (!valid.includes(profile)) {
330
+ return {
331
+ content: `Invalid profile "${args.profile}". Valid values: ${valid.join(", ")}.`,
332
+ };
333
+ }
334
+ const message = await changeProfile(targetDir, profile);
335
+ ccc();
336
+ const newConfig = lc(targetDir);
337
+ const { constitution: newConstitution } = await lc2(newConfig, targetDir);
338
+ if (activeState && activeState.directory === targetDir) {
339
+ activeState.config = newConfig;
340
+ activeState.constitution = newConstitution;
341
+ }
342
+ return { content: `${message} Change applied immediately.` };
343
+ },
344
+ });
345
+ editor.add({
346
+ name: "dev_framework_status",
347
+ 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.",
348
+ input: {
349
+ type: "object",
350
+ properties: {
351
+ directory: {
352
+ type: "string",
353
+ description: "Project directory (defaults to current project)",
354
+ },
355
+ },
356
+ additionalProperties: false,
357
+ },
358
+ async execute(input) {
359
+ const { renderStatus } = await import("./format-status.js");
360
+ const args = input;
361
+ const targetDir = args.directory ?? directory;
362
+ const cfg = activeState && activeState.directory === targetDir
363
+ ? activeState.config
364
+ : loadConfig(targetDir);
365
+ // renderStatus expects HookState? pass activeState
366
+ return {
367
+ content: renderStatus(cfg, activeState),
368
+ };
369
+ },
370
+ });
371
+ });
372
+ // 4) Event subscription — file tracking + gate enforcement (V1: event hook)
373
+ // Keeps the completion gate intent without session.stopping: on idle, run gate;
374
+ // on failure inside budget, re-prompt the session (async block).
375
+ const controller = new AbortController();
376
+ const eventLoop = (async () => {
377
+ try {
378
+ for await (const rawEvent of ctx.event.subscribe({ signal: controller.signal })) {
379
+ const event = rawEvent;
380
+ const type = event.type;
381
+ if (isSessionDeletedEvent(type)) {
382
+ // session.deleted: cleanup blockCounts (and tracker if needed)
383
+ const sid = getEventSessionID(event);
384
+ if (sid && activeState)
385
+ activeState.blockCounts.delete(sid);
386
+ continue;
387
+ }
388
+ if (isFilesystemChangedEvent(type)) {
389
+ if (!activeState)
390
+ continue;
391
+ await reloadConfigIfChanged(activeState);
392
+ if (activeState.config.profile === "off")
393
+ continue;
394
+ const filePath = getEventFilePath(event);
395
+ if (!filePath)
396
+ continue;
397
+ activeState.tracker.add(filePath, activeState.directory);
398
+ // per-edit lint (V1: event file.edited -> lintFile)
399
+ if (!activeState.config.on_edit.lint)
400
+ continue;
401
+ if (activeState.config.precommit === "auto" &&
402
+ activeState.precommitAvailable === undefined) {
403
+ activeState.precommitAvailable = await detectPreCommitAvailability(activeState.run, activeState.directory);
404
+ }
405
+ const outcome = await lintFile(activeState.run, activeState.config, filePath, {
406
+ cwd: activeState.directory,
407
+ timeout: activeState.config.gate?.timeout,
408
+ precommitAvailable: activeState.precommitAvailable,
409
+ });
410
+ if (outcome.skipped) {
411
+ await safeLog(activeState, "debug", summarizeLint(outcome), {
412
+ filePath,
413
+ reason: outcome.reason,
414
+ });
415
+ continue;
416
+ }
417
+ if (!isLintFailure(outcome)) {
418
+ await safeLog(activeState, "info", summarizeLint(outcome), { filePath });
419
+ continue;
420
+ }
421
+ const summary = summarizeLint(outcome);
422
+ await safeLog(activeState, "error", summary, {
423
+ filePath,
424
+ command: outcome.command?.join(" "),
425
+ stdout: outcome.result?.stdout,
426
+ stderr: outcome.result?.stderr,
427
+ });
428
+ if (activeState.config.profile === "strict") {
429
+ // Event handlers cannot throw to block the edit (edit already happened), but we log loudly.
430
+ // In V2 we also have the tool hook to block before; this is advisory.
431
+ }
432
+ continue;
433
+ }
434
+ if (isIdleEvent(event)) {
435
+ if (!activeState)
436
+ continue;
437
+ await reloadConfigIfChanged(activeState);
438
+ if (activeState.config.profile === "off")
439
+ continue;
440
+ if (!activeState.config.gate) {
441
+ await safeLog(activeState, "warn", "plugin config is incomplete (missing gate section), skipping completion gate", {
442
+ directory: activeState.directory,
443
+ });
444
+ continue;
445
+ }
446
+ const sessionID = getEventSessionID(event);
447
+ if (!sessionID)
448
+ continue;
449
+ const verdict = await runGateVerdict(activeState, sessionID);
450
+ if (verdict.decision === "pass")
451
+ continue;
452
+ if (verdict.decision === "standdown") {
453
+ // already logged in runGateVerdict; do not re-prompt
454
+ continue;
455
+ }
456
+ // blocked -> re-prompt the session (V2 replacement for session.stopping output.stop=false)
457
+ const message = stoppingMessage(verdict);
458
+ try {
459
+ // Prefer prompt (creates a user turn and wakes the agent); fallback to synthetic if prompt not available
460
+ if (typeof ctx.session.prompt === "function") {
461
+ await ctx.session.prompt({ sessionID, text: message });
462
+ }
463
+ else if (typeof ctx.session.synthetic === "function") {
464
+ await ctx.session.synthetic({ sessionID, text: message });
465
+ }
466
+ else {
467
+ await safeLog(activeState, "error", `gate blocked but no session prompt API available: ${message}`);
468
+ }
469
+ await safeLog(activeState, "info", `completion gate re-prompted session ${sessionID} (block ${verdict.blockCount}/${verdict.maxBlocks})`);
470
+ }
471
+ catch (err) {
472
+ await safeLog(activeState, "error", `failed to re-prompt session ${sessionID} after gate block: ${String(err)}`, {
473
+ sessionID,
474
+ });
475
+ }
476
+ }
243
477
  }
244
- return;
245
478
  }
246
- if (event.type === "session.idle") {
247
- if (!state.config.gate) {
248
- await safeLog(state, "warn", "plugin config is incomplete (missing gate section), skipping completion gate", { directory: state.directory });
249
- return;
250
- }
251
- const changedFiles = state.tracker.getChangedFiles();
252
- const report = await runGate(state.run, state.config, changedFiles, {
253
- cwd: state.directory,
254
- });
255
- state.tracker.clearChangedFiles();
256
- const summary = summarizeGate(report);
257
- if (!report.ran) {
258
- await safeLog(state, "debug", summary);
259
- return;
260
- }
261
- if (report.ok) {
262
- await safeLog(state, "info", summary);
479
+ catch (err) {
480
+ if (err?.name === "AbortError") {
481
+ // normal on dispose
263
482
  return;
264
483
  }
265
- // The gate cannot physically block on session.idle (the turn already
266
- // ended), so failure visibility is the enforcement mechanism.
267
- const level = state.config.gate.block_on_failure ? "error" : "warn";
268
- await safeLog(state, level, summary, {
269
- failedSteps: report.failedSteps.map((step) => ({
270
- name: step.name,
271
- command: step.command?.join(" "),
272
- exitCode: step.result?.exitCode,
273
- timedOut: step.result?.timedOut,
274
- stderr: step.result?.stderr,
275
- })),
276
- });
484
+ await safeLog(activeState, "error", `event loop error: ${String(err)}`);
277
485
  }
278
- },
279
- };
280
- }
281
- export const devFramework = async (ctx) => {
282
- const log = createLogger(ctx.client);
283
- fallbackLog = log;
284
- let config;
285
- try {
286
- config = loadConfig(ctx.directory);
287
- }
288
- catch (error) {
289
- const message = error instanceof Error ? error.message : String(error);
290
- await log("error", message, { directory: ctx.directory });
291
- const clientTui = ctx.client.tui;
292
- try {
293
- await clientTui?.showToast?.({
294
- type: "error",
295
- message: `[opencode-dev-framework] ${message}`,
296
- });
297
- }
298
- catch {
299
- // TUI may not be available; the log line is enough.
300
- }
301
- return {};
302
- }
303
- // Hooks are now registered for every profile; each enforcement hook gates its
304
- // own behavior by `state.config.profile` (off => no-op). Registering always
305
- // guarantees HookState.log is populated at init, so a runtime `off` -> `standard`
306
- // switch (via /df-profile) takes effect on the next hook call via
307
- // reloadConfigIfChanged — no restart required — and a hook can never crash on a
308
- // missing `log` (see safeLog).
309
- setBaseDirectory(ctx.directory);
310
- const { constitution, warning } = await loadConstitution(config, ctx.directory);
311
- if (warning) {
312
- await log("warn", warning);
313
- }
314
- let configMtime;
315
- try {
316
- configMtime = (await stat(join(ctx.directory, ".opencode-dev-framework.yml"))).mtimeMs;
317
- }
318
- catch {
319
- // Config file may not exist yet; reloadConfigIfChanged will pick it up.
320
- }
321
- return buildHooks(ctx, config, log, runCommand, createChangedFileTracker(), constitution, configMtime);
322
- };
323
- export default devFramework;
486
+ })();
487
+ // Ensure the loop doesn't block setup
488
+ void eventLoop;
489
+ return () => {
490
+ controller.abort();
491
+ activeState = null;
492
+ };
493
+ },
494
+ });
495
+ export default plugin;