opencode-dev-framework 0.1.29 → 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,16 +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
- * - session.stopping -> same blocking gate, new contract (OpenCode PR #44712)
11
- * - config hook -> registers /df-profile and /df-verify prompt commands
12
- * - 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).
13
15
  */
16
+ import { Plugin } from "@opencode/plugin";
14
17
  import { stat } from "node:fs/promises";
15
18
  import { join } from "node:path";
16
19
  import { clearConfigCache, loadConfig } from "./config.js";
@@ -19,54 +22,49 @@ import { runCommand } from "./host.js";
19
22
  import { detectPreCommitAvailability, isLintFailure, lintFile, summarizeLint } from "./lint.js";
20
23
  import { createLogger } from "./logger.js";
21
24
  import { checkToolCall } from "./protect.js";
22
- import { clearSessionDirectory, getHookState, getStateForSession, setBaseDirectory, setHookState, setSessionDirectory, } from "./registry.js";
23
- import { injectConstitution, loadConstitution } from "./rules.js";
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
- */
25
+ import { loadConstitution } from "./rules.js";
26
+ let activeState = null;
32
27
  let fallbackLog = async () => { };
33
28
  function safeLog(state, level, message, extra) {
34
- const fn = typeof state.log === "function" ? state.log : fallbackLog;
29
+ const fn = state && typeof state.log === "function" ? state.log : fallbackLog;
35
30
  return fn(level, message, extra);
36
31
  }
37
- /**
38
- * Reload the in-memory config if the config file on disk changed since we last
39
- * loaded it. This makes out-of-process edits (e.g. a `/df-profile` change made
40
- * from the TUI module, which writes the file directly) take effect on the next
41
- * enforcement hook without restarting OpenCode.
42
- */
43
32
  async function reloadConfigIfChanged(state) {
44
- const configPath = join(state.directory, ".opencode-dev-framework.yml");
45
- try {
46
- const stats = await stat(configPath);
47
- if (state.configMtime !== undefined && state.configMtime === stats.mtimeMs) {
48
- 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;
49
44
  }
45
+ catch {
46
+ // continue
47
+ }
48
+ }
49
+ if (!configPath || mtime === undefined) {
50
+ return;
51
+ }
52
+ if (state.configMtime !== undefined && state.configMtime === mtime) {
53
+ return;
54
+ }
55
+ try {
50
56
  clearConfigCache();
51
57
  const next = loadConfig(state.directory);
52
58
  const { constitution } = await loadConstitution(next, state.directory);
53
59
  state.config = next;
54
60
  state.constitution = constitution;
55
- state.configMtime = stats.mtimeMs;
61
+ state.configMtime = mtime;
56
62
  }
57
63
  catch {
58
- // Config file missing/unreadable — keep the current state.
64
+ // keep current state on read failure
59
65
  }
60
66
  }
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) {
67
+ async function runGateVerdict(state, _sessionID) {
70
68
  if (!state.config.gate || state.config.profile === "off") {
71
69
  return { decision: "pass" };
72
70
  }
@@ -74,285 +72,424 @@ async function runStoppingGate(state, sessionID) {
74
72
  const report = await runGate(state.run, state.config, changedFiles, { cwd: state.directory });
75
73
  if (!report.ran || report.ok) {
76
74
  state.tracker.clearChangedFiles();
77
- state.blockCounts.delete(sessionID);
75
+ state.blockCounts.delete(_sessionID);
78
76
  return { decision: "pass" };
79
77
  }
80
78
  const maxBlocks = state.config.gate.max_blocks ?? 3;
81
- const blockCount = (state.blockCounts.get(sessionID) ?? 0) + 1;
82
- state.blockCounts.set(sessionID, blockCount);
79
+ const blockCount = (state.blockCounts.get(_sessionID) ?? 0) + 1;
80
+ state.blockCounts.set(_sessionID, blockCount);
83
81
  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
82
  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) };
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) };
89
87
  }
90
88
  const summary = summarizeGate(report);
91
- await safeLog(state, "error", summary, {
92
- failedSteps: report.failedSteps.map((step) => step.name),
93
- });
89
+ await safeLog(state, "error", summary, { failedSteps: report.failedSteps.map((s) => s.name) });
94
90
  return { decision: "blocked", summary, blockCount, maxBlocks };
95
91
  }
96
- /** The continuation message both stopping hooks inject on a gate block. */
97
92
  function stoppingMessage(verdict) {
98
93
  return (`opencode-dev-framework completion gate blocked you from finishing (block ${verdict.blockCount}/${verdict.maxBlocks}). ` +
99
94
  `The following checks failed:\n\n${verdict.summary}\n\n` +
100
95
  `Fix the underlying cause and continue. Do NOT disable, skip, or weaken these checks to make them pass.`);
101
96
  }
