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 CHANGED
@@ -18,11 +18,21 @@ reimplemented as an OpenCode-native plugin.
18
18
  - **Per-edit lint.** Runs your configured linter on each file the agent edits
19
19
  and reports failures loudly. Optionally delegates per-file linting to
20
20
  `pre-commit run --files` when `precommit: auto` is set.
21
- - **Completion gate.** When the session goes idle, runs typecheck, tests, and
22
- (optionally) lint on changed files. In OpenCode versions with the
23
- `experimental.session.stopping` hook, gate failures keep the session running
24
- (up to `gate.max_blocks` times) so the agent must fix the failures. In older
25
- versions the gate reports loudly via `session.idle`.
21
+ - **Completion gate.** When the session goes idle (`session.idle`/`session.status:idle`),
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.
26
36
  - **Custom tools.** `dev_framework_init` scaffolds project-level agents,
27
37
  skills, local rules directory, and config; `dev_framework_set_profile` changes the profile
28
38
  in-session without restarting; `dev_framework_status` reports the current
@@ -43,12 +53,12 @@ reimplemented as an OpenCode-native plugin.
43
53
 
44
54
  ## Profiles
45
55
 
46
- | Profile | Guardrails | Gate failures | Lint on edit | Notes |
47
- | ---------- | ---------- | ------------- | ------------ | ----- |
48
- | `off` | disabled | not reported | no | Plugin registers no hooks at all. |
49
- | `advisory` | warn | warn | yes | Nothing blocks; everything is logged. |
50
- | `standard` | deny | error | yes | The default when a config file exists. |
51
- | `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. |
52
62
 
53
63
  ## Install
54
64
 
@@ -60,14 +70,13 @@ Then add the plugin to your project's `opencode.json`:
60
70
 
61
71
  ```json
62
72
  {
63
- "plugin": ["opencode-dev-framework"]
73
+ "plugins": ["opencode-dev-framework"]
64
74
  }
65
75
  ```
66
76
 
67
- On OpenCode 1.18.18+ the `./tui` companion (the `/df-status` and `/df-help`
68
- modals) is auto-discovered from the npm plugin entry above, so the server and
69
- TUI parts load together. (On older builds, or if the modals do not appear, also
70
- add the package to `tui.json` — see *Local development* below.)
77
+ Requires OpenCode `v2.0.0+` (`@opencode/plugin` `^2`). On `v1.18.18–1.18.31` use the `v1` branch
78
+ of this plugin (`plugin` key). The `./tui` companion (`/df-status` and `/df-help`
79
+ modals) is auto-discovered from the npm entry on `v2` — no separate `tui.json` needed.
71
80
 
72
81
  Finally, scaffold the project-level files (agents, skills, local rules directory,
73
82
  and default config) into your repo with the bundled `df` CLI:
@@ -94,25 +103,16 @@ local filesystem paths — it only loads when the package is listed in the TUI
94
103
  config. OpenCode reads `tui.json` from the global config dir
95
104
  (`~/.config/opencode/tui.json`) and the project dir (`.opencode/tui.json`).
96
105
 
97
- `opencode.json` (server plugin):
106
+ `opencode.json` (V2):
98
107
 
99
108
  ```json
100
109
  {
101
- "plugin": ["/home/jerome/opencode-dev-framework"]
102
- }
103
- ```
104
-
105
- `tui.json` (TUI plugin — same path):
106
-
107
- ```json
108
- {
109
- "plugin": ["/home/jerome/opencode-dev-framework"]
110
+ "plugins": ["/home/jerome/opencode-dev-framework"]
110
111
  }
111
112
  ```
112
113
 
113
114
  The path must be the **repository root** (where `package.json` lives). OpenCode
114
- loads the server plugin from `dist/index.js` and the TUI plugin from `tui.tsx`,
115
- so rebuild after every source change:
115
+ loads the plugin from `dist/index.js` (TUI from `tui.tsx`), so rebuild after every source change:
116
116
 
117
117
  ```bash
118
118
  npm run build
@@ -156,6 +156,17 @@ gate:
156
156
  run_typecheck: true
157
157
  run_tests: true
158
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"
159
170
 
160
171
  on_edit:
161
172
  lint: true
@@ -202,15 +213,16 @@ itself).
202
213
 
203
214
  ## Limitations
204
215
 
