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.
@@ -1,3 +1,4 @@
1
+ import picomatch from "picomatch";
1
2
  /**
2
3
  * Normalize a command map: a plain string becomes the default command; a record
3
4
  * may contain a `default` key plus per-extension overrides.
@@ -44,3 +45,23 @@ export function splitCommand(command) {
44
45
  }
45
46
  return tokens;
46
47
  }
48
+ /**
49
+ * Compile glob patterns to picomatch matchers, cached by pattern-array
50
+ * identity. Compilation is the expensive part; the per-tool-call hot path
51
+ * pays matching only. A re-resolved config carries new arrays and naturally
52
+ * recompiles once. Shared by protected-path and exclude matching so the
53
+ * cache scheme exists exactly once.
54
+ */
55
+ const globMatcherCache = new WeakMap();
56
+ export function compileGlobMatchers(patterns) {
57
+ const cached = globMatcherCache.get(patterns);
58
+ if (cached !== undefined) {
59
+ return cached;
60
+ }
61
+ const compiled = patterns.map((pattern) => ({
62
+ pattern,
63
+ match: picomatch(pattern, { dot: true }),
64
+ }));
65
+ globMatcherCache.set(patterns, compiled);
66
+ return compiled;
67
+ }
package/dist/commands.js CHANGED
@@ -2,6 +2,7 @@ import { join } from "node:path";
2
2
  import { loadConfig } from "./config.js";
3
3
  import { inspectCompletion } from "./harness.js";
4
4
  import { setProfileInFile } from "./installer.js";
5
+ import { createLintLimiter } from "./lint.js";
5
6
  /**
6
7
  * Change the project profile by editing the config file on disk. The server
7
8
  * plugin reloads the in-memory config on the next tool call / gate run (see
@@ -33,6 +34,9 @@ export async function verifyGate(run, directory, config, changedFiles = []) {
33
34
  config: cfg,
34
35
  directory,
35
36
  trackerFiles: changedFiles,
37
+ // Fresh limiter per manual verify (bounds its own lint burst); no pass
38
+ // cache — an explicit verify always inspects the live tree.
39
+ lintLimiter: createLintLimiter(),
36
40
  });
37
41
  const verdict = inspection.ok ? "PASS" : "FAIL";
38
42
  const summary = `DEV_FRAMEWORK_VERDICT: ${verdict}\n${inspection.summary}`;
package/dist/config.d.ts CHANGED
@@ -30,9 +30,11 @@ export declare function resolveConfig(raw: Config, configPath?: string): Resolve
30
30
  * A verified goal must imply deterministic evidence where none would exist
31
31
  * otherwise, so `/df-goal` refuses to delegate when the resolved
32
32
  * configuration provides no real completion check at all. A check counts
33
- * only when its step would actually run in `runGate` — a `run_*` flag with
34
- * no command behind it produces a skipped step, which is vacuous. Users
35
- * wanting a purely semantic objective use native `/goal` directly.
33
+ * only when its step would actually run — a `run_*` flag with no command
34
+ * behind it produces a skipped step, which is vacuous. The review check
35
+ * runs in the harness (`reviewMissing`), not in `runGate`, but counts all
36
+ * the same. Users wanting a purely semantic objective use native `/goal`
37
+ * directly.
36
38
  */
37
39
  export declare function hasMeaningfulChecks(config: ResolvedConfig): boolean;
38
40
  /** Clear the per-session config cache (mainly for tests). */
package/dist/config.js CHANGED
@@ -8,6 +8,7 @@ import { existsSync, readFileSync } from "node:fs";
8
8
  import { basename, join } from "node:path";
9
9
  import { parse as parseYaml } from "yaml";
10
10
  import { z } from "zod";
11
+ import { normalizeCommandMap } from "./command-utils.js";
11
12
  /** Config file precedence, highest first. The first file found wins. */