102
- /**
103
- * Build the plugin's hooks and custom tools. Exported (rather than inlined in
104
- * the plugin) so tests can inject a stubbed command runner and tracker.
105
- */
106
- export function buildHooks(ctx, config, log, run = runCommand, tracker = createChangedFileTracker(), constitution = null, configMtime) {
107
- // All hook state — including the project directory — lives in the registry
108
- // and is looked up at call time. OpenCode's Effect runtime stripped closure
109
- // captures in production (config/log/run came back undefined), so hooks must
110
- // not rely on variables from this scope.
111
- const showToast = (message, variant = "info") => {
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;
112
160
  try {
113
- const tui = ctx.client.tui;
114
- tui?.showToast?.({ title: "opencode-dev-framework", message, variant });
161
+ config = loadConfig(directory);
115
162
  }
116
- catch {
117
- // 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;
118
168
  }
119
- };
120
- setHookState(ctx.directory, {
121
- directory: ctx.directory,
122
- config,
123
- log,
124
- run,
125
- tracker,
126
- constitution,
127
- blockCounts: new Map(),
128
- showToast,
129
- configMtime,
130
- });
131
- return {
132
- tool: buildTools(ctx),
133
- config: async (opencodeConfig) => {
134
- const typedConfig = opencodeConfig;
135
- const state = getHookState(ctx.directory);
136
- if (state) {
137
- // OpenCode's native `permission` is a per-agent tool-to-mode object
138
- // (e.g. `{ edit: "deny", bash: "deny" }`), not an array. Adopt it when
139
- // it is a plain object; anything else (array, string, undefined) is
140
- // ignored so the guardrail falls back to its own evaluation. See
141
- // hostDenies in protect.ts.
142
- const perm = typedConfig.permission;
143
- state.hostPermissions =
144
- perm !== undefined && typeof perm === "object" && !Array.isArray(perm) ? perm : undefined;
145
- }
146
- // `df-profile`, `df-verify`, `df-status`, and `df-help` are all registered
147
- // as TUI commands (keymap layer with `slashName`) in `tui.tsx`. TUI
148
- // commands never insert text into the chat stream, so they cannot leak
149
- // into a model turn. No server prompt command is registered here — such
150
- // commands always produce a model turn, which is exactly what we avoid.
151
- },
152
- "experimental.chat.system.transform": async (input, output) => {
153
- const state = getStateForSession(input.sessionID);
154
- if (!state) {
155
- 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;
156
178
  }
157
- await reloadConfigIfChanged(state);
158
- if (input.sessionID) {
159
- setSessionDirectory(input.sessionID, state.directory);
179
+ catch {
180
+ // continue
160
181
  }
161
- 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)
162
199
  return;
163
- }
164
- const next = injectConstitution(output.system, state.constitution);
165
- if (next !== output.system) {
166
- await safeLog(state, "info", "constitution injected into system prompt");
167
- output.system = next;
168
- }
169
- },
170
- "tool.execute.before": async (input, output) => {
171
- const state = getStateForSession(input.sessionID);
172
- 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) {
173
235
  throw new Error("[opencode-dev-framework] plugin state is not available; guardrail cannot evaluate this tool call");
174
236
  }
175
- await reloadConfigIfChanged(state);
176
- if (state.config.profile === "off") {
237
+ await reloadConfigIfChanged(activeState);
238
+ if (activeState.config.profile === "off")
177
239
  return;
178
- }
179
- const result = checkToolCall(state.config, input.tool, output.args, state.directory, state.hostPermissions);
180
- 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")
181
247
  return;
182
- }
183
248
  const message = result.reason ?? "blocked by guardrails";
184
- const extra = {
185
- tool: input.tool,
186
- sessionID: input.sessionID,
187
- pattern: result.matchedPattern,
188
- };
249
+ const extra = { tool: toolName, sessionID, pattern: result.matchedPattern };
189
250
  if (result.decision === "warn") {
190
- await safeLog(state, "warn", message, extra);
251
+ await safeLog(activeState, "warn", message, extra);
191
252
  return;
192
253
  }
193
- await safeLog(state, "error", message, extra);
254
+ await safeLog(activeState, "error", message, extra);
194
255
  throw new Error(`[opencode-dev-framework] ${message}`);
195
- },
196
- "experimental.session.stopping": async (input, output) => {
197
- const state = getStateForSession(input.sessionID);
198
- if (!state) {
199
- return;
200
- }
201
- await reloadConfigIfChanged(state);
202
- const verdict = await runStoppingGate(state, input.sessionID);
203
- if (verdict.decision !== "blocked") {
204
- return;
205
- }
206
- output.context.push(stoppingMessage(verdict));
207
- },
208
- "session.stopping": async (input, output) => {
209
- const state = getStateForSession(input.sessionID);
210
- if (!state) {
211
- return;
212
- }
213
- await reloadConfigIfChanged(state);
214
- const verdict = await runStoppingGate(state, input.sessionID);
215
- if (verdict.decision !== "blocked") {
216
- return;
217
- }
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);
222
- },
223
- event: async ({ event }) => {
224
- // session.deleted must run even without hook state so the session map
225
- // does not grow unboundedly.
226
- if (event.type === "session.deleted") {
227
- clearSessionDirectory(event.properties.info.id);
228
- return;
229
- }
230
- const sessionID = event.type === "session.idle"
231
- ? event.properties.sessionID
232
- : undefined;
233
- const state = getStateForSession(sessionID);
234
- if (!state) {
235
- return;
236
- }
237
- await reloadConfigIfChanged(state);
238
- if (state.config.profile === "off") {
239
- return;
240
- }
241
- if (event.type === "file.edited") {
242
- const filePath = event.properties.file;
243
- state.tracker.add(filePath, state.directory);
244
- if (!state.config.on_edit.lint) {
245
- return;
246
- }
247
- if (state.config.precommit === "auto" && state.precommitAvailable === undefined) {
248
- state.precommitAvailable = await detectPreCommitAvailability(state.run, state.directory);
249
- }
250
- const outcome = await lintFile(state.run, state.config, filePath, {
251
- cwd: state.directory,
252
- timeout: state.config.gate?.timeout,
253
- precommitAvailable: state.precommitAvailable,
254
- });
255
- if (outcome.skipped) {
256
- await safeLog(state, "debug", summarizeLint(outcome), {
257
- filePath,
258
- 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),
259
284
  });
260
- return;
261
- }
262
- if (!isLintFailure(outcome)) {
263
- await safeLog(state, "info", summarizeLint(outcome), { filePath });
264
- return;
265
- }
266
- const summary = summarizeLint(outcome);
267
- await safeLog(state, "error", summary, {
268
- filePath,
269
- command: outcome.command?.join(" "),
270
- stdout: outcome.result?.stdout,
271
- stderr: outcome.result?.stderr,
272
- });
273
- // In strict mode lint failures throw. Note: file.edited is an event
274
- // notification (the edit already happened), so this cannot undo the
275
- // edit — it surfaces the failure loudly to the session.
276
- if (state.config.profile === "strict") {
277
- 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
+ }
278
477
  }
279
- return;
280
478
  }
281
- if (event.type === "session.idle") {
282
- if (!state.config.gate) {
283
- await safeLog(state, "warn", "plugin config is incomplete (missing gate section), skipping completion gate", { directory: state.directory });
284
- return;
285
- }
286
- const changedFiles = state.tracker.getChangedFiles();
287
- const report = await runGate(state.run, state.config, changedFiles, {
288
- cwd: state.directory,
289
- });
290
- state.tracker.clearChangedFiles();
291
- const summary = summarizeGate(report);
292
- if (!report.ran) {
293
- await safeLog(state, "debug", summary);
479
+ catch (err) {
480
+ if (err?.name === "AbortError") {
481
+ // normal on dispose
294
482
  return;
295
483
  }
296
- if (report.ok) {
297
- await safeLog(state, "info", summary);
298
- return;
299
- }
300
- // The gate cannot physically block on session.idle (the turn already
301
- // ended), so failure visibility is the enforcement mechanism.
302
- const level = state.config.gate.block_on_failure ? "error" : "warn";
303
- await safeLog(state, level, summary, {
304
- failedSteps: report.failedSteps.map((step) => ({
305
- name: step.name,
306
- command: step.command?.join(" "),
307
- exitCode: step.result?.exitCode,
308
- timedOut: step.result?.timedOut,
309
- stderr: step.result?.stderr,
310
- })),
311
- });
484
+ await safeLog(activeState, "error", `event loop error: ${String(err)}`);
312
485
  }
313
- },
314
- };
315
- }
316
- export const devFramework = async (ctx) => {
317
- const log = createLogger(ctx.client);
318
- fallbackLog = log;
319
- let config;
320
- try {
321
- config = loadConfig(ctx.directory);
322
- }
323
- catch (error) {
324
- const message = error instanceof Error ? error.message : String(error);
325
- await log("error", message, { directory: ctx.directory });
326
- const clientTui = ctx.client.tui;
327
- try {
328
- await clientTui?.showToast?.({
329
- type: "error",
330
- message: `[opencode-dev-framework] ${message}`,
331
- });
332
- }
333
- catch {
334
- // TUI may not be available; the log line is enough.
335
- }
336
- return {};
337
- }
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).
344
- setBaseDirectory(ctx.directory);
345
- const { constitution, warning } = await loadConstitution(config, ctx.directory);
346
- if (warning) {
347
- await log("warn", warning);
348
- }
349
- let configMtime;
350
- try {
351
- configMtime = (await stat(join(ctx.directory, ".opencode-dev-framework.yml"))).mtimeMs;
352
- }
353
- catch {
354
- // Config file may not exist yet; reloadConfigIfChanged will pick it up.
355
- }
356
- return buildHooks(ctx, config, log, runCommand, createChangedFileTracker(), constitution, configMtime);
357
- };
358
- 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;