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/dist/index.js CHANGED
@@ -23,23 +23,36 @@
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
- import { artifactState, evaluateCompletion, PREFLIGHT_ARTIFACT_REL, preflightBlockReason, } from "./harness.js";
29
+ import { artifactState, createPassCache, evaluateCompletion, PREFLIGHT_ARTIFACT_REL, preflightBlockReason, } from "./harness.js";
30
30
  import { runCommand } from "./host.js";
31
- import { lintFile, detectPreCommitAvailability, isLintFailure, summarizeLint } from "./lint.js";
31
+ import { createLintLimiter, detectPreCommitAvailability, isLintFailure, lintFile, summarizeLint, } from "./lint.js";
32
32
  import { createLogger } from "./logger.js";
33
33
  import { checkToolCall, extractFilePath, FILE_TOOLS, toPermissionGuard } from "./protect.js";
34
- import { loadConstitution } from "./rules.js";
34
+ import { constitutionPresent, loadConstitution } from "./rules.js";
35
35
  import { writeRuntimeStatus } from "./runtime-status.js";
36
36
  let activeState = null;
37
37
  let fallbackLog = async () => { };
38
+ /**
39
+ * Minimum interval between config-mtime checks. Every hook fire calls
40
+ * `reloadConfigIfChanged`, but the config file almost never changes
41
+ * mid-session, so a 1s staleness window is invisible.
42
+ */
43
+ const CONFIG_RELOAD_MIN_INTERVAL_MS = 1000;
38
44
  function safeLog(state, level, message, extra) {
39
45
  const fn = state && typeof state.log === "function" ? state.log : fallbackLog;
40
46
  return fn(level, message, extra);
41
47
  }
