opencode-dev-framework 0.1.29 → 0.2.3

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,358 +1,591 @@
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";
17
- import { createChangedFileTracker, runGate, summarizeGate, } from "./gate.js";
20
+ import { createChangedFileTracker } from "./gate.js";
21
+ import { artifactState, evaluateCompletion, PREFLIGHT_ARTIFACT_REL, preflightBlockReason, } from "./harness.js";
18
22
  import { runCommand } from "./host.js";
19
- import { detectPreCommitAvailability, isLintFailure, lintFile, summarizeLint } from "./lint.js";
23
+ import { lintFile, detectPreCommitAvailability, isLintFailure, summarizeLint } from "./lint.js";
20
24
  import { createLogger } from "./logger.js";
21
- 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 { checkToolCall, extractFilePath } from "./protect.js";
26
+ import { loadConstitution } from "./rules.js";
27
+ let activeState = null;
32
28
  let fallbackLog = async () => { };
33
29
  function safeLog(state, level, message, extra) {
34
- const fn = typeof state.log === "function" ? state.log : fallbackLog;
30
+ const fn = state && typeof state.log === "function" ? state.log : fallbackLog;
35
31
  return fn(level, message, extra);
36
32
  }
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
33
  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;
34
+ const primary = join(state.directory, ".opencode-dev-framework.yml");
35
+ const fallback = join(state.directory, ".dev-framework.yml");
36
+ // check both names; stat whichever exists
37
+ let configPath = null;
38
+ let mtime;
39
+ for (const p of [primary, fallback]) {
40
+ try {
41
+ const s = await stat(p);
42
+ configPath = p;
43
+ mtime = s.mtimeMs;
44
+ break;
45
+ }
46
+ catch {
47
+ // continue
49
48
  }
49
+ }
50
+ if (!configPath || mtime === undefined) {
51
+ return;
52
+ }
53
+ if (state.configMtime !== undefined && state.configMtime === mtime) {
54
+ return;
55
+ }
56
+ try {
50
57
  clearConfigCache();
51
58
  const next = loadConfig(state.directory);
52
59
  const { constitution } = await loadConstitution(next, state.directory);
53
60
  state.config = next;
54
61
  state.constitution = constitution;
55
- state.configMtime = stats.mtimeMs;
62
+ state.configMtime = mtime;
56
63
  }
57
64
  catch {
58
- // Config file missing/unreadable — keep the current state.
65
+ // keep current state on read failure
59
66
  }
60
67
  }
61
68
  /**
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.
69
+ * Turn a completion verdict into the continuation message fed back to the
70
+ * agent when blocked. Shared by the `session.stopping` hard-stop path and
71
+ * the `session.idle` re-prompt fallback so wording (and block counting) is
72
+ * identical on either core support level.
68
73
  */
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" };
74
+ function continuationMessage(verdict) {
75
+ const why = verdict.reason === "review"
76
+ ? "the peer-review requirement is unmet"
77
+ : "the repo's checks are failing";
78
+ return (`opencode-dev-framework completion gate blocked you from finishing because ${why} ` +
79
+ `(block ${verdict.blockCount}/${verdict.maxBlocks}).\n\n${verdict.summary}\n\n` +
80
+ `Fix the underlying cause and continue. Do NOT disable, skip, or weaken these checks to ` +
81
+ `get past the gate. If a failure is pre-existing and unrelated to your work, prove it ` +
82
+ `(show it fails on a clean tree) and report it to the user.`);
83
+ }
84
+ /** Log pass/standdown verdicts; returns the continuation message when blocked. */
85
+ async function actOnVerdict(state, verdict) {
86
+ if (verdict.decision === "pass") {
87
+ if (verdict.note) {
88
+ await safeLog(state, "info", verdict.note, { changedFiles: verdict.changedFiles });
89
+ }
90
+ return null;
79
91
  }
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) };
92
+ if (verdict.decision === "standdown") {
93
+ // evaluateCompletion already logged the stand-down loudly.
94
+ return null;
89
95
  }
