opencode-dev-framework 1.1.0 → 1.2.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 CHANGED
@@ -6,72 +6,87 @@ edits, through `/df-goal`. Inspired by
6
6
  [anticomputer/dev-framework](https://github.com/anticomputer/dev-framework),
7
7
  reimplemented as an OpenCode-native plugin.
8
8
 
9
+ ## Quickstart
10
+
11
+ Five minutes from zero to your first gated session:
12
+
13
+ ```bash
14
+ npm install opencode-dev-framework
15
+ ```
16
+
17
+ ```json
18
+ // opencode.jsonc
19
+ {
20
+ "plugins": ["opencode-dev-framework"]
21
+ }
22
+ ```
23
+
24
+ ```bash
25
+ npx df init
26
+ ```
27
+
28
+ `df init` auto-detects your language and writes a matching
29
+ `.opencode-dev-framework.yml`. Then start a session in your project and ask
30
+ the agent for a small edit. You will see the plugin working: the edit is
31
+ checked against guardrails before it lands, your linter runs on the edited
32
+ file, and when the session goes idle the completion gate runs your
33
+ typecheck/tests. `/df-status` shows the live state at any time. Start with
34
+ `profile: advisory` if you want to observe before enforcing.
35
+
36
+ Requires OpenCode `v2.x` — tested on `v2.0.26` and `v2.2.0`. On
37
+ `v1.18.18–1.18.31` use the `v1` branch (`plugin` key). Stuck? See
38
+ [`docs/user/troubleshooting.md`](docs/user/troubleshooting.md).
39
+
9
40
  ## What it does
10
41
 
11
- - **Constitution injection.** Adds a project constitution (quality bar, test
12
- discipline, focus rules) to the system prompt at session start. Ships with a
13
- bundled default split into numbered rule files. Override it by dropping files
14
- in `.opencode/opencode-dev-framework/rules/`, by setting explicit `rules`, or
15
- by letting the plugin auto-discover `STYLE.md` / `CONTRIBUTING.md`.
16
- - **Guardrails.** Blocks or warns on edits to protected paths (`.env` files,
17
- `node_modules`, vendored code, your own globs) and on dangerous shell
18
- commands (`git push`, `rm -rf`, `git reset --hard`, ...).
19
- - **Per-edit lint.** Runs your configured linter on each file the agent edits
20
- and reports failures loudly. Optionally delegates per-file linting to
21
- `pre-commit run --files` when `precommit: auto` is set.
22
- - **Completion gate.** At the would-go-idle boundary (`session.hook("experimental.idle")`,
23
- with an `idle` alias registered for a future rename), runs typecheck, tests,
24
- named acceptance commands (`gate.acceptance`), and (optionally) lint on changed files — changed files are
25
- tracked from edit events and cross-checked against `git status`, so the gate cannot
26
- silently skip due to an event-shape mismatch. In `standard`/`strict`, sessions that
27
- changed files must also produce a **peer-review artifact**
28
- (`.opencode/opencode-dev-framework/review.md`) covering the delegation rule's review
29
- cadence. On failure inside `gate.max_blocks` the plugin admits a synthetic
30
- continuation in the same execution with the failure summary. The
31
- `event.subscribe` idle net catches the boundaries the hook skips
32
- (interruption, failure, steer-parked drains) — deduped so one boundary never
33
- runs the gate twice, synthetic-first with `prompt` only as fallback.
34
- `/df-status` shows `Continuation (idle): active` once the hook has completed
35
- an evaluation, else the event-subscribe fallback.
36
- - **Verified goals (`/df-goal`).** Runs a whole task — typically a written
37
- plan — inside a native `/goal` with a verification contract appended:
38
- the agent must produce a `dev_framework_verify` PASS on the final tree,
39
- and the native reviewer weighs that tool result as completion evidence.
40
- Refuses vacuous configs, non-blocking profiles, and goal-less cores
41
- instead of starting an unverified substitute. See *Slash commands* below.
42
- - **Pre-flight gate (optional).** When a `preflight:` task list is configured, edit
43
- tools are **denied** (standard/strict) until the agent writes its pre-flight findings
44
- to `.opencode/opencode-dev-framework/preflight.md`. Use it for work that requires
45
- establishing baseline state/knowledge first (e.g. research on an existing strategy).
46
- Read-only tools stay open; the block lifts automatically once the artifact exists.
47
- - **Custom tools.** `dev_framework_init` scaffolds project-level agents,
48
- skills, local rules directory, and config; `dev_framework_set_profile` changes the profile
49
- in-session without restarting; `dev_framework_status` reports the current
50
- profile, guardrails, gate, and tracked changed files; `dev_framework_verify`
51
- runs the completion gate on demand and returns the summary to the agent.
52
- - **CLI installer.** `df init` auto-detects your language and writes a config
53
- with sensible commands; `df profile <name>` changes the profile from the
54
- shell; `df status` / `df version` report template state and the version.
55
- - **Slash commands.** The plugin registers four TUI commands that open instant
56
- modal dialogs and never feed anything to the LLM: `/df-status`, `/df-help`,
57
- `/df-profile` (bare for a picker, or with an argument), and `/df-verify`
58
- (runs the gate manually). `/df-goal <objective>` is a server-side command
59
- instead: it starts a verified native goal (see *Slash commands* below). The `dev_framework_*` custom *tools* above remain
60
- available for in-agent use.
61
-
62
- ### How it fits together
42
+ - **Constitution injection.** Adds a project quality bar to the system prompt
43
+ at session start (bundled default, overridable per project).
44
+ - **Guardrails.** Blocks or warns on protected paths (`.env`, vendored
45
+ code, your own globs) and dangerous shell commands (`git push`, `rm -rf`).
46
+ - **Per-edit lint.** Runs your linter on each edited file and reports loudly.
47
+ - **Completion gate.** At the would-go-idle boundary, runs typecheck, tests,
48
+ acceptance checks, and (optionally) lint on changed files — plus a required
49
+ peer-review artifact in `standard`/`strict`. Failures steer the session
50
+ back with the failure summary, bounded by `gate.max_blocks` (fewer when
51
+ the failure repeats with no new edits — the gate stands down early on
52
+ zero progress).
53
+ - **Verified goals (`/df-goal`).** Wraps a task in native `/goal` with a
54
+ verification contract the reviewer weighs as evidence.
55
+ - **Pre-flight gate (optional).** Denies edits until the agent records
56
+ required upfront research.
57
+ - **Custom tools + CLI.** `dev_framework_*` tools for in-agent use;
58
+ `df init / profile / status / version` from the shell.
59
+
60
+ ## Minimal configuration
61
+
62
+ ```yaml
63
+ profile: standard
64
+
65
+ commands:
66
+ typecheck: "npm run typecheck"
67
+ test: "npm test"
68
+ ```
69
+
70
+ Full reference (all keys, acceptance checks, pre-flight, rule overrides):
71
+ [`docs/user/configuration.md`](docs/user/configuration.md). Copy-paste
72
+ starters: [`examples/go-service/`](examples/go-service/).
73
+
74
+ ## How it fits together
75
+
76
+ Every session runs the same loop — constitution, guardrails, lint, gate —
77
+ whether or not it starts under `/df-goal`. A goal just wraps that loop in
78
+ native verification:
63
79
 
64
80
  ```mermaid
65
81
  flowchart TD
66
- G["/df-goal plan"] --> N["native /goal\nowns state + review"]
67
- N --> A["agent implements"]
82
+ U["user prompt\nplain or /df-goal plan"] --> A["agent implements"]
68
83
  A --> B{"tool.execute.before"}
69
84
  B -- "deny: protected /\ndangerous / pre-flight" --> X["blocked before landing"]
70
85
  B -- allow --> C["edit lands"]
71
86
  C --> D["per-edit lint\n+ change tracker"]
72
87
  D --> V["agent runs\ndev_framework_verify"]
73
88
  V --> R{"verdict"}
74
- R -- PASS --> N
89
+ R -- PASS --> OK["gate green"]
75
90
  R -- FAIL --> A
76
91
  D --> S{"session idle"}
77
92
  S --> GT["completion gate\nsame full contract"]
@@ -79,6 +94,10 @@ flowchart TD
79
94
  GT -- "FAIL, within max_blocks" --> SYN["synthetic continuation"]
80
95
  SYN --> A
81
96
  GT -- "FAIL, past max_blocks" --> SD["stand down:\nhonest unmet report"]
97
+ GT -- "FAIL, identical x3\nwith no new edits" --> SD
98
+ G["/df-goal plan\n(optional wrapper)"] -. "delegates once,\nappends contract" .-> N["native /goal\nowns objective + review"]
99
+ N -. "wraps the loop:\ndrives turns" .-> A
100
+ OK -. "in a goal: PASS reported\nas evidence into /goal" .-> N
82
101
  ```
83
102
 
84
103
  ## Profiles
@@ -88,283 +107,47 @@ flowchart TD
88
107
  | `off` | disabled | not reported | no | no | no | Plugin registers no hooks at all. |
89
108
  | `advisory` | warn | warn | yes | warn only | warned, not blocked | Nothing blocks; everything is logged. |
90
109
  | `standard` | deny | error | yes | deny edits | blocks completion | The default when a config file exists. |
91
- | `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). |
110
+ | `strict` | deny | error | yes | deny edits | blocks completion | Also lints changed files in the gate. |
92
111
 
93
- ## Enforcement layers
112
+ How each layer is enforced, and what it honestly cannot do:
113
+ [`docs/user/enforcement.md`](docs/user/enforcement.md).
94
114
 
95
- How each mechanism is enforced on OpenCode `v2` (idle hook landed via
96
- [`anomalyco/opencode#59437`](https://github.com/anomalyco/opencode/pull/59437)):
115
+ ## Commands
97
116
 
98
- | Mechanism | Primary layer | Backstop / fallback | Strength |
99
- | --------- | ------------- | ------------------- | -------- |
100
- | Pre-flight gate | `tool.execute.before` deny | — | **Hard block** on every build: the edit never lands. |
101
- | Protected paths + dangerous commands | `tool.execute.before` deny/throw (load-bearing: the pipeline runs before-hooks first) | `permission.evaluate` native layer (deny) as defense-in-depth — it only ever sees calls the primary already passed; matters if core ever reorders the pipeline | **Hard block** via the primary deny; the native layer is belt-and-braces, never a weakening (it only denies or abstains). |
102
- | 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. |
103
- | Completion gate | `session.hook("experimental.idle")` (+ `idle` alias) → `session.synthetic` (same execution) | `event.subscribe` idle net for the boundaries the hook skips (deduped; synthetic-first, `prompt` fallback) | **Async, bounded** by `gate.max_blocks`. `/df-status` shows `Continuation (idle): active` vs the event-subscribe fallback. `execute.before` stays the only true hard wall. |
117
+ | Command | What it does |
118
+ | ------- | -------------- |
119
+ | `/df-status` | Instant modal: profile, guardrails, gate, configured commands. |
120
+ | `/df-runtime` | Instant modal: plugin version + live hook/gate runtime state. |
121
+ | `/df-help` | Instant modal: lists the dev-framework commands. |
122
+ | `/df-profile` | Instant modal picker (or `/df-profile <name>`): switches profile now, written to config. |
123
+ | `/df-verify` | Runs the verification suite manually; pass/fail summary in a modal. |
124
+ | `/df-goal <objective>` | Server-side command: starts a **verified** native goal (requires native `/goal`, a blocking profile, and at least one real check). |
104
125
 
105
- ## Install
126
+ The first five are TUI commands — they open instantly and never feed the
127
+ LLM. Full reference:
128
+ [`docs/user/commands.md`](docs/user/commands.md).
106
129
 
107
- ```bash
108
- npm install opencode-dev-framework
109
- ```
130
+ ## Limitations (short version)
110
131
 
111
- Then add the plugin to your project's `opencode.jsonc`:
112
-
113
- ```json
114
- {
115
- "plugins": ["opencode-dev-framework"]
116
- }
117
- ```
132
+ The completion gate **steers, it does not veto**: it continues the turn via a
133
+ synthetic message at the idle boundary (bounded by `gate.max_blocks` — fewer
134
+ when the failure repeats with no new edits), and you
135
+ can always close the session. A genuine pre-stop veto is proposed upstream
136
+ ([`anomalyco/opencode#54487`](https://github.com/anomalyco/opencode/pull/54487),
137
+ open) — if it lands, the gate vetoes there instead of continuing. The
138
+ **pre-flight** gate is the one genuine hard block today. Guardrails add to OpenCode permissions, never replace them. Formatters
139
+ and linters are yours — the plugin runs them, it does not reimplement them.
140
+ Full story: [`docs/user/enforcement.md`](docs/user/enforcement.md).
118
141
 
119
- Requires OpenCode `v2.x` (`@opencode/plugin` `^2`) — tested on `v2.0.26`. On `v1.18.18–1.18.31` use the `v1` branch
120
- of this plugin (`plugin` key). The `./tui` companion (`/df-status` and `/df-help`
121
- modals) is auto-discovered from the npm entry on `v2` — no separate `tui.json` needed.
142
+ ## Troubleshooting
122
143
 
123
- Finally, scaffold the project-level files (agents, skills, local rules directory,
124
- and default config) into your repo with the bundled `df` CLI:
125
-
126
- ```bash
127
- npx df init # if installed locally as a project dependency
128
- # or, after npm i -g opencode-dev-framework:
129
- df init
130
- ```
131
-
132
- `df init` is interactive by default: it asks before overwriting existing files.
133
- Use `--skip-existing` or `--overwrite-existing` for non-interactive runs.
134
- `df init` auto-detects your project's language and writes a matching
135
- `.opencode-dev-framework.yml` with sensible commands. `df status` shows what is
136
- and isn't scaffolded; `df profile off|advisory|standard|strict` changes the
137
- profile from the shell; `df version` prints the plugin version.
138
-
139
- ## Local development and testing
140
-
141
- To test the plugin from source without publishing to npm, point OpenCode at the
142
- local repository **root** in your project's `opencode.jsonc`:
143
-
144
- ```json
145
- {
146
- "plugins": [{ "package": "/home/jerome/opencode-dev-framework" }]
147
- }
148
- ```
149
-
150
- The root path resolves through the package's `exports` map, so one entry
151
- loads **both** parts: the server (`dist/index.js` — hooks, guardrails, gate,
152
- custom tools) and the TUI (`tui.tsx` — `/df-status`, `/df-help` modals).
153
- Rebuild after every source change (`npm run build`) since OpenCode loads the
154
- compiled `dist/` output:
155
-
156
- ```bash
157
- npm run build
158
- ```
159
-
160
- ### Important caveats
161
-
162
- - Register the plugin **exactly once** per project. Plugin arrays **merge**
163
- across config files (global `opencode.jsonc`, project `./opencode.jsonc`,
164
- `./.opencode/opencode.json[c]`), so a second entry in another file —
165
- even one pointing at a different path of the same repo such as `dist/`
166
- — loads the same plugin ID twice and the duplicate fails with
167
- `Duplicate plugin ID: opencode-dev-framework` (check
168
- `opencode api get "/api/plugin?location[directory]=/path/to/project"`).
169
- If a session loads an unexpected plugin source, check all three locations.
170
- - Do **not** point the entry at `dist/` directly: a bare directory without
171
- `package.json`/`exports` resolves only the server part, so the TUI
172
- commands (`/df-status`, `/df-help`) never load. (On OpenCode `v2.0.x` the
173
- entrypoint resolved as `<dir>/index.js` and ignored `package.json`, which
174
- is why older revisions of this section recommended `dist/` — verified on
175
- `v2.2.0` that the root path resolves correctly through `exports`. The
176
- `.opencode/tui.json` listing from that era is likewise no longer needed:
177
- one `plugins` entry loads every part.)
178
- - OpenCode caches downloaded plugins in
179
- `~/.cache/opencode/packages/opencode-dev-framework*/`. If you previously
180
- loaded a published version and then switch to a local source, clear that
181
- cache so OpenCode does not reuse the old build:
182
-
183
- ```bash
184
- rm -rf ~/.cache/opencode/packages/opencode-dev-framework*
185
- ```
186
-
187
- ## Configuration
188
-
189
- Create `.opencode-dev-framework.yml` in your project root. The easiest way to
190
- override the bundled constitution is to run `df init` and then add Markdown
191
- files to `.opencode/opencode-dev-framework/rules/`.
192
-
193
- ```yaml
194
- profile: standard
195
-
196
- commands:
197
- typecheck: "go build ./..."
198
- test: "go test ./..."
199
- lint:
200
- ".go": "golangci-lint run {dir}"
201
-
202
- protect:
203
- - ".env*"
204
- - "deploy/prod/**"
205
-
206
- gate:
207
- run_typecheck: true
208
- run_tests: true
209
- block_on_failure: true
210
- # standard/strict default: sessions that changed files must produce a
211
- # peer-review artifact (.opencode/opencode-dev-framework/review.md)
212
- # before the completion gate passes.
213
- require_review: true
214
-
215
- # Optional: named project-specific acceptance checks. Run sequentially
216
- # after the typecheck/test steps; a failure fails the gate but other
217
- # steps still run. Timeouts are per-check seconds (default: gate timeout).
218
- # acceptance:
219
- # - name: api-contract
220
- # command: "./scripts/verify-api-contract.sh"
221
- # - name: migration-safety
222
- # command: "./scripts/check-migrations.sh"
223
- # timeout: 120
224
-
225
- # Optional: pre-flight task list. When set, edit tools are denied
226
- # (standard/strict) until the agent writes its findings to
227
- # .opencode/opencode-dev-framework/preflight.md.
228
- # preflight:
229
- # - "Summarize the current strategy configuration and its intent"
230
- # - "Load the most recent backtest results and record headline metrics"
231
-
232
- on_edit:
233
- lint: true
234
-
235
- # Optional: delegate per-file linting to pre-commit when available
236
- # precommit: auto
237
-
238
- # Optional: explicit rule files (replace bundled; use mode: append to extend)
239
- # rules:
240
- # - docs/team-rules.md
241
- # Append form (keeps the bundled rules, adds project files after them):
242
- # rules:
243
- # mode: append
244
- # files:
245
- # - .opencode/opencode-dev-framework/hardening.md
246
-
247
- # Optional: project style guide appended to the constitution.
248
- # Auto-discovers STYLE.md / CONTRIBUTING.md / docs/STYLE.md when not set.
249
- # style_guide: STYLE.md
250
- ```
251
-
252
- The legacy `.dev-framework.yml` flat-key format is read as a fallback for
253
- compatibility, but the native format above is preferred. See
254
- [`docs/plans/03-config-spec.md`](docs/plans/03-config-spec.md) for the full
255
- config reference and [`examples/go-service/`](examples/go-service/) for a
256
- complete example.
257
-
258
- ## Slash commands
259
-
260
- Five slash commands are **TUI commands** registered by the bundled `./tui`
261
- companion module (see *Local development* above for the `tui.json` requirement).
262
- They open instantly and **never** feed text back to the LLM:
263
-
264
- - `/df-status` — shows the current profile, guardrails, completion gate, and
265
- configured commands in a modal dialog.
266
- - `/df-runtime` — shows the plugin version and live hook/gate runtime state
267
- (which idle-hook method the core accepted, dispatch history) in a modal
268
- dialog. Read from a snapshot the server writes per project; reports
269
- "not reported yet" before the first session instead of guessing.
270
- - `/df-help` — lists the available dev-framework commands in a modal dialog.
271
- - `/df-profile` — opens a profile picker (off / advisory / standard / strict) in
272
- a modal dialog; selecting one switches the active profile immediately (written
273
- to the config file). With an argument (`/df-profile standard`) it switches
274
- directly with a toast instead of the picker.
275
- - `/df-verify` — runs the configured verification suite (the completion gate)
276
- manually and shows a pass/fail summary in a modal dialog.
277
-
278
- You can still run `df init` to install the bundled agents, skills, and default
279
- config; the commands themselves are provided by the plugin. The
280
- `dev_framework_*` custom *tools* remain
281
- available for in-agent use (e.g. when the model wants to change the profile
282
- itself).
283
-
284
- `/df-goal <objective>` is a **server-side command** instead (registered by the
285
- server plugin, not the TUI): it starts a **verified** native goal. The plugin
286
- appends a short verification contract to your objective verbatim and delegates
287
- exactly once to native `/goal`, which keeps owning state, review,
288
- pause/resume/clear, and continuations. Requires all three: native `/goal` on
289
- the core, a blocking profile (`standard`/`strict`, i.e.
290
- `gate.block_on_failure: true`), and at least one configured completion check
291
- (typecheck/test command, changed-file lint, `gate.acceptance`, or
292
- `gate.require_review`). Otherwise it fails with an actionable error instead of
293
- starting an unverified goal — use native `/goal` directly for purely semantic
294
- objectives. The objective plus addendum must fit native `/goal`'s 4,000-character
295
- limit; overflow is rejected, never truncated.
296
-
297
- The agent must run `dev_framework_verify` after its final changes; the native
298
- reviewer weighs that tool result as evidence and the framework idle gate stays
299
- an independent backstop. This is layered verification, not a hard lock:
300
- native `/goal` can still mark complete while the gate fails (or keep going
301
- after it passes), both tenants can admit a continuation at one idle boundary,
302
- and the framework stands down after `gate.max_blocks`.
303
-
304
- **Run plans under `/df-goal`.** When a task starts from a written plan, make
305
- the objective the plan inline (short plans) or `Implement the plan in <path>`
306
- (long plans). Native completion then requires the gate's PASS on the final
307
- tree — a stronger enforcement than a bare turn, where only your summary stands
308
- between the plan and "done".
309
-
310
- ## Limitations
311
-
312
- - **Post-flight enforcement is a same-execution continuation, not a veto.**
313
- At the would-go-idle boundary the `experimental.idle` hook (landed via
314
- [`anomalyco/opencode#59437`](https://github.com/anomalyco/opencode/pull/59437))
315
- runs the gate, and on failure inside `gate.max_blocks` admits a synthetic
316
- continuation in the same execution. The `event.subscribe` idle net covers
317
- the boundaries the hook skips (interruption, failure, steer-parked drains),
318
- deduped so one boundary never runs the gate twice. On builds without the
319
- hook only the net applies. `/df-status` shows which lever completed an
320
- evaluation (`Continuation (idle): active` vs the event-subscribe fallback).
321
- The user can always close the session, so treat the gate
322
- as the strongest available enforcement, not an unbreakable lock. The missing piece — a pre-terminal vote hook — is proposed upstream ([`anomalyco/opencode#54487`](https://github.com/anomalyco/opencode/pull/54487), open); until it lands, the above is the enforcement story. The **pre-flight**
323
- gate, by contrast, is a genuine hard block on every build: it denies edit tools in
324
- `tool.execute.before`, before the edit lands.
325
- - **Guardrails run inside OpenCode.** The `tool.execute.before` hook runs
326
- after OpenCode's own permission system; it adds project rules on top, it
327
- does not replace OpenCode permissions.
328
- - **Formatting and linting are delegated.** The plugin does not reimplement
329
- formatters or linters; you declare your linter commands in
330
- `.opencode-dev-framework.yml` and the plugin runs them on edited files and
331
- at the completion gate. Formatting is OpenCode core's job (`formatter` in
332
- `opencode.json`, off by default) — the plugin's `commands.format` /
333
- `on_edit.format` are accepted but ignored, deliberately not duplicated.
334
- The plugin does not automatically rewrite `opencode.json`
335
- formatter/permission fragments.
336
-
337
- ## Development
338
-
339
- ```bash
340
- npm install
341
- npm run format:check
342
- npm run lint
343
- npm run lint:md
344
- npm run typecheck
345
- npm run test
346
- npm run build
347
- ```
348
-
349
- For persistent debug traces, set `OPENCODE_DEV_FRAMEWORK_LOG_FILE`:
350
-
351
- ```bash
352
- OPENCODE_DEV_FRAMEWORK_LOG_FILE=/tmp/odf.log opencode run
353
- ```
354
-
355
- Plugin code runs in the `opencode serve` backend, not in your terminal
356
- process — a variable exported only in the TUI shell never reaches it. For
357
- full server logs plus the plugin trace, run a private server:
358
-
359
- ```bash
360
- OPENCODE_DEV_FRAMEWORK_LOG_FILE=/tmp/odf.log opencode run --standalone --print-logs
361
- ```
144
+ Duplicate plugin IDs, stale npm cache, TUI not loading, version matrix:
145
+ [`docs/user/troubleshooting.md`](docs/user/troubleshooting.md).
362
146
 
363
- (There is no `cli.json` interaction: the plugin never reads or writes CLI
364
- config; the flags above are stock OpenCode CLI options.)
147
+ ## Contributing
365
148
 
366
- See `AGENTS.md` and `docs/plans/` for the architecture and implementation
367
- plan.
149
+ `AGENTS.md` is the canonical contributor contract. Build/test commands and
150
+ the release path: [`docs/dev/contributing.md`](docs/dev/contributing.md).
368
151
 
369
152
  ## Disclaimer
370
153
 
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Persistent per-session completion-gate block counts.
2
+ * Persistent per-session completion-gate block counts (+ stuck snapshots).
3
3
  *
4
4
  * Counts live in `ctx.storage` (survives plugin reload / `session_move` /
5
5
  * server restart) with a caller-provided `Map` as the write-through L1
@@ -9,12 +9,14 @@
9
9
  * a broken storage backend degrades to pre-Phase-23 behavior instead of
10
10
  * breaking the gate.
11
11
  *
12
- * Stored values are only block counts (`number`). Never store secrets,
13
- * prompts, or file contents here.
12
+ * Stored values are only block counts (`number`) and stuck-detection
13
+ * snapshots (`{ signature, files, repeats }` — step names and relative
14
+ * paths, no file contents). Never store secrets, prompts, or file contents
15
+ * here.
14
16
  *
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).
17
+ * Key namespacing: counts are keyed `df:blocks:<sessionID>`, snapshots
18
+ * `df:stuck:<sessionID>` (OpenCode session IDs are globally unique, so
19
+ * this is safe even if storage is shared across projects).
18
20
  *
19
21
  * Historical note: pre-cutover builds persisted a `df:stopSupported` flag
20
22
  * recording which stopping probe fired. The idle-first cutover removed
@@ -24,6 +26,7 @@ import type { Context } from "@opencode/plugin/promise/plugin";
24
26
  /** Minimal storage surface we need (subset of `Context["storage"]`). */
25
27
  export type StorageLike = Pick<Context["storage"], "get" | "set" | "remove">;
26
28
  export declare const BLOCK_COUNT_KEY_PREFIX = "df:blocks:";
29
+ export declare const STUCK_SNAPSHOT_KEY_PREFIX = "df:stuck:";
27
30
  export interface BlockStore {
28
31
  get(sessionID: string): Promise<number>;
29
32
  /** Read, add one, persist, and return the new count. */
@@ -35,3 +38,22 @@ export interface BlockStore {
35
38
  isDegraded(): boolean;
36
39
  }
37
40
  export declare function createBlockStore(storage: StorageLike | undefined | null, memory?: Map<string, number>): BlockStore;
41
+ /**
42
+ * Last blocked evaluation per session, for no-progress early stand-down
43
+ * (docs/plans/14-stuck-detection.md). `signature` identifies the failure (`gate:<sorted step
44
+ * names>` or `review`); `files` is the sorted changed-file list at that
45
+ * evaluation; `repeats` counts consecutive no-progress repeats so far.
46
+ */
47
+ export interface StuckSnapshot {
48
+ signature: string;
49
+ files: string[];
50
+ repeats: number;
51
+ }
52
+ export interface StuckSnapshotStore {
53
+ get(sessionID: string): Promise<StuckSnapshot | undefined>;
54
+ record(sessionID: string, snapshot: StuckSnapshot): Promise<void>;
55
+ clear(sessionID: string): Promise<void>;
56
+ readonly size: number;
57
+ isDegraded(): boolean;
58
+ }
59
+ export declare function createStuckSnapshotStore(storage: StorageLike | undefined | null, memory?: Map<string, StuckSnapshot>): StuckSnapshotStore;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Persistent per-session completion-gate block counts.
2
+ * Persistent per-session completion-gate block counts (+ stuck snapshots).
3
3
  *
4
4
  * Counts live in `ctx.storage` (survives plugin reload / `session_move` /
5
5
  * server restart) with a caller-provided `Map` as the write-through L1
@@ -9,21 +9,27 @@
9
9
  * a broken storage backend degrades to pre-Phase-23 behavior instead of
10
10
  * breaking the gate.
11
11
  *
12
- * Stored values are only block counts (`number`). Never store secrets,
13
- * prompts, or file contents here.
12
+ * Stored values are only block counts (`number`) and stuck-detection
13
+ * snapshots (`{ signature, files, repeats }` — step names and relative
14
+ * paths, no file contents). Never store secrets, prompts, or file contents
15
+ * here.
14
16
  *
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).
17
+ * Key namespacing: counts are keyed `df:blocks:<sessionID>`, snapshots
18
+ * `df:stuck:<sessionID>` (OpenCode session IDs are globally unique, so
19
+ * this is safe even if storage is shared across projects).
18
20
  *
19
21
  * Historical note: pre-cutover builds persisted a `df:stopSupported` flag
20
22
  * recording which stopping probe fired. The idle-first cutover removed
21
23
  * that API; a stale key left by an older install is simply never read.
22
24
  */
23
25
  export const BLOCK_COUNT_KEY_PREFIX = "df:blocks:";
26
+ export const STUCK_SNAPSHOT_KEY_PREFIX = "df:stuck:";
24
27
  function blockKey(sessionID) {
25
28
  return `${BLOCK_COUNT_KEY_PREFIX}${sessionID}`;
26
29
  }
30
+ function stuckKey(sessionID) {
31
+ return `${STUCK_SNAPSHOT_KEY_PREFIX}${sessionID}`;
32
+ }
27
33
  /** Accept only sane counts; anything else (foreign/corrupt value) is treated as missing. */
28
34
  function asCount(value) {
29
35
  if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
@@ -88,3 +94,85 @@ export function createBlockStore(storage, memory) {
88
94
  },
89
95
  };
90
96
  }
97
+ /** Accept only sane snapshots; anything else is treated as missing. */
98
+ function asSnapshot(value) {
99
+ if (typeof value !== "object" || value === null)
100
+ return undefined;
101
+ const v = value;
102
+ if (typeof v.signature !== "string" || v.signature.length === 0 || v.signature.length > 4096)
103
+ return undefined;
104
+ if (!Array.isArray(v.files) || !v.files.every((f) => typeof f === "string"))
105
+ return undefined;
106
+ if (typeof v.repeats !== "number" || !Number.isFinite(v.repeats) || v.repeats < 0)
107
+ return undefined;
108
+ return {
109
+ signature: v.signature,
110
+ files: [...v.files].sort(),
111
+ repeats: Math.floor(v.repeats),
112
+ };
113
+ }
114
+ export function createStuckSnapshotStore(storage, memory) {
115
+ const snapshots = memory ?? new Map();
116
+ let degraded = false;
117
+ async function readSnapshot(sessionID) {
118
+ if (storage == null)
119
+ return snapshots.get(sessionID);
120
+ try {
121
+ const stored = asSnapshot(await storage.get(stuckKey(sessionID)));
122
+ if (stored !== undefined) {
123
+ snapshots.set(sessionID, stored);
124
+ return stored;
125
+ }
126
+ return snapshots.get(sessionID);
127
+ }
128
+ catch {
129
+ degraded = true;
130
+ return snapshots.get(sessionID);
131
+ }
132
+ }
133
+ async function writeSnapshot(sessionID, snapshot) {
134
+ snapshots.set(sessionID, snapshot);
135
+ if (storage == null)
136
+ return;
137
+ try {
138
+ // Plain literal (not the interface): satisfies the Json param type.
139
+ await storage.set(stuckKey(sessionID), {
140
+ signature: snapshot.signature,
141
+ files: [...snapshot.files],
142
+ repeats: snapshot.repeats,
143
+ });
144
+ }
145
+ catch {
146
+ degraded = true;
147
+ }
148
+ }
149
+ return {
150
+ get(sessionID) {
151
+ return readSnapshot(sessionID);
152
+ },
153
+ async record(sessionID, snapshot) {
154
+ await writeSnapshot(sessionID, {
155
+ signature: snapshot.signature,
156
+ files: [...snapshot.files].sort(),
157
+ repeats: Math.max(0, Math.floor(snapshot.repeats)),
158
+ });
159
+ },
160
+ async clear(sessionID) {
161
+ snapshots.delete(sessionID);
162
+ if (storage == null)
163
+ return;
164
+ try {
165
+ await storage.remove(stuckKey(sessionID));
166
+ }
167
+ catch {
168
+ degraded = true;
169
+ }
170
+ },
171
+ get size() {
172
+ return snapshots.size;
173
+ },
174
+ isDegraded() {
175
+ return degraded;
176
+ },
177
+ };
178
+ }
package/dist/harness.d.ts CHANGED
@@ -16,7 +16,7 @@
16
16
  * The verdict is consumed by the `experimental.idle` hook (same-execution
17
17
  * synthetic continuation) and the `session.idle` event net (re-prompt).
18
18
  */
19
- import type { BlockStore } from "./block-store.js";
19
+ import type { BlockStore, StuckSnapshotStore } from "./block-store.js";
20
20
  import { type ChangedFileTracker, type GateReport } from "./gate.js";
21
21
  import type { RunCommand } from "./host.js";
22
22
  import type { LintLimiter } from "./lint.js";
@@ -26,6 +26,14 @@ import type { ResolvedConfig } from "./types.js";
26
26
  export declare const REVIEW_ARTIFACT_REL = ".opencode/opencode-dev-framework/review.md";
27
27
  /** Project-relative path of the pre-flight artifact the agent must produce. */
28
28
  export declare const PREFLIGHT_ARTIFACT_REL = ".opencode/opencode-dev-framework/preflight.md";
29
+ /**
30
+ * Consecutive no-progress repeats before early stand-down (docs/plans/14-stuck-detection.md): the
31
+ * third identical blocked evaluation (two repeats) stands down. One
32
+ * investigate-then-fix cycle — a repeat with no edits while the agent
33
+ * reads logs or runs diagnostics — still blocks. Hardcoded, not a config
34
+ * key: the profile stays the single enforcement axis.
35
+ */
36
+ export declare const NO_PROGRESS_REPEATS = 2;
29
37
  export type ArtifactState = "missing" | "empty" | "present";
30
38
  /**
31
39
  * Inspect an artifact file: present (non-trivial content), empty, or missing.
@@ -79,6 +87,8 @@ export interface CompletionDeps {
79
87
  sessionID: string;
80
88
  tracker: ChangedFileTracker;
81
89
  blockCounts: BlockStore;
90
+ /** Last-blocked-evaluation snapshots for no-progress early stand-down. */
91
+ stuckSnapshots: StuckSnapshotStore;
82
92
  log: LogFn;
83
93
  /** Shared limiter bounding concurrent linter subprocesses. */
84
94
  lintLimiter?: LintLimiter;
package/dist/harness.js CHANGED
@@ -23,6 +23,14 @@ import { runGate, summarizeGate } from "./gate.js";
23
23
  export const REVIEW_ARTIFACT_REL = ".opencode/opencode-dev-framework/review.md";
24
24
  /** Project-relative path of the pre-flight artifact the agent must produce. */
25
25
  export const PREFLIGHT_ARTIFACT_REL = ".opencode/opencode-dev-framework/preflight.md";
26
+ /**
27
+ * Consecutive no-progress repeats before early stand-down (docs/plans/14-stuck-detection.md): the
28
+ * third identical blocked evaluation (two repeats) stands down. One
29
+ * investigate-then-fix cycle — a repeat with no edits while the agent
30
+ * reads logs or runs diagnostics — still blocks. Hardcoded, not a config
31
+ * key: the profile stays the single enforcement axis.
32
+ */
33
+ export const NO_PROGRESS_REPEATS = 2;
26
34
  /**
27
35
  * Inspect an artifact file: present (non-trivial content), empty, or missing.
28
36
  * Never throws — unreadable files count as missing.
@@ -283,7 +291,7 @@ export async function inspectCompletion(deps) {
283
291
  * block count applies to either lever.
284
292
  */
285
293
  export async function evaluateCompletion(deps) {
286
- const { run, config, directory, sessionID, tracker, blockCounts } = deps;
294
+ const { run, config, directory, sessionID, tracker, blockCounts, stuckSnapshots } = deps;
287
295
  if (config.profile === "off" || !config.gate) {
288
296
  return { decision: "pass", changedFiles: [] };
289
297
  }
@@ -301,6 +309,7 @@ export async function evaluateCompletion(deps) {
301
309
  if (!gateFailed && !reviewMissing) {
302
310
  tracker.clearChangedFiles();
303
311
  await blockCounts.clear(sessionID);
312
+ await stuckSnapshots.clear(sessionID);
304
313
  return {
305
314
  decision: "pass",
306
315
  changedFiles,
@@ -322,10 +331,41 @@ export async function evaluateCompletion(deps) {
322
331
  const reason = gateFailed ? "gate" : "review";
323
332
  const summary = inspection.summary;
324
333
  const maxBlocks = config.gate.max_blocks ?? 3;
334
+ // No-progress early stand-down (docs/plans/14-stuck-detection.md): consecutive blocked
335
+ // evaluations with the identical failure signature and no new edits buy
336
+ // zero information, so stop spending the budget on them. One
337
+ // investigate-then-fix cycle is tolerated (a single repeat still
338
+ // blocks); the third identical evaluation stands down.
339
+ const signature = gateFailed
340
+ ? `gate:${report.failedSteps
341
+ .map((s) => s.name)
342
+ .sort()
343
+ .join(",")}`
344
+ : "review";
345
+ const files = [...changedFiles].sort();
346
+ const previous = await stuckSnapshots.get(sessionID);
347
+ const noProgress = previous !== undefined &&
348
+ previous.signature === signature &&
349
+ previous.files.length === files.length &&
350
+ previous.files.every((f, i) => f === files[i]);
351
+ const repeats = noProgress ? previous.repeats + 1 : 0;
352
+ if (repeats >= NO_PROGRESS_REPEATS) {
353
+ tracker.clearChangedFiles();
354
+ await blockCounts.clear(sessionID);
355
+ await stuckSnapshots.clear(sessionID);
356
+ const stuckSummary = `opencode-dev-framework completion gate has seen the identical failure across ` +
357
+ `${repeats + 1} evaluations with no new changes and is standing down to avoid ` +
358
+ `trapping you. The requirement is STILL unmet:\n\n${summary}\n\n` +
359
+ `Do not claim the work is complete. Tell the user plainly what remains unmet and why.`;
360
+ await deps.log("error", stuckSummary, { reason, sessionID });
361
+ return { decision: "standdown", reason, summary: stuckSummary, changedFiles };
362
+ }
363
+ await stuckSnapshots.record(sessionID, { signature, files, repeats });
325
364
  const blockCount = await blockCounts.increment(sessionID);
326
365
  if (blockCount > maxBlocks) {
327
366
  tracker.clearChangedFiles();
328
367
  await blockCounts.clear(sessionID);
368
+ await stuckSnapshots.clear(sessionID);
329
369
  const standdownSummary = `opencode-dev-framework completion gate has blocked ${maxBlocks} times and is standing ` +
330
370
  `down to avoid trapping you. The requirement is STILL unmet:\n\n${summary}\n\n` +
331
371
  `Do not claim the work is complete. Tell the user plainly what remains unmet and why.`;
package/dist/index.d.ts CHANGED
@@ -21,7 +21,7 @@
21
21
  * stays as a deduped fallback for the boundaries the hook skips.
22
22
  */
23
23
  import { Plugin } from "@opencode/plugin";
24
- import { type BlockStore } from "./block-store.js";
24
+ import { type BlockStore, type StuckSnapshotStore } from "./block-store.js";
25
25
  import { type ChangedFileTracker } from "./gate.js";
26
26
  import { type PassCache } from "./harness.js";
27
27
  import { type RunCommand } from "./host.js";
@@ -46,6 +46,12 @@ export interface HookState {
46
46
  * store keeps live on every get/increment/clear.
47
47
  */
48
48
  blocks: BlockStore;
49
+ /**
50
+ * Last-blocked-evaluation snapshots for no-progress early stand-down
51
+ * (docs/plans/14-stuck-detection.md). Same storage-backed, best-effort pattern as `blocks`;
52
+ * memory-only here (no status projection needed).
53
+ */
54
+ stuckSnapshots: StuckSnapshotStore;
49
55
  precommitAvailable?: boolean;
50
56
  configMtime?: number;
51
57
  /**
package/dist/index.js CHANGED
@@ -23,7 +23,7 @@
23
23
  import { Plugin } from "@opencode/plugin";
24
24
  import { stat } from "node:fs/promises";
25
25
  import { join } from "node:path";
26
- import { createBlockStore } from "./block-store.js";
26
+ import { createBlockStore, createStuckSnapshotStore, } from "./block-store.js";
27
27
  import { clearConfigCache, loadConfig } from "./config.js";
28
28
  import { createChangedFileTracker } from "./gate.js";
29
29
  import { artifactState, createPassCache, evaluateCompletion, PREFLIGHT_ARTIFACT_REL, preflightBlockReason, } from "./harness.js";
@@ -162,6 +162,7 @@ function runCompletion(state, sessionID) {
162
162
  sessionID,
163
163
  tracker: state.tracker,
164
164
  blockCounts: state.blocks,
165
+ stuckSnapshots: state.stuckSnapshots,
165
166
  lintLimiter: state.lintLimiter,
166
167
  passCache: state.passCache,
167
168
  log: (level, message, extra) => safeLog(state, level, message, extra),
@@ -274,6 +275,7 @@ const plugin = Plugin.define({
274
275
  const tracker = createChangedFileTracker();
275
276
  const blockCounts = new Map();
276
277
  const blocks = createBlockStore(ctx.storage, blockCounts);
278
+ const stuckSnapshots = createStuckSnapshotStore(ctx.storage);
277
279
  const state = {
278
280
  directory,
279
281
  config,
@@ -283,6 +285,7 @@ const plugin = Plugin.define({
283
285
  constitution,
284
286
  blockCounts,
285
287
  blocks,
288
+ stuckSnapshots,
286
289
  configMtime,
287
290
  lintLimiter: createLintLimiter(),
288
291
  passCache: createPassCache(),
@@ -294,7 +297,7 @@ const plugin = Plugin.define({
294
297
  // With the stop-level hydration gone there is no setup-time storage
295
298
  // read left, so this rarely fires here — the store still degrades
296
299
  // lazily on first use and reports via isDegraded().
297
- if (blocks.isDegraded()) {
300
+ if (blocks.isDegraded() || stuckSnapshots.isDegraded()) {
298
301
  await log("warn", "ctx.storage is unavailable; gate block counts are in-memory only and reset on reload", { directory });
299
302
  }
300
303
  const registrations = [];
@@ -833,11 +836,12 @@ const plugin = Plugin.define({
833
836
  const event = rawEvent;
834
837
  const type = event.type;
835
838
  if (isSessionDeletedEvent(type)) {
836
- // session.deleted: cleanup block counts (memory + storage) and
837
- // the idle dedup stamp for the session.
839
+ // session.deleted: cleanup block counts + stuck snapshots
840
+ // (memory + storage) and the idle dedup stamp for the session.
838
841
  const sid = getEventSessionID(event);
839
842
  if (sid) {
840
843
  await state.blocks.clear(sid);
844
+ await state.stuckSnapshots.clear(sid);
841
845
  state.lastIdleHandled.delete(sid);
842
846
  }
843
847
  continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-dev-framework",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "OpenCode plugin that enforces project-specific quality gates during AI coding sessions",
5
5
  "license": "MIT",
6
6
  "type": "module",