opencode-dev-framework 0.2.2 → 0.2.4
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 +41 -15
- package/dist/config.js +27 -1
- package/dist/format-status.js +15 -0
- package/dist/harness.d.ts +90 -0
- package/dist/harness.js +193 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +219 -100
- package/dist/installer.js +11 -0
- package/dist/registry.d.ts +2 -0
- package/dist/types.d.ts +13 -1
- package/package.json +1 -1
- 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/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
|
|
23
|
-
|
|
24
|
-
|
|
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
|
-
- **
|
|
195
|
-
(
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
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
|
-
|
|
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). */
|
package/dist/format-status.js
CHANGED
|
@@ -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>;
|
package/dist/harness.js
ADDED
|
@@ -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
|
|
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,
|
|
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
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
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
|
-
|
|
79
|
-
|
|
80
|
-
|
|
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
|
-
|
|
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
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
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,71 +205,153 @@ 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
|
+
}
|
|
217
|
+
// Stale-hook guard: every closure below captures its own `state` and
|
|
218
|
+
// no-ops when it is no longer the live singleton. This covers three
|
|
219
|
+
// cases disposal alone cannot: (a) teardown with no fresh setup
|
|
220
|
+
// (activeState is null), (b) teardown + reload where an old
|
|
221
|
+
// registration outlives disposal (activeState is a newer state —
|
|
222
|
+
// the stale hook must NOT double-enforce), and (c) teardown racing
|
|
223
|
+
// an in-flight handler between awaits (captured `state` stays valid
|
|
224
|
+
// while the global may be cleared). See issue #1 follow-up.
|
|
195
225
|
// 1) Constitution injection — per model request (V1: experimental.chat.system.transform -> V2: session.hook("context", ...))
|
|
196
226
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
197
|
-
await ctx.session.hook("context", async (event) => {
|
|
198
|
-
if (
|
|
227
|
+
trackRegistration(await ctx.session.hook("context", async (event) => {
|
|
228
|
+
if (activeState !== state)
|
|
199
229
|
return;
|
|
200
|
-
await reloadConfigIfChanged(
|
|
201
|
-
if (
|
|
230
|
+
await reloadConfigIfChanged(state);
|
|
231
|
+
if (state.config.profile === "off")
|
|
202
232
|
return;
|
|
203
|
-
if (!
|
|
233
|
+
if (!state.constitution)
|
|
204
234
|
return;
|
|
205
235
|
// V2 system is Array<SystemPart> {type:"text", text:string}
|
|
206
|
-
const already = event.system.some((part) => part.text.includes(
|
|
236
|
+
const already = event.system.some((part) => part.text.includes(state.constitution));
|
|
207
237
|
if (already)
|
|
208
238
|
return;
|
|
209
239
|
event.system.push({
|
|
210
240
|
type: "text",
|
|
211
|
-
text:
|
|
241
|
+
text: state.constitution,
|
|
212
242
|
});
|
|
213
|
-
await safeLog(
|
|
214
|
-
});
|
|
243
|
+
await safeLog(state, "info", "constitution injected into system prompt");
|
|
244
|
+
}));
|
|
215
245
|
// Also hook other request kinds so the reminder is not missed on title/generate
|
|
216
246
|
// (no-op if model doesn't need it; cheap)
|
|
217
247
|
for (const kind of ["generate", "compaction"]) {
|
|
218
248
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
219
|
-
await ctx.session.hook(kind, async (event) => {
|
|
220
|
-
if (
|
|
249
|
+
trackRegistration(await ctx.session.hook(kind, async (event) => {
|
|
250
|
+
if (activeState !== state)
|
|
251
|
+
return;
|
|
252
|
+
if (state.config.profile === "off" || !state.constitution)
|
|
221
253
|
return;
|
|
222
254
|
// generate/compaction also have system — inject similarly if present
|
|
223
255
|
const ev = event;
|
|
224
256
|
if (!ev.system)
|
|
225
257
|
return;
|
|
226
|
-
const already = ev.system.some((p) => p.text.includes(
|
|
258
|
+
const already = ev.system.some((p) => p.text.includes(state.constitution));
|
|
227
259
|
if (!already)
|
|
228
|
-
ev.system.push({ type: "text", text:
|
|
229
|
-
});
|
|
260
|
+
ev.system.push({ type: "text", text: state.constitution });
|
|
261
|
+
}));
|
|
262
|
+
}
|
|
263
|
+
// 1b) Hard-stop completion gate — `session.stopping` (OpenCode PR #44712).
|
|
264
|
+
// Fires before the agent loop breaks on natural exit: a blocked verdict
|
|
265
|
+
// sets stop=false + message and the loop re-enters, so gate failures
|
|
266
|
+
// physically prevent completion. Registered defensively: on builds
|
|
267
|
+
// without core support the hook is simply never dispatched, and the
|
|
268
|
+
// session.idle fallback below provides re-prompt enforcement instead.
|
|
269
|
+
// The first invocation flips `stopHookSupported` so /df-status can show
|
|
270
|
+
// which enforcement level is active.
|
|
271
|
+
try {
|
|
272
|
+
trackRegistration(
|
|
273
|
+
// biome-ignore lint/suspicious/noExplicitAny: V2 hook names are not yet typed for session.stopping
|
|
274
|
+
await ctx.session.hook("stopping",
|
|
275
|
+
// biome-ignore lint/suspicious/noExplicitAny: core may dispatch (input, output) or a single mutable event
|
|
276
|
+
async (input, output) => {
|
|
277
|
+
if (activeState !== state)
|
|
278
|
+
return;
|
|
279
|
+
const out = output ?? input ?? {};
|
|
280
|
+
const sessionID = input?.sessionID ??
|
|
281
|
+
out.sessionID ??
|
|
282
|
+
getEventSessionID(input) ??
|
|
283
|
+
"unknown";
|
|
284
|
+
state.stopHookSupported = true;
|
|
285
|
+
await reloadConfigIfChanged(state);
|
|
286
|
+
if (state.config.profile === "off")
|
|
287
|
+
return;
|
|
288
|
+
const verdict = await runCompletion(state, sessionID);
|
|
289
|
+
const message = await actOnVerdict(state, verdict);
|
|
290
|
+
if (message !== null) {
|
|
291
|
+
out.stop = false;
|
|
292
|
+
out.message = message;
|
|
293
|
+
}
|
|
294
|
+
}));
|
|
295
|
+
await safeLog(state, "info", "registered session.stopping hook; if this OpenCode build dispatches it, gate failures become hard stops before loop exit");
|
|
296
|
+
}
|
|
297
|
+
catch {
|
|
298
|
+
await safeLog(state, "warn", "could not register session.stopping hook; using session.idle re-prompt fallback only");
|
|
230
299
|
}
|
|
231
300
|
// 2) Guardrails — tool execution blocking (V1: tool.execute.before -> V2: ctx.tool.hook("execute.before", ...))
|
|
301
|
+
// Stale-hook fail-open: the closure captures its own `state` and allows
|
|
302
|
+
// the call whenever it is no longer live — torn down (activeState null)
|
|
303
|
+
// or superseded by a newer setup (activeState is a different instance,
|
|
304
|
+
// whose own hook enforces; this one must not double-enforce). Using the
|
|
305
|
+
// captured `state` throughout also closes the teardown race where the
|
|
306
|
+
// global is cleared between awaits. See issue #1.
|
|
232
307
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
233
|
-
await ctx.tool.hook("execute.before", async (event) => {
|
|
234
|
-
if (
|
|
235
|
-
|
|
308
|
+
trackRegistration(await ctx.tool.hook("execute.before", async (event) => {
|
|
309
|
+
if (activeState !== state) {
|
|
310
|
+
if (activeState == null) {
|
|
311
|
+
await safeLog(null, "warn", "[opencode-dev-framework] plugin state is not available; allowing tool call (fail-open after teardown)", { tool: event.tool });
|
|
312
|
+
}
|
|
313
|
+
return;
|
|
236
314
|
}
|
|
237
|
-
await reloadConfigIfChanged(
|
|
238
|
-
if (
|
|
315
|
+
await reloadConfigIfChanged(state);
|
|
316
|
+
if (state.config.profile === "off")
|
|
239
317
|
return;
|
|
240
318
|
// V2 event shapes: { tool, sessionID, agent, messageID, id, input: unknown }
|
|
241
319
|
const toolName = event.tool;
|
|
242
320
|
const input = event.input;
|
|
243
321
|
const sessionID = event.sessionID;
|
|
322
|
+
// Pre-flight harness: when `preflight:` tasks are configured, file
|
|
323
|
+
// edits are denied (standard/strict) until the pre-flight artifact
|
|
324
|
+
// exists. This is a true hard gate — it runs before the edit lands.
|
|
325
|
+
if (state.config.preflight.length > 0) {
|
|
326
|
+
const artifact = await artifactState(state.directory, PREFLIGHT_ARTIFACT_REL);
|
|
327
|
+
const reason = preflightBlockReason(state.config, toolName, extractFilePath(input), artifact);
|
|
328
|
+
if (reason !== null) {
|
|
329
|
+
const extra = { tool: toolName, sessionID, artifact: PREFLIGHT_ARTIFACT_REL };
|
|
330
|
+
if (state.config.profile === "advisory") {
|
|
331
|
+
await safeLog(state, "warn", reason, extra);
|
|
332
|
+
}
|
|
333
|
+
else {
|
|
334
|
+
await safeLog(state, "error", reason, extra);
|
|
335
|
+
throw new Error(`[opencode-dev-framework] ${reason}`);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
244
339
|
// hostPermissions: not available in V2 permission model; pass undefined (conservative — still guard)
|
|
245
|
-
const result = checkToolCall(
|
|
340
|
+
const result = checkToolCall(state.config, toolName, input, state.directory, undefined);
|
|
246
341
|
if (result.decision === "allow")
|
|
247
342
|
return;
|
|
248
343
|
const message = result.reason ?? "blocked by guardrails";
|
|
249
344
|
const extra = { tool: toolName, sessionID, pattern: result.matchedPattern };
|
|
250
345
|
if (result.decision === "warn") {
|
|
251
|
-
await safeLog(
|
|
346
|
+
await safeLog(state, "warn", message, extra);
|
|
252
347
|
return;
|
|
253
348
|
}
|
|
254
|
-
await safeLog(
|
|
349
|
+
await safeLog(state, "error", message, extra);
|
|
255
350
|
throw new Error(`[opencode-dev-framework] ${message}`);
|
|
256
|
-
});
|
|
351
|
+
}));
|
|
257
352
|
// 3) Custom tools — V2: ctx.tool.transform(editor => editor.add(...))
|
|
258
353
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
259
|
-
await ctx.tool.transform((editor) => {
|
|
354
|
+
trackRegistration(await ctx.tool.transform((editor) => {
|
|
260
355
|
editor.add({
|
|
261
356
|
name: "dev_framework_init",
|
|
262
357
|
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.",
|
|
@@ -335,7 +430,11 @@ const plugin = Plugin.define({
|
|
|
335
430
|
ccc();
|
|
336
431
|
const newConfig = lc(targetDir);
|
|
337
432
|
const { constitution: newConstitution } = await lc2(newConfig, targetDir);
|
|
338
|
-
if (
|
|
433
|
+
if (state.directory === targetDir) {
|
|
434
|
+
state.config = newConfig;
|
|
435
|
+
state.constitution = newConstitution;
|
|
436
|
+
}
|
|
437
|
+
if (activeState && activeState !== state && activeState.directory === targetDir) {
|
|
339
438
|
activeState.config = newConfig;
|
|
340
439
|
activeState.constitution = newConstitution;
|
|
341
440
|
}
|
|
@@ -359,16 +458,16 @@ const plugin = Plugin.define({
|
|
|
359
458
|
const { renderStatus } = await import("./format-status.js");
|
|
360
459
|
const args = input;
|
|
361
460
|
const targetDir = args.directory ?? directory;
|
|
362
|
-
const
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
// renderStatus expects HookState? pass
|
|
461
|
+
const live = activeState && activeState.directory === targetDir ? activeState : null;
|
|
462
|
+
const own = state.directory === targetDir ? state : null;
|
|
463
|
+
const cfg = (live ?? own)?.config ?? loadConfig(targetDir);
|
|
464
|
+
// renderStatus expects HookState? pass live ?? own (may be null for other dirs)
|
|
366
465
|
return {
|
|
367
|
-
content: renderStatus(cfg,
|
|
466
|
+
content: renderStatus(cfg, (live ?? own)),
|
|
368
467
|
};
|
|
369
468
|
},
|
|
370
469
|
});
|
|
371
|
-
});
|
|
470
|
+
}));
|
|
372
471
|
// 4) Event subscription — file tracking + gate enforcement (V1: event hook)
|
|
373
472
|
// Keeps the completion gate intent without session.stopping: on idle, run gate;
|
|
374
473
|
// on failure inside budget, re-prompt the session (async block).
|
|
@@ -376,85 +475,88 @@ const plugin = Plugin.define({
|
|
|
376
475
|
const eventLoop = (async () => {
|
|
377
476
|
try {
|
|
378
477
|
for await (const rawEvent of ctx.event.subscribe({ signal: controller.signal })) {
|
|
478
|
+
// Stale-loop guard: a previous setup's loop must exit rather than
|
|
479
|
+
// hijack a newer setup's state (duplicate gate re-prompts / lint).
|
|
480
|
+
if (activeState !== state)
|
|
481
|
+
return;
|
|
379
482
|
const event = rawEvent;
|
|
380
483
|
const type = event.type;
|
|
381
484
|
if (isSessionDeletedEvent(type)) {
|
|
382
485
|
// session.deleted: cleanup blockCounts (and tracker if needed)
|
|
383
486
|
const sid = getEventSessionID(event);
|
|
384
|
-
if (sid
|
|
385
|
-
|
|
487
|
+
if (sid)
|
|
488
|
+
state.blockCounts.delete(sid);
|
|
386
489
|
continue;
|
|
387
490
|
}
|
|
388
491
|
if (isFilesystemChangedEvent(type)) {
|
|
389
|
-
if (
|
|
390
|
-
|
|
391
|
-
await reloadConfigIfChanged(
|
|
392
|
-
if (
|
|
492
|
+
if (activeState !== state)
|
|
493
|
+
return;
|
|
494
|
+
await reloadConfigIfChanged(state);
|
|
495
|
+
if (state.config.profile === "off")
|
|
393
496
|
continue;
|
|
394
497
|
const filePath = getEventFilePath(event);
|
|
395
498
|
if (!filePath)
|
|
396
499
|
continue;
|
|
397
|
-
|
|
500
|
+
state.tracker.add(filePath, state.directory);
|
|
398
501
|
// per-edit lint (V1: event file.edited -> lintFile)
|
|
399
|
-
if (!
|
|
502
|
+
if (!state.config.on_edit.lint)
|
|
400
503
|
continue;
|
|
401
|
-
if (
|
|
402
|
-
|
|
403
|
-
activeState.precommitAvailable = await detectPreCommitAvailability(activeState.run, activeState.directory);
|
|
504
|
+
if (state.config.precommit === "auto" && state.precommitAvailable === undefined) {
|
|
505
|
+
state.precommitAvailable = await detectPreCommitAvailability(state.run, state.directory);
|
|
404
506
|
}
|
|
405
|
-
const outcome = await lintFile(
|
|
406
|
-
cwd:
|
|
407
|
-
timeout:
|
|
408
|
-
precommitAvailable:
|
|
507
|
+
const outcome = await lintFile(state.run, state.config, filePath, {
|
|
508
|
+
cwd: state.directory,
|
|
509
|
+
timeout: state.config.gate?.timeout,
|
|
510
|
+
precommitAvailable: state.precommitAvailable,
|
|
409
511
|
});
|
|
410
512
|
if (outcome.skipped) {
|
|
411
|
-
await safeLog(
|
|
513
|
+
await safeLog(state, "debug", summarizeLint(outcome), {
|
|
412
514
|
filePath,
|
|
413
515
|
reason: outcome.reason,
|
|
414
516
|
});
|
|
415
517
|
continue;
|
|
416
518
|
}
|
|
417
519
|
if (!isLintFailure(outcome)) {
|
|
418
|
-
await safeLog(
|
|
520
|
+
await safeLog(state, "info", summarizeLint(outcome), { filePath });
|
|
419
521
|
continue;
|
|
420
522
|
}
|
|
421
523
|
const summary = summarizeLint(outcome);
|
|
422
|
-
await safeLog(
|
|
524
|
+
await safeLog(state, "error", summary, {
|
|
423
525
|
filePath,
|
|
424
526
|
command: outcome.command?.join(" "),
|
|
425
527
|
stdout: outcome.result?.stdout,
|
|
426
528
|
stderr: outcome.result?.stderr,
|
|
427
529
|
});
|
|
428
|
-
if (
|
|
530
|
+
if (state.config.profile === "strict") {
|
|
429
531
|
// Event handlers cannot throw to block the edit (edit already happened), but we log loudly.
|
|
430
532
|
// In V2 we also have the tool hook to block before; this is advisory.
|
|
431
533
|
}
|
|
432
534
|
continue;
|
|
433
535
|
}
|
|
434
536
|
if (isIdleEvent(event)) {
|
|
435
|
-
if (
|
|
537
|
+
if (activeState !== state)
|
|
538
|
+
return;
|
|
539
|
+
await reloadConfigIfChanged(state);
|
|
540
|
+
if (state.config.profile === "off")
|
|
436
541
|
continue;
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
if (!activeState.config.gate) {
|
|
441
|
-
await safeLog(activeState, "warn", "plugin config is incomplete (missing gate section), skipping completion gate", {
|
|
442
|
-
directory: activeState.directory,
|
|
542
|
+
if (!state.config.gate) {
|
|
543
|
+
await safeLog(state, "warn", "plugin config is incomplete (missing gate section), skipping completion gate", {
|
|
544
|
+
directory: state.directory,
|
|
443
545
|
});
|
|
444
546
|
continue;
|
|
445
547
|
}
|
|
446
548
|
const sessionID = getEventSessionID(event);
|
|
447
549
|
if (!sessionID)
|
|
448
550
|
continue;
|
|
449
|
-
const verdict = await
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
if (verdict.decision === "standdown") {
|
|
453
|
-
// already logged in runGateVerdict; do not re-prompt
|
|
551
|
+
const verdict = await runCompletion(state, sessionID);
|
|
552
|
+
const message = await actOnVerdict(state, verdict);
|
|
553
|
+
if (message === null)
|
|
454
554
|
continue;
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
555
|
+
const blockInfo = verdict.decision === "blocked"
|
|
556
|
+
? ` (block ${verdict.blockCount}/${verdict.maxBlocks})`
|
|
557
|
+
: "";
|
|
558
|
+
// blocked -> re-prompt the session (fallback when session.stopping
|
|
559
|
+
// is not dispatched by this OpenCode build)
|
|
458
560
|
try {
|
|
459
561
|
// Prefer prompt (creates a user turn and wakes the agent); fallback to synthetic if prompt not available
|
|
460
562
|
if (typeof ctx.session.prompt === "function") {
|
|
@@ -464,12 +566,12 @@ const plugin = Plugin.define({
|
|
|
464
566
|
await ctx.session.synthetic({ sessionID, text: message });
|
|
465
567
|
}
|
|
466
568
|
else {
|
|
467
|
-
await safeLog(
|
|
569
|
+
await safeLog(state, "error", `gate blocked but no session prompt API available: ${message}`);
|
|
468
570
|
}
|
|
469
|
-
await safeLog(
|
|
571
|
+
await safeLog(state, "info", `completion gate re-prompted session ${sessionID}${blockInfo}`);
|
|
470
572
|
}
|
|
471
573
|
catch (err) {
|
|
472
|
-
await safeLog(
|
|
574
|
+
await safeLog(state, "error", `failed to re-prompt session ${sessionID} after gate block: ${String(err)}`, {
|
|
473
575
|
sessionID,
|
|
474
576
|
});
|
|
475
577
|
}
|
|
@@ -481,14 +583,31 @@ const plugin = Plugin.define({
|
|
|
481
583
|
// normal on dispose
|
|
482
584
|
return;
|
|
483
585
|
}
|
|
484
|
-
await safeLog(
|
|
586
|
+
await safeLog(state, "error", `event loop error: ${String(err)}`);
|
|
485
587
|
}
|
|
486
588
|
})();
|
|
487
589
|
// Ensure the loop doesn't block setup
|
|
488
590
|
void eventLoop;
|
|
489
|
-
return () => {
|
|
591
|
+
return async () => {
|
|
490
592
|
controller.abort();
|
|
491
|
-
|
|
593
|
+
// Unregister every hook/transform registered by this setup() so a
|
|
594
|
+
// teardown/reload (e.g. session_move into a worktree) does not leave
|
|
595
|
+
// stale closures alive. Disposal failures are ignored — the
|
|
596
|
+
// stale-hook guard (`activeState !== state` → no-op / fail-open) keeps
|
|
597
|
+
// the session usable regardless.
|
|
598
|
+
for (const registration of registrations) {
|
|
599
|
+
try {
|
|
600
|
+
await registration.dispose();
|
|
601
|
+
}
|
|
602
|
+
catch {
|
|
603
|
+
// ignore — stale-hook guard is the safety net
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
// Only clear the singleton if it is still ours; a newer setup() may
|
|
607
|
+
// already have replaced it (reload race).
|
|
608
|
+
if (activeState === state) {
|
|
609
|
+
activeState = null;
|
|
610
|
+
}
|
|
492
611
|
};
|
|
493
612
|
},
|
|
494
613
|
});
|
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");
|
package/dist/registry.d.ts
CHANGED
|
@@ -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
|
-
/**
|
|
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