opencode-dev-framework 0.2.2 → 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 CHANGED
@@ -19,9 +19,20 @@ reimplemented as an OpenCode-native plugin.
19
19
  and reports failures loudly. Optionally delegates per-file linting to
20
20
  `pre-commit run --files` when `precommit: auto` is set.
21
21
  - **Completion gate.** When the session goes idle (`session.idle`/`session.status:idle`),
22
- runs typecheck, tests, and (optionally) lint on changed files. On failure inside
23
- `gate.max_blocks` the plugin re-prompts the session with the failure summary,
24
- keeping the agent loop alive (V2 async replacement for `session.stopping`).
22
+ runs typecheck, tests, and (optionally) lint on changed files — changed files are
23
+ tracked from edit events and cross-checked against `git status`, so the gate cannot
24
+ silently skip due to an event-shape mismatch. In `standard`/`strict`, sessions that
25
+ changed files must also produce a **peer-review artifact**
26
+ (`.opencode/opencode-dev-framework/review.md`) covering the delegation rule's review
27
+ cadence. On failure inside `gate.max_blocks` the plugin re-prompts the session with
28
+ the failure summary. On OpenCode builds that dispatch the `session.stopping` hook
29
+ (PR #44712) the same verdict vetoes loop exit *before* the agent stops — a true hard
30
+ stop; `/df-status` shows which mode is active.
31
+ - **Pre-flight gate (optional).** When a `preflight:` task list is configured, edit
32
+ tools are **denied** (standard/strict) until the agent writes its pre-flight findings
33
+ to `.opencode/opencode-dev-framework/preflight.md`. Use it for work that requires
34
+ establishing baseline state/knowledge first (e.g. research on an existing strategy).
35
+ Read-only tools stay open; the block lifts automatically once the artifact exists.
25
36
  - **Custom tools.** `dev_framework_init` scaffolds project-level agents,
26
37
  skills, local rules directory, and config; `dev_framework_set_profile` changes the profile
27
38
  in-session without restarting; `dev_framework_status` reports the current
@@ -42,12 +53,12 @@ reimplemented as an OpenCode-native plugin.
42
53
 
43
54
  ## Profiles
44
55
 
45
- | Profile | Guardrails | Gate failures | Lint on edit | Notes |
46
- | ---------- | ---------- | ------------- | ------------ | ----- |
47
- | `off` | disabled | not reported | no | Plugin registers no hooks at all. |
48
- | `advisory` | warn | warn | yes | Nothing blocks; everything is logged. |
49
- | `standard` | deny | error | yes | The default when a config file exists. |
50
- | `strict` | deny | error | yes | Also lints changed files in the gate and throws on per-edit lint failures. |
56
+ | Profile | Guardrails | Gate failures | Lint on edit | Pre-flight | Review required | Notes |
57
+ | ---------- | ---------- | ------------- | ------------ | ---------- | --------------- | ----- |
58
+ | `off` | disabled | not reported | no | no | no | Plugin registers no hooks at all. |
59
+ | `advisory` | warn | warn | yes | warn only | warned, not blocked | Nothing blocks; everything is logged. |
60
+ | `standard` | deny | error | yes | deny edits | blocks completion | The default when a config file exists. |
61
+ | `strict` | deny | error | yes | deny edits | blocks completion | Also lints changed files in the gate and throws on per-edit lint failures. |
51
62
 
52
63
  ## Install
53
64
 
@@ -145,6 +156,17 @@ gate:
145
156
  run_typecheck: true
146
157
  run_tests: true
147
158
  block_on_failure: true
159
+ # standard/strict default: sessions that changed files must produce a
160
+ # peer-review artifact (.opencode/opencode-dev-framework/review.md)
161
+ # before the completion gate passes.
162
+ require_review: true
163
+
164
+ # Optional: pre-flight task list. When set, edit tools are denied
165
+ # (standard/strict) until the agent writes its findings to
166
+ # .opencode/opencode-dev-framework/preflight.md.
167
+ # preflight:
168
+ # - "Summarize the current strategy configuration and its intent"
169
+ # - "Load the most recent backtest results and record headline metrics"
148
170
 
149
171
  on_edit:
150
172
  lint: true
@@ -191,12 +213,16 @@ itself).
191
213
 
192
214
  ## Limitations
193
215
 
