opencode-dev-framework 0.5.1 → 1.1.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
@@ -10,6 +10,8 @@
10
10
  * (`filesystem.changed` stays as a fallback this release; see Phase 24)
11
11
  * - ctx.event.subscribe() -> file tracking + gate enforcement via re-prompt
12
12
  * - ctx.tool.transform(...) -> custom tools
13
+ * - ctx.command.transform(...) -> server-side `/df-goal` verified-goal
14
+ * wrapper (thin adapter delegating to native `/goal`; see src/goal.ts)
13
15
  *
14
16
  * Gate enforcement: no synchronous pre-stop veto. On `experimental.idle`
15
17
  * (same execution) we run the gate and if it fails inside budget we admit
@@ -24,20 +26,33 @@ import { join } from "node:path";
24
26
  import { createBlockStore } from "./block-store.js";
25
27
  import { clearConfigCache, loadConfig } from "./config.js";
26
28
  import { createChangedFileTracker } from "./gate.js";
27
- import { artifactState, evaluateCompletion, PREFLIGHT_ARTIFACT_REL, preflightBlockReason, } from "./harness.js";
29
+ import { artifactState, createPassCache, evaluateCompletion, PREFLIGHT_ARTIFACT_REL, preflightBlockReason, } from "./harness.js";
28
30
  import { runCommand } from "./host.js";
29
- import { lintFile, detectPreCommitAvailability, isLintFailure, summarizeLint } from "./lint.js";
31
+ import { createLintLimiter, detectPreCommitAvailability, isLintFailure, lintFile, summarizeLint, } from "./lint.js";
30
32
  import { createLogger } from "./logger.js";
31
33
  import { checkToolCall, extractFilePath, FILE_TOOLS, toPermissionGuard } from "./protect.js";
32
- import { loadConstitution } from "./rules.js";
34
+ import { constitutionPresent, loadConstitution } from "./rules.js";
33
35
  import { writeRuntimeStatus } from "./runtime-status.js";
34
36
  let activeState = null;
35
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;
36
44
  function safeLog(state, level, message, extra) {
37
45
  const fn = state && typeof state.log === "function" ? state.log : fallbackLog;
38
46
  return fn(level, message, extra);
39
47
  }
40
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;
41
56
  const primary = join(state.directory, ".opencode-dev-framework.yml");
42
57
  const fallback = join(state.directory, ".dev-framework.yml");
43
58
  // check both names; stat whichever exists