12
13
  export const CONFIG_FILE_PRECEDENCE = [
13
14
  ".opencode-dev-framework.yml",
@@ -32,7 +33,10 @@ const acceptanceCheckSchema = z.object({
32
33
  .string()
33
34
  .min(1, "acceptance check name must not be empty")
34
35
  .refine((s) => s.trim().length > 0, "acceptance check name must not be blank"),
35
- command: z.string().min(1, "acceptance check command must not be empty"),
36
+ command: z
37
+ .string()
38
+ .min(1, "acceptance check command must not be empty")
39
+ .refine((s) => s.trim().length > 0, "acceptance check command must not be blank"),
36
40
  timeout: z.number().positive("acceptance check timeout must be positive").optional(),
37
41
  });
38
42
  const acceptanceListSchema = z
@@ -343,9 +347,11 @@ export function resolveConfig(raw, configPath) {
343
347
  * A verified goal must imply deterministic evidence where none would exist
344
348
  * otherwise, so `/df-goal` refuses to delegate when the resolved
345
349
  * configuration provides no real completion check at all. A check counts
346
- * only when its step would actually run in `runGate` — a `run_*` flag with
347
- * no command behind it produces a skipped step, which is vacuous. Users
348
- * wanting a purely semantic objective use native `/goal` directly.
350
+ * only when its step would actually run — a `run_*` flag with no command
351
+ * behind it produces a skipped step, which is vacuous. The review check
352
+ * runs in the harness (`reviewMissing`), not in `runGate`, but counts all
353
+ * the same. Users wanting a purely semantic objective use native `/goal`
354
+ * directly.
349
355
  */
350
356
  export function hasMeaningfulChecks(config) {
351
357
  const gate = config.gate;
@@ -363,8 +369,13 @@ export function hasMeaningfulChecks(config) {
363
369
  return true;
364
370
  }
365
371
  if (gate.lint_changed) {
366
- const lint = config.commands.lint;
367
- if (typeof lint === "string" || (lint !== undefined && Object.keys(lint).length > 0)) {
372
+ // Same resolution as the gate's per-file lint (lint.ts): a plain string
373
+ // is the default command, a record holds default and/or per-extension
374
+ // overrides. Any configured command counts as meaningful here — the
375
+ // per-file skip (excluded path, unmatched extension) is decided at
376
+ // gate time with the file list this static check does not have.
377
+ const { default: defaultLint, byExtension } = normalizeCommandMap(config.commands.lint);
378
+ if (defaultLint !== undefined || Object.keys(byExtension).length > 0) {
368
379
  return true;
369
380
  }
370
381
  }
package/dist/gate.d.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  * hook skips.
10
10
  */
11
11
  import type { CommandResult, RunCommand } from "./host.js";
12
+ import { type LintLimiter } from "./lint.js";
12
13
  import type { ResolvedConfig } from "./types.js";
13
14
  /** Fallback per-command timeout (seconds) when `gate.timeout` is unset. */
14
15
  export declare const DEFAULT_GATE_TIMEOUT_SECONDS = 300;
@@ -48,12 +49,19 @@ export interface GateReport {
48
49
  * without a shell); an embedded token is replaced inline.
49
50
  */
50
51
  export declare function substituteFiles(template: string, files: string[]): string[];
52
+ /** Options for `runGate`. */
53
+ export interface GateOptions {
54
+ /** Project directory to run commands in. */
55
+ cwd?: string;
56
+ /** Shared limiter bounding concurrent linter subprocesses; lints run direct when absent. */
57
+ lintLimiter?: LintLimiter;
58
+ }
51
59
  /**
52
- * Run the completion gate. Steps run sequentially and all results are
60
+ * Run the completion gate. Independent steps (typecheck, test) run
61
+ * concurrently while the reported step order stays stable (typecheck, test,
62
+ * lint per file, acceptance in declaration order). All results are
53
63
  * aggregated — a failing step does not abort the remaining steps.
54
64
  */
55
- export declare function runGate(run: RunCommand, config: ResolvedConfig, changedFiles: string[], options?: {
56
- cwd?: string;
57
- }): Promise<GateReport>;
65
+ export declare function runGate(run: RunCommand, config: ResolvedConfig, changedFiles: string[], options?: GateOptions): Promise<GateReport>;
58
66
  /** One-line-per-step summary of a gate report for logging. */
59
67
  export declare function summarizeGate(report: GateReport): string;
package/dist/gate.js CHANGED
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import { isAbsolute, relative } from "node:path";
12
12
  import { splitCommand } from "./command-utils.js";
13
- import { lintFile } from "./lint.js";
13
+ import { lintFile, MAX_CONCURRENT_LINTS } 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
16
  function normalizeTrackedPath(filePath, directory) {
@@ -53,7 +53,29 @@ export function substituteFiles(template, files) {
53
53
  return splitCommand(template).flatMap((token) => token === "{files}" ? files : [token.replaceAll("{files}", files.join(" "))]);
54
54
  }
55
55
  /**
56
- * Run the completion gate. Steps run sequentially and all results are
56
+ * Map items through an async function with at most `limit` in flight.
57
+ * Output order matches input order regardless of completion order.
58
+ */
59
+ async function mapBounded(items, limit, fn) {
60
+ const results = new Array(items.length);
61
+ let next = 0;
62
+ const workers = Array.from({ length: Math.min(Math.max(limit, 1), items.length) }, async () => {
63
+ while (true) {
64
+ const index = next;
65
+ next += 1;
66
+ if (index >= items.length) {
67
+ return;
68
+ }
69
+ results[index] = await fn(items[index], index);
70
+ }
71
+ });
72
+ await Promise.all(workers);
73
+ return results;
74
+ }
75
+ /**
76
+ * Run the completion gate. Independent steps (typecheck, test) run
77
+ * concurrently while the reported step order stays stable (typecheck, test,
78
+ * lint per file, acceptance in declaration order). All results are
57
79
  * aggregated — a failing step does not abort the remaining steps.
58
80
  */
59
81
  export async function runGate(run, config, changedFiles, options) {
@@ -72,38 +94,61 @@ export async function runGate(run, config, changedFiles, options) {
72
94
  const timeout = config.gate.timeout ?? DEFAULT_GATE_TIMEOUT_SECONDS;
73
95
  const runOptions = { cwd: options?.cwd, timeout };
74
96
  const steps = [];
97
+ // Typecheck and test are independent — run them concurrently and report in
98
+ // stable order. Skipped steps assign synchronously and never enter the
99
+ // promise flow.
100
+ let typecheckStep = null;
101
+ let testStep = null;
102
+ const independent = [];
75
103
  if (config.gate.run_typecheck) {
76
104
  if (config.commands.typecheck !== undefined) {
77
105
  const command = splitCommand(config.commands.typecheck);
78
- steps.push({
79
- name: "typecheck",
80
- command,
81
- skipped: false,
82
- result: await run(command, runOptions),
83
- });
106
+ independent.push(run(command, runOptions).then((result) => {
107
+ typecheckStep = { name: "typecheck", command, skipped: false, result };
108
+ }));
84
109
  }
85
110
  else {
86
- steps.push({ name: "typecheck", skipped: true, reason: "no typecheck command configured" });
111
+ typecheckStep = {
112
+ name: "typecheck",
113
+ skipped: true,
114
+ reason: "no typecheck command configured",
115
+ };
87
116
  }
88
117
  }
89
118
  if (config.gate.run_tests) {
90
119
  const template = config.gate.scope === "changed" ? config.commands.test_changed : config.commands.test;
91
120
  if (template !== undefined) {
92
121
  const command = substituteFiles(template, changedFiles);
93
- steps.push({ name: "test", command, skipped: false, result: await run(command, runOptions) });
122
+ independent.push(run(command, runOptions).then((result) => {
123
+ testStep = { name: "test", command, skipped: false, result };
124
+ }));
94
125
  }
95
126
  else {
96
127
  const reason = config.gate.scope === "changed"
97
128
  ? "no test_changed command configured"
98
129
  : "no test command configured";
99
- steps.push({ name: "test", skipped: true, reason });
130
+ testStep = { name: "test", skipped: true, reason };
100
131
  }
101
132
  }
133
+ await Promise.all(independent);
134
+ if (typecheckStep !== null) {
135
+ steps.push(typecheckStep);
136
+ }
137
+ if (testStep !== null) {
138
+ steps.push(testStep);
139
+ }
102
140
  if (config.gate.lint_changed) {
103
- for (const file of changedFiles) {
104
- const outcome = await lintFile(run, config, file, runOptions);
141
+ // Per-file lints are independent — bound concurrency instead of running
142
+ // them one at a time. When the session limiter is provided it also
143
+ // applies, so gate bursts share headroom with per-edit lints.
144
+ const limiter = options?.lintLimiter;
145
+ const runOne = (file) => limiter !== undefined
146
+ ? limiter.run(() => lintFile(run, config, file, runOptions))
147
+ : lintFile(run, config, file, runOptions);
148
+ const outcomes = await mapBounded(changedFiles, MAX_CONCURRENT_LINTS, runOne);
149
+ for (const [index, outcome] of outcomes.entries()) {
105
150
  steps.push({
106
- name: `lint:${file}`,
151
+ name: `lint:${changedFiles[index]}`,
107
152
  command: outcome.command,
108
153
  skipped: outcome.skipped,
109
154
  reason: outcome.reason,
package/dist/goal.d.ts CHANGED
@@ -9,8 +9,10 @@
9
9
  * framework's idle gate stays the independent deterministic backstop.
10
10
  *
11
11
  * All policy here is pure (input -> data, no session I/O): `src/index.ts`
12
- * owns the `ctx.command.transform` registration, capability probing, and
13
- * delegation call. Unit tests drive these functions with a stub delegate.
12
+ * owns the `ctx.command.transform` registration, the `command.list()`
13
+ * call, and the delegation call; the shape-tolerant listing predicate
14
+ * (`isNativeGoalListed`) lives here. Unit tests drive these functions
15
+ * with a stub delegate.
14
16
  */
15
17
  import type { ResolvedConfig } from "./types.js";
16
18
  /**
package/dist/goal.js CHANGED
@@ -9,8 +9,10 @@
9
9
  * framework's idle gate stays the independent deterministic backstop.
10
10
  *
11
11
  * All policy here is pure (input -> data, no session I/O): `src/index.ts`
12
- * owns the `ctx.command.transform` registration, capability probing, and
13
- * delegation call. Unit tests drive these functions with a stub delegate.
12
+ * owns the `ctx.command.transform` registration, the `command.list()`
13
+ * call, and the delegation call; the shape-tolerant listing predicate
14
+ * (`isNativeGoalListed`) lives here. Unit tests drive these functions
15
+ * with a stub delegate.
14
16
  */
15
17
  import { hasMeaningfulChecks } from "./config.js";
16
18
  /**
package/dist/harness.d.ts CHANGED
@@ -16,15 +16,24 @@
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
+ import type { LintLimiter } from "./lint.js";
22
23
  import type { LogFn } from "./logger.js";
23
24
  import type { ResolvedConfig } from "./types.js";
24
25
  /** Project-relative path of the peer-review artifact the agent must produce. */
25
26
  export declare const REVIEW_ARTIFACT_REL = ".opencode/opencode-dev-framework/review.md";
26
27
  /** Project-relative path of the pre-flight artifact the agent must produce. */
27
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;
28
37
  export type ArtifactState = "missing" | "empty" | "present";
29
38
  /**
30
39
  * Inspect an artifact file: present (non-trivial content), empty, or missing.
@@ -78,13 +87,22 @@ export interface CompletionDeps {
78
87
  sessionID: string;
79
88
  tracker: ChangedFileTracker;
80
89
  blockCounts: BlockStore;
90
+ /** Last-blocked-evaluation snapshots for no-progress early stand-down. */
91
+ stuckSnapshots: StuckSnapshotStore;
81
92
  log: LogFn;
93
+ /** Shared limiter bounding concurrent linter subprocesses. */
94
+ lintLimiter?: LintLimiter;
95
+ /** Session pass cache; skips redundant gate suites across idle boundaries. */
96
+ passCache?: PassCache;
82
97
  }
83
98
  /**
84
- * Side-effect-free inputs for a completion inspection. The tracker file
85
- * list is a read-only snapshot: inspection never clears it, never touches
86
- * block counts, and never admits input — those are policy decisions owned
87
- * by `evaluateCompletion`.
99
+ * Side-effect-free inputs for a completion inspection, with one deliberate
100
+ * exception: the session pass-cache write-through (`passCache.key/summary`
101
+ * store on clean runs, clear on failures) when the caller opts in by
102
+ * passing `passCache`. The tracker file list is a read-only snapshot:
103
+ * inspection never clears it, never touches block counts, never logs, and
104
+ * never admits input — those are policy decisions owned by
105
+ * `evaluateCompletion`.
88
106
  */
89
107
  export interface InspectionDeps {
90
108
  run: RunCommand;
@@ -92,7 +110,30 @@ export interface InspectionDeps {
92
110
  directory: string;
93
111
  /** Read-only snapshot of tracker files; never mutated. */
94
112
  trackerFiles: string[];
113
+ /** Shared limiter bounding concurrent linter subprocesses. */
114
+ lintLimiter?: LintLimiter;
115
+ /**
116
+ * Pass cache owned by the session state. When set and the working tree
117
+ * still matches the last clean pass (same files, same mtimes/sizes,
118
+ * same gate-relevant config, review artifact untouched — modulo the
119
+ * mtime/size same-tick rewrite window), inspection returns the cached
120
+ * pass without spawning any gate command. Any content change, config
121
+ * change, or review removal misses the cache and re-runs. Only
122
+ * genuinely clean passes are stored — advisory problems and failures
123
+ * never are, so loud reporting is preserved.
124
+ */
125
+ passCache?: PassCache;
126
+ }
127
+ /**
128
+ * Fingerprint of the last clean pass. `key` is null when nothing is cached;
129
+ * a non-null key with its summary replays the pass verbatim.
130
+ */
131
+ export interface PassCache {
132
+ key: string | null;
133
+ summary: string | null;
95
134
  }
135
+ /** Create an empty pass cache (one per session state). */
136
+ export declare function createPassCache(): PassCache;
96
137
  /**
97
138
  * Raw completion report. `ok` is the unadjudicated outcome (gate passed and
98
139
  * review satisfied); profiles, block counting, and stand-down are applied by
@@ -113,10 +154,11 @@ export interface CompletionInspection {
113
154
  summary: string;
114
155
  }
115
156
  /**
116
- * Inspect the current completion state without mutating anything: no
117
- * tracker clearing, no block-count changes, no logging, no input admitted.
118
- * Both the idle policy (`evaluateCompletion`) and manual verification
119
- * (`verifyGate`) read from here so they evaluate the same full contract.
157
+ * Inspect the current completion state without mutating anything except the
158
+ * opted-in session pass-cache write-through: no tracker clearing, no
159
+ * block-count changes, no logging, no input admitted. Both the idle policy
160
+ * (`evaluateCompletion`) and manual verification (`verifyGate`) read from
161
+ * here so they evaluate the same full contract.
120
162
  */
121
163
  export declare function inspectCompletion(deps: InspectionDeps): Promise<CompletionInspection>;
122
164
  /**
package/dist/harness.js CHANGED
@@ -16,13 +16,21 @@
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 { readFile } from "node:fs/promises";
19
+ import { readFile, stat } from "node:fs/promises";
20
20
  import { join } from "node:path";
21
21
  import { runGate, summarizeGate } from "./gate.js";
22
22
  /** Project-relative path of the peer-review artifact the agent must produce. */
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.
@@ -122,11 +130,53 @@ function reviewMissingMessage(changedFiles) {
122
130
  `review findings and their resolution to ${REVIEW_ARTIFACT_REL}.\n\n` +
123
131
  `Investigation-only reviewers: do not ask them to edit product code.`);
124
132
  }
133
+ /** Create an empty pass cache (one per session state). */
134
+ export function createPassCache() {
135
+ return { key: null, summary: null };
136
+ }
137
+ /**
138
+ * Fingerprint the current tree state for cache comparison. Returns null
139
+ * when any input is unreadable — an unreadable file can never prove the
140
+ * tree unchanged, so null forces a re-run (the safe direction). Covers
141
+ * every live input to `runGate` (commands, gate options, `exclude`) plus
142
+ * the review artifact, so any behavior-changing config edit misses.
143
+ */
144
+ async function passCacheKey(config, directory, changedFiles, reviewRequired) {
145
+ const gateConfig = JSON.stringify({
146
+ commands: config.commands,
147
+ gate: config.gate,
148
+ exclude: config.exclude,
149
+ });
150
+ const parts = [];
151
+ for (const file of [...changedFiles].sort()) {
152
+ try {
153
+ const s = await stat(join(directory, file));
154
+ parts.push(`${file}:${s.mtimeMs}:${s.size}`);
155
+ }
156
+ catch {
157
+ return null;
158
+ }
159
+ }
160
+ let review = "not-required";
161
+ if (reviewRequired) {
162
+ try {
163
+ const s = await stat(join(directory, REVIEW_ARTIFACT_REL));
164
+ review = `${s.mtimeMs}:${s.size}`;
165
+ }
166
+ catch {
167
+ // Review was required at pass time but is now unreadable: the
168
+ // requirement may have become unmet, so force a re-run.
169
+ return null;
170
+ }
171
+ }
172
+ return `${gateConfig}\n${parts.join("\n")}\nreview:${review}`;
173
+ }
125
174
  /**
126
- * Inspect the current completion state without mutating anything: no
127
- * tracker clearing, no block-count changes, no logging, no input admitted.
128
- * Both the idle policy (`evaluateCompletion`) and manual verification
129
- * (`verifyGate`) read from here so they evaluate the same full contract.
175
+ * Inspect the current completion state without mutating anything except the
176
+ * opted-in session pass-cache write-through: no tracker clearing, no
177
+ * block-count changes, no logging, no input admitted. Both the idle policy
178
+ * (`evaluateCompletion`) and manual verification (`verifyGate`) read from
179
+ * here so they evaluate the same full contract.
130
180
  */
131
181
  export async function inspectCompletion(deps) {
132
182
  const { run, config, directory, trackerFiles } = deps;
@@ -160,9 +210,43 @@ export async function inspectCompletion(deps) {
160
210
  summary: "completion gate skipped: no changed files",
161
211
  };
162
212
  }
163
- const report = await runGate(run, config, changedFiles, { cwd: directory });
164
- const gateFailed = report.ran && !report.ok;
165
213
  const reviewRequired = config.gate.require_review && changedFiles.length > 0;
214
+ // Fingerprint the tree the gate is about to validate, once. A hit replays
215
+ // the cached pass; a clean run stores this same pre-run key. Storing the
216
+ // pre-run (not post-run) state matters: an edit landing mid-gate-run
217
+ // changes the stats, so the next idle misses and gates the edit instead
218
+ // of replaying a pass over content the gate never saw.
219
+ const fingerprint = deps.passCache !== undefined
220
+ ? await passCacheKey(config, directory, changedFiles, reviewRequired)
221
+ : null;
222
+ // Fast path: the tree still matches the last clean pass — replay it
223
+ // without spawning gate commands. The key covers file identity, content
224
+ // freshness (mtime+size), gate-relevant config, and the review artifact,
225
+ // so any real change misses and re-runs.
226
+ const cachedKey = deps.passCache?.key;
227
+ const cachedSummary = deps.passCache?.summary;
228
+ if (cachedKey !== undefined &&
229
+ cachedKey !== null &&
230
+ cachedSummary !== undefined &&
231
+ cachedSummary !== null) {
232
+ if (fingerprint !== null && fingerprint === cachedKey) {
233
+ return {
234
+ changedFiles,
235
+ report: { ran: true, steps: [], ok: true, failedSteps: [] },
236
+ reviewRequired,
237
+ reviewState: "present",
238
+ reviewMissing: false,
239
+ skipped: false,
240
+ ok: true,
241
+ summary: cachedSummary,
242
+ };
243
+ }
244
+ }
245
+ const report = await runGate(run, config, changedFiles, {
246
+ cwd: directory,
247
+ lintLimiter: deps.lintLimiter,
248
+ });
249
+ const gateFailed = report.ran && !report.ok;
166
250
  const reviewState = reviewRequired
167
251
  ? await artifactState(directory, REVIEW_ARTIFACT_REL)
168
252
  : "present";
@@ -175,6 +259,20 @@ export async function inspectCompletion(deps) {
175
259
  : report.ran
176
260
  ? `completion gate passed\n${summarizeGate(report)}`
177
261
  : `completion gate passed (${report.reason ?? "nothing to run"})`;
262
+ if (deps.passCache !== undefined) {
263
+ if (!gateFailed && !reviewMissing && report.ran && fingerprint !== null) {
264
+ // Genuinely clean pass that actually ran — store the pre-run
265
+ // fingerprint for the next idle. Advisory problems (gateFailed) and
266
+ // missing reviews never store; vacuous passes (nothing ran) neither
267
+ // store nor clear.
268
+ deps.passCache.key = fingerprint;
269
+ deps.passCache.summary = summary;
270
+ }
271
+ else if (gateFailed || reviewMissing) {
272
+ deps.passCache.key = null;
273
+ deps.passCache.summary = null;
274
+ }
275
+ }
178
276
  return {
179
277
  changedFiles,
180
278
  report,
@@ -193,7 +291,7 @@ export async function inspectCompletion(deps) {
193
291
  * block count applies to either lever.
194
292
  */
195
293
  export async function evaluateCompletion(deps) {
196
- const { run, config, directory, sessionID, tracker, blockCounts } = deps;
294
+ const { run, config, directory, sessionID, tracker, blockCounts, stuckSnapshots } = deps;
197
295
  if (config.profile === "off" || !config.gate) {
198
296
  return { decision: "pass", changedFiles: [] };
199
297
  }
@@ -202,6 +300,8 @@ export async function evaluateCompletion(deps) {
202
300
  config,
203
301
  directory,
204
302
  trackerFiles: tracker.getChangedFiles(),
303
+ lintLimiter: deps.lintLimiter,
304
+ passCache: deps.passCache,
205
305
  });
206
306
  const { changedFiles, report } = inspection;
207
307
  const gateFailed = report.ran && !report.ok;
@@ -209,6 +309,7 @@ export async function evaluateCompletion(deps) {
209
309
  if (!gateFailed && !reviewMissing) {
210
310
  tracker.clearChangedFiles();
211
311
  await blockCounts.clear(sessionID);
312
+ await stuckSnapshots.clear(sessionID);
212
313
  return {
213
314
  decision: "pass",
214
315
  changedFiles,
@@ -230,10 +331,41 @@ export async function evaluateCompletion(deps) {
230
331
  const reason = gateFailed ? "gate" : "review";
231
332
  const summary = inspection.summary;
232
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 });
233
364
  const blockCount = await blockCounts.increment(sessionID);
234
365
  if (blockCount > maxBlocks) {
235
366
  tracker.clearChangedFiles();
236
367
  await blockCounts.clear(sessionID);
368
+ await stuckSnapshots.clear(sessionID);
237
369
  const standdownSummary = `opencode-dev-framework completion gate has blocked ${maxBlocks} times and is standing ` +
238
370
  `down to avoid trapping you. The requirement is STILL unmet:\n\n${summary}\n\n` +
239
371
  `Do not claim the work is complete. Tell the user plainly what remains unmet and why.`;
package/dist/index.d.ts CHANGED
@@ -21,9 +21,11 @@
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
+ import { type PassCache } from "./harness.js";
26
27
  import { type RunCommand } from "./host.js";
28
+ import { type LintLimiter } from "./lint.js";
27
29
  import { type LogFn } from "./logger.js";
28
30
  import type { ResolvedConfig } from "./types.js";
29
31
  export interface HookState {
@@ -44,8 +46,26 @@ export interface HookState {
44
46
  * store keeps live on every get/increment/clear.
45
47
  */
46
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;
47
55
  precommitAvailable?: boolean;
48
56
  configMtime?: number;
57
+ /**
58
+ * Shared FIFO limiter bounding concurrent linter subprocesses across
59
+ * per-edit lints and gate lint steps.
60
+ */
61
+ lintLimiter: LintLimiter;
62
+ /** Fingerprint of the last clean gate pass; skips redundant suites. */
63
+ passCache: PassCache;
64
+ /**
65
+ * `Date.now()` of the last config-mtime check. Hook fires are far more
66
+ * frequent than config edits, so mtime stats are throttled to a 1s window.
67
+ */
68
+ lastConfigCheck: number;
49
69
  /**
50
70
  * Which lever completed a gate evaluation most recently in this process:
51
71
  * `"idle"` once the `experimental.idle` hook has (same-execution