205
- - **The completion gate blocks only in newer OpenCode versions.** Newer
206
- builds support the `session.stopping` hook (OpenCode PR #44712) and
207
- the earlier `experimental.session.stopping` hook (PR #41811); either
208
- lets the plugin keep the session running until checks pass. The new
209
- hook uses a fail-closed `{ stop, message }` contract and applies only
210
- to natural loop exits; OpenCode core also caps continuations at 3
211
- regardless of `gate.max_blocks`. In older OpenCode versions the gate
212
- runs on `session.idle` and reports failures loudly but cannot force
213
- the agent to keep working.
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.
214
226
  - **Guardrails run inside OpenCode.** The `tool.execute.before` hook runs
215
227
  after OpenCode's own permission system; it adds project rules on top, it
216
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
  }
package/dist/gate.d.ts CHANGED
@@ -3,8 +3,8 @@
3
3
  * session tries to stop, plus the changed-file tracking that feeds it.
4
4
  *
5
5
  * The gate runs from two call sites:
6
- * - `experimental.session.stopping` (OpenCode PR #41811): on failure, a
7
- * synthetic user message keeps the session running, up to `gate.max_blocks`.
6
+ * - `session.stopping` (OpenCode PR #44712): on failure, the adapter sets
7
+ * `stop: false` with a continuation message, up to `gate.max_blocks`.
8
8
  * - `session.idle` (fallback on older OpenCode): advisory logging only — by
9
9
  * then the agent's turn has already finished, so failures cannot block.
10
10
  */
package/dist/gate.js CHANGED
@@ -3,8 +3,8 @@
3
3
  * session tries to stop, plus the changed-file tracking that feeds it.
4
4
  *
5
5
  * The gate runs from two call sites:
6
- * - `experimental.session.stopping` (OpenCode PR #41811): on failure, a
7
- * synthetic user message keeps the session running, up to `gate.max_blocks`.
6
+ * - `session.stopping` (OpenCode PR #44712): on failure, the adapter sets
7
+ * `stop: false` with a continuation message, up to `gate.max_blocks`.
8
8
  * - `session.idle` (fallback on older OpenCode): advisory logging only — by
9
9
  * then the agent's turn has already finished, so failures cannot block.
10
10
  */
@@ -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
@@ -1,51 +1,39 @@
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
  */
14
- import type { Hooks, Plugin, PluginInput } from "@opencode-ai/plugin";
16
+ import { Plugin } from "@opencode/plugin";
15
17
  import { type ChangedFileTracker } from "./gate.js";
16
18
  import { type RunCommand } from "./host.js";
17
19
  import { type LogFn } from "./logger.js";
18
20
  import type { ResolvedConfig } from "./types.js";
19
- /**
20
- * OpenCode exposes two competing "loop continuation" hooks that are not yet in
21
- * the published `@opencode-ai/plugin` types, so we declare both locally and use
22
- * whichever the runtime supports:
23
- *
24
- * - `experimental.session.stopping` (OpenCode PR #41811): plugin pushes text
25
- * into `output.context`; presence keeps the session running.
26
- * - `session.stopping` (OpenCode PR #44712): fail-closed contract. The default
27
- * `stop: true` lets the session end; setting `stop: false` with a non-empty
28
- * `message` injects a synthetic user turn and continues the loop. The hook
29
- * fires only on natural loop exit and OpenCode core enforces its own
30
- * re-entry cap (3) regardless of `gate.max_blocks`.
31
- */
32
- export interface HooksWithStopping extends Hooks {
33
- "experimental.session.stopping"?: (input: {
34
- sessionID: string;
35
- }, output: {
36
- context: string[];
37
- }) => Promise<void>;
38
- "session.stopping"?: (input: {
39
- sessionID: string;
40
- }, output: {
41
- stop: boolean;
42
- message?: string;
43
- }) => Promise<void>;
21
+ export interface HookState {
22
+ directory: string;
23
+ config: ResolvedConfig;
24
+ log: LogFn;
25
+ run: RunCommand;
26
+ tracker: ChangedFileTracker;
27
+ constitution: string | null;
28
+ blockCounts: Map<string, number>;
29
+ precommitAvailable?: boolean;
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;
44
37
  }
45
- /**
46
- * Build the plugin's hooks and custom tools. Exported (rather than inlined in
47
- * the plugin) so tests can inject a stubbed command runner and tracker.
48
- */
49
- export declare function buildHooks(ctx: PluginInput, config: ResolvedConfig, log: LogFn, run?: RunCommand, tracker?: ChangedFileTracker, constitution?: string | null, configMtime?: number): HooksWithStopping;
50
- export declare const devFramework: Plugin;
51
- export default devFramework;
38
+ declare const plugin: Plugin.Plugin;
39
+ export default plugin;