opencode-dev-framework 1.0.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
@@ -1,320 +1,153 @@
1
1
  # opencode-dev-framework
2
2
 
3
3
  An [OpenCode](https://opencode.ai) plugin that enforces project-specific
4
- quality gates during AI coding sessions. Inspired by
4
+ quality gates during AI coding sessions — and verifies whole tasks, not just
5
+ edits, through `/df-goal`. Inspired by
5
6
  [anticomputer/dev-framework](https://github.com/anticomputer/dev-framework),
6
7
  reimplemented as an OpenCode-native plugin.
7
8
 
8
- ## What it does
9
-
10
- - **Constitution injection.** Adds a project constitution (quality bar, test
11
- discipline, focus rules) to the system prompt at session start. Ships with a
12
- bundled default split into numbered rule files. Override it by dropping files
13
- in `.opencode/opencode-dev-framework/rules/`, by setting explicit `rules`, or
14
- by letting the plugin auto-discover `STYLE.md` / `CONTRIBUTING.md`.
15
- - **Guardrails.** Blocks or warns on edits to protected paths (`.env` files,
16
- `node_modules`, vendored code, your own globs) and on dangerous shell
17
- commands (`git push`, `rm -rf`, `git reset --hard`, ...).
18
- - **Per-edit lint.** Runs your configured linter on each file the agent edits
19
- and reports failures loudly. Optionally delegates per-file linting to
20
- `pre-commit run --files` when `precommit: auto` is set.
21
- - **Completion gate.** At the would-go-idle boundary (`session.hook("experimental.idle")`,
22
- with an `idle` alias registered for a future rename), runs typecheck, tests,
23
- and (optionally) lint on changed files — changed files are
24
- tracked from edit events and cross-checked against `git status`, so the gate cannot
25
- silently skip due to an event-shape mismatch. In `standard`/`strict`, sessions that
26
- changed files must also produce a **peer-review artifact**
27
- (`.opencode/opencode-dev-framework/review.md`) covering the delegation rule's review
28
- cadence. On failure inside `gate.max_blocks` the plugin admits a synthetic
29
- continuation in the same execution with the failure summary. The
30
- `event.subscribe` idle net catches the boundaries the hook skips
31
- (interruption, failure, steer-parked drains) — deduped so one boundary never
32
- runs the gate twice, synthetic-first with `prompt` only as fallback.
33
- `/df-status` shows `Continuation (idle): active` once the hook has completed
34
- an evaluation, else the event-subscribe fallback.
35
- - **Pre-flight gate (optional).** When a `preflight:` task list is configured, edit
36
- tools are **denied** (standard/strict) until the agent writes its pre-flight findings
37
- to `.opencode/opencode-dev-framework/preflight.md`. Use it for work that requires
38
- establishing baseline state/knowledge first (e.g. research on an existing strategy).
39
- Read-only tools stay open; the block lifts automatically once the artifact exists.
40
- - **Custom tools.** `dev_framework_init` scaffolds project-level agents,
41
- skills, local rules directory, and config; `dev_framework_set_profile` changes the profile
42
- in-session without restarting; `dev_framework_status` reports the current
43
- profile, guardrails, gate, and tracked changed files; `dev_framework_verify`
44
- runs the completion gate on demand and returns the summary to the agent.
45
- - **CLI installer.** `df init` auto-detects your language and writes a config
46
- with sensible commands; `df profile <name>` changes the profile from the
47
- shell; `df status` / `df version` report template state and the version.
48
- - **Slash commands.** The plugin registers four TUI commands that open instant
49
- modal dialogs and never feed anything to the LLM: `/df-status`, `/df-help`,
50
- `/df-profile` (bare for a picker, or with an argument), and `/df-verify`
51
- (runs the gate manually). `/df-goal <objective>` is a server-side command
52
- instead: it starts a verified native goal (see *Slash commands* below). The `dev_framework_*` custom *tools* above remain
53
- available for in-agent use.
54
-
55
- ## Profiles
56
-
57
- | Profile | Guardrails | Gate failures | Lint on edit | Pre-flight | Review required | Notes |
58
- | ---------- | ---------- | ------------- | ------------ | ---------- | --------------- | ----- |
59
- | `off` | disabled | not reported | no | no | no | Plugin registers no hooks at all. |
60
- | `advisory` | warn | warn | yes | warn only | warned, not blocked | Nothing blocks; everything is logged. |
61
- | `standard` | deny | error | yes | deny edits | blocks completion | The default when a config file exists. |
62
- | `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). |
63
-
64
- ## Enforcement layers
9
+ ## Quickstart
65
10
 
66
- How each mechanism is enforced on OpenCode `v2` (idle hook landed via
67
- [`anomalyco/opencode#59437`](https://github.com/anomalyco/opencode/pull/59437)):
68
-
69
- | Mechanism | Primary layer | Backstop / fallback | Strength |
70
- | --------- | ------------- | ------------------- | -------- |
71
- | Pre-flight gate | `tool.execute.before` deny | — | **Hard block** on every build: the edit never lands. |
72
- | 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). |
73
- | 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. |
74
- | 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. |
75
-
76
- ## Install
11
+ Five minutes from zero to your first gated session:
77
12
 
78
13
  ```bash
79
14
  npm install opencode-dev-framework
80
15
  ```
81
16
 
82
- Then add the plugin to your project's `opencode.jsonc`:
83
-
84
17
  ```json
18
+ // opencode.jsonc
85
19
  {
86
20
  "plugins": ["opencode-dev-framework"]
87
21
  }
88
22
  ```
89
23
 
90
- Requires OpenCode `v2.x` (`@opencode/plugin` `^2`) — tested on `v2.0.26`. On `v1.18.18–1.18.31` use the `v1` branch
91
- of this plugin (`plugin` key). The `./tui` companion (`/df-status` and `/df-help`
92
- modals) is auto-discovered from the npm entry on `v2` — no separate `tui.json` needed.
93
-
94
- Finally, scaffold the project-level files (agents, skills, local rules directory,
95
- and default config) into your repo with the bundled `df` CLI:
96
-
97
24
  ```bash
98
- npx df init # if installed locally as a project dependency
99
- # or, after npm i -g opencode-dev-framework:
100
- df init
25
+ npx df init
101
26
  ```
102
27
 
103
- `df init` is interactive by default: it asks before overwriting existing files.
104
- Use `--skip-existing` or `--overwrite-existing` for non-interactive runs.
105
- `df init` auto-detects your project's language and writes a matching
106
- `.opencode-dev-framework.yml` with sensible commands. `df status` shows what is
107
- and isn't scaffolded; `df profile off|advisory|standard|strict` changes the
108
- profile from the shell; `df version` prints the plugin version.
109
-
110
- ## Local development and testing
111
-
112
- To test the plugin from source without publishing to npm, point OpenCode at the
113
- local repository **root** in your project's `opencode.jsonc`:
114
-
115
- ```json
116
- {
117
- "plugins": [{ "package": "/home/jerome/opencode-dev-framework" }]
118
- }
119
- ```
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.
120
35
 
121
- The root path resolves through the package's `exports` map, so one entry
122
- loads **both** parts: the server (`dist/index.js` — hooks, guardrails, gate,
123
- custom tools) and the TUI (`tui.tsx` — `/df-status`, `/df-help` modals).
124
- Rebuild after every source change (`npm run build`) since OpenCode loads the
125
- compiled `dist/` output:
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).
126
39
 
127
- ```bash
128
- npm run build
129
- ```
40
+ ## What it does
130
41
 
131
- ### Important caveats
132
-
133
- - Register the plugin **exactly once** per project. Plugin arrays **merge**
134
- across config files (global `opencode.jsonc`, project `./opencode.jsonc`,
135
- `./.opencode/opencode.json[c]`), so a second entry in another file —
136
- even one pointing at a different path of the same repo such as `dist/`
137
- — loads the same plugin ID twice and the duplicate fails with
138
- `Duplicate plugin ID: opencode-dev-framework` (check
139
- `opencode api get "/api/plugin?location[directory]=/path/to/project"`).
140
- If a session loads an unexpected plugin source, check all three locations.
141
- - Do **not** point the entry at `dist/` directly: a bare directory without
142
- `package.json`/`exports` resolves only the server part, so the TUI
143
- commands (`/df-status`, `/df-help`) never load. (On OpenCode `v2.0.x` the
144
- entrypoint resolved as `<dir>/index.js` and ignored `package.json`, which
145
- is why older revisions of this section recommended `dist/` — verified on
146
- `v2.2.0` that the root path resolves correctly through `exports`. The
147
- `.opencode/tui.json` listing from that era is likewise no longer needed:
148
- one `plugins` entry loads every part.)
149
- - OpenCode caches downloaded plugins in
150
- `~/.cache/opencode/packages/opencode-dev-framework*/`. If you previously
151
- loaded a published version and then switch to a local source, clear that
152
- cache so OpenCode does not reuse the old build:
153
-
154
- ```bash
155
- rm -rf ~/.cache/opencode/packages/opencode-dev-framework*
156
- ```
157
-
158
- ## Configuration
159
-
160
- Create `.opencode-dev-framework.yml` in your project root. The easiest way to
161
- override the bundled constitution is to run `df init` and then add Markdown
162
- files to `.opencode/opencode-dev-framework/rules/`.
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
163
61
 