194
- - **The completion gate in V2 re-prompts instead of vetoing.** `session.stopping`
195
- (`PR #44712`) was removed in the V2 plugin API. On failure inside `gate.max_blocks`
196
- the plugin now calls `ctx.session.prompt()` from the `session.idle`/`session.status`
197
- event, waking the agent with the failure summary — same UX, async instead of a
198
- synchronous `stop=false` veto. Standing down after `max_blocks` is plugin-owned
199
- (no core 3-re-entry cap). There is no synchronous hard block in V2.
216
+ - **Post-flight enforcement depends on core support.** OpenCode v2.0.12 has no
217
+ `session.stopping` veto (PR #44712 is open; the earlier PR #41811 was never merged),
218
+ so on failure inside `gate.max_blocks` the plugin re-prompts via
219
+ `ctx.session.prompt()` from the `session.idle` event. The plugin still registers the
220
+ `session.stopping` hook defensively: on builds that dispatch it, the same verdict
221
+ vetoes loop exit before the agent stops — a true hard stop. `/df-status` shows which
222
+ mode is active. Until then, the user can always close the session, so treat the gate
223
+ as the strongest available enforcement, not an unbreakable lock. The **pre-flight**
224
+ gate, by contrast, is a genuine hard block on every build: it denies edit tools in
225
+ `tool.execute.before`, before the edit lands.
200
226
  - **Guardrails run inside OpenCode.** The `tool.execute.before` hook runs
201
227
  after OpenCode's own permission system; it adds project rules on top, it
202
228
  does not replace OpenCode permissions.
package/dist/config.js CHANGED
@@ -49,10 +49,12 @@ const configSchema = z.object({
49
49
  skip_unchanged: z.boolean().optional(),
50
50
  scope: z.enum(["all", "changed"]).optional(),
51
51
  lint_changed: z.boolean().optional(),
52
+ require_review: z.boolean().optional(),
52
53
  timeout: z.number().positive().optional(),
53
54
  max_blocks: z.number().int().positive().optional(),
54
55
  })
55
56
  .optional(),
57
+ preflight: z.union([z.array(z.string()), z.string()]).optional(),
56
58
  on_edit: z
57
59
  .object({
58
60
  format: z.boolean().optional(),
@@ -196,6 +198,9 @@ export function mapFlatConfig(flat) {
196
198
  case "gate_lint_changed":
197
199
  gate.lint_changed = toBoolean(value);
198
200
  break;
201
+ case "gate_require_review":
202
+ gate.require_review = toBoolean(value);
203
+ break;
199
204
  case "gate_timeout":
200
205
  gate.timeout = toNumber(value);
201
206
  break;
@@ -223,6 +228,17 @@ export function mapFlatConfig(flat) {
223
228
  case "precommit":
224
229
  config.precommit = value === "auto" || value === true ? "auto" : "off";
225
230
  break;
231
+ case "preflight":
232
+ if (Array.isArray(value)) {
233
+ config.preflight = value.map(String).filter((t) => t.trim() !== "");
234
+ }
235
+ else if (typeof value === "string") {
236
+ config.preflight = value
237
+ .split("\n")
238
+ .map((t) => t.trim())
239
+ .filter((t) => t !== "" && !t.startsWith("#"));
240
+ }
241
+ break;
226
242
  default:
227
243
  // Unknown flat keys are ignored for forward compatibility.
228
244
  break;
@@ -275,6 +291,7 @@ export function resolveConfig(raw, configPath) {
275
291
  skip_unchanged: raw.gate?.skip_unchanged ?? true,
276
292
  scope: raw.gate?.scope ?? "all",
277
293
  lint_changed: raw.gate?.lint_changed ?? defaults.lint_changed,
294
+ require_review: raw.gate?.require_review ?? profile !== "off",
278
295
  timeout: raw.gate?.timeout,
279
296
  max_blocks: raw.gate?.max_blocks ?? 3,
280
297
  },
@@ -286,6 +303,7 @@ export function resolveConfig(raw, configPath) {
286
303
  rules: Array.isArray(raw.rules) ? { mode: "replace", files: raw.rules } : raw.rules,
287
304
  style_guide: raw.style_guide,
288
305
  precommit: raw.precommit ?? "off",
306
+ preflight: raw.preflight ?? [],
289
307
  };
290
308
  }
291
309
  function validateConfig(data, configPath) {
@@ -296,7 +314,15 @@ function validateConfig(data, configPath) {
296
314
  .join("\n");
297
315
  throw new Error(`Invalid configuration in ${configPath}:\n${issues}`);
298
316
  }
299
- return result.data;
317
+ const config = result.data;
318
+ // Normalize the preflight union to a plain string list.
319
+ const preflight = typeof config.preflight === "string"
320
+ ? config.preflight
321
+ .split("\n")
322
+ .map((t) => t.trim())
323
+ .filter((t) => t !== "")
324
+ : config.preflight;
325
+ return { ...config, preflight };
300
326
  }
301
327
  const configCache = new Map();
302
328
  /** Clear the per-session config cache (mainly for tests). */
@@ -62,12 +62,25 @@ export function renderConfigStatus(config) {
62
62
  lines.push(` run_typecheck: ${config.gate.run_typecheck}`);
63
63
  lines.push(` run_tests: ${config.gate.run_tests}`);
64
64
  lines.push(` lint_changed: ${config.gate.lint_changed}`);
65
+ lines.push(` require_review: ${config.gate.require_review}`);
65
66
  lines.push(` block_on_failure: ${config.gate.block_on_failure}`);
66
67
  lines.push(` skip_unchanged: ${config.gate.skip_unchanged}`);
67
68
  lines.push(` scope: ${config.gate.scope}`);
68
69
  lines.push(` timeout: ${config.gate.timeout ?? "(default)"}`);
69
70
  lines.push(` max_blocks: ${config.gate.max_blocks}`);
70
71
  lines.push("");
72
+ lines.push("Pre-flight:");
73
+ if (config.preflight.length === 0) {
74
+ lines.push(" (disabled — no preflight tasks configured)");
75
+ }
76
+ else {
77
+ lines.push(` artifact: .opencode/opencode-dev-framework/preflight.md`);
78
+ lines.push(" tasks:");
79
+ for (const task of config.preflight) {
80
+ lines.push(` - ${task}`);
81
+ }
82
+ }
83
+ lines.push("");
71
84
  lines.push("Commands:");
72
85
  lines.push(" typecheck:");
73
86
  lines.push(formatCommandMap(config.commands.typecheck, " "));
@@ -109,6 +122,8 @@ export function renderHelp() {
109
122
  export function renderStatus(config, state) {
110
123
  const lines = [renderConfigStatus(config)];
111
124
  if (state) {
125
+ lines.push("");
126
+ lines.push(`Hard stop (session.stopping): ${state.stopHookSupported ? "active — gate vetoes loop exit" : "not dispatched by this OpenCode build — idle re-prompt fallback"}`);
112
127
  if (config.precommit === "auto") {
113
128
  lines.push(` pre-commit binary available: ${state.precommitAvailable === true ? "yes" : state.precommitAvailable === false ? "no" : "not checked yet"}`);
114
129
  }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Pre/post-flight harness.
3
+ *
4
+ * Two enforcement layers around the agent's work loop, mirroring the original
5
+ * dev-framework's `preToolUse` deny and `agentStop` gate primitives:
6
+ *
7
+ * - **Pre-flight** (optional, config-gated): when `preflight:` tasks are
8
+ * configured, edit tools are denied (standard/strict) until the agent has
9
+ * written the pre-flight artifact. This is a true hard gate: it runs in
10
+ * `tool.execute.before`, before the edit lands. This is the only fully hard
11
+ * enforcement available on OpenCode builds without a `session.stopping`
12
+ * hook.
13
+ * - **Post-flight**: the completion verdict runner. It unions event-tracked
14
+ * changed files with `git status --porcelain` (robust against event-shape
15
+ * mismatches), runs the command gate, and — when `gate.require_review` is
16
+ * set — requires a peer-review artifact for sessions that changed files.
17
+ * The verdict is consumed by both the `session.stopping` hook (hard stop,
18
+ * when the OpenCode build supports it) and the `session.idle` fallback
19
+ * (re-prompt).
20
+ */
21
+ import { type ChangedFileTracker } from "./gate.js";
22
+ import type { RunCommand } from "./host.js";
23
+ import type { LogFn } from "./logger.js";
24
+ import type { ResolvedConfig } from "./types.js";
25
+ /** Project-relative path of the peer-review artifact the agent must produce. */
26
+ export declare const REVIEW_ARTIFACT_REL = ".opencode/opencode-dev-framework/review.md";
27
+ /** Project-relative path of the pre-flight artifact the agent must produce. */
28
+ export declare const PREFLIGHT_ARTIFACT_REL = ".opencode/opencode-dev-framework/preflight.md";
29
+ export type ArtifactState = "missing" | "empty" | "present";
30
+ /**
31
+ * Inspect an artifact file: present (non-trivial content), empty, or missing.
32
+ * Never throws — unreadable files count as missing.
33
+ */
34
+ export declare function artifactState(directory: string, relPath: string): Promise<ArtifactState>;
35
+ /**
36
+ * Parse `git status --porcelain=v1` output into repo-relative changed paths.
37
+ * Handles renames (`R old -> new` — keeps the new path) and dedupes.
38
+ */
39
+ export declare function parseGitStatusPorcelain(stdout: string): string[];
40
+ /**
41
+ * List changed files via git. Returns an empty list when the directory is not
42
+ * a git work tree or git is unavailable — the event tracker remains the
43
+ * primary source in that case.
44
+ */
45
+ export declare function gitChangedFiles(run: RunCommand, cwd: string): Promise<string[]>;
46
+ /** Union of tracker and git changed files, sorted and deduped. */
47
+ export declare function mergeChangedFiles(trackerFiles: string[], gitFiles: string[]): string[];
48
+ /**
49
+ * Decide whether a pre-flight config blocks a tool call. Returns the denial
50
+ * reason, or null when the call is allowed. The artifact path itself is
51
+ * always writable so the agent can produce the artifact; read-only tools are
52
+ * never blocked.
53
+ *
54
+ * Blocking only applies to standard/strict; advisory callers should treat a
55
+ * non-null reason as a warning instead of a denial.
56
+ */
57
+ export declare function preflightBlockReason(config: ResolvedConfig, toolName: string, targetFile: string | undefined, artifact: ArtifactState): string | null;
58
+ export type CompletionVerdict = {
59
+ decision: "pass";
60
+ changedFiles: string[];
61
+ note?: string;
62
+ } | {
63
+ decision: "blocked";
64
+ reason: "gate" | "review";
65
+ summary: string;
66
+ blockCount: number;
67
+ maxBlocks: number;
68
+ changedFiles: string[];
69
+ } | {
70
+ decision: "standdown";
71
+ reason: "gate" | "review";
72
+ summary: string;
73
+ changedFiles: string[];
74
+ };
75
+ export interface CompletionDeps {
76
+ run: RunCommand;
77
+ config: ResolvedConfig;
78
+ directory: string;
79
+ sessionID: string;
80
+ tracker: ChangedFileTracker;
81
+ blockCounts: Map<string, number>;
82
+ log: LogFn;
83
+ }
84
+ /**
85
+ * Evaluate the completion gate + review requirement and update block state.
86
+ * Pure orchestration: both the `session.stopping` and `session.idle` call
87
+ * sites feed their outcome from here so one session's block count applies to
88
+ * either hook.
89
+ */
90
+ export declare function evaluateCompletion(deps: CompletionDeps): Promise<CompletionVerdict>;
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Pre/post-flight harness.
3
+ *
4
+ * Two enforcement layers around the agent's work loop, mirroring the original
5
+ * dev-framework's `preToolUse` deny and `agentStop` gate primitives:
6
+ *
7
+ * - **Pre-flight** (optional, config-gated): when `preflight:` tasks are
8
+ * configured, edit tools are denied (standard/strict) until the agent has
9
+ * written the pre-flight artifact. This is a true hard gate: it runs in
10
+ * `tool.execute.before`, before the edit lands. This is the only fully hard
11
+ * enforcement available on OpenCode builds without a `session.stopping`
12
+ * hook.
13
+ * - **Post-flight**: the completion verdict runner. It unions event-tracked
14
+ * changed files with `git status --porcelain` (robust against event-shape
15
+ * mismatches), runs the command gate, and — when `gate.require_review` is
16
+ * set — requires a peer-review artifact for sessions that changed files.
17
+ * The verdict is consumed by both the `session.stopping` hook (hard stop,
18
+ * when the OpenCode build supports it) and the `session.idle` fallback
19
+ * (re-prompt).
20
+ */
21
+ import { readFile } from "node:fs/promises";
22
+ import { join } from "node:path";
23
+ import { runGate, summarizeGate } from "./gate.js";
24
+ /** Project-relative path of the peer-review artifact the agent must produce. */
25
+ export const REVIEW_ARTIFACT_REL = ".opencode/opencode-dev-framework/review.md";
26
+ /** Project-relative path of the pre-flight artifact the agent must produce. */
27
+ export const PREFLIGHT_ARTIFACT_REL = ".opencode/opencode-dev-framework/preflight.md";
28
+ /**
29
+ * Inspect an artifact file: present (non-trivial content), empty, or missing.
30
+ * Never throws — unreadable files count as missing.
31
+ */
32
+ export async function artifactState(directory, relPath) {
33
+ try {
34
+ const content = await readFile(join(directory, relPath), "utf8");
35
+ return content.trim() === "" ? "empty" : "present";
36
+ }
37
+ catch {
38
+ return "missing";
39
+ }
40
+ }
41
+ /**
42
+ * Parse `git status --porcelain=v1` output into repo-relative changed paths.
43
+ * Handles renames (`R old -> new` — keeps the new path) and dedupes.
44
+ */
45
+ export function parseGitStatusPorcelain(stdout) {
46
+ const files = new Set();
47
+ for (const line of stdout.split("\n")) {
48
+ if (line.length < 4)
49
+ continue;
50
+ const status = line.slice(0, 2);
51
+ if (status === "!!")
52
+ continue; // ignored files are never "changed"
53
+ if (status === "??") {
54
+ // untracked: path starts at column 3
55
+ const p = line.slice(3).trim();
56
+ if (p !== "")
57
+ files.add(p);
58
+ continue;
59
+ }
60
+ let path = line.slice(3);
61
+ const arrow = path.indexOf(" -> ");
62
+ if (arrow !== -1)
63
+ path = path.slice(arrow + 4);
64
+ path = path.trim().replace(/^"|"$/g, "");
65
+ if (path !== "")
66
+ files.add(path);
67
+ }
68
+ return [...files].sort();
69
+ }
70
+ /**
71
+ * List changed files via git. Returns an empty list when the directory is not
72
+ * a git work tree or git is unavailable — the event tracker remains the
73
+ * primary source in that case.
74
+ */
75
+ export async function gitChangedFiles(run, cwd) {
76
+ const result = await run(["git", "status", "--porcelain=v1", "--untracked-files=normal"], {
77
+ cwd,
78
+ });
79
+ if (result.timedOut || result.exitCode !== 0)
80
+ return [];
81
+ return parseGitStatusPorcelain(result.stdout);
82
+ }
83
+ /** Union of tracker and git changed files, sorted and deduped. */
84
+ export function mergeChangedFiles(trackerFiles, gitFiles) {
85
+ return [...new Set([...trackerFiles, ...gitFiles])].sort();
86
+ }
87
+ /**
88
+ * Decide whether a pre-flight config blocks a tool call. Returns the denial
89
+ * reason, or null when the call is allowed. The artifact path itself is
90
+ * always writable so the agent can produce the artifact; read-only tools are
91
+ * never blocked.
92
+ *
93
+ * Blocking only applies to standard/strict; advisory callers should treat a
94
+ * non-null reason as a warning instead of a denial.
95
+ */
96
+ export function preflightBlockReason(config, toolName, targetFile, artifact) {
97
+ if (config.preflight.length === 0)
98
+ return null;
99
+ if (config.profile === "off")
100
+ return null;
101
+ if (artifact === "present")
102
+ return null;
103
+ const FILE_TOOLS = new Set(["edit", "write", "patch"]);
104
+ if (!FILE_TOOLS.has(toolName))
105
+ return null;
106
+ if (targetFile !== undefined && targetFile.replace(/^\.\//, "") === PREFLIGHT_ARTIFACT_REL) {
107
+ return null;
108
+ }
109
+ const tasks = config.preflight.map((t, i) => `${i + 1}. ${t}`).join("\n");
110
+ return (`opencode-dev-framework pre-flight check is not complete. Before editing product code, ` +
111
+ `complete the following pre-flight tasks and write your findings to ${PREFLIGHT_ARTIFACT_REL}:\n\n` +
112
+ `${tasks}\n\n` +
113
+ `Read-only tools (read/grep/glob/bash for inspection) remain available. ` +
114
+ `This block lifts automatically once the artifact exists.`);
115
+ }
116
+ function reviewMissingMessage(changedFiles) {
117
+ const files = changedFiles.map((f) => ` - ${f}`).join("\n");
118
+ return (`opencode-dev-framework completion gate — the peer-review loop has not run. ` +
119
+ `This session changed files:\n${files}\n\n` +
120
+ `Per the delegation rule (40-delegation), before declaring done you must run the review ` +
121
+ `cadence: style-enforcer on the changed files, then test-grounder (evidence: tests that ` +
122
+ `fail without the change, commands that actually pass), and code-reviewer / pattern-guardian ` +
123
+ `for correctness and drift. Resolve every blocking finding, then write a summary of the ` +
124
+ `review findings and their resolution to ${REVIEW_ARTIFACT_REL}.\n\n` +
125
+ `Investigation-only reviewers: do not ask them to edit product code.`);
126
+ }
127
+ /**
128
+ * Evaluate the completion gate + review requirement and update block state.
129
+ * Pure orchestration: both the `session.stopping` and `session.idle` call
130
+ * sites feed their outcome from here so one session's block count applies to
131
+ * either hook.
132
+ */
133
+ export async function evaluateCompletion(deps) {
134
+ const { run, config, directory, sessionID, tracker, blockCounts } = deps;
135
+ if (config.profile === "off" || !config.gate) {
136
+ return { decision: "pass", changedFiles: [] };
137
+ }
138
+ const trackerFiles = tracker.getChangedFiles();
139
+ const gitFiles = await gitChangedFiles(run, directory);
140
+ const changedFiles = mergeChangedFiles(trackerFiles, gitFiles);
141
+ if (config.gate.skip_unchanged && changedFiles.length === 0) {
142
+ return { decision: "pass", changedFiles, note: "completion gate skipped: no changed files" };
143
+ }
144
+ const report = await runGate(run, config, changedFiles, { cwd: directory });
145
+ const gateFailed = report.ran && !report.ok;
146
+ const reviewRequired = config.gate.require_review && changedFiles.length > 0;
147
+ const reviewState = reviewRequired
148
+ ? await artifactState(directory, REVIEW_ARTIFACT_REL)
149
+ : "present";
150
+ const reviewMissing = reviewRequired && reviewState !== "present";
151
+ if (!gateFailed && !reviewMissing) {
152
+ tracker.clearChangedFiles();
153
+ blockCounts.delete(sessionID);
154
+ return {
155
+ decision: "pass",
156
+ changedFiles,
157
+ note: report.ran ? `completion gate passed\n${summarizeGate(report)}` : undefined,
158
+ };
159
+ }
160
+ // Advisory: report loudly, never block.
161
+ if (!config.gate.block_on_failure) {
162
+ const summary = gateFailed ? summarizeGate(report) : reviewMissingMessage(changedFiles);
163
+ await deps.log("error", `completion gate (advisory — not blocking) saw problems:\n${summary}`);
164
+ return {
165
+ decision: "pass",
166
+ changedFiles,
167
+ note: `completion gate (advisory — not blocking) saw problems:\n${summary}`,
168
+ };
169
+ }
170
+ const reason = gateFailed ? "gate" : "review";
171
+ const summary = gateFailed ? summarizeGate(report) : reviewMissingMessage(changedFiles);
172
+ const maxBlocks = config.gate.max_blocks ?? 3;
173
+ const blockCount = (blockCounts.get(sessionID) ?? 0) + 1;
174
+ if (blockCount > maxBlocks) {
175
+ tracker.clearChangedFiles();
176
+ blockCounts.delete(sessionID);
177
+ const standdownSummary = `opencode-dev-framework completion gate has blocked ${maxBlocks} times and is standing ` +
178
+ `down to avoid trapping you. The requirement is STILL unmet:\n\n${summary}\n\n` +
179
+ `Do not claim the work is complete. Tell the user plainly what remains unmet and why.`;
180
+ await deps.log("error", standdownSummary, { reason, sessionID });
181
+ return { decision: "standdown", reason, summary: standdownSummary, changedFiles };
182
+ }
183
+ blockCounts.set(sessionID, blockCount);
184
+ await deps.log("error", summary, { reason, sessionID, blockCount, maxBlocks });
185
+ return {
186
+ decision: "blocked",
187
+ reason,
188
+ summary: `${summary}\n\n(Block ${blockCount}/${maxBlocks} this session.)`,
189
+ blockCount,
190
+ maxBlocks,
191
+ changedFiles,
192
+ };
193
+ }
package/dist/index.d.ts CHANGED
@@ -28,6 +28,12 @@ export interface HookState {
28
28
  blockCounts: Map<string, number>;
29
29
  precommitAvailable?: boolean;
30
30
  configMtime?: number;
31
+ /**
32
+ * Set once the `session.stopping` hook has actually been invoked by core —
33
+ * i.e. this OpenCode build supports pre-break gate vetoes (hard stops).
34
+ * Until then the idle re-prompt fallback is the only post-flight lever.
35
+ */
36
+ stopHookSupported?: boolean;
31
37
  }
32
38
  declare const plugin: Plugin.Plugin;
33
39
  export default plugin;
package/dist/index.js CHANGED
@@ -17,11 +17,12 @@ import { Plugin } from "@opencode/plugin";
17
17
  import { stat } from "node:fs/promises";
18
18
  import { join } from "node:path";
19
19
  import { clearConfigCache, loadConfig } from "./config.js";
20
- import { createChangedFileTracker, runGate, summarizeGate, } from "./gate.js";
20
+ import { createChangedFileTracker } from "./gate.js";
21
+ import { artifactState, evaluateCompletion, PREFLIGHT_ARTIFACT_REL, preflightBlockReason, } from "./harness.js";
21
22
  import { runCommand } from "./host.js";
22
- import { detectPreCommitAvailability, isLintFailure, lintFile, summarizeLint } from "./lint.js";
23
+ import { lintFile, detectPreCommitAvailability, isLintFailure, summarizeLint } from "./lint.js";
23
24
  import { createLogger } from "./logger.js";
24
- import { checkToolCall } from "./protect.js";
25
+ import { checkToolCall, extractFilePath } from "./protect.js";
25
26
  import { loadConstitution } from "./rules.js";
26
27
  let activeState = null;
27
28
  let fallbackLog = async () => { };
@@ -64,35 +65,47 @@ async function reloadConfigIfChanged(state) {
64
65
  // keep current state on read failure
65
66
  }
66
67
  }
67
- async function runGateVerdict(state, _sessionID) {
68
- if (!state.config.gate || state.config.profile === "off") {
69
- return { decision: "pass" };
70
- }
71
- const changedFiles = state.tracker.getChangedFiles();
72
- const report = await runGate(state.run, state.config, changedFiles, { cwd: state.directory });
73
- if (!report.ran || report.ok) {
74
- state.tracker.clearChangedFiles();
75
- state.blockCounts.delete(_sessionID);
76
- return { decision: "pass" };
68
+ /**
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.
73
+ */
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;
77
91
  }
78
- const maxBlocks = state.config.gate.max_blocks ?? 3;
79
- const blockCount = (state.blockCounts.get(_sessionID) ?? 0) + 1;
80
- state.blockCounts.set(_sessionID, blockCount);
81
- if (blockCount > maxBlocks) {
82
- state.tracker.clearChangedFiles();
83
- await safeLog(state, "warn", `completion gate has blocked ${maxBlocks} times; standing down but checks are still failing`, {
84
- failedSteps: report.failedSteps.map((s) => s.name),
85
- });
86
- return { decision: "standdown", failedSteps: report.failedSteps.map((s) => s.name) };
92
+ if (verdict.decision === "standdown") {
93
+ // evaluateCompletion already logged the stand-down loudly.
94
+ return null;
87
95
  }
88
- const summary = summarizeGate(report);
89
- await safeLog(state, "error", summary, { failedSteps: report.failedSteps.map((s) => s.name) });
90
- return { decision: "blocked", summary, blockCount, maxBlocks };
96
+ return continuationMessage(verdict);
91
97
  }
92
- function stoppingMessage(verdict) {
93
- return (`opencode-dev-framework completion gate blocked you from finishing (block ${verdict.blockCount}/${verdict.maxBlocks}). ` +
94
- `The following checks failed:\n\n${verdict.summary}\n\n` +
95
- `Fix the underlying cause and continue. Do NOT disable, skip, or weaken these checks to make them pass.`);
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),
108
+ });
96
109
  }
97
110
  // Helpers to normalize V2 event shapes (data vs properties vs direct)
98
111
  function getEventSessionID(event) {
@@ -192,9 +205,18 @@ const plugin = Plugin.define({
192
205
  configMtime,
193
206
  };
194
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);
215
+ }
216
+ }
195
217
  // 1) Constitution injection — per model request (V1: experimental.chat.system.transform -> V2: session.hook("context", ...))
196
218
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
197
- await ctx.session.hook("context", async (event) => {
219
+ trackRegistration(await ctx.session.hook("context", async (event) => {
198
220
  if (!activeState)
199
221
  return;
200
222
  await reloadConfigIfChanged(activeState);
@@ -211,12 +233,12 @@ const plugin = Plugin.define({
211
233
  text: activeState.constitution,
212
234
  });
213
235
  await safeLog(activeState, "info", "constitution injected into system prompt");
214
- });
236
+ }));
215
237
  // Also hook other request kinds so the reminder is not missed on title/generate
216
238
  // (no-op if model doesn't need it; cheap)
217
239
  for (const kind of ["generate", "compaction"]) {
218
240
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
219
- await ctx.session.hook(kind, async (event) => {
241
+ trackRegistration(await ctx.session.hook(kind, async (event) => {
220
242
  if (!activeState || activeState.config.profile === "off" || !activeState.constitution)
221
243
  return;
222
244
  // generate/compaction also have system — inject similarly if present
@@ -226,13 +248,54 @@ const plugin = Plugin.define({
226
248
  const already = ev.system.some((p) => p.text.includes(activeState.constitution));
227
249
  if (!already)
228
250
  ev.system.push({ type: "text", text: activeState.constitution });
229
- });
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");
230
289
  }
231
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.
232
294
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
233
- await ctx.tool.hook("execute.before", async (event) => {
295
+ trackRegistration(await ctx.tool.hook("execute.before", async (event) => {
234
296
  if (!activeState) {
235
- throw new Error("[opencode-dev-framework] plugin state is not available; guardrail cannot evaluate this tool call");
297
+ await safeLog(null, "warn", "[opencode-dev-framework] plugin state is not available; allowing tool call (fail-open after teardown)", { tool: event.tool });
298
+ return;
236
299
  }
237
300
  await reloadConfigIfChanged(activeState);
238
301
  if (activeState.config.profile === "off")
@@ -241,6 +304,23 @@ const plugin = Plugin.define({
241
304
  const toolName = event.tool;
242
305
  const input = event.input;
243
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
+ }
323
+ }
244
324
  // hostPermissions: not available in V2 permission model; pass undefined (conservative — still guard)
245
325
  const result = checkToolCall(activeState.config, toolName, input, activeState.directory, undefined);
246
326
  if (result.decision === "allow")
@@ -253,10 +333,10 @@ const plugin = Plugin.define({
253
333
  }
254
334
  await safeLog(activeState, "error", message, extra);
255
335
  throw new Error(`[opencode-dev-framework] ${message}`);
256
- });
336
+ }));
257
337
  // 3) Custom tools — V2: ctx.tool.transform(editor => editor.add(...))
258
338
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
259
- await ctx.tool.transform((editor) => {
339
+ trackRegistration(await ctx.tool.transform((editor) => {
260
340
  editor.add({
261
341
  name: "dev_framework_init",
262
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.",
@@ -368,7 +448,7 @@ const plugin = Plugin.define({
368
448
  };
369
449
  },
370
450
  });
371
- });
451
+ }));
372
452
  // 4) Event subscription — file tracking + gate enforcement (V1: event hook)
373
453
  // Keeps the completion gate intent without session.stopping: on idle, run gate;
374
454
  // on failure inside budget, re-prompt the session (async block).
@@ -446,15 +526,15 @@ const plugin = Plugin.define({
446
526
  const sessionID = getEventSessionID(event);
447
527
  if (!sessionID)
448
528
  continue;
449
- const verdict = await runGateVerdict(activeState, sessionID);
450
- if (verdict.decision === "pass")
529
+ const verdict = await runCompletion(activeState, sessionID);
530
+ const message = await actOnVerdict(activeState, verdict);
531
+ if (message === null)
451
532
  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);
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)
458
538
  try {
459
539
  // Prefer prompt (creates a user turn and wakes the agent); fallback to synthetic if prompt not available
460
540
  if (typeof ctx.session.prompt === "function") {
@@ -466,7 +546,7 @@ const plugin = Plugin.define({
466
546
  else {
467
547
  await safeLog(activeState, "error", `gate blocked but no session prompt API available: ${message}`);
468
548
  }
469
- await safeLog(activeState, "info", `completion gate re-prompted session ${sessionID} (block ${verdict.blockCount}/${verdict.maxBlocks})`);
549
+ await safeLog(activeState, "info", `completion gate re-prompted session ${sessionID}${blockInfo}`);
470
550
  }
471
551
  catch (err) {
472
552
  await safeLog(activeState, "error", `failed to re-prompt session ${sessionID} after gate block: ${String(err)}`, {
@@ -486,9 +566,25 @@ const plugin = Plugin.define({
486
566
  })();
487
567
  // Ensure the loop doesn't block setup
488
568
  void eventLoop;
489
- return () => {
569
+ return async () => {
490
570
  controller.abort();
491
- activeState = null;
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();
578
+ }
579
+ catch {
580
+ // ignore — fail-open guard is the safety net
581
+ }
582
+ }
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
+ }
492
588
  };
493
589
  },
494
590
  });
package/dist/installer.js CHANGED
@@ -210,9 +210,20 @@ function buildDefaultConfigYaml(language, commands, hasPreCommitConfig) {
210
210
  lines.push(" skip_unchanged: true");
211
211
  lines.push(" scope: all");
212
212
  lines.push(" lint_changed: false");
213
+ lines.push(" # standard/strict default: sessions that changed files must produce a");
214
+ lines.push(" # peer-review artifact (.opencode/opencode-dev-framework/review.md).");
215
+ lines.push(" require_review: true");
213
216
  lines.push(" timeout: 300");
214
217
  lines.push(" max_blocks: 3");
215
218
  lines.push("");
219
+ lines.push("# Optional: pre-flight task list. When set, edit tools are denied");
220
+ lines.push("# (standard/strict) until the agent writes its findings to");
221
+ lines.push("# .opencode/opencode-dev-framework/preflight.md. Use for work that");
222
+ lines.push("# must establish baseline state/knowledge before editing.");
223
+ lines.push("# preflight:");
224
+ lines.push('# - "Summarize the current state of the component you will change"');
225
+ lines.push('# - "Record the baseline metrics this work will be judged against"');
226
+ lines.push("");
216
227
  lines.push("on_edit:");
217
228
  lines.push(" format: true");
218
229
  lines.push(" lint: true");
@@ -32,6 +32,8 @@ export interface HookState {
32
32
  /** mtime (ms) of the config file at last load; used to detect out-of-process
33
33
  * edits (e.g. a `/df-profile` change made from the TUI module). */
34
34
  configMtime?: number;
35
+ /** True once core has actually dispatched `session.stopping` (hard stops active). */
36
+ stopHookSupported?: boolean;
35
37
  }
36
38
  export declare function setBaseDirectory(directory: string): void;
37
39
  export declare function getBaseDirectory(): string | null;
package/dist/types.d.ts CHANGED
@@ -29,9 +29,14 @@ export interface GateConfig {
29
29
  skip_unchanged: boolean;
30
30
  scope: GateScope;
31
31
  lint_changed: boolean;
32
+ /**
33
+ * When true (standard/strict default), a session that changed files must
34
+ * also produce a peer-review artifact before the completion gate passes.
35
+ */
36
+ require_review: boolean;
32
37
  /** Per-command timeout in seconds. */
33
38
  timeout?: number;
34
- /** Reserved for future use; advisory mode currently ignores this. */
39
+ /** Maximum number of times a failing gate may re-block before standing down. */
35
40
  max_blocks: number;
36
41
  }
37
42
  export interface OnEditConfig {
@@ -62,6 +67,12 @@ export interface Config {
62
67
  style_guide?: string;
63
68
  /** Use pre-commit for per-file linting when available (`auto`) or never (`off`). */
64
69
  precommit?: "auto" | "off";
70
+ /**
71
+ * Pre-flight task list: knowledge/state-building tasks that must be
72
+ * completed (and written to the pre-flight artifact) before edit tools
73
+ * are allowed. Empty (default) disables pre-flight enforcement.
74
+ */
75
+ preflight?: string[];
65
76
  }
66
77
  /**
67
78
  * Fully resolved config with profile defaults applied. All consumers of the
@@ -81,4 +92,5 @@ export interface ResolvedConfig {
81
92
  rules?: RulesConfig;
82
93
  style_guide?: string;
83
94
  precommit: "auto" | "off";
95
+ preflight: string[];
84
96
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-dev-framework",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "OpenCode plugin that enforces project-specific quality gates during AI coding sessions",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,5 +1,6 @@
1
1
  ---
2
2
  name: code-reviewer
3
+ mode: subagent
3
4
  description: >
4
5
  Correctness reviewer. Scans changed code for bugs, logic errors, security
5
6
  issues, and unsafe edge cases — independent of style and pattern concerns.
@@ -1,5 +1,6 @@
1
1
  ---
2
2
  name: pattern-guardian
3
+ mode: subagent
3
4
  description: >
4
5
  Anti-drift reviewer. Checks new or changed code against the patterns already
5
6
  established in this codebase and flags duplication, re-invented helpers,
@@ -1,5 +1,6 @@
1
1
  ---
2
2
  name: style-enforcer
3
+ mode: subagent
3
4
  description: >
4
5
  Style-guide reviewer. Checks changed files against the project's documented
5
6
  style guide (and, in its absence, the conventions of the surrounding code):
@@ -1,5 +1,6 @@
1
1
  ---
2
2
  name: test-grounder
3
+ mode: subagent
3
4
  description: >
4
5
  Evidence auditor. Verifies that claims about a change are backed by reality:
5
6
  that new behavior has a test which fails without the change and passes with