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/README.md +49 -37
- package/dist/config.js +27 -1
- package/dist/format-status.js +15 -0
- package/dist/gate.d.ts +2 -2
- package/dist/gate.js +2 -2
- package/dist/harness.d.ts +90 -0
- package/dist/harness.js +193 -0
- package/dist/index.d.ts +31 -43
- package/dist/index.js +536 -303
- package/dist/installer.js +11 -0
- package/dist/logger.d.ts +21 -11
- package/dist/logger.js +34 -17
- package/dist/registry.d.ts +2 -0
- package/dist/types.d.ts +13 -1
- package/package.json +6 -5
- package/templates/.opencode/agents/code-reviewer.md +1 -0
- package/templates/.opencode/agents/pattern-guardian.md +1 -0
- package/templates/.opencode/agents/style-enforcer.md +1 -0
- package/templates/.opencode/agents/test-grounder.md +1 -0
- package/tui.tsx +126 -178
- package/dist/tools.d.ts +0 -3
- package/dist/tools.js +0 -95
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
|
-
*
|
|
5
|
-
* -
|
|
6
|
-
* -
|
|
7
|
-
* - event
|
|
8
|
-
* -
|
|
9
|
-
* -
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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
|
|
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,
|
|
23
|
+
import { lintFile, detectPreCommitAvailability, isLintFailure, summarizeLint } from "./lint.js";
|
|
20
24
|
import { createLogger } from "./logger.js";
|
|
21
|
-
import { checkToolCall } from "./protect.js";
|
|
22
|
-
import {
|
|
23
|
-
|
|
24
|
-
import { buildTools } from "./tools.js";
|
|
25
|
-
/**
|
|
26
|
-
* Module-level fallback logger, captured at plugin init. `safeLog` uses it when
|
|
27
|
-
* a hook's `HookState.log` is missing or was stripped, so a logging failure can
|
|
28
|
-
* never crash a hook. The original `state.log is not a function` error (seen when
|
|
29
|
-
* switching `off` -> `standard` at runtime) happened because a hook fired against
|
|
30
|
-
* a `HookState` whose `log` was never populated.
|
|
31
|
-
*/
|
|
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
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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 =
|
|
62
|
+
state.configMtime = mtime;
|
|
56
63
|
}
|
|
57
64
|
catch {
|
|
58
|
-
//
|
|
65
|
+
// keep current state on read failure
|
|
59
66
|
}
|
|
60
67
|
}
|
|
61
68
|
/**
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
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
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
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
|
-
|
|
81
|
-
|
|
82
|
-
|
|
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
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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
|
-
|
|
97
|
-
function
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
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
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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
|
-
|
|
114
|
-
tui?.showToast?.({ title: "opencode-dev-framework", message, variant });
|
|
174
|
+
config = loadConfig(directory);
|
|
115
175
|
}
|
|
116
|
-
catch {
|
|
117
|
-
|
|
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
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
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
|
-
|
|
176
|
-
|
|
177
|
-
return;
|
|
192
|
+
catch {
|
|
193
|
+
// continue
|
|
178
194
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
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
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
214
|
-
|
|
215
|
-
|
|
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
|
-
|
|
219
|
-
|
|
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
|
-
|
|
231
|
-
|
|
232
|
-
|
|
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
|
-
|
|
238
|
-
if (
|
|
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
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
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
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
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
|
-
|
|
282
|
-
if (
|
|
283
|
-
|
|
559
|
+
catch (err) {
|
|
560
|
+
if (err?.name === "AbortError") {
|
|
561
|
+
// normal on dispose
|
|
284
562
|
return;
|
|
285
563
|
}
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
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
|
-
|
|
297
|
-
|
|
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
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
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;
|