164
62
  ```yaml
165
63
  profile: standard
166
64
 
167
65
  commands:
168
- typecheck: "go build ./..."
169
- test: "go test ./..."
170
- lint:
171
- ".go": "golangci-lint run {dir}"
172
-
173
- protect:
174
- - ".env*"
175
- - "deploy/prod/**"
176
-
177
- gate:
178
- run_typecheck: true
179
- run_tests: true
180
- block_on_failure: true
181
- # standard/strict default: sessions that changed files must produce a
182
- # peer-review artifact (.opencode/opencode-dev-framework/review.md)
183
- # before the completion gate passes.
184
- require_review: true
185
-
186
- # Optional: pre-flight task list. When set, edit tools are denied
187
- # (standard/strict) until the agent writes its findings to
188
- # .opencode/opencode-dev-framework/preflight.md.
189
- # preflight:
190
- # - "Summarize the current strategy configuration and its intent"
191
- # - "Load the most recent backtest results and record headline metrics"
192
-
193
- on_edit:
194
- lint: true
195
-
196
- # Optional: delegate per-file linting to pre-commit when available
197
- # precommit: auto
198
-
199
- # Optional: explicit rule files (replace bundled; use mode: append to extend)
200
- # rules:
201
- # - docs/team-rules.md
202
-
203
- # Optional: project style guide appended to the constitution.
204
- # Auto-discovers STYLE.md / CONTRIBUTING.md / docs/STYLE.md when not set.
205
- # style_guide: STYLE.md
66
+ typecheck: "npm run typecheck"
67
+ test: "npm test"
206
68
  ```
207
69
 
208
- The legacy `.dev-framework.yml` flat-key format is read as a fallback for
209
- compatibility, but the native format above is preferred. See
210
- [`docs/plans/03-config-spec.md`](docs/plans/03-config-spec.md) for the full
211
- config reference and [`examples/go-service/`](examples/go-service/) for a
212
- complete example.
213
-
214
- ## Slash commands
215
-
216
- Five slash commands are **TUI commands** registered by the bundled `./tui`
217
- companion module (see *Local development* above for the `tui.json` requirement).
218
- They open instantly and **never** feed text back to the LLM:
219
-
220
- - `/df-status` — shows the current profile, guardrails, completion gate, and
221
- configured commands in a modal dialog.
222
- - `/df-runtime` — shows the plugin version and live hook/gate runtime state
223
- (which idle-hook method the core accepted, dispatch history) in a modal
224
- dialog. Read from a snapshot the server writes per project; reports
225
- "not reported yet" before the first session instead of guessing.
226
- - `/df-help` — lists the available dev-framework commands in a modal dialog.
227
- - `/df-profile` — opens a profile picker (off / advisory / standard / strict) in
228
- a modal dialog; selecting one switches the active profile immediately (written
229
- to the config file). With an argument (`/df-profile standard`) it switches
230
- directly with a toast instead of the picker.
231
- - `/df-verify` — runs the configured verification suite (the completion gate)
232
- manually and shows a pass/fail summary in a modal dialog.
233
-
234
- You can still run `df init` to install the bundled agents, skills, and default
235
- config; the commands themselves are provided by the plugin. The
236
- `dev_framework_*` custom *tools* remain
237
- available for in-agent use (e.g. when the model wants to change the profile
238
- itself).
239
-
240
- `/df-goal <objective>` is a **server-side command** instead (registered by the
241
- server plugin, not the TUI): it starts a **verified** native goal. The plugin
242
- appends a short verification contract to your objective verbatim and delegates
243
- exactly once to native `/goal`, which keeps owning state, review,
244
- pause/resume/clear, and continuations. Requires all three: native `/goal` on
245
- the core, a blocking profile (`standard`/`strict`, i.e.
246
- `gate.block_on_failure: true`), and at least one configured completion check
247
- (typecheck/test command, changed-file lint, `gate.acceptance`, or
248
- `gate.require_review`). Otherwise it fails with an actionable error instead of
249
- starting an unverified goal — use native `/goal` directly for purely semantic
250
- objectives. The objective plus addendum must fit native `/goal`'s 4,000-character
251
- limit; overflow is rejected, never truncated.
252
-
253
- The agent must run `dev_framework_verify` after its final changes; the native
254
- reviewer weighs that tool result as evidence and the framework idle gate stays
255
- an independent backstop. This is layered verification, not a hard lock:
256
- native `/goal` can still mark complete while the gate fails (or keep going
257
- after it passes), both tenants can admit a continuation at one idle boundary,
258
- and the framework stands down after `gate.max_blocks`.
259
-
260
- ## Limitations
261
-
262
- - **Post-flight enforcement is a same-execution continuation, not a veto.**
263
- At the would-go-idle boundary the `experimental.idle` hook (landed via
264
- [`anomalyco/opencode#59437`](https://github.com/anomalyco/opencode/pull/59437))
265
- runs the gate, and on failure inside `gate.max_blocks` admits a synthetic
266
- continuation in the same execution. The `event.subscribe` idle net covers
267
- the boundaries the hook skips (interruption, failure, steer-parked drains),
268
- deduped so one boundary never runs the gate twice. On builds without the
269
- hook only the net applies. `/df-status` shows which lever completed an
270
- evaluation (`Continuation (idle): active` vs the event-subscribe fallback).
271
- The user can always close the session, so treat the gate
272
- 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**
273
- gate, by contrast, is a genuine hard block on every build: it denies edit tools in
274
- `tool.execute.before`, before the edit lands.
275
- - **Guardrails run inside OpenCode.** The `tool.execute.before` hook runs
276
- after OpenCode's own permission system; it adds project rules on top, it
277
- does not replace OpenCode permissions.
278
- - **Formatting and linting are delegated.** The plugin does not reimplement
279
- formatters or linters; you declare your linter commands in
280
- `.opencode-dev-framework.yml` and the plugin runs them on edited files and
281
- at the completion gate. Formatting is OpenCode core's job (`formatter` in
282
- `opencode.json`, off by default) — the plugin's `commands.format` /
283
- `on_edit.format` are accepted but ignored, deliberately not duplicated.
284
- The plugin does not automatically rewrite `opencode.json`
285
- formatter/permission fragments.
286
-
287
- ## Development
288
-
289
- ```bash
290
- npm install
291
- npm run format:check
292
- npm run lint
293
- npm run lint:md
294
- npm run typecheck
295
- npm run test
296
- npm run build
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:
79
+
80
+ ```mermaid
81
+ flowchart TD
82
+ U["user prompt\nplain or /df-goal plan"] --> A["agent implements"]
83
+ A --> B{"tool.execute.before"}
84
+ B -- "deny: protected /\ndangerous / pre-flight" --> X["blocked before landing"]
85
+ B -- allow --> C["edit lands"]
86
+ C --> D["per-edit lint\n+ change tracker"]
87
+ D --> V["agent runs\ndev_framework_verify"]
88
+ V --> R{"verdict"}
89
+ R -- PASS --> OK["gate green"]
90
+ R -- FAIL --> A
91
+ D --> S{"session idle"}
92
+ S --> GT["completion gate\nsame full contract"]
93
+ GT -- PASS --> DONE["done"]
94
+ GT -- "FAIL, within max_blocks" --> SYN["synthetic continuation"]
95
+ SYN --> A
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
297
101
  ```
298
102
 
299
- For persistent debug traces, set `OPENCODE_DEV_FRAMEWORK_LOG_FILE`:
103
+ ## Profiles
300
104
 
301
- ```bash
302
- OPENCODE_DEV_FRAMEWORK_LOG_FILE=/tmp/odf.log opencode run
303
- ```
105
+ | Profile | Guardrails | Gate failures | Lint on edit | Pre-flight | Review required | Notes |
106
+ | ---------- | ---------- | ------------- | ------------ | ---------- | --------------- | ----- |
107
+ | `off` | disabled | not reported | no | no | no | Plugin registers no hooks at all. |
108
+ | `advisory` | warn | warn | yes | warn only | warned, not blocked | Nothing blocks; everything is logged. |
109
+ | `standard` | deny | error | yes | deny edits | blocks completion | The default when a config file exists. |
110
+ | `strict` | deny | error | yes | deny edits | blocks completion | Also lints changed files in the gate. |
304
111
 
305
- Plugin code runs in the `opencode serve` backend, not in your terminal
306
- process — a variable exported only in the TUI shell never reaches it. For
307
- full server logs plus the plugin trace, run a private server:
112
+ How each layer is enforced, and what it honestly cannot do:
113
+ [`docs/user/enforcement.md`](docs/user/enforcement.md).
308
114
 
309
- ```bash
310
- OPENCODE_DEV_FRAMEWORK_LOG_FILE=/tmp/odf.log opencode run --standalone --print-logs
311
- ```
115
+ ## Commands
116
+
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). |
125
+
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).
129
+
130
+ ## Limitations (short version)
131
+
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).
141
+
142
+ ## Troubleshooting
143
+
144
+ Duplicate plugin IDs, stale npm cache, TUI not loading, version matrix:
145
+ [`docs/user/troubleshooting.md`](docs/user/troubleshooting.md).
312
146
 
313
- (There is no `cli.json` interaction: the plugin never reads or writes CLI
314
- config; the flags above are stock OpenCode CLI options.)
147
+ ## Contributing
315
148
 
316
- See `AGENTS.md` and `docs/plans/` for the architecture and implementation
317
- 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).
318
151
 
319
152
  ## Disclaimer
320
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
+ }
@@ -10,3 +10,8 @@ export interface NormalizedCommandMap {
10
10
  export declare function normalizeCommandMap(map: CommandMap | undefined): NormalizedCommandMap;
11
11
  /** Split a command string into argv tokens, honoring simple quotes. */
12
12
  export declare function splitCommand(command: string): string[];
13
+ export interface GlobMatcher {
14
+ pattern: string;
15
+ match: (candidate: string) => boolean;
16
+ }
17
+ export declare function compileGlobMatchers(patterns: readonly string[]): GlobMatcher[];