@@ -115,11 +130,11 @@ async function runPerEditLint(state, filePath) {
115
130
  if (state.config.precommit === "auto" && state.precommitAvailable === undefined) {
116
131
  state.precommitAvailable = await detectPreCommitAvailability(state.run, state.directory);
117
132
  }
118
- const outcome = await lintFile(state.run, state.config, filePath, {
133
+ const outcome = await state.lintLimiter.run(() => lintFile(state.run, state.config, filePath, {
119
134
  cwd: state.directory,
120
135
  timeout: state.config.gate?.timeout,
121
136
  precommitAvailable: state.precommitAvailable,
122
- });
137
+ }));
123
138
  if (outcome.skipped) {
124
139
  await safeLog(state, "debug", summarizeLint(outcome), {
125
140
  filePath,
@@ -147,6 +162,8 @@ function runCompletion(state, sessionID) {
147
162
  sessionID,
148
163
  tracker: state.tracker,
149
164
  blockCounts: state.blocks,
165
+ lintLimiter: state.lintLimiter,
166
+ passCache: state.passCache,
150
167
  log: (level, message, extra) => safeLog(state, level, message, extra),
151
168
  });
152
169
  }
@@ -267,6 +284,9 @@ const plugin = Plugin.define({
267
284
  blockCounts,
268
285
  blocks,
269
286
  configMtime,
287
+ lintLimiter: createLintLimiter(),
288
+ passCache: createPassCache(),
289
+ lastConfigCheck: 0,
270
290
  lastIdleHandled: new Map(),
271
291
  };
272
292
  activeState = state;
@@ -305,7 +325,7 @@ const plugin = Plugin.define({
305
325
  if (!constitution)
306
326
  return;
307
327
  // V2 system is Array<SystemPart> {type:"text", text:string}
308
- const already = event.system.some((part) => part.text.includes(constitution));
328
+ const already = constitutionPresent(event.system, constitution);
309
329
  if (already)
310
330
  return;
311
331
  event.system.push({
@@ -326,7 +346,7 @@ const plugin = Plugin.define({
326
346
  // generate/compaction/title also have system — inject similarly if present
327
347
  if (!event.system)
328
348
  return;
329
- const already = event.system.some((p) => p.text.includes(constitution));
349
+ const already = constitutionPresent(event.system, constitution);
330
350
  if (!already)
331
351
  event.system.push({ type: "text", text: constitution });
332
352
  }));
@@ -685,7 +705,7 @@ const plugin = Plugin.define({
685
705
  });
686
706
  editor.add({
687
707
  name: "dev_framework_verify",
688
- description: "Run the opencode-dev-framework completion gate now (typecheck, tests, changed-file lint) and return the summary. Use for a mid-session gate check without waiting for session idle; unlike the idle gate this never re-prompts, it only reports.",
708
+ description: "Run the full opencode-dev-framework completion contract now (typecheck, tests, changed-file lint, peer-review state) and return the summary. The first line is DEV_FRAMEWORK_VERDICT: PASS or FAIL, reporting the raw inspection outcome. Use for a mid-session gate check without waiting for session idle; unlike the idle gate this never re-prompts, it only reports, and it never mutates retry state.",
689
709
  input: {
690
710
  type: "object",
691
711
  properties: {
@@ -738,6 +758,64 @@ const plugin = Plugin.define({
738
758
  },
739
759
  });
740
760
  }));
761
+ // 3b) Verified-goal wrapper — server-side `/df-goal` through
762
+ // `ctx.command.transform` (see src/goal.ts for the pure policy). Thin
763
+ // adapter around native `/goal`: probes native capability, checks
764
+ // availability/profile/meaningful-checks, appends the verification
765
+ // addendum verbatim, and delegates exactly once via the flat core
766
+ // `session.command` shape. Defensive like the permission hook: on a
767
+ // core without the command API the wrapper is skipped with a warning
768
+ // and every other layer keeps working.
769
+ try {
770
+ trackRegistration(await ctx.command.transform((editor) => {
771
+ editor.add({
772
+ name: "df-goal",
773
+ 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.",
774
+ execute: async (invocation) => {
775
+ if (activeState !== state) {
776
+ throw new Error("Cannot start a verified goal: the plugin session state changed " +
777
+ "(teardown or reload raced the command); retry /df-goal.");
778
+ }
779
+ await reloadConfigIfChanged(state);
780
+ const { extractObjectiveText, isNativeGoalListed, runGoalCommand } = await import("./goal.js");
781
+ let nativeGoalAvailable = false;
782
+ try {
783
+ nativeGoalAvailable = isNativeGoalListed(await ctx.command.list());
784
+ }
785
+ catch {
786
+ nativeGoalAvailable = false;
787
+ }
788
+ // Flat core protocol shape
789
+ // (packages/protocol/src/groups/session.ts `session.command`:
790
+ // `{ sessionID, name: string, text, ... }`). The installed
791
+ // client types agree (indexed-access rendering resolves to
792
+ // flat `name: string`) and core source is truth (Phase 0
793
+ // spike receipt) — keep this cast flat.
794
+ const sessionCommand = ctx.session.command;
795
+ if (typeof sessionCommand !== "function") {
796
+ throw new Error("Cannot start a verified goal: session.command is not available on this " +
797
+ "core. Upgrade OpenCode to a build containing native /goal, or run the " +
798
+ "objective without verification where native /goal exists.");
799
+ }
800
+ const result = await runGoalCommand({
801
+ config: state.config,
802
+ objective: extractObjectiveText(invocation.prompt),
803
+ sessionID: invocation.sessionID,
804
+ nativeGoalAvailable,
805
+ delegate: (args) => sessionCommand(args),
806
+ });
807
+ if (!result.delegated) {
808
+ throw new Error(result.error);
809
+ }
810
+ },
811
+ });
812
+ }));
813
+ }
814
+ catch (err) {
815
+ await safeLog(state, "warn", "could not register df-goal command; verified goals unavailable", {
816
+ error: String(err),
817
+ });
818
+ }
741
819
  // 4) Event subscription — file tracking + gate enforcement net.
742
820
  // Runs the gate on `session.idle` for the boundaries the §1b hook
743
821
  // skipped (interruption, failure, steer-parked drains) or for builds
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/dist/types.d.ts CHANGED
@@ -18,6 +18,19 @@ export interface CommandsConfig {
18
18
  lint?: CommandMap;
19
19
  test_changed?: string;
20
20
  }
21
+ /**
22
+ * A named project-specific acceptance check, run by the gate after the
23
+ * built-in steps. Sequential in declaration order; every step runs even
24
+ * when an earlier one fails (same aggregation as the rest of `runGate`).
25
+ */
26
+ export interface AcceptanceCheck {
27
+ /** Unique, non-empty step name. Reported as `acceptance:<name>`. */
28
+ name: string;
29
+ /** Command template. Supports the same `{files}` substitution as tests. */
30
+ command: string;
31
+ /** Per-check timeout in seconds. Falls back to `gate.timeout`, then default. */
32
+ timeout?: number;
33
+ }
21
34
  export interface GateConfig {
22
35
  run_typecheck: boolean;
23
36
  run_tests: boolean;
@@ -34,6 +47,11 @@ export interface GateConfig {
34
47
  * also produce a peer-review artifact before the completion gate passes.
35
48
  */
36
49
  require_review: boolean;
50
+ /**
51
+ * Named project-specific acceptance checks (`acceptance:<name>` steps).
52
+ * Empty by default; run after the built-in gate steps, sequentially.
53
+ */
54
+ acceptance: AcceptanceCheck[];
37
55
  /** Per-command timeout in seconds. */
38
56
  timeout?: number;
39
57
  /** Maximum number of times a failing gate may re-block before standing down. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-dev-framework",
3
- "version": "0.5.1",
3
+ "version": "1.1.0",
4
4
  "description": "OpenCode plugin that enforces project-specific quality gates during AI coding sessions",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -29,6 +29,12 @@ A task is done only when:
29
29
  - The change matches existing patterns in the surrounding code (see
30
30
  `20-match-existing-patterns`).
31
31
  - A peer-review pass found no blocking issues (see `40-delegation`).
32
+ - If the task came from a written plan, you re-read the plan and verified every
33
+ requirement was implemented — fix gaps rather than declaring success.
34
+ - Any required review artifact describes THIS session's changes. Never reuse a
35
+ review file left over from a previous task; rewrite it fresh every time.
36
+ - You ran the project's full verification yourself (not just the completion
37
+ gate) and read the output — the gate is a backstop, not your test run.
32
38
 
33
39
  If you cannot meet the bar, stop and tell the user what is blocking you rather than
34
40
  declaring success.
@@ -15,7 +15,12 @@ plausible-sounding assertions. Running code is the source of truth.
15
15
  concrete command), then fix it, then show the same check now passes.
16
16
  4. **Run the narrowest useful check often, the full suite before done.** Iterate with
17
17
  targeted tests for speed; the completion gate will run the broader suite.
18
- 5. **Read the actual output.** Don't pattern-match on exit codes — read failures and
18
+ Do not treat the gate as your test run — run the full verification yourself
19
+ before finishing, and read the output.
20
+ 5. **A stale PASS is not evidence.** Any further product edit after a passing run
21
+ invalidates it. Re-run the checks on the final tree; never present an earlier
22
+ PASS as covering later changes.
23
+ 6. **Read the actual output.** Don't pattern-match on exit codes — read failures and
19
24
  address the real cause. Treat a flaky or skipped test as a finding, not a pass.
20
25
 
21
26
  ## Use existing tooling only
@@ -37,12 +37,28 @@ before completion.
37
37
  3. **After a batch of edits** → `style-enforcer` on the changed files.
38
38
  4. **Before declaring done** → `test-grounder` (evidence) and a final
39
39
  `pattern-guardian` / review pass; resolve every blocking item.
40
+ 5. **Write the review artifact fresh, every task.** When the completion gate
41
+ requires a review file, rewrite it for THIS session's changes — scope,
42
+ findings, and resolutions. A file left over from a previous task never
43
+ counts, even if it exists and is non-empty.
40
44
 
45
+ This cadence is the default working loop, not an opt-in. For a non-trivial
46
+ change you plan first, implement from the plan without expanding scope, then
47
+ harden (full verification + review + fresh artifact) before declaring done.
41
48
  Keep delegation proportional: a one-line fix doesn't need the full loop; a new module
42
49
  does. Use judgment, but never skip the test-grounding and review steps for behavioral
43
50
  changes. If the specialist agents are not installed in this project, perform the same
44
51
  checks yourself with the skills in this section.
45
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
+
46
62
  ## Skills
47
63
 
48
64
  For explicit, repeatable workflows you can invoke the bundled skills: