opencode-dev-framework 0.2.3 → 0.3.0
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 -18
- package/dist/block-store.d.ts +36 -0
- package/dist/block-store.js +117 -0
- package/dist/gate.d.ts +2 -0
- package/dist/gate.js +11 -5
- package/dist/harness.d.ts +2 -1
- package/dist/harness.js +3 -4
- package/dist/index.d.ts +17 -3
- package/dist/index.js +292 -108
- package/dist/protect.d.ts +16 -0
- package/dist/protect.js +32 -0
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -36,20 +36,16 @@ reimplemented as an OpenCode-native plugin.
|
|
|
36
36
|
- **Custom tools.** `dev_framework_init` scaffolds project-level agents,
|
|
37
37
|
skills, local rules directory, and config; `dev_framework_set_profile` changes the profile
|
|
38
38
|
in-session without restarting; `dev_framework_status` reports the current
|
|
39
|
-
profile, guardrails, gate, and tracked changed files
|
|
39
|
+
profile, guardrails, gate, and tracked changed files; `dev_framework_verify`
|
|
40
|
+
runs the completion gate on demand and returns the summary to the agent.
|
|
40
41
|
- **CLI installer.** `df init` auto-detects your language and writes a config
|
|
41
42
|
with sensible commands; `df profile <name>` changes the profile from the
|
|
42
43
|
shell; `df status` / `df version` report template state and the version.
|
|
43
|
-
- **Slash commands.** The plugin registers four commands
|
|
44
|
-
anything to the LLM:
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
registered with an empty template so the argument (e.g. `standard`) is
|
|
49
|
-
captured by the plugin and the model never sees it; the result is shown as a
|
|
50
|
-
toast and the user turn is suppressed.
|
|
51
|
-
- The `dev_framework_init` and `dev_framework_set_profile` custom *tools* remain
|
|
52
|
-
available for in-agent use.
|
|
44
|
+
- **Slash commands.** The plugin registers four TUI commands that open instant
|
|
45
|
+
modal dialogs and never feed anything to the LLM: `/df-status`, `/df-help`,
|
|
46
|
+
`/df-profile` (bare for a picker, or with an argument), and `/df-verify`
|
|
47
|
+
(runs the gate manually). The `dev_framework_*` custom *tools* above remain
|
|
48
|
+
available for in-agent use.
|
|
53
49
|
|
|
54
50
|
## Profiles
|
|
55
51
|
|
|
@@ -58,7 +54,18 @@ reimplemented as an OpenCode-native plugin.
|
|
|
58
54
|
| `off` | disabled | not reported | no | no | no | Plugin registers no hooks at all. |
|
|
59
55
|
| `advisory` | warn | warn | yes | warn only | warned, not blocked | Nothing blocks; everything is logged. |
|
|
60
56
|
| `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
|
|
57
|
+
| `strict` | deny | error | yes | deny edits | blocks completion | Also lints changed files in the gate; per-edit lint failures are reported loudly (error level — the edit already landed, so nothing throws there). |
|
|
58
|
+
|
|
59
|
+
## Enforcement layers
|
|
60
|
+
|
|
61
|
+
How each mechanism is enforced on OpenCode `v2` (verified on `v2.0.26`):
|
|
62
|
+
|
|
63
|
+
| Mechanism | Primary layer | Backstop / fallback | Strength |
|
|
64
|
+
| --------- | ------------- | ------------------- | -------- |
|
|
65
|
+
| Pre-flight gate | `tool.execute.before` deny | — | **Hard block** on every build: the edit never lands. |
|
|
66
|
+
| Protected paths + dangerous commands | `tool.execute.before` deny/throw | `permission.evaluate` native layer (deny) | **Hard block** via the backstop; the native layer is defense-in-depth (the pipeline runs before-hooks first, so it only sees calls the backstop passed). |
|
|
67
|
+
| Per-edit lint | `tool.execute.after` track + lint | `filesystem.changed` event (this release) | Report-only: the edit already landed, so failures log loudly but never throw. |
|
|
68
|
+
| Completion gate | `session.idle` re-prompt via `session.prompt` | `session.stopping` hard-stop veto, if the core dispatches it | **Async, bounded** by `gate.max_blocks` (re-prompt, not a veto); hard stop only on builds with core support. `/df-status` shows which mode is active. |
|
|
62
69
|
|
|
63
70
|
## Install
|
|
64
71
|
|
|
@@ -74,7 +81,7 @@ Then add the plugin to your project's `opencode.json`:
|
|
|
74
81
|
}
|
|
75
82
|
```
|
|
76
83
|
|
|
77
|
-
Requires OpenCode `v2.
|
|
84
|
+
Requires OpenCode `v2.x` (`@opencode/plugin` `^2`) — tested on `v2.0.26`. On `v1.18.18–1.18.31` use the `v1` branch
|
|
78
85
|
of this plugin (`plugin` key). The `./tui` companion (`/df-status` and `/df-help`
|
|
79
86
|
modals) is auto-discovered from the npm entry on `v2` — no separate `tui.json` needed.
|
|
80
87
|
|
|
@@ -107,12 +114,17 @@ config. OpenCode reads `tui.json` from the global config dir
|
|
|
107
114
|
|
|
108
115
|
```json
|
|
109
116
|
{
|
|
110
|
-
"plugins": ["/home/jerome/opencode-dev-framework"]
|
|
117
|
+
"plugins": [{ "package": "/home/jerome/opencode-dev-framework/dist" }]
|
|
111
118
|
}
|
|
112
119
|
```
|
|
113
120
|
|
|
114
|
-
The path must be the
|
|
115
|
-
|
|
121
|
+
The path must be the package's **`dist/` directory**, not the repository
|
|
122
|
+
root. Verified on OpenCode `v2.0.26`: for local directory entries the server
|
|
123
|
+
resolves the entrypoint as `<dir>/index.js` and ignores `package.json`
|
|
124
|
+
`main`, so a repo-root path fails silently with `Plugin entrypoint not
|
|
125
|
+
found` (visible only via `/plugins` or server logs) and no hook runs at
|
|
126
|
+
all. Rebuild after every source change (`npm run build`) since OpenCode
|
|
127
|
+
loads `dist/index.js` directly:
|
|
116
128
|
|
|
117
129
|
```bash
|
|
118
130
|
npm run build
|
|
@@ -200,8 +212,8 @@ They open instantly and **never** feed text back to the LLM:
|
|
|
200
212
|
- `/df-help` — lists the available dev-framework commands in a modal dialog.
|
|
201
213
|
- `/df-profile` — opens a profile picker (off / advisory / standard / strict) in
|
|
202
214
|
a modal dialog; selecting one switches the active profile immediately (written
|
|
203
|
-
to the config file).
|
|
204
|
-
|
|
215
|
+
to the config file). With an argument (`/df-profile standard`) it switches
|
|
216
|
+
directly with a toast instead of the picker.
|
|
205
217
|
- `/df-verify` — runs the configured verification suite (the completion gate)
|
|
206
218
|
manually and shows a pass/fail summary in a modal dialog.
|
|
207
219
|
|
|
@@ -250,6 +262,17 @@ For persistent debug traces, set `OPENCODE_DEV_FRAMEWORK_LOG_FILE`:
|
|
|
250
262
|
OPENCODE_DEV_FRAMEWORK_LOG_FILE=/tmp/odf.log opencode run
|
|
251
263
|
```
|
|
252
264
|
|
|
265
|
+
Plugin code runs in the `opencode serve` backend, not in your terminal
|
|
266
|
+
process — a variable exported only in the TUI shell never reaches it. For
|
|
267
|
+
full server logs plus the plugin trace, run a private server:
|
|
268
|
+
|
|
269
|
+
```bash
|
|
270
|
+
OPENCODE_DEV_FRAMEWORK_LOG_FILE=/tmp/odf.log opencode run --standalone --print-logs
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
(There is no `cli.json` interaction: the plugin never reads or writes CLI
|
|
274
|
+
config; the flags above are stock OpenCode CLI options.)
|
|
275
|
+
|
|
253
276
|
See `AGENTS.md` and `docs/plans/` for the architecture and implementation
|
|
254
277
|
plan.
|
|
255
278
|
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persistent per-session completion-gate block counts.
|
|
3
|
+
*
|
|
4
|
+
* Counts live in `ctx.storage` (survives plugin reload / `session_move` /
|
|
5
|
+
* server restart) with a caller-provided `Map` as the write-through L1
|
|
6
|
+
* cache (keeps `/df-status` rendering and the synchronous status paths
|
|
7
|
+
* working off live data). Every storage call is best-effort: on failure the
|
|
8
|
+
* store falls back to memory, records `isDegraded()`, and never throws — so
|
|
9
|
+
* a broken storage backend degrades to pre-Phase-23 behavior instead of
|
|
10
|
+
* breaking the gate.
|
|
11
|
+
*
|
|
12
|
+
* Stored values are only block counts (`number`) and one `boolean` flag.
|
|
13
|
+
* Never store secrets, prompts, or file contents here.
|
|
14
|
+
*
|
|
15
|
+
* Key namespacing: counts are keyed `df:blocks:<sessionID>` (OpenCode
|
|
16
|
+
* session IDs are globally unique, so this is safe even if storage is
|
|
17
|
+
* shared across projects); the hard-stop probe flag is `df:stopSupported`.
|
|
18
|
+
*/
|
|
19
|
+
import type { Context } from "@opencode/plugin/promise/plugin";
|
|
20
|
+
/** Minimal storage surface we need (subset of `Context["storage"]`). */
|
|
21
|
+
export type StorageLike = Pick<Context["storage"], "get" | "set" | "remove">;
|
|
22
|
+
export declare const BLOCK_COUNT_KEY_PREFIX = "df:blocks:";
|
|
23
|
+
export declare const STOP_SUPPORTED_KEY = "df:stopSupported";
|
|
24
|
+
export interface BlockStore {
|
|
25
|
+
get(sessionID: string): Promise<number>;
|
|
26
|
+
/** Read, add one, persist, and return the new count. */
|
|
27
|
+
increment(sessionID: string): Promise<number>;
|
|
28
|
+
clear(sessionID: string): Promise<void>;
|
|
29
|
+
/** Live entries (mirrors the L1 map; used by tests). */
|
|
30
|
+
readonly size: number;
|
|
31
|
+
getStopSupported(): Promise<boolean>;
|
|
32
|
+
setStopSupported(): Promise<void>;
|
|
33
|
+
/** True once any storage call has failed (in-memory fallback in use). */
|
|
34
|
+
isDegraded(): boolean;
|
|
35
|
+
}
|
|
36
|
+
export declare function createBlockStore(storage: StorageLike | undefined | null, memory?: Map<string, number>): BlockStore;
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persistent per-session completion-gate block counts.
|
|
3
|
+
*
|
|
4
|
+
* Counts live in `ctx.storage` (survives plugin reload / `session_move` /
|
|
5
|
+
* server restart) with a caller-provided `Map` as the write-through L1
|
|
6
|
+
* cache (keeps `/df-status` rendering and the synchronous status paths
|
|
7
|
+
* working off live data). Every storage call is best-effort: on failure the
|
|
8
|
+
* store falls back to memory, records `isDegraded()`, and never throws — so
|
|
9
|
+
* a broken storage backend degrades to pre-Phase-23 behavior instead of
|
|
10
|
+
* breaking the gate.
|
|
11
|
+
*
|
|
12
|
+
* Stored values are only block counts (`number`) and one `boolean` flag.
|
|
13
|
+
* Never store secrets, prompts, or file contents here.
|
|
14
|
+
*
|
|
15
|
+
* Key namespacing: counts are keyed `df:blocks:<sessionID>` (OpenCode
|
|
16
|
+
* session IDs are globally unique, so this is safe even if storage is
|
|
17
|
+
* shared across projects); the hard-stop probe flag is `df:stopSupported`.
|
|
18
|
+
*/
|
|
19
|
+
export const BLOCK_COUNT_KEY_PREFIX = "df:blocks:";
|
|
20
|
+
export const STOP_SUPPORTED_KEY = "df:stopSupported";
|
|
21
|
+
function blockKey(sessionID) {
|
|
22
|
+
return `${BLOCK_COUNT_KEY_PREFIX}${sessionID}`;
|
|
23
|
+
}
|
|
24
|
+
/** Accept only sane counts; anything else (foreign/corrupt value) is treated as missing. */
|
|
25
|
+
function asCount(value) {
|
|
26
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
|
|
27
|
+
return undefined;
|
|
28
|
+
return Math.floor(value);
|
|
29
|
+
}
|
|
30
|
+
export function createBlockStore(storage, memory) {
|
|
31
|
+
const counts = memory ?? new Map();
|
|
32
|
+
let stopMemory = false;
|
|
33
|
+
let degraded = false;
|
|
34
|
+
async function readCount(sessionID) {
|
|
35
|
+
if (storage == null)
|
|
36
|
+
return counts.get(sessionID) ?? 0;
|
|
37
|
+
try {
|
|
38
|
+
const stored = asCount(await storage.get(blockKey(sessionID)));
|
|
39
|
+
if (stored !== undefined) {
|
|
40
|
+
counts.set(sessionID, stored);
|
|
41
|
+
return stored;
|
|
42
|
+
}
|
|
43
|
+
return counts.get(sessionID) ?? 0;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
degraded = true;
|
|
47
|
+
return counts.get(sessionID) ?? 0;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
async function writeCount(sessionID, count) {
|
|
51
|
+
counts.set(sessionID, count);
|
|
52
|
+
if (storage == null)
|
|
53
|
+
return;
|
|
54
|
+
try {
|
|
55
|
+
await storage.set(blockKey(sessionID), count);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
degraded = true;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
get(sessionID) {
|
|
63
|
+
return readCount(sessionID);
|
|
64
|
+
},
|
|
65
|
+
async increment(sessionID) {
|
|
66
|
+
const next = (await readCount(sessionID)) + 1;
|
|
67
|
+
await writeCount(sessionID, next);
|
|
68
|
+
return next;
|
|
69
|
+
},
|
|
70
|
+
async clear(sessionID) {
|
|
71
|
+
counts.delete(sessionID);
|
|
72
|
+
if (storage == null)
|
|
73
|
+
return;
|
|
74
|
+
try {
|
|
75
|
+
await storage.remove(blockKey(sessionID));
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
degraded = true;
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
get size() {
|
|
82
|
+
return counts.size;
|
|
83
|
+
},
|
|
84
|
+
async getStopSupported() {
|
|
85
|
+
if (stopMemory)
|
|
86
|
+
return true;
|
|
87
|
+
if (storage == null)
|
|
88
|
+
return false;
|
|
89
|
+
try {
|
|
90
|
+
const stored = await storage.get(STOP_SUPPORTED_KEY);
|
|
91
|
+
if (stored === true) {
|
|
92
|
+
stopMemory = true;
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
degraded = true;
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
async setStopSupported() {
|
|
103
|
+
stopMemory = true;
|
|
104
|
+
if (storage == null)
|
|
105
|
+
return;
|
|
106
|
+
try {
|
|
107
|
+
await storage.set(STOP_SUPPORTED_KEY, true);
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
degraded = true;
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
isDegraded() {
|
|
114
|
+
return degraded;
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|
package/dist/gate.d.ts
CHANGED
|
@@ -15,6 +15,8 @@ export declare const DEFAULT_GATE_TIMEOUT_SECONDS = 300;
|
|
|
15
15
|
/** Tracks files edited during a session so the gate can scope work. */
|
|
16
16
|
export interface ChangedFileTracker {
|
|
17
17
|
add: (filePath: string, directory?: string) => void;
|
|
18
|
+
/** True when the (normalized) path is already tracked. */
|
|
19
|
+
has: (filePath: string, directory?: string) => boolean;
|
|
18
20
|
getChangedFiles: () => string[];
|
|
19
21
|
clearChangedFiles: () => void;
|
|
20
22
|
}
|
package/dist/gate.js
CHANGED
|
@@ -13,6 +13,13 @@ import { splitCommand } from "./command-utils.js";
|
|
|
13
13
|
import { lintFile } from "./lint.js";
|
|
14
14
|
/** Fallback per-command timeout (seconds) when `gate.timeout` is unset. */
|
|
15
15
|
export const DEFAULT_GATE_TIMEOUT_SECONDS = 300;
|
|
16
|
+
function normalizeTrackedPath(filePath, directory) {
|
|
17
|
+
let candidate = filePath;
|
|
18
|
+
if (directory !== undefined && isAbsolute(filePath)) {
|
|
19
|
+
candidate = relative(directory, filePath);
|
|
20
|
+
}
|
|
21
|
+
return candidate.replace(/^\.\//, "");
|
|
22
|
+
}
|
|
16
23
|
/**
|
|
17
24
|
* Create a changed-file tracker. Paths are deduplicated and stored relative
|
|
18
25
|
* to the project directory when one is provided.
|
|
@@ -21,11 +28,10 @@ export function createChangedFileTracker() {
|
|
|
21
28
|
const files = new Set();
|
|
22
29
|
return {
|
|
23
30
|
add(filePath, directory) {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
files.add(candidate.replace(/^\.\//, ""));
|
|
31
|
+
files.add(normalizeTrackedPath(filePath, directory));
|
|
32
|
+
},
|
|
33
|
+
has(filePath, directory) {
|
|
34
|
+
return files.has(normalizeTrackedPath(filePath, directory));
|
|
29
35
|
},
|
|
30
36
|
getChangedFiles() {
|
|
31
37
|
return [...files];
|
package/dist/harness.d.ts
CHANGED
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
* when the OpenCode build supports it) and the `session.idle` fallback
|
|
19
19
|
* (re-prompt).
|
|
20
20
|
*/
|
|
21
|
+
import type { BlockStore } from "./block-store.js";
|
|
21
22
|
import { type ChangedFileTracker } from "./gate.js";
|
|
22
23
|
import type { RunCommand } from "./host.js";
|
|
23
24
|
import type { LogFn } from "./logger.js";
|
|
@@ -78,7 +79,7 @@ export interface CompletionDeps {
|
|
|
78
79
|
directory: string;
|
|
79
80
|
sessionID: string;
|
|
80
81
|
tracker: ChangedFileTracker;
|
|
81
|
-
blockCounts:
|
|
82
|
+
blockCounts: BlockStore;
|
|
82
83
|
log: LogFn;
|
|
83
84
|
}
|
|
84
85
|
/**
|
package/dist/harness.js
CHANGED
|
@@ -150,7 +150,7 @@ export async function evaluateCompletion(deps) {
|
|
|
150
150
|
const reviewMissing = reviewRequired && reviewState !== "present";
|
|
151
151
|
if (!gateFailed && !reviewMissing) {
|
|
152
152
|
tracker.clearChangedFiles();
|
|
153
|
-
blockCounts.
|
|
153
|
+
await blockCounts.clear(sessionID);
|
|
154
154
|
return {
|
|
155
155
|
decision: "pass",
|
|
156
156
|
changedFiles,
|
|
@@ -170,17 +170,16 @@ export async function evaluateCompletion(deps) {
|
|
|
170
170
|
const reason = gateFailed ? "gate" : "review";
|
|
171
171
|
const summary = gateFailed ? summarizeGate(report) : reviewMissingMessage(changedFiles);
|
|
172
172
|
const maxBlocks = config.gate.max_blocks ?? 3;
|
|
173
|
-
const blockCount =
|
|
173
|
+
const blockCount = await blockCounts.increment(sessionID);
|
|
174
174
|
if (blockCount > maxBlocks) {
|
|
175
175
|
tracker.clearChangedFiles();
|
|
176
|
-
blockCounts.
|
|
176
|
+
await blockCounts.clear(sessionID);
|
|
177
177
|
const standdownSummary = `opencode-dev-framework completion gate has blocked ${maxBlocks} times and is standing ` +
|
|
178
178
|
`down to avoid trapping you. The requirement is STILL unmet:\n\n${summary}\n\n` +
|
|
179
179
|
`Do not claim the work is complete. Tell the user plainly what remains unmet and why.`;
|
|
180
180
|
await deps.log("error", standdownSummary, { reason, sessionID });
|
|
181
181
|
return { decision: "standdown", reason, summary: standdownSummary, changedFiles };
|
|
182
182
|
}
|
|
183
|
-
blockCounts.set(sessionID, blockCount);
|
|
184
183
|
await deps.log("error", summary, { reason, sessionID, blockCount, maxBlocks });
|
|
185
184
|
return {
|
|
186
185
|
decision: "blocked",
|
package/dist/index.d.ts
CHANGED
|
@@ -2,11 +2,14 @@
|
|
|
2
2
|
* opencode-dev-framework V2 plugin entry point.
|
|
3
3
|
*
|
|
4
4
|
* V2 framework (opencode v2): Plugin.define({ id, setup(ctx) })
|
|
5
|
-
* - ctx.session.hook("context", ...) -> constitution injection
|
|
6
|
-
* - ctx.
|
|
5
|
+
* - ctx.session.hook("context"/"generate"/"compaction"/"title", ...) -> constitution injection
|
|
6
|
+
* - ctx.permission.hook("evaluate", ...) -> native permission layer (Phase 25;
|
|
7
|
+
* observe-only spike in 25.1, enforcing mapper from 25.2)
|
|
8
|
+
* - ctx.tool.hook("execute.before", ...) -> guardrails (backstop from Phase 25)
|
|
9
|
+
* - ctx.tool.hook("execute.after", ...) -> per-edit lint + change tracking
|
|
10
|
+
* (`filesystem.changed` stays as a fallback this release; see Phase 24)
|
|
7
11
|
* - ctx.event.subscribe() -> file tracking + gate enforcement via re-prompt
|
|
8
12
|
* - ctx.tool.transform(...) -> custom tools
|
|
9
|
-
* - ctx.command.transform(...) -> slash commands (optional)
|
|
10
13
|
*
|
|
11
14
|
* Gate enforcement: no synchronous `session.stopping`. On `session.idle`
|
|
12
15
|
* / `session.status:idle` we run the gate and if it fails inside budget we
|
|
@@ -14,6 +17,7 @@
|
|
|
14
17
|
* agent — async re-injection preserving the enforcement intent (see docs/plans/08-notes).
|
|
15
18
|
*/
|
|
16
19
|
import { Plugin } from "@opencode/plugin";
|
|
20
|
+
import { type BlockStore } from "./block-store.js";
|
|
17
21
|
import { type ChangedFileTracker } from "./gate.js";
|
|
18
22
|
import { type RunCommand } from "./host.js";
|
|
19
23
|
import { type LogFn } from "./logger.js";
|
|
@@ -26,6 +30,16 @@ export interface HookState {
|
|
|
26
30
|
tracker: ChangedFileTracker;
|
|
27
31
|
constitution: string | null;
|
|
28
32
|
blockCounts: Map<string, number>;
|
|
33
|
+
/**
|
|
34
|
+
* Persistent block-count store over `ctx.storage`, write-through into
|
|
35
|
+
* `blockCounts` (which stays the live L1 cache for status rendering).
|
|
36
|
+
* Survives plugin reload / session_move / server restart.
|
|
37
|
+
* Note: this `HookState` is intentionally forked from `registry.ts`
|
|
38
|
+
* `HookState` (module state is per-location here, not registry-keyed);
|
|
39
|
+
* `format-status.ts` reads the `blockCounts` Map projection, which the
|
|
40
|
+
* store keeps live on every get/increment/clear.
|
|
41
|
+
*/
|
|
42
|
+
blocks: BlockStore;
|
|
29
43
|
precommitAvailable?: boolean;
|
|
30
44
|
configMtime?: number;
|
|
31
45
|
/**
|
package/dist/index.js
CHANGED
|
@@ -2,11 +2,14 @@
|
|
|
2
2
|
* opencode-dev-framework V2 plugin entry point.
|
|
3
3
|
*
|
|
4
4
|
* V2 framework (opencode v2): Plugin.define({ id, setup(ctx) })
|
|
5
|
-
* - ctx.session.hook("context", ...) -> constitution injection
|
|
6
|
-
* - ctx.
|
|
5
|
+
* - ctx.session.hook("context"/"generate"/"compaction"/"title", ...) -> constitution injection
|
|
6
|
+
* - ctx.permission.hook("evaluate", ...) -> native permission layer (Phase 25;
|
|
7
|
+
* observe-only spike in 25.1, enforcing mapper from 25.2)
|
|
8
|
+
* - ctx.tool.hook("execute.before", ...) -> guardrails (backstop from Phase 25)
|
|
9
|
+
* - ctx.tool.hook("execute.after", ...) -> per-edit lint + change tracking
|
|
10
|
+
* (`filesystem.changed` stays as a fallback this release; see Phase 24)
|
|
7
11
|
* - ctx.event.subscribe() -> file tracking + gate enforcement via re-prompt
|
|
8
12
|
* - ctx.tool.transform(...) -> custom tools
|
|
9
|
-
* - ctx.command.transform(...) -> slash commands (optional)
|
|
10
13
|
*
|
|
11
14
|
* Gate enforcement: no synchronous `session.stopping`. On `session.idle`
|
|
12
15
|
* / `session.status:idle` we run the gate and if it fails inside budget we
|
|
@@ -16,13 +19,14 @@
|
|
|
16
19
|
import { Plugin } from "@opencode/plugin";
|
|
17
20
|
import { stat } from "node:fs/promises";
|
|
18
21
|
import { join } from "node:path";
|
|
22
|
+
import { createBlockStore } from "./block-store.js";
|
|
19
23
|
import { clearConfigCache, loadConfig } from "./config.js";
|
|
20
24
|
import { createChangedFileTracker } from "./gate.js";
|
|
21
25
|
import { artifactState, evaluateCompletion, PREFLIGHT_ARTIFACT_REL, preflightBlockReason, } from "./harness.js";
|
|
22
26
|
import { runCommand } from "./host.js";
|
|
23
27
|
import { lintFile, detectPreCommitAvailability, isLintFailure, summarizeLint } from "./lint.js";
|
|
24
28
|
import { createLogger } from "./logger.js";
|
|
25
|
-
import { checkToolCall, extractFilePath } from "./protect.js";
|
|
29
|
+
import { checkToolCall, extractFilePath, FILE_TOOLS, toPermissionGuard } from "./protect.js";
|
|
26
30
|
import { loadConstitution } from "./rules.js";
|
|
27
31
|
let activeState = null;
|
|
28
32
|
let fallbackLog = async () => { };
|
|
@@ -95,6 +99,41 @@ async function actOnVerdict(state, verdict) {
|
|
|
95
99
|
}
|
|
96
100
|
return continuationMessage(verdict);
|
|
97
101
|
}
|
|
102
|
+
/**
|
|
103
|
+
* Per-edit lint flow, shared by the `execute.after` hook (primary) and the
|
|
104
|
+
* `filesystem.changed` fallback. Skipped files log at debug; passes at info;
|
|
105
|
+
* failures log loudly at error (the edit already landed, so unlike
|
|
106
|
+
* `execute.before` this never throws — it only reports).
|
|
107
|
+
*/
|
|
108
|
+
async function runPerEditLint(state, filePath) {
|
|
109
|
+
if (!state.config.on_edit.lint)
|
|
110
|
+
return;
|
|
111
|
+
if (state.config.precommit === "auto" && state.precommitAvailable === undefined) {
|
|
112
|
+
state.precommitAvailable = await detectPreCommitAvailability(state.run, state.directory);
|
|
113
|
+
}
|
|
114
|
+
const outcome = await lintFile(state.run, state.config, filePath, {
|
|
115
|
+
cwd: state.directory,
|
|
116
|
+
timeout: state.config.gate?.timeout,
|
|
117
|
+
precommitAvailable: state.precommitAvailable,
|
|
118
|
+
});
|
|
119
|
+
if (outcome.skipped) {
|
|
120
|
+
await safeLog(state, "debug", summarizeLint(outcome), {
|
|
121
|
+
filePath,
|
|
122
|
+
reason: outcome.reason,
|
|
123
|
+
});
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (!isLintFailure(outcome)) {
|
|
127
|
+
await safeLog(state, "info", summarizeLint(outcome), { filePath });
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
await safeLog(state, "error", summarizeLint(outcome), {
|
|
131
|
+
filePath,
|
|
132
|
+
command: outcome.command?.join(" "),
|
|
133
|
+
stdout: outcome.result?.stdout,
|
|
134
|
+
stderr: outcome.result?.stderr,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
98
137
|
/** Assemble the completion verdict with the state's live dependencies. */
|
|
99
138
|
function runCompletion(state, sessionID) {
|
|
100
139
|
return evaluateCompletion({
|
|
@@ -103,7 +142,7 @@ function runCompletion(state, sessionID) {
|
|
|
103
142
|
directory: state.directory,
|
|
104
143
|
sessionID,
|
|
105
144
|
tracker: state.tracker,
|
|
106
|
-
blockCounts: state.
|
|
145
|
+
blockCounts: state.blocks,
|
|
107
146
|
log: (level, message, extra) => safeLog(state, level, message, extra),
|
|
108
147
|
});
|
|
109
148
|
}
|
|
@@ -194,6 +233,8 @@ const plugin = Plugin.define({
|
|
|
194
233
|
}
|
|
195
234
|
}
|
|
196
235
|
const tracker = createChangedFileTracker();
|
|
236
|
+
const blockCounts = new Map();
|
|
237
|
+
const blocks = createBlockStore(ctx.storage, blockCounts);
|
|
197
238
|
const state = {
|
|
198
239
|
directory,
|
|
199
240
|
config,
|
|
@@ -201,10 +242,18 @@ const plugin = Plugin.define({
|
|
|
201
242
|
run: runCommand,
|
|
202
243
|
tracker,
|
|
203
244
|
constitution,
|
|
204
|
-
blockCounts
|
|
245
|
+
blockCounts,
|
|
246
|
+
blocks,
|
|
205
247
|
configMtime,
|
|
206
248
|
};
|
|
207
249
|
activeState = state;
|
|
250
|
+
// Hydrate the hard-stop probe flag: a previous setup may have seen core
|
|
251
|
+
// dispatch `session.stopping`. A storage failure degrades to in-memory
|
|
252
|
+
// counts (pre-Phase-23 behavior) and is logged, never thrown.
|
|
253
|
+
state.stopHookSupported = await blocks.getStopSupported();
|
|
254
|
+
if (blocks.isDegraded()) {
|
|
255
|
+
await log("warn", "ctx.storage is unavailable; gate block counts are in-memory only and reset on reload", { directory });
|
|
256
|
+
}
|
|
208
257
|
const registrations = [];
|
|
209
258
|
function trackRegistration(value) {
|
|
210
259
|
if (value !== null &&
|
|
@@ -214,40 +263,49 @@ const plugin = Plugin.define({
|
|
|
214
263
|
registrations.push(value);
|
|
215
264
|
}
|
|
216
265
|
}
|
|
266
|
+
// Stale-hook guard: every closure below captures its own `state` and
|
|
267
|
+
// no-ops when it is no longer the live singleton. This covers three
|
|
268
|
+
// cases disposal alone cannot: (a) teardown with no fresh setup
|
|
269
|
+
// (activeState is null), (b) teardown + reload where an old
|
|
270
|
+
// registration outlives disposal (activeState is a newer state —
|
|
271
|
+
// the stale hook must NOT double-enforce), and (c) teardown racing
|
|
272
|
+
// an in-flight handler between awaits (captured `state` stays valid
|
|
273
|
+
// while the global may be cleared). See issue #1 follow-up.
|
|
217
274
|
// 1) Constitution injection — per model request (V1: experimental.chat.system.transform -> V2: session.hook("context", ...))
|
|
218
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
219
275
|
trackRegistration(await ctx.session.hook("context", async (event) => {
|
|
220
|
-
if (
|
|
276
|
+
if (activeState !== state)
|
|
221
277
|
return;
|
|
222
|
-
await reloadConfigIfChanged(
|
|
223
|
-
if (
|
|
278
|
+
await reloadConfigIfChanged(state);
|
|
279
|
+
if (state.config.profile === "off")
|
|
224
280
|
return;
|
|
225
|
-
|
|
281
|
+
const constitution = state.constitution;
|
|
282
|
+
if (!constitution)
|
|
226
283
|
return;
|
|
227
284
|
// V2 system is Array<SystemPart> {type:"text", text:string}
|
|
228
|
-
const already = event.system.some((part) => part.text.includes(
|
|
285
|
+
const already = event.system.some((part) => part.text.includes(constitution));
|
|
229
286
|
if (already)
|
|
230
287
|
return;
|
|
231
288
|
event.system.push({
|
|
232
289
|
type: "text",
|
|
233
|
-
text:
|
|
290
|
+
text: constitution,
|
|
234
291
|
});
|
|
235
|
-
await safeLog(
|
|
292
|
+
await safeLog(state, "info", "constitution injected into system prompt");
|
|
236
293
|
}));
|
|
237
294
|
// Also hook other request kinds so the reminder is not missed on title/generate
|
|
238
295
|
// (no-op if model doesn't need it; cheap)
|
|
239
|
-
for (const kind of ["generate", "compaction"]) {
|
|
240
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
296
|
+
for (const kind of ["generate", "compaction", "title"]) {
|
|
241
297
|
trackRegistration(await ctx.session.hook(kind, async (event) => {
|
|
242
|
-
if (
|
|
298
|
+
if (activeState !== state)
|
|
299
|
+
return;
|
|
300
|
+
const constitution = state.constitution;
|
|
301
|
+
if (state.config.profile === "off" || !constitution)
|
|
243
302
|
return;
|
|
244
|
-
// generate/compaction also have system — inject similarly if present
|
|
245
|
-
|
|
246
|
-
if (!ev.system)
|
|
303
|
+
// generate/compaction/title also have system — inject similarly if present
|
|
304
|
+
if (!event.system)
|
|
247
305
|
return;
|
|
248
|
-
const already =
|
|
306
|
+
const already = event.system.some((p) => p.text.includes(constitution));
|
|
249
307
|
if (!already)
|
|
250
|
-
|
|
308
|
+
event.system.push({ type: "text", text: constitution });
|
|
251
309
|
}));
|
|
252
310
|
}
|
|
253
311
|
// 1b) Hard-stop completion gate — `session.stopping` (OpenCode PR #44712).
|
|
@@ -258,25 +316,30 @@ const plugin = Plugin.define({
|
|
|
258
316
|
// session.idle fallback below provides re-prompt enforcement instead.
|
|
259
317
|
// The first invocation flips `stopHookSupported` so /df-status can show
|
|
260
318
|
// which enforcement level is active.
|
|
319
|
+
// DEFENSIVE: "stopping" is not in SessionHooks as of 2.0.x; fires only
|
|
320
|
+
// if a future core dispatches it (see PR #44712). This is the ONLY
|
|
321
|
+
// remaining any-cast in src/ — all other hooks are fully typed so the
|
|
322
|
+
// compiler guards future SDK upgrades.
|
|
261
323
|
try {
|
|
262
324
|
trackRegistration(
|
|
263
|
-
// biome-ignore lint/suspicious/noExplicitAny:
|
|
325
|
+
// biome-ignore lint/suspicious/noExplicitAny: defensive stopping probe, not in SessionHooks (PR #44712)
|
|
264
326
|
await ctx.session.hook("stopping",
|
|
265
327
|
// biome-ignore lint/suspicious/noExplicitAny: core may dispatch (input, output) or a single mutable event
|
|
266
328
|
async (input, output) => {
|
|
267
|
-
if (
|
|
329
|
+
if (activeState !== state)
|
|
268
330
|
return;
|
|
269
331
|
const out = output ?? input ?? {};
|
|
270
332
|
const sessionID = input?.sessionID ??
|
|
271
333
|
out.sessionID ??
|
|
272
334
|
getEventSessionID(input) ??
|
|
273
335
|
"unknown";
|
|
274
|
-
|
|
275
|
-
await
|
|
276
|
-
|
|
336
|
+
state.stopHookSupported = true;
|
|
337
|
+
await state.blocks.setStopSupported();
|
|
338
|
+
await reloadConfigIfChanged(state);
|
|
339
|
+
if (state.config.profile === "off")
|
|
277
340
|
return;
|
|
278
|
-
const verdict = await runCompletion(
|
|
279
|
-
const message = await actOnVerdict(
|
|
341
|
+
const verdict = await runCompletion(state, sessionID);
|
|
342
|
+
const message = await actOnVerdict(state, verdict);
|
|
280
343
|
if (message !== null) {
|
|
281
344
|
out.stop = false;
|
|
282
345
|
out.message = message;
|
|
@@ -287,18 +350,104 @@ const plugin = Plugin.define({
|
|
|
287
350
|
catch {
|
|
288
351
|
await safeLog(state, "warn", "could not register session.stopping hook; using session.idle re-prompt fallback only");
|
|
289
352
|
}
|
|
353
|
+
// 2a) Native permission layer (Phase 25): `permission.evaluate` fires
|
|
354
|
+
// with `{action, resources, effect}` (shapes recorded in the 25.1 spike,
|
|
355
|
+
// docs/plans/08-notes.md — never guessed: action "edit" covers
|
|
356
|
+
// edit/write/patch with resources[0] = file path; action "shell" covers
|
|
357
|
+
// bash/shell with resources[0] = command).
|
|
358
|
+
// The mapper only ever denies or abstains (never allows), so it can
|
|
359
|
+
// never weaken host/engine enforcement. `execute.before` below stays as
|
|
360
|
+
// the backstop — and is the load-bearing layer: the firing investigation
|
|
361
|
+
// (08-notes) proved the pipeline runs before-hooks FIRST, so evaluate
|
|
362
|
+
// only ever sees calls the backstop already passed. The native layer is
|
|
363
|
+
// defense-in-depth (it still matters if core ever reorders the pipeline
|
|
364
|
+
// or adds paths bypassing tool hooks). Quiet paths log at debug — in
|
|
365
|
+
// particular advisory warns stay debug here because execute.before
|
|
366
|
+
// already warned for the same call.
|
|
367
|
+
try {
|
|
368
|
+
trackRegistration(await ctx.permission.hook("evaluate", async (event) => {
|
|
369
|
+
if (activeState !== state)
|
|
370
|
+
return;
|
|
371
|
+
await reloadConfigIfChanged(state);
|
|
372
|
+
if (state.config.profile === "off")
|
|
373
|
+
return;
|
|
374
|
+
const action = event.action;
|
|
375
|
+
const target = event.resources[0];
|
|
376
|
+
const baseExtra = {
|
|
377
|
+
action,
|
|
378
|
+
resources: [...event.resources],
|
|
379
|
+
sessionID: event.sessionID,
|
|
380
|
+
};
|
|
381
|
+
// Already denied by the host/engine: abstain so its verdict and
|
|
382
|
+
// message survive untouched (mirrors the backstop's hostDenies
|
|
383
|
+
// stand-down; the mapper must never overwrite a denial).
|
|
384
|
+
if (event.effect === "deny") {
|
|
385
|
+
await safeLog(state, "debug", `permission.evaluate action=${action} already denied; leaving host/engine verdict untouched`, { ...baseExtra, message: event.message });
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
// Pre-flight (mirrors execute.before; the artifact itself stays
|
|
389
|
+
// writable). Deny/warn per profile, exactly like the backstop.
|
|
390
|
+
if (state.config.preflight.length > 0 && action === "edit") {
|
|
391
|
+
const artifact = await artifactState(state.directory, PREFLIGHT_ARTIFACT_REL);
|
|
392
|
+
const reason = preflightBlockReason(state.config, "edit", target, artifact);
|
|
393
|
+
if (reason !== null) {
|
|
394
|
+
if (state.config.profile === "advisory") {
|
|
395
|
+
// Debug, not warn: execute.before runs first and already
|
|
396
|
+
// warned for this exact call (same double-noise rule as the
|
|
397
|
+
// guardrail warn path below).
|
|
398
|
+
await safeLog(state, "debug", reason, {
|
|
399
|
+
...baseExtra,
|
|
400
|
+
artifact: PREFLIGHT_ARTIFACT_REL,
|
|
401
|
+
});
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
event.effect = "deny";
|
|
405
|
+
event.message = reason;
|
|
406
|
+
await safeLog(state, "error", reason, {
|
|
407
|
+
...baseExtra,
|
|
408
|
+
artifact: PREFLIGHT_ARTIFACT_REL,
|
|
409
|
+
});
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
const verdict = toPermissionGuard(state.config, action, event.resources, state.directory);
|
|
414
|
+
if (verdict === null) {
|
|
415
|
+
await safeLog(state, "debug", `permission.evaluate action=${action} effect=${event.effect} (no guardrail verdict; engine default wins)`, { ...baseExtra, effect: event.effect });
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
const message = verdict.reason ?? "blocked by guardrails";
|
|
419
|
+
const extra = { ...baseExtra, pattern: verdict.matchedPattern };
|
|
420
|
+
if (verdict.decision === "warn") {
|
|
421
|
+
// Advisory: stay silent at warn level — `execute.before` runs
|
|
422
|
+
// first in the pipeline and already warned for this exact call.
|
|
423
|
+
// A debug trace keeps the layer observable without double noise.
|
|
424
|
+
await safeLog(state, "debug", message, extra);
|
|
425
|
+
return; // leave the engine verdict untouched
|
|
426
|
+
}
|
|
427
|
+
event.effect = "deny";
|
|
428
|
+
event.message = message;
|
|
429
|
+
await safeLog(state, "error", message, extra);
|
|
430
|
+
}));
|
|
431
|
+
}
|
|
432
|
+
catch {
|
|
433
|
+
await safeLog(state, "warn", "could not register permission.evaluate hook; guardrails use execute.before only");
|
|
434
|
+
}
|
|
290
435
|
// 2) Guardrails — tool execution blocking (V1: tool.execute.before -> V2: ctx.tool.hook("execute.before", ...))
|
|
291
|
-
//
|
|
292
|
-
//
|
|
293
|
-
//
|
|
294
|
-
//
|
|
436
|
+
// Stale-hook fail-open: the closure captures its own `state` and allows
|
|
437
|
+
// the call whenever it is no longer live — torn down (activeState null)
|
|
438
|
+
// or superseded by a newer setup (activeState is a different instance,
|
|
439
|
+
// whose own hook enforces; this one must not double-enforce). Using the
|
|
440
|
+
// captured `state` throughout also closes the teardown race where the
|
|
441
|
+
// global is cleared between awaits. See issue #1.
|
|
295
442
|
trackRegistration(await ctx.tool.hook("execute.before", async (event) => {
|
|
296
|
-
if (
|
|
297
|
-
|
|
443
|
+
if (activeState !== state) {
|
|
444
|
+
if (activeState === null) {
|
|
445
|
+
await safeLog(null, "warn", "[opencode-dev-framework] plugin state is not available; allowing tool call (fail-open after teardown)", { tool: event.tool });
|
|
446
|
+
}
|
|
298
447
|
return;
|
|
299
448
|
}
|
|
300
|
-
await reloadConfigIfChanged(
|
|
301
|
-
if (
|
|
449
|
+
await reloadConfigIfChanged(state);
|
|
450
|
+
if (state.config.profile === "off")
|
|
302
451
|
return;
|
|
303
452
|
// V2 event shapes: { tool, sessionID, agent, messageID, id, input: unknown }
|
|
304
453
|
const toolName = event.tool;
|
|
@@ -307,35 +456,58 @@ const plugin = Plugin.define({
|
|
|
307
456
|
// Pre-flight harness: when `preflight:` tasks are configured, file
|
|
308
457
|
// edits are denied (standard/strict) until the pre-flight artifact
|
|
309
458
|
// exists. This is a true hard gate — it runs before the edit lands.
|
|
310
|
-
if (
|
|
311
|
-
const artifact = await artifactState(
|
|
312
|
-
const reason = preflightBlockReason(
|
|
459
|
+
if (state.config.preflight.length > 0) {
|
|
460
|
+
const artifact = await artifactState(state.directory, PREFLIGHT_ARTIFACT_REL);
|
|
461
|
+
const reason = preflightBlockReason(state.config, toolName, extractFilePath(input), artifact);
|
|
313
462
|
if (reason !== null) {
|
|
314
463
|
const extra = { tool: toolName, sessionID, artifact: PREFLIGHT_ARTIFACT_REL };
|
|
315
|
-
if (
|
|
316
|
-
await safeLog(
|
|
464
|
+
if (state.config.profile === "advisory") {
|
|
465
|
+
await safeLog(state, "warn", reason, extra);
|
|
317
466
|
}
|
|
318
467
|
else {
|
|
319
|
-
await safeLog(
|
|
468
|
+
await safeLog(state, "error", reason, extra);
|
|
320
469
|
throw new Error(`[opencode-dev-framework] ${reason}`);
|
|
321
470
|
}
|
|
322
471
|
}
|
|
323
472
|
}
|
|
324
473
|
// hostPermissions: not available in V2 permission model; pass undefined (conservative — still guard)
|
|
325
|
-
const result = checkToolCall(
|
|
474
|
+
const result = checkToolCall(state.config, toolName, input, state.directory, undefined);
|
|
326
475
|
if (result.decision === "allow")
|
|
327
476
|
return;
|
|
328
477
|
const message = result.reason ?? "blocked by guardrails";
|
|
329
478
|
const extra = { tool: toolName, sessionID, pattern: result.matchedPattern };
|
|
330
479
|
if (result.decision === "warn") {
|
|
331
|
-
await safeLog(
|
|
480
|
+
await safeLog(state, "warn", message, extra);
|
|
332
481
|
return;
|
|
333
482
|
}
|
|
334
|
-
await safeLog(
|
|
483
|
+
await safeLog(state, "error", message, extra);
|
|
335
484
|
throw new Error(`[opencode-dev-framework] ${message}`);
|
|
336
485
|
}));
|
|
486
|
+
// 2b) Per-edit lint — `tool.execute.after` (primary; the
|
|
487
|
+
// `filesystem.changed` branch below stays as a fallback this release).
|
|
488
|
+
// Edit tools with `completed` status are tracked + linted via the shared
|
|
489
|
+
// flow; `error` status tracks without linting (the tool failed, so there
|
|
490
|
+
// is nothing reliable to lint); read-only tools never touch the tracker.
|
|
491
|
+
// The edit already landed, so this hook only reports — it never throws.
|
|
492
|
+
trackRegistration(await ctx.tool.hook("execute.after", async (event) => {
|
|
493
|
+
if (activeState !== state)
|
|
494
|
+
return;
|
|
495
|
+
await reloadConfigIfChanged(state);
|
|
496
|
+
if (state.config.profile === "off")
|
|
497
|
+
return;
|
|
498
|
+
const filePath = extractFilePath(event.input);
|
|
499
|
+
if (!filePath)
|
|
500
|
+
return;
|
|
501
|
+
if (!FILE_TOOLS.has(event.tool))
|
|
502
|
+
return;
|
|
503
|
+
state.tracker.add(filePath, state.directory);
|
|
504
|
+
if (event.status !== "completed") {
|
|
505
|
+
await safeLog(state, "debug", `tracked ${filePath} from failed ${event.tool} call (lint skipped)`, { tool: event.tool, sessionID: event.sessionID, filePath });
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
await runPerEditLint(state, filePath);
|
|
509
|
+
}));
|
|
337
510
|
// 3) Custom tools — V2: ctx.tool.transform(editor => editor.add(...))
|
|
338
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
339
511
|
trackRegistration(await ctx.tool.transform((editor) => {
|
|
340
512
|
editor.add({
|
|
341
513
|
name: "dev_framework_init",
|
|
@@ -415,13 +587,45 @@ const plugin = Plugin.define({
|
|
|
415
587
|
ccc();
|
|
416
588
|
const newConfig = lc(targetDir);
|
|
417
589
|
const { constitution: newConstitution } = await lc2(newConfig, targetDir);
|
|
418
|
-
if (
|
|
590
|
+
if (state.directory === targetDir) {
|
|
591
|
+
state.config = newConfig;
|
|
592
|
+
state.constitution = newConstitution;
|
|
593
|
+
}
|
|
594
|
+
if (activeState && activeState !== state && activeState.directory === targetDir) {
|
|
419
595
|
activeState.config = newConfig;
|
|
420
596
|
activeState.constitution = newConstitution;
|
|
421
597
|
}
|
|
422
598
|
return { content: `${message} Change applied immediately.` };
|
|
423
599
|
},
|
|
424
600
|
});
|
|
601
|
+
editor.add({
|
|
602
|
+
name: "dev_framework_verify",
|
|
603
|
+
description: "Run the opencode-dev-framework completion gate now (typecheck, tests, changed-file lint) and return the summary. Use for a mid-session gate check without waiting for session idle; unlike the idle gate this never re-prompts, it only reports.",
|
|
604
|
+
input: {
|
|
605
|
+
type: "object",
|
|
606
|
+
properties: {
|
|
607
|
+
directory: {
|
|
608
|
+
type: "string",
|
|
609
|
+
description: "Project directory (defaults to current project)",
|
|
610
|
+
},
|
|
611
|
+
},
|
|
612
|
+
additionalProperties: false,
|
|
613
|
+
},
|
|
614
|
+
async execute(input) {
|
|
615
|
+
const { verifyGate } = await import("./commands.js");
|
|
616
|
+
const args = input;
|
|
617
|
+
const targetDir = args.directory ?? directory;
|
|
618
|
+
const live = activeState && activeState.directory === targetDir ? activeState : null;
|
|
619
|
+
const own = state.directory === targetDir ? state : null;
|
|
620
|
+
const holder = live ?? own;
|
|
621
|
+
// Live tracker's changed files beat the TUI's empty default: a
|
|
622
|
+
// mid-session verify scopes `changed` steps to real edits.
|
|
623
|
+
const cfg = holder?.config ?? loadConfig(targetDir);
|
|
624
|
+
const changed = holder ? holder.tracker.getChangedFiles() : [];
|
|
625
|
+
const { summary } = await verifyGate(state.run, targetDir, cfg, changed);
|
|
626
|
+
return { content: summary };
|
|
627
|
+
},
|
|
628
|
+
});
|
|
425
629
|
editor.add({
|
|
426
630
|
name: "dev_framework_status",
|
|
427
631
|
description: "Show the current opencode-dev-framework state for the project: active profile, guardrails, completion gate, on-edit behavior, tracked changed files, and block counts.",
|
|
@@ -439,12 +643,12 @@ const plugin = Plugin.define({
|
|
|
439
643
|
const { renderStatus } = await import("./format-status.js");
|
|
440
644
|
const args = input;
|
|
441
645
|
const targetDir = args.directory ?? directory;
|
|
442
|
-
const
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
// renderStatus expects HookState? pass
|
|
646
|
+
const live = activeState && activeState.directory === targetDir ? activeState : null;
|
|
647
|
+
const own = state.directory === targetDir ? state : null;
|
|
648
|
+
const cfg = (live ?? own)?.config ?? loadConfig(targetDir);
|
|
649
|
+
// renderStatus expects HookState? pass live ?? own (may be null for other dirs)
|
|
446
650
|
return {
|
|
447
|
-
content: renderStatus(cfg,
|
|
651
|
+
content: renderStatus(cfg, (live ?? own)),
|
|
448
652
|
};
|
|
449
653
|
},
|
|
450
654
|
});
|
|
@@ -456,78 +660,57 @@ const plugin = Plugin.define({
|
|
|
456
660
|
const eventLoop = (async () => {
|
|
457
661
|
try {
|
|
458
662
|
for await (const rawEvent of ctx.event.subscribe({ signal: controller.signal })) {
|
|
663
|
+
// Stale-loop guard: a previous setup's loop must exit rather than
|
|
664
|
+
// hijack a newer setup's state (duplicate gate re-prompts / lint).
|
|
665
|
+
if (activeState !== state)
|
|
666
|
+
return;
|
|
459
667
|
const event = rawEvent;
|
|
460
668
|
const type = event.type;
|
|
461
669
|
if (isSessionDeletedEvent(type)) {
|
|
462
|
-
// session.deleted: cleanup
|
|
670
|
+
// session.deleted: cleanup block counts (memory + storage) and
|
|
671
|
+
// forget the session's directory mapping if present.
|
|
463
672
|
const sid = getEventSessionID(event);
|
|
464
|
-
if (sid
|
|
465
|
-
|
|
673
|
+
if (sid)
|
|
674
|
+
await state.blocks.clear(sid);
|
|
466
675
|
continue;
|
|
467
676
|
}
|
|
468
677
|
if (isFilesystemChangedEvent(type)) {
|
|
469
|
-
if (
|
|
470
|
-
|
|
471
|
-
await reloadConfigIfChanged(
|
|
472
|
-
if (
|
|
678
|
+
if (activeState !== state)
|
|
679
|
+
return;
|
|
680
|
+
await reloadConfigIfChanged(state);
|
|
681
|
+
if (state.config.profile === "off")
|
|
473
682
|
continue;
|
|
474
683
|
const filePath = getEventFilePath(event);
|
|
475
684
|
if (!filePath)
|
|
476
685
|
continue;
|
|
477
|
-
|
|
478
|
-
//
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
activeState.precommitAvailable === undefined) {
|
|
483
|
-
activeState.precommitAvailable = await detectPreCommitAvailability(activeState.run, activeState.directory);
|
|
484
|
-
}
|
|
485
|
-
const outcome = await lintFile(activeState.run, activeState.config, filePath, {
|
|
486
|
-
cwd: activeState.directory,
|
|
487
|
-
timeout: activeState.config.gate?.timeout,
|
|
488
|
-
precommitAvailable: activeState.precommitAvailable,
|
|
489
|
-
});
|
|
490
|
-
if (outcome.skipped) {
|
|
491
|
-
await safeLog(activeState, "debug", summarizeLint(outcome), {
|
|
492
|
-
filePath,
|
|
493
|
-
reason: outcome.reason,
|
|
494
|
-
});
|
|
495
|
-
continue;
|
|
496
|
-
}
|
|
497
|
-
if (!isLintFailure(outcome)) {
|
|
498
|
-
await safeLog(activeState, "info", summarizeLint(outcome), { filePath });
|
|
686
|
+
// Fallback path (primary is `execute.after` since Phase 24): the
|
|
687
|
+
// tracker is add-idempotent, so a file already seen via
|
|
688
|
+
// `execute.after` just logs at debug instead of linting twice.
|
|
689
|
+
if (state.tracker.has(filePath, state.directory)) {
|
|
690
|
+
await safeLog(state, "debug", `already tracked ${filePath} (skipping fallback lint; execute.after is primary)`, { filePath });
|
|
499
691
|
continue;
|
|
500
692
|
}
|
|
501
|
-
|
|
502
|
-
await
|
|
503
|
-
filePath,
|
|
504
|
-
command: outcome.command?.join(" "),
|
|
505
|
-
stdout: outcome.result?.stdout,
|
|
506
|
-
stderr: outcome.result?.stderr,
|
|
507
|
-
});
|
|
508
|
-
if (activeState.config.profile === "strict") {
|
|
509
|
-
// Event handlers cannot throw to block the edit (edit already happened), but we log loudly.
|
|
510
|
-
// In V2 we also have the tool hook to block before; this is advisory.
|
|
511
|
-
}
|
|
693
|
+
state.tracker.add(filePath, state.directory);
|
|
694
|
+
await runPerEditLint(state, filePath);
|
|
512
695
|
continue;
|
|
513
696
|
}
|
|
514
697
|
if (isIdleEvent(event)) {
|
|
515
|
-
if (
|
|
516
|
-
|
|
517
|
-
await reloadConfigIfChanged(
|
|
518
|
-
if (
|
|
698
|
+
if (activeState !== state)
|
|
699
|
+
return;
|
|
700
|
+
await reloadConfigIfChanged(state);
|
|
701
|
+
if (state.config.profile === "off")
|
|
519
702
|
continue;
|
|
520
|
-
if (!
|
|
521
|
-
await safeLog(
|
|
522
|
-
directory:
|
|
703
|
+
if (!state.config.gate) {
|
|
704
|
+
await safeLog(state, "warn", "plugin config is incomplete (missing gate section), skipping completion gate", {
|
|
705
|
+
directory: state.directory,
|
|
523
706
|
});
|
|
524
707
|
continue;
|
|
525
708
|
}
|
|
526
709
|
const sessionID = getEventSessionID(event);
|
|
527
710
|
if (!sessionID)
|
|
528
711
|
continue;
|
|
529
|
-
const verdict = await runCompletion(
|
|
530
|
-
const message = await actOnVerdict(
|
|
712
|
+
const verdict = await runCompletion(state, sessionID);
|
|
713
|
+
const message = await actOnVerdict(state, verdict);
|
|
531
714
|
if (message === null)
|
|
532
715
|
continue;
|
|
533
716
|
const blockInfo = verdict.decision === "blocked"
|
|
@@ -544,12 +727,12 @@ const plugin = Plugin.define({
|
|
|
544
727
|
await ctx.session.synthetic({ sessionID, text: message });
|
|
545
728
|
}
|
|
546
729
|
else {
|
|
547
|
-
await safeLog(
|
|
730
|
+
await safeLog(state, "error", `gate blocked but no session prompt API available: ${message}`);
|
|
548
731
|
}
|
|
549
|
-
await safeLog(
|
|
732
|
+
await safeLog(state, "info", `completion gate re-prompted session ${sessionID}${blockInfo}`);
|
|
550
733
|
}
|
|
551
734
|
catch (err) {
|
|
552
|
-
await safeLog(
|
|
735
|
+
await safeLog(state, "error", `failed to re-prompt session ${sessionID} after gate block: ${String(err)}`, {
|
|
553
736
|
sessionID,
|
|
554
737
|
});
|
|
555
738
|
}
|
|
@@ -561,7 +744,7 @@ const plugin = Plugin.define({
|
|
|
561
744
|
// normal on dispose
|
|
562
745
|
return;
|
|
563
746
|
}
|
|
564
|
-
await safeLog(
|
|
747
|
+
await safeLog(state, "error", `event loop error: ${String(err)}`);
|
|
565
748
|
}
|
|
566
749
|
})();
|
|
567
750
|
// Ensure the loop doesn't block setup
|
|
@@ -571,13 +754,14 @@ const plugin = Plugin.define({
|
|
|
571
754
|
// Unregister every hook/transform registered by this setup() so a
|
|
572
755
|
// teardown/reload (e.g. session_move into a worktree) does not leave
|
|
573
756
|
// stale closures alive. Disposal failures are ignored — the
|
|
574
|
-
//
|
|
757
|
+
// stale-hook guard (`activeState !== state` → no-op / fail-open) keeps
|
|
758
|
+
// the session usable regardless.
|
|
575
759
|
for (const registration of registrations) {
|
|
576
760
|
try {
|
|
577
761
|
await registration.dispose();
|
|
578
762
|
}
|
|
579
763
|
catch {
|
|
580
|
-
// ignore —
|
|
764
|
+
// ignore — stale-hook guard is the safety net
|
|
581
765
|
}
|
|
582
766
|
}
|
|
583
767
|
// Only clear the singleton if it is still ours; a newer setup() may
|
package/dist/protect.d.ts
CHANGED
|
@@ -42,3 +42,19 @@ export declare function matchDangerousCommand(command: string): DangerousCommand
|
|
|
42
42
|
* matched. Otherwise returns `deny` or `warn` per `protect_mode`.
|
|
43
43
|
*/
|
|
44
44
|
export declare function checkToolCall(config: ResolvedConfig, tool: string, args: unknown, directory?: string, hostPermissions?: OpenCodePermission): GuardResult;
|
|
45
|
+
/**
|
|
46
|
+
* Phase 25: adapt a native `permission.evaluate` event to the guardrail
|
|
47
|
+
* verdict. Maps the observed engine shapes (spike 25.1, OpenCode v2.0.26 —
|
|
48
|
+
* recorded in docs/plans/08-notes.md, never guessed):
|
|
49
|
+
* - action `"edit"` (covers edit/write/patch tools) with `resources[0]` =
|
|
50
|
+
* the target file path (repo-relative).
|
|
51
|
+
* - action `"shell"` (covers bash/shell tools) with `resources[0]` = the
|
|
52
|
+
* shell command string.
|
|
53
|
+
*
|
|
54
|
+
* Returns the guardrail verdict (`deny`/`warn`) or `null` when the mapper
|
|
55
|
+
* abstains (unknown action, empty resources, protection off, or no match) —
|
|
56
|
+
* `null` leaves the engine verdict untouched so the engine default wins.
|
|
57
|
+
* Never returns `allow`: the mapper can only deny, warn, or abstain, so it
|
|
58
|
+
* can never weaken host/engine enforcement.
|
|
59
|
+
*/
|
|
60
|
+
export declare function toPermissionGuard(config: ResolvedConfig, action: string, resources: ReadonlyArray<string>, directory?: string): GuardResult | null;
|
package/dist/protect.js
CHANGED
|
@@ -157,3 +157,35 @@ export function checkToolCall(config, tool, args, directory, hostPermissions) {
|
|
|
157
157
|
}
|
|
158
158
|
return { decision: "allow" };
|
|
159
159
|
}
|
|
160
|
+
/**
|
|
161
|
+
* Phase 25: adapt a native `permission.evaluate` event to the guardrail
|
|
162
|
+
* verdict. Maps the observed engine shapes (spike 25.1, OpenCode v2.0.26 —
|
|
163
|
+
* recorded in docs/plans/08-notes.md, never guessed):
|
|
164
|
+
* - action `"edit"` (covers edit/write/patch tools) with `resources[0]` =
|
|
165
|
+
* the target file path (repo-relative).
|
|
166
|
+
* - action `"shell"` (covers bash/shell tools) with `resources[0]` = the
|
|
167
|
+
* shell command string.
|
|
168
|
+
*
|
|
169
|
+
* Returns the guardrail verdict (`deny`/`warn`) or `null` when the mapper
|
|
170
|
+
* abstains (unknown action, empty resources, protection off, or no match) —
|
|
171
|
+
* `null` leaves the engine verdict untouched so the engine default wins.
|
|
172
|
+
* Never returns `allow`: the mapper can only deny, warn, or abstain, so it
|
|
173
|
+
* can never weaken host/engine enforcement.
|
|
174
|
+
*/
|
|
175
|
+
export function toPermissionGuard(config, action, resources, directory) {
|
|
176
|
+
if (config.profile === "off" || config.protect_off) {
|
|
177
|
+
return null;
|
|
178
|
+
}
|
|
179
|
+
if (resources.length === 0) {
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
if (action === "edit") {
|
|
183
|
+
const result = checkToolCall(config, "edit", { filePath: resources[0] }, directory, undefined);
|
|
184
|
+
return result.decision === "allow" ? null : result;
|
|
185
|
+
}
|
|
186
|
+
if (action === "shell") {
|
|
187
|
+
const result = checkToolCall(config, "bash", { command: resources[0] }, directory, undefined);
|
|
188
|
+
return result.decision === "allow" ? null : result;
|
|
189
|
+
}
|
|
190
|
+
return null;
|
|
191
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-dev-framework",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "OpenCode plugin that enforces project-specific quality gates during AI coding sessions",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -56,16 +56,16 @@
|
|
|
56
56
|
"guardrails"
|
|
57
57
|
],
|
|
58
58
|
"dependencies": {
|
|
59
|
-
"@opencode/plugin": "^2.0.
|
|
59
|
+
"@opencode/plugin": "^2.0.26",
|
|
60
60
|
"picomatch": "^4.0.5",
|
|
61
61
|
"yaml": "^2.9.0",
|
|
62
62
|
"zod": "^4.4.3"
|
|
63
63
|
},
|
|
64
64
|
"devDependencies": {
|
|
65
65
|
"@biomejs/biome": "^2.5.8",
|
|
66
|
-
"@opentui/core": "^0.5.
|
|
67
|
-
"@opentui/keymap": "^0.5.
|
|
68
|
-
"@opentui/solid": "^0.5.
|
|
66
|
+
"@opentui/core": "^0.5.17",
|
|
67
|
+
"@opentui/keymap": "^0.5.17",
|
|
68
|
+
"@opentui/solid": "^0.5.17",
|
|
69
69
|
"@types/node": "^26.2.0",
|
|
70
70
|
"@types/picomatch": "^4.0.3",
|
|
71
71
|
"markdownlint-cli2": "^0.23.2",
|