90
- const summary = summarizeGate(report);
91
- await safeLog(state, "error", summary, {
92
- failedSteps: report.failedSteps.map((step) => step.name),
96
+ return continuationMessage(verdict);
97
+ }
98
+ /** Assemble the completion verdict with the state's live dependencies. */
99
+ function runCompletion(state, sessionID) {
100
+ return evaluateCompletion({
101
+ run: state.run,
102
+ config: state.config,
103
+ directory: state.directory,
104
+ sessionID,
105
+ tracker: state.tracker,
106
+ blockCounts: state.blockCounts,
107
+ log: (level, message, extra) => safeLog(state, level, message, extra),
93
108
  });
94
- return { decision: "blocked", summary, blockCount, maxBlocks };
95
109
  }
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.`);
110
+ // Helpers to normalize V2 event shapes (data vs properties vs direct)
111
+ function getEventSessionID(event) {
112
+ const e = event;
113
+ // try common locations
114
+ if (typeof e.sessionID === "string")
115
+ return e.sessionID;
116
+ const data = (e.data ?? e.properties ?? e.payload);
117
+ if (data && typeof data.sessionID === "string")
118
+ return data.sessionID;
119
+ if (data && typeof data.session_id === "string")
120
+ return data.session_id;
121
+ // session.status carries sessionID at data.sessionID
122
+ if (e.properties && typeof e.properties.sessionID === "string") {
123
+ return e.properties.sessionID;
124
+ }
125
+ return undefined;
101
126
  }
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") => {
127
+ function getEventFilePath(event) {
128
+ const e = event;
129
+ const data = (e.data ?? e.properties ?? e.payload);
130
+ if (data && typeof data.file === "string")
131
+ return data.file;
132
+ if (data && typeof data.filePath === "string")
133
+ return data.filePath;
134
+ if (typeof e.file === "string")
135
+ return e.file;
136
+ return undefined;
137
+ }
138
+ function isIdleEvent(event) {
139
+ if (event.type === "session.idle")
140
+ return true;
141
+ if (event.type === "session.status") {
142
+ const d = event.data;
143
+ const p = event.properties;
144
+ const statusType = d?.status?.type ??
145
+ p?.status?.type ??
146
+ event.status?.type;
147
+ return statusType === "idle";
148
+ }
149
+ if (event.type === "session.status") {
150
+ // also handle flattened shape where data is {status: "idle"}? check
151
+ const d2 = event.data;
152
+ if (d2?.status === "idle")
153
+ return true;
154
+ }
155
+ return false;
156
+ }
157
+ function isFilesystemChangedEvent(type) {
158
+ return type === "filesystem.changed" || type === "file.edited" || type === "file.changed";
159
+ }
160
+ function isSessionDeletedEvent(type) {
161
+ return type === "session.deleted";
162
+ }
163
+ // ---------------------------------------------------------------------------
164
+ // V2 Plugin definition
165
+ // ---------------------------------------------------------------------------
166
+ const plugin = Plugin.define({
167
+ id: "opencode-dev-framework",
168
+ async setup(ctx) {
169
+ const log = createLogger();
170
+ fallbackLog = log;
171
+ const directory = ctx.location.directory;
172
+ let config;
112
173
  try {
113
- const tui = ctx.client.tui;
114
- tui?.showToast?.({ title: "opencode-dev-framework", message, variant });
174
+ config = loadConfig(directory);
115
175
  }
116
- catch {
117
- // TUI may be unavailable; the log line is enough.
176
+ catch (error) {
177
+ const message = error instanceof Error ? error.message : String(error);
178
+ await log("error", message, { directory });
179
+ // No client.app.log in V2 — stderr is enough
180
+ return;
118
181
  }
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;
156
- }
157
- await reloadConfigIfChanged(state);
158
- if (input.sessionID) {
159
- setSessionDirectory(input.sessionID, state.directory);
160
- }
161
- if (state.config.profile === "off") {
162
- 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) {
173
- throw new Error("[opencode-dev-framework] plugin state is not available; guardrail cannot evaluate this tool call");
182
+ const { constitution, warning } = await loadConstitution(config, directory);
183
+ if (warning) {
184
+ await log("warn", warning);
185
+ }
186
+ let configMtime;
187
+ for (const name of [".opencode-dev-framework.yml", ".dev-framework.yml"]) {
188
+ try {
189
+ configMtime = (await stat(join(directory, name))).mtimeMs;
190
+ break;
174
191
  }
175
- await reloadConfigIfChanged(state);
176
- if (state.config.profile === "off") {
177
- return;
192
+ catch {
193
+ // continue
178
194
  }
179
- const result = checkToolCall(state.config, input.tool, output.args, state.directory, state.hostPermissions);
180
- if (result.decision === "allow") {
181
- return;
195
+ }
196
+ const tracker = createChangedFileTracker();
197
+ const state = {
198
+ directory,
199
+ config,
200
+ log,
201
+ run: runCommand,
202
+ tracker,
203
+ constitution,
204
+ blockCounts: new Map(),
205
+ configMtime,
206
+ };
207
+ activeState = state;
208
+ const registrations = [];
209
+ function trackRegistration(value) {
210
+ if (value !== null &&
211
+ typeof value === "object" &&
212
+ "dispose" in value &&
213
+ typeof value.dispose === "function") {
214
+ registrations.push(value);
182
215
  }
183
- const message = result.reason ?? "blocked by guardrails";
184
- const extra = {
185
- tool: input.tool,
186
- sessionID: input.sessionID,
187
- pattern: result.matchedPattern,
188
- };
189
- if (result.decision === "warn") {
190
- await safeLog(state, "warn", message, extra);
216
+ }
217
+ // 1) Constitution injection — per model request (V1: experimental.chat.system.transform -> V2: session.hook("context", ...))
218
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
219
+ trackRegistration(await ctx.session.hook("context", async (event) => {
220
+ if (!activeState)
191
221
  return;
192
- }
193
- await safeLog(state, "error", message, extra);
194
- throw new Error(`[opencode-dev-framework] ${message}`);
195
- },
196
- "experimental.session.stopping": async (input, output) => {
197
- const state = getStateForSession(input.sessionID);
198
- if (!state) {
222
+ await reloadConfigIfChanged(activeState);
223
+ if (activeState.config.profile === "off")
199
224
  return;
200
- }
201
- await reloadConfigIfChanged(state);
202
- const verdict = await runStoppingGate(state, input.sessionID);
203
- if (verdict.decision !== "blocked") {
225
+ if (!activeState.constitution)
204
226
  return;
205
- }
206
- output.context.push(stoppingMessage(verdict));
207
- },
208
- "session.stopping": async (input, output) => {
209
- const state = getStateForSession(input.sessionID);
210
- if (!state) {
227
+ // V2 system is Array<SystemPart> {type:"text", text:string}
228
+ const already = event.system.some((part) => part.text.includes(activeState.constitution));
229
+ if (already)
211
230
  return;
212
- }
213
- await reloadConfigIfChanged(state);
214
- const verdict = await runStoppingGate(state, input.sessionID);
215
- if (verdict.decision !== "blocked") {
231
+ event.system.push({
232
+ type: "text",
233
+ text: activeState.constitution,
234
+ });
235
+ await safeLog(activeState, "info", "constitution injected into system prompt");
236
+ }));
237
+ // Also hook other request kinds so the reminder is not missed on title/generate
238
+ // (no-op if model doesn't need it; cheap)
239
+ for (const kind of ["generate", "compaction"]) {
240
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
241
+ trackRegistration(await ctx.session.hook(kind, async (event) => {
242
+ if (!activeState || activeState.config.profile === "off" || !activeState.constitution)
243
+ return;
244
+ // generate/compaction also have system — inject similarly if present
245
+ const ev = event;
246
+ if (!ev.system)
247
+ return;
248
+ const already = ev.system.some((p) => p.text.includes(activeState.constitution));
249
+ if (!already)
250
+ ev.system.push({ type: "text", text: activeState.constitution });
251
+ }));
252
+ }
253
+ // 1b) Hard-stop completion gate — `session.stopping` (OpenCode PR #44712).
254
+ // Fires before the agent loop breaks on natural exit: a blocked verdict
255
+ // sets stop=false + message and the loop re-enters, so gate failures
256
+ // physically prevent completion. Registered defensively: on builds
257
+ // without core support the hook is simply never dispatched, and the
258
+ // session.idle fallback below provides re-prompt enforcement instead.
259
+ // The first invocation flips `stopHookSupported` so /df-status can show
260
+ // which enforcement level is active.
261
+ try {
262
+ trackRegistration(
263
+ // biome-ignore lint/suspicious/noExplicitAny: V2 hook names are not yet typed for session.stopping
264
+ await ctx.session.hook("stopping",
265
+ // biome-ignore lint/suspicious/noExplicitAny: core may dispatch (input, output) or a single mutable event
266
+ async (input, output) => {
267
+ if (!activeState)
268
+ return;
269
+ const out = output ?? input ?? {};
270
+ const sessionID = input?.sessionID ??
271
+ out.sessionID ??
272
+ getEventSessionID(input) ??
273
+ "unknown";
274
+ activeState.stopHookSupported = true;
275
+ await reloadConfigIfChanged(activeState);
276
+ if (activeState.config.profile === "off")
277
+ return;
278
+ const verdict = await runCompletion(activeState, sessionID);
279
+ const message = await actOnVerdict(activeState, verdict);
280
+ if (message !== null) {
281
+ out.stop = false;
282
+ out.message = message;
283
+ }
284
+ }));
285
+ await safeLog(state, "info", "registered session.stopping hook; if this OpenCode build dispatches it, gate failures become hard stops before loop exit");
286
+ }
287
+ catch {
288
+ await safeLog(state, "warn", "could not register session.stopping hook; using session.idle re-prompt fallback only");
289
+ }
290
+ // 2) Guardrails — tool execution blocking (V1: tool.execute.before -> V2: ctx.tool.hook("execute.before", ...))
291
+ // Fail-open when state is absent: after a teardown/reload the hook may
292
+ // briefly outlive its state (or disposal may be unsupported on an older
293
+ // core). Allowing the call keeps the session usable; see issue #1.
294
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
295
+ trackRegistration(await ctx.tool.hook("execute.before", async (event) => {
296
+ if (!activeState) {
297
+ await safeLog(null, "warn", "[opencode-dev-framework] plugin state is not available; allowing tool call (fail-open after teardown)", { tool: event.tool });
216
298
  return;
217
299
  }
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);
300
+ await reloadConfigIfChanged(activeState);
301
+ if (activeState.config.profile === "off")
228
302
  return;
303
+ // V2 event shapes: { tool, sessionID, agent, messageID, id, input: unknown }
304
+ const toolName = event.tool;
305
+ const input = event.input;
306
+ const sessionID = event.sessionID;
307
+ // Pre-flight harness: when `preflight:` tasks are configured, file
308
+ // edits are denied (standard/strict) until the pre-flight artifact
309
+ // exists. This is a true hard gate — it runs before the edit lands.
310
+ if (activeState.config.preflight.length > 0) {
311
+ const artifact = await artifactState(activeState.directory, PREFLIGHT_ARTIFACT_REL);
312
+ const reason = preflightBlockReason(activeState.config, toolName, extractFilePath(input), artifact);
313
+ if (reason !== null) {
314
+ const extra = { tool: toolName, sessionID, artifact: PREFLIGHT_ARTIFACT_REL };
315
+ if (activeState.config.profile === "advisory") {
316
+ await safeLog(activeState, "warn", reason, extra);
317
+ }
318
+ else {
319
+ await safeLog(activeState, "error", reason, extra);
320
+ throw new Error(`[opencode-dev-framework] ${reason}`);
321
+ }
322
+ }
229
323
  }
230
- const sessionID = event.type === "session.idle"
231
- ? event.properties.sessionID
232
- : undefined;
233
- const state = getStateForSession(sessionID);
234
- if (!state) {
324
+ // hostPermissions: not available in V2 permission model; pass undefined (conservative — still guard)
325
+ const result = checkToolCall(activeState.config, toolName, input, activeState.directory, undefined);
326
+ if (result.decision === "allow")
235
327
  return;
236
- }
237
- await reloadConfigIfChanged(state);
238
- if (state.config.profile === "off") {
328
+ const message = result.reason ?? "blocked by guardrails";
329
+ const extra = { tool: toolName, sessionID, pattern: result.matchedPattern };
330
+ if (result.decision === "warn") {
331
+ await safeLog(activeState, "warn", message, extra);
239
332
  return;
240
333
  }
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,
334
+ await safeLog(activeState, "error", message, extra);
335
+ throw new Error(`[opencode-dev-framework] ${message}`);
336
+ }));
337
+ // 3) Custom tools — V2: ctx.tool.transform(editor => editor.add(...))
338
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
339
+ trackRegistration(await ctx.tool.transform((editor) => {
340
+ editor.add({
341
+ name: "dev_framework_init",
342
+ 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.",
343
+ input: {
344
+ type: "object",
345
+ properties: {
346
+ directory: {
347
+ type: "string",
348
+ description: "Target project directory (defaults to current project)",
349
+ },
350
+ overwrite: {
351
+ type: "boolean",
352
+ description: "Overwrite existing files that differ from templates",
353
+ },
354
+ },
355
+ additionalProperties: false,
356
+ },
357
+ async execute(input) {
358
+ const { installTemplates, writeDetectedConfig } = await import("./installer.js");
359
+ const args = input;
360
+ const targetDir = args.directory ?? directory;
361
+ const result = await installTemplates(targetDir, {
362
+ overwriteExisting: args.overwrite ?? false,
363
+ skipExisting: !(args.overwrite ?? false),
259
364
  });
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}`);
365
+ const configResult = await writeDetectedConfig(targetDir, {
366
+ overwriteExisting: args.overwrite ?? false,
367
+ skipExisting: !(args.overwrite ?? false),
368
+ });
369
+ const lines = [
370
+ `Installed opencode-dev-framework templates into ${targetDir}.`,
371
+ `Created: ${result.created.length} file(s)`,
372
+ `Overwritten: ${result.overwritten.length} file(s)`,
373
+ `Skipped: ${result.skipped.length} file(s)`,
374
+ `Config: ${configResult.action}`,
375
+ ];
376
+ if (result.created.length > 0)
377
+ lines.push("", "Created files:", ...result.created.map((f) => `- ${f}`));
378
+ if (result.overwritten.length > 0)
379
+ lines.push("", "Overwritten files:", ...result.overwritten.map((f) => `- ${f}`));
380
+ return { content: lines.join("\n") };
381
+ },
382
+ });
383
+ editor.add({
384
+ name: "dev_framework_set_profile",
385
+ description: "Change the opencode-dev-framework profile (off, advisory, standard, strict) for the current project and apply it immediately without restarting OpenCode.",
386
+ input: {
387
+ type: "object",
388
+ properties: {
389
+ profile: {
390
+ type: "string",
391
+ description: "New profile: off, advisory, standard, or strict",
392
+ },
393
+ directory: {
394
+ type: "string",
395
+ description: "Project directory (defaults to current project)",
396
+ },
397
+ },
398
+ required: ["profile"],
399
+ additionalProperties: false,
400
+ },
401
+ async execute(input) {
402
+ const { clearConfigCache: ccc, loadConfig: lc } = await import("./config.js");
403
+ const { changeProfile } = await import("./commands.js");
404
+ const { loadConstitution: lc2 } = await import("./rules.js");
405
+ const args = input;
406
+ const targetDir = args.directory ?? directory;
407
+ const profile = args.profile.trim().toLowerCase();
408
+ const valid = ["off", "advisory", "standard", "strict"];
409
+ if (!valid.includes(profile)) {
410
+ return {
411
+ content: `Invalid profile "${args.profile}". Valid values: ${valid.join(", ")}.`,
412
+ };
413
+ }
414
+ const message = await changeProfile(targetDir, profile);
415
+ ccc();
416
+ const newConfig = lc(targetDir);
417
+ const { constitution: newConstitution } = await lc2(newConfig, targetDir);
418
+ if (activeState && activeState.directory === targetDir) {
419
+ activeState.config = newConfig;
420
+ activeState.constitution = newConstitution;
421
+ }
422
+ return { content: `${message} Change applied immediately.` };
423
+ },
424
+ });
425
+ editor.add({
426
+ name: "dev_framework_status",
427
+ 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.",
428
+ input: {
429
+ type: "object",
430
+ properties: {
431
+ directory: {
432
+ type: "string",
433
+ description: "Project directory (defaults to current project)",
434
+ },
435
+ },
436
+ additionalProperties: false,
437
+ },
438
+ async execute(input) {
439
+ const { renderStatus } = await import("./format-status.js");
440
+ const args = input;
441
+ const targetDir = args.directory ?? directory;
442
+ const cfg = activeState && activeState.directory === targetDir
443
+ ? activeState.config
444
+ : loadConfig(targetDir);
445
+ // renderStatus expects HookState? pass activeState
446
+ return {
447
+ content: renderStatus(cfg, activeState),
448
+ };
449
+ },
450
+ });
451
+ }));
452
+ // 4) Event subscription — file tracking + gate enforcement (V1: event hook)
453
+ // Keeps the completion gate intent without session.stopping: on idle, run gate;
454
+ // on failure inside budget, re-prompt the session (async block).
455
+ const controller = new AbortController();
456
+ const eventLoop = (async () => {
457
+ try {
458
+ for await (const rawEvent of ctx.event.subscribe({ signal: controller.signal })) {
459
+ const event = rawEvent;
460
+ const type = event.type;
461
+ if (isSessionDeletedEvent(type)) {
462
+ // session.deleted: cleanup blockCounts (and tracker if needed)
463
+ const sid = getEventSessionID(event);
464
+ if (sid && activeState)
465
+ activeState.blockCounts.delete(sid);
466
+ continue;
467
+ }
468
+ if (isFilesystemChangedEvent(type)) {
469
+ if (!activeState)
470
+ continue;
471
+ await reloadConfigIfChanged(activeState);
472
+ if (activeState.config.profile === "off")
473
+ continue;
474
+ const filePath = getEventFilePath(event);
475
+ if (!filePath)
476
+ continue;
477
+ activeState.tracker.add(filePath, activeState.directory);
478
+ // per-edit lint (V1: event file.edited -> lintFile)
479
+ if (!activeState.config.on_edit.lint)
480
+ continue;
481
+ if (activeState.config.precommit === "auto" &&
482
+ activeState.precommitAvailable === undefined) {
483
+ activeState.precommitAvailable = await detectPreCommitAvailability(activeState.run, activeState.directory);
484
+ }
485
+ const outcome = await lintFile(activeState.run, activeState.config, filePath, {
486
+ cwd: activeState.directory,
487
+ timeout: activeState.config.gate?.timeout,
488
+ precommitAvailable: activeState.precommitAvailable,
489
+ });
490
+ if (outcome.skipped) {
491
+ await safeLog(activeState, "debug", summarizeLint(outcome), {
492
+ filePath,
493
+ reason: outcome.reason,
494
+ });
495
+ continue;
496
+ }
497
+ if (!isLintFailure(outcome)) {
498
+ await safeLog(activeState, "info", summarizeLint(outcome), { filePath });
499
+ continue;
500
+ }
501
+ const summary = summarizeLint(outcome);
502
+ await safeLog(activeState, "error", summary, {
503
+ filePath,
504
+ command: outcome.command?.join(" "),
505
+ stdout: outcome.result?.stdout,
506
+ stderr: outcome.result?.stderr,
507
+ });
508
+ if (activeState.config.profile === "strict") {
509
+ // Event handlers cannot throw to block the edit (edit already happened), but we log loudly.
510
+ // In V2 we also have the tool hook to block before; this is advisory.
511
+ }
512
+ continue;
513
+ }
514
+ if (isIdleEvent(event)) {
515
+ if (!activeState)
516
+ continue;
517
+ await reloadConfigIfChanged(activeState);
518
+ if (activeState.config.profile === "off")
519
+ continue;
520
+ if (!activeState.config.gate) {
521
+ await safeLog(activeState, "warn", "plugin config is incomplete (missing gate section), skipping completion gate", {
522
+ directory: activeState.directory,
523
+ });
524
+ continue;
525
+ }
526
+ const sessionID = getEventSessionID(event);
527
+ if (!sessionID)
528
+ continue;
529
+ const verdict = await runCompletion(activeState, sessionID);
530
+ const message = await actOnVerdict(activeState, verdict);
531
+ if (message === null)
532
+ continue;
533
+ const blockInfo = verdict.decision === "blocked"
534
+ ? ` (block ${verdict.blockCount}/${verdict.maxBlocks})`
535
+ : "";
536
+ // blocked -> re-prompt the session (fallback when session.stopping
537
+ // is not dispatched by this OpenCode build)
538
+ try {
539
+ // Prefer prompt (creates a user turn and wakes the agent); fallback to synthetic if prompt not available
540
+ if (typeof ctx.session.prompt === "function") {
541
+ await ctx.session.prompt({ sessionID, text: message });
542
+ }
543
+ else if (typeof ctx.session.synthetic === "function") {
544
+ await ctx.session.synthetic({ sessionID, text: message });
545
+ }
546
+ else {
547
+ await safeLog(activeState, "error", `gate blocked but no session prompt API available: ${message}`);
548
+ }
549
+ await safeLog(activeState, "info", `completion gate re-prompted session ${sessionID}${blockInfo}`);
550
+ }
551
+ catch (err) {
552
+ await safeLog(activeState, "error", `failed to re-prompt session ${sessionID} after gate block: ${String(err)}`, {
553
+ sessionID,
554
+ });
555
+ }
556
+ }
278
557
  }
279
- return;
280
558
  }
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 });
559
+ catch (err) {
560
+ if (err?.name === "AbortError") {
561
+ // normal on dispose
284
562
  return;
285
563
  }
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);
294
- return;
564
+ await safeLog(activeState, "error", `event loop error: ${String(err)}`);
565
+ }
566
+ })();
567
+ // Ensure the loop doesn't block setup
568
+ void eventLoop;
569
+ return async () => {
570
+ controller.abort();
571
+ // Unregister every hook/transform registered by this setup() so a
572
+ // teardown/reload (e.g. session_move into a worktree) does not leave
573
+ // stale closures alive. Disposal failures are ignored — the
574
+ // fail-open guard above keeps the session usable regardless.
575
+ for (const registration of registrations) {
576
+ try {
577
+ await registration.dispose();
295
578
  }
296
- if (report.ok) {
297
- await safeLog(state, "info", summary);
298
- return;
579
+ catch {
580
+ // ignore — fail-open guard is the safety net
299
581
  }
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
- });
312
582
  }
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;
583
+ // Only clear the singleton if it is still ours; a newer setup() may
584
+ // already have replaced it (reload race).
585
+ if (activeState === state) {
586
+ activeState = null;
587
+ }
588
+ };
589
+ },
590
+ });
591
+ export default plugin;