42
48
  async function reloadConfigIfChanged(state) {
49
+ // Throttle mtime checks: every hook fire calls this, but the config file
50
+ // almost never changes mid-session. A 1s staleness window is invisible.
51
+ const now = Date.now();
52
+ if (now - state.lastConfigCheck < CONFIG_RELOAD_MIN_INTERVAL_MS) {
53
+ return;
54
+ }
55
+ state.lastConfigCheck = now;
43
56
  const primary = join(state.directory, ".opencode-dev-framework.yml");
44
57
  const fallback = join(state.directory, ".dev-framework.yml");
45
58
  // check both names; stat whichever exists
@@ -117,11 +130,11 @@ async function runPerEditLint(state, filePath) {
117
130
  if (state.config.precommit === "auto" && state.precommitAvailable === undefined) {
118
131
  state.precommitAvailable = await detectPreCommitAvailability(state.run, state.directory);
119
132
  }
120
- const outcome = await lintFile(state.run, state.config, filePath, {
133
+ const outcome = await state.lintLimiter.run(() => lintFile(state.run, state.config, filePath, {
121
134
  cwd: state.directory,
122
135
  timeout: state.config.gate?.timeout,
123
136
  precommitAvailable: state.precommitAvailable,
124
- });
137
+ }));
125
138
  if (outcome.skipped) {
126
139
  await safeLog(state, "debug", summarizeLint(outcome), {
127
140
  filePath,
@@ -149,6 +162,9 @@ function runCompletion(state, sessionID) {
149
162
  sessionID,
150
163
  tracker: state.tracker,
151
164
  blockCounts: state.blocks,
165
+ stuckSnapshots: state.stuckSnapshots,
166
+ lintLimiter: state.lintLimiter,
167
+ passCache: state.passCache,
152
168
  log: (level, message, extra) => safeLog(state, level, message, extra),
153
169
  });
154
170
  }
@@ -259,6 +275,7 @@ const plugin = Plugin.define({
259
275
  const tracker = createChangedFileTracker();
260
276
  const blockCounts = new Map();
261
277
  const blocks = createBlockStore(ctx.storage, blockCounts);
278
+ const stuckSnapshots = createStuckSnapshotStore(ctx.storage);
262
279
  const state = {
263
280
  directory,
264
281
  config,
@@ -268,7 +285,11 @@ const plugin = Plugin.define({
268
285
  constitution,
269
286
  blockCounts,
270
287
  blocks,
288
+ stuckSnapshots,
271
289
  configMtime,
290
+ lintLimiter: createLintLimiter(),
291
+ passCache: createPassCache(),
292
+ lastConfigCheck: 0,
272
293
  lastIdleHandled: new Map(),
273
294
  };
274
295
  activeState = state;
@@ -276,7 +297,7 @@ const plugin = Plugin.define({
276
297
  // With the stop-level hydration gone there is no setup-time storage
277
298
  // read left, so this rarely fires here — the store still degrades
278
299
  // lazily on first use and reports via isDegraded().
279
- if (blocks.isDegraded()) {
300
+ if (blocks.isDegraded() || stuckSnapshots.isDegraded()) {
280
301
  await log("warn", "ctx.storage is unavailable; gate block counts are in-memory only and reset on reload", { directory });
281
302
  }
282
303
  const registrations = [];
@@ -307,7 +328,7 @@ const plugin = Plugin.define({
307
328
  if (!constitution)
308
329
  return;
309
330
  // V2 system is Array<SystemPart> {type:"text", text:string}
310
- const already = event.system.some((part) => part.text.includes(constitution));
331
+ const already = constitutionPresent(event.system, constitution);
311
332
  if (already)
312
333
  return;
313
334
  event.system.push({
@@ -328,7 +349,7 @@ const plugin = Plugin.define({
328
349
  // generate/compaction/title also have system — inject similarly if present
329
350
  if (!event.system)
330
351
  return;
331
- const already = event.system.some((p) => p.text.includes(constitution));
352
+ const already = constitutionPresent(event.system, constitution);
332
353
  if (!already)
333
354
  event.system.push({ type: "text", text: constitution });
334
355
  }));
@@ -754,8 +775,10 @@ const plugin = Plugin.define({
754
775
  name: "df-goal",
755
776
  description: "Start a verified native goal: appends a dev_framework_verify contract to the objective and delegates to native /goal exactly once. Requires native /goal, a blocking profile, and at least one configured completion check.",
756
777
  execute: async (invocation) => {
757
- if (activeState !== state)
758
- return;
778
+ if (activeState !== state) {
779
+ throw new Error("Cannot start a verified goal: the plugin session state changed " +
780
+ "(teardown or reload raced the command); retry /df-goal.");
781
+ }
759
782
  await reloadConfigIfChanged(state);
760
783
  const { extractObjectiveText, isNativeGoalListed, runGoalCommand } = await import("./goal.js");
761
784
  let nativeGoalAvailable = false;
@@ -765,7 +788,18 @@ const plugin = Plugin.define({
765
788
  catch {
766
789
  nativeGoalAvailable = false;
767
790
  }
791
+ // Flat core protocol shape
792
+ // (packages/protocol/src/groups/session.ts `session.command`:
793
+ // `{ sessionID, name: string, text, ... }`). The installed
794
+ // client types agree (indexed-access rendering resolves to
795
+ // flat `name: string`) and core source is truth (Phase 0
796
+ // spike receipt) — keep this cast flat.
768
797
  const sessionCommand = ctx.session.command;
798
+ if (typeof sessionCommand !== "function") {
799
+ throw new Error("Cannot start a verified goal: session.command is not available on this " +
800
+ "core. Upgrade OpenCode to a build containing native /goal, or run the " +
801
+ "objective without verification where native /goal exists.");
802
+ }
769
803
  const result = await runGoalCommand({
770
804
  config: state.config,
771
805
  objective: extractObjectiveText(invocation.prompt),
@@ -802,11 +836,12 @@ const plugin = Plugin.define({
802
836
  const event = rawEvent;
803
837
  const type = event.type;
804
838
  if (isSessionDeletedEvent(type)) {
805
- // session.deleted: cleanup block counts (memory + storage) and
806
- // 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.
807
841
  const sid = getEventSessionID(event);
808
842
  if (sid) {
809
843
  await state.blocks.clear(sid);
844
+ await state.stuckSnapshots.clear(sid);
810
845
  state.lastIdleHandled.delete(sid);
811
846
  }
812
847
  continue;
package/dist/lint.d.ts CHANGED
@@ -7,6 +7,19 @@ import type { CommandResult, RunCommand } from "./host.js";
7
7
  import type { ResolvedConfig } from "./types.js";
8
8
  /** Fallback per-lint timeout (seconds) when the config sets none. */
9
9
  export declare const DEFAULT_LINT_TIMEOUT_SECONDS = 60;
10
+ /** Cap on concurrent linter subprocesses; per-edit and gate lints share one limiter per session. */
11
+ export declare const MAX_CONCURRENT_LINTS = 4;
12
+ /** FIFO semaphore bounding concurrent linter subprocesses, shared per session. */
13
+ export interface LintLimiter {
14
+ run<T>(fn: () => Promise<T>): Promise<T>;
15
+ }
16
+ /**
17
+ * Create a FIFO semaphore bounding concurrent linter subprocesses. Queued
18
+ * callers wait their turn — lint output is delayed under burst load, never
19
+ * dropped. Release is in `finally`, so a throwing linter cannot wedge the
20
+ * limiter. Non-positive limits clamp to 1 (serial) instead of deadlocking.
21
+ */
22
+ export declare function createLintLimiter(limit?: number): LintLimiter;
10
23
  export interface LintOutcome {
11
24
  /** True when no linter ran (file excluded or no command configured). */
12
25
  skipped: boolean;
@@ -20,7 +33,8 @@ export interface LintOutcome {
20
33
  /**
21
34
  * Match a file path against the config `exclude` globs. Returns the matching
22
35
  * pattern, or undefined. Patterns without a slash also match basenames at
23
- * any depth, mirroring protected-path semantics.
36
+ * any depth, mirroring protected-path semantics. Matchers are compiled once
37
+ * per config via the shared `compileGlobMatchers` cache.
24
38
  */
25
39
  export declare function matchExclude(config: ResolvedConfig, filePath: string, directory?: string): string | undefined;
26
40
  /**
package/dist/lint.js CHANGED
@@ -4,14 +4,47 @@
4
4
  * hook wiring lives in src/index.ts.
5
5
  */
6
6
  import { basename, dirname, extname, isAbsolute, relative } from "node:path";
7
- import picomatch from "picomatch";
8
- import { normalizeCommandMap, splitCommand } from "./command-utils.js";
7
+ import { compileGlobMatchers, normalizeCommandMap, splitCommand } from "./command-utils.js";
9
8
  /** Fallback per-lint timeout (seconds) when the config sets none. */
10
9
  export const DEFAULT_LINT_TIMEOUT_SECONDS = 60;
10
+ /** Cap on concurrent linter subprocesses; per-edit and gate lints share one limiter per session. */
11
+ export const MAX_CONCURRENT_LINTS = 4;
12
+ /**
13
+ * Create a FIFO semaphore bounding concurrent linter subprocesses. Queued
14
+ * callers wait their turn — lint output is delayed under burst load, never
15
+ * dropped. Release is in `finally`, so a throwing linter cannot wedge the
16
+ * limiter. Non-positive limits clamp to 1 (serial) instead of deadlocking.
17
+ */
18
+ export function createLintLimiter(limit = MAX_CONCURRENT_LINTS) {
19
+ const capacity = Math.max(1, Math.floor(limit));
20
+ let active = 0;
21
+ const queue = [];
22
+ return {
23
+ async run(fn) {
24
+ if (active >= capacity) {
25
+ await new Promise((resolve) => {
26
+ queue.push(resolve);
27
+ });
28
+ }
29
+ active += 1;
30
+ try {
31
+ return await fn();
32
+ }
33
+ finally {
34
+ active -= 1;
35
+ const next = queue.shift();
36
+ if (next !== undefined) {
37
+ next();
38
+ }
39
+ }
40
+ },
41
+ };
42
+ }
11
43
  /**
12
44
  * Match a file path against the config `exclude` globs. Returns the matching
13
45
  * pattern, or undefined. Patterns without a slash also match basenames at
14
- * any depth, mirroring protected-path semantics.
46
+ * any depth, mirroring protected-path semantics. Matchers are compiled once
47
+ * per config via the shared `compileGlobMatchers` cache.
15
48
  */
16
49
  export function matchExclude(config, filePath, directory) {
17
50
  let candidate = filePath;
@@ -20,12 +53,11 @@ export function matchExclude(config, filePath, directory) {
20
53
  }
21
54
  candidate = candidate.replace(/^\.\//, "");
22
55
  const name = basename(candidate);
23
- for (const pattern of config.exclude) {
24
- const isMatch = picomatch(pattern, { dot: true });
25
- if (isMatch(candidate)) {
56
+ for (const { pattern, match } of compileGlobMatchers(config.exclude)) {
57
+ if (match(candidate)) {
26
58
  return pattern;
27
59
  }
28
- if (!pattern.includes("/") && isMatch(name)) {
60
+ if (!pattern.includes("/") && match(name)) {
29
61
  return pattern;
30
62
  }
31
63
  }
package/dist/protect.d.ts CHANGED
@@ -29,7 +29,8 @@ export declare function extractCommand(args: unknown): string | undefined;
29
29
  /**
30
30
  * Check a file path against the protected globs. Returns the matching
31
31
  * pattern, or undefined. Patterns without a slash also match basenames at
32
- * any depth (so `.env*` protects `config/.env.local` too).
32
+ * any depth (so `.env*` protects `config/.env.local` too). Matchers are
33
+ * compiled once per config via the shared `compileGlobMatchers` cache.
33
34
  */
34
35
  export declare function matchProtectedPath(config: ResolvedConfig, filePath: string, directory?: string): string | undefined;
35
36
  /** Check a shell command against the dangerous-command list. */
package/dist/protect.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * src/index.ts.
5
5
  */
6
6
  import { basename, isAbsolute, relative } from "node:path";
7
- import picomatch from "picomatch";
7
+ import { compileGlobMatchers } from "./command-utils.js";
8
8
  /** Tools whose args carry a target file path. */
9
9
  export const FILE_TOOLS = new Set(["edit", "write", "patch"]);
10
10
  /** Tools whose args carry a shell command. */
@@ -55,7 +55,8 @@ export function extractCommand(args) {
55
55
  /**
56
56
  * Check a file path against the protected globs. Returns the matching
57
57
  * pattern, or undefined. Patterns without a slash also match basenames at
58
- * any depth (so `.env*` protects `config/.env.local` too).
58
+ * any depth (so `.env*` protects `config/.env.local` too). Matchers are
59
+ * compiled once per config via the shared `compileGlobMatchers` cache.
59
60
  */
60
61
  export function matchProtectedPath(config, filePath, directory) {
61
62
  let candidate = filePath;
@@ -64,12 +65,11 @@ export function matchProtectedPath(config, filePath, directory) {
64
65
  }
65
66
  candidate = candidate.replace(/^\.\//, "");
66
67
  const name = basename(candidate);
67
- for (const pattern of config.protect) {
68
- const isMatch = picomatch(pattern, { dot: true });
69
- if (isMatch(candidate)) {
68
+ for (const { pattern, match } of compileGlobMatchers(config.protect)) {
69
+ if (match(candidate)) {
70
70
  return pattern;
71
71
  }
72
- if (!pattern.includes("/") && isMatch(name)) {
72
+ if (!pattern.includes("/") && match(name)) {
73
73
  return pattern;
74
74
  }
75
75
  }
package/dist/rules.d.ts CHANGED
@@ -37,6 +37,21 @@ export interface ConstitutionResult {
37
37
  * "Style Guide" heading.
38
38
  */
39
39
  export declare function loadConstitution(config: ResolvedConfig, directory?: string): Promise<ConstitutionResult>;
40
+ /**
41
+ * Length of the constitution prefix used as a fast precheck. Most model
42
+ * requests do not contain the constitution yet; scanning for a short prefix
43
+ * fails fast instead of running the full-text search over a 10–20KB needle.
44
+ */
45
+ export declare const CONSTITUTION_PREFIX_LENGTH = 128;
46
+ /**
47
+ * True when the constitution is already present in the system prompt parts.
48
+ * Semantics match the old inline check exactly (`some(part =>
49
+ * part.includes(constitution))`); the prefix precheck only skips the
50
+ * expensive full scan when the constitution is absent.
51
+ */
52
+ export declare function constitutionPresent(parts: ReadonlyArray<{
53
+ text: string;
54
+ } | string>, constitution: string): boolean;
40
55
  /**
41
56
  * Appends the constitution to the last system-prompt entry, unless it is already
42
57
  * present. This keeps the system prompt compact instead of adding a separate
package/dist/rules.js CHANGED
@@ -169,6 +169,25 @@ export async function loadConstitution(config, directory) {
169
169
  warning: warnings.length > 0 ? warnings.join("\n") : undefined,
170
170
  };
171
171
  }
172
+ /**
173
+ * Length of the constitution prefix used as a fast precheck. Most model
174
+ * requests do not contain the constitution yet; scanning for a short prefix
175
+ * fails fast instead of running the full-text search over a 10–20KB needle.
176
+ */
177
+ export const CONSTITUTION_PREFIX_LENGTH = 128;
178
+ /**
179
+ * True when the constitution is already present in the system prompt parts.
180
+ * Semantics match the old inline check exactly (`some(part =>
181
+ * part.includes(constitution))`); the prefix precheck only skips the
182
+ * expensive full scan when the constitution is absent.
183
+ */
184
+ export function constitutionPresent(parts, constitution) {
185
+ const prefix = constitution.slice(0, CONSTITUTION_PREFIX_LENGTH);
186
+ return parts.some((part) => {
187
+ const text = typeof part === "string" ? part : part.text;
188
+ return text.includes(prefix) && text.includes(constitution);
189
+ });
190
+ }
172
191
  /**
173
192
  * Appends the constitution to the last system-prompt entry, unless it is already
174
193
  * present. This keeps the system prompt compact instead of adding a separate
@@ -178,7 +197,7 @@ export function injectConstitution(system, constitution) {
178
197
  if (constitution === null) {
179
198
  return system;
180
199
  }
181
- if (system.some((entry) => entry.includes(constitution))) {
200
+ if (constitutionPresent(system, constitution)) {
182
201
  return system;
183
202
  }
184
203
  if (system.length === 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-dev-framework",
3
- "version": "1.0.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",
@@ -50,6 +50,15 @@ does. Use judgment, but never skip the test-grounding and review steps for behav
50
50
  changes. If the specialist agents are not installed in this project, perform the same
51
51
  checks yourself with the skills in this section.
52
52
 
53
+ ## Execute plans under `/df-goal`
54
+
55
+ When the task starts from a written plan (yours or the user's), execute it as
56
+ `/df-goal <objective>` — the objective is the plan inline when short, or
57
+ `Implement the plan in <path>` when long — so native completion requires the
58
+ framework gate's PASS, not just your summary. A `dev_framework_verify` FAIL is
59
+ a verdict: fix the underlying cause and re-verify, never declare the plan met
60
+ without a tool-result PASS in the transcript.
61
+
53
62
  ## Skills
54
63
 
55
64
  For explicit, repeatable workflows you can invoke the bundled skills: