opencode-dev-framework 0.5.0 → 1.0.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/goal.js ADDED
@@ -0,0 +1,175 @@
1
+ /**
2
+ * `/df-goal`: verified-goal wrapper around native `/goal`.
3
+ *
4
+ * A thin adapter, not a second goal engine: it validates that verified-goal
5
+ * mode is meaningful and available (§3.3), appends the framework verification
6
+ * addendum to the user's objective verbatim (§3.2), and delegates exactly
7
+ * once to native `/goal` via `session.command`. Native `/goal` keeps owning
8
+ * kickoff, state, reviewer, pause/resume/clear, and continuations; the
9
+ * framework's idle gate stays the independent deterministic backstop.
10
+ *
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.
14
+ */
15
+ import { hasMeaningfulChecks } from "./config.js";
16
+ /**
17
+ * Native `/goal` objective limit. Counts JS `text.length` (UTF-16 code
18
+ * units) — confirmed by the Phase 0 spike against core `goal.ts`
19
+ * (`MAX_OBJECTIVE = 4_000`), not bytes or grapheme clusters.
20
+ */
21
+ export const NATIVE_GOAL_LIMIT = 4000;
22
+ /**
23
+ * Verification addendum appended to the objective (plan §3.2). The addendum
24
+ * length in limit accounting is computed from this exact string at
25
+ * delegation time, never from a hardcoded constant.
26
+ */
27
+ export const VERIFICATION_ADDENDUM = `Verification contract added by opencode-dev-framework:
28
+
29
+ Before declaring this goal complete, run dev_framework_verify after your final changes. A FAIL result means the goal is incomplete: fix the underlying cause and run verification again. Any later edit invalidates an earlier verification result. PASS is required but does not replace the original objective or its acceptance criteria. Do not disable, skip, or weaken the configured checks to obtain PASS.`;
30
+ /** Separator between the verbatim objective and the addendum. */
31
+ const OBJECTIVE_SEPARATOR = "\n\n";
32
+ /**
33
+ * Append the verification addendum to the objective without rewriting the
34
+ * user's text. An objective that already contains the addendum is used
35
+ * verbatim (never double-wrapped on retry). The complete string counts
36
+ * toward the native limit; overflow is rejected with lengths, never
37
+ * silently truncated.
38
+ */
39
+ export function buildVerifiedObjective(objective) {
40
+ if (objective.trim().length === 0) {
41
+ return {
42
+ ok: false,
43
+ error: "Cannot start a verified goal: the objective is empty. " +
44
+ "Provide an objective, e.g. /df-goal <objective>.",
45
+ };
46
+ }
47
+ if (objective.includes(VERIFICATION_ADDENDUM)) {
48
+ // Already wrapped (e.g. a retry of wrapper output): idempotent, but the
49
+ // combined text still counts toward the native limit. Report the single
50
+ // combined length — the addendum is inside, not additive.
51
+ if (objective.length > NATIVE_GOAL_LIMIT) {
52
+ return {
53
+ ok: false,
54
+ error: `Cannot start a verified goal: objective including the previously appended ` +
55
+ `verification addendum is ${objective.length} characters, exceeding the native ` +
56
+ `/goal limit of ${NATIVE_GOAL_LIMIT} characters. Shorten the objective by at ` +
57
+ `least ${objective.length - NATIVE_GOAL_LIMIT} characters; the addendum is never truncated.`,
58
+ };
59
+ }
60
+ return { ok: true, text: objective, alreadyWrapped: true };
61
+ }
62
+ const text = `${objective}${OBJECTIVE_SEPARATOR}${VERIFICATION_ADDENDUM}`;
63
+ // Same unit native uses: JS string length (UTF-16 code units).
64
+ if (text.length > NATIVE_GOAL_LIMIT) {
65
+ return {
66
+ ok: false,
67
+ error: `Cannot start a verified goal: objective is ${objective.length} characters, ` +
68
+ `the verification addendum adds ${VERIFICATION_ADDENDUM.length} characters plus a ` +
69
+ `blank-line separator, total ${text.length} exceeds the native /goal limit of ` +
70
+ `${NATIVE_GOAL_LIMIT} characters. ` +
71
+ `Shorten the objective; the addendum is never truncated.`,
72
+ };
73
+ }
74
+ return { ok: true, text, alreadyWrapped: false };
75
+ }
76
+ /**
77
+ * Availability/profile/meaningful-check rules (plan §3.3). `/df-goal` means
78
+ * verified goal, not an alias for `/goal`: every failure names the exact
79
+ * cause and points at the alternatives (enable a blocking profile or use
80
+ * native `/goal` directly for an unverified objective).
81
+ */
82
+ export function checkGoalAvailability(config, nativeGoalAvailable) {
83
+ if (!nativeGoalAvailable) {
84
+ return {
85
+ ok: false,
86
+ error: "Cannot start a verified goal: native /goal is not available on this core. " +
87
+ "Upgrade OpenCode to a build containing native /goal, or run the objective " +
88
+ "without verification where native /goal exists.",
89
+ };
90
+ }
91
+ if (config.profile === "off") {
92
+ return {
93
+ ok: false,
94
+ error: 'Cannot start a verified goal: profile is "off", so verification would be vacuous. ' +
95
+ "Enable a blocking profile (standard or strict), or use native /goal directly " +
96
+ "for an unverified objective.",
97
+ };
98
+ }
99
+ if (!config.gate?.block_on_failure) {
100
+ const found = config.gate?.block_on_failure;
101
+ return {
102
+ ok: false,
103
+ error: `Cannot start a verified goal: gate.block_on_failure is ${String(found)}, ` +
104
+ "but /df-goal requires it to be true. Advisory mode must not gain a blocking " +
105
+ "side channel through /df-goal. Enable a blocking profile (standard or strict), " +
106
+ "or use native /goal directly.",
107
+ };
108
+ }
109
+ if (!hasMeaningfulChecks(config)) {
110
+ return {
111
+ ok: false,
112
+ error: "Cannot start a verified goal: the resolved configuration provides no meaningful " +
113
+ "completion check (no typecheck/test command, no changed-file lint, no acceptance " +
114
+ "commands, and no review requirement). Configure at least one check, or use native " +
115
+ "/goal directly for a purely semantic objective.",
116
+ };
117
+ }
118
+ return { ok: true };
119
+ }
120
+ /**
121
+ * Validate, wrap, and delegate exactly once. Native delegation errors
122
+ * propagate untouched — never an unverified fallback. The wrapper itself
123
+ * admits no kickoff synthetic message.
124
+ */
125
+ export async function runGoalCommand(deps) {
126
+ const availability = checkGoalAvailability(deps.config, deps.nativeGoalAvailable);
127
+ if (!availability.ok) {
128
+ return { delegated: false, error: availability.error };
129
+ }
130
+ const built = buildVerifiedObjective(deps.objective);
131
+ if (!built.ok) {
132
+ return { delegated: false, error: built.error };
133
+ }
134
+ await deps.delegate({ sessionID: deps.sessionID, name: "goal", text: built.text });
135
+ return { delegated: true, text: built.text, alreadyWrapped: built.alreadyWrapped };
136
+ }
137
+ /**
138
+ * Extract the raw objective from a command invocation prompt. The
139
+ * invocation prompt is a `Prompt` struct (`{ text, ... }`); accept a bare
140
+ * string defensively and fall back to empty (rejected downstream as an
141
+ * empty objective) for anything else.
142
+ */
143
+ export function extractObjectiveText(prompt) {
144
+ if (typeof prompt === "string")
145
+ return prompt;
146
+ if (prompt !== null && typeof prompt === "object") {
147
+ const text = prompt.text;
148
+ if (typeof text === "string")
149
+ return text;
150
+ }
151
+ return "";
152
+ }
153
+ /**
154
+ * Capability probe over `command.list()` output: true when an entry named
155
+ * `goal` is present. The real output shape is `{ location, data: [...] }`
156
+ * (`CommandListOutput`); a bare array is tolerated for forward
157
+ * compatibility. Defensive throughout (SDK codegen drifts; core is truth) —
158
+ * anything unrecognized means unavailable, never an assumed capability.
159
+ */
160
+ export function isNativeGoalListed(listed) {
161
+ const entries = unwrapCommandEntries(listed);
162
+ if (entries === null)
163
+ return false;
164
+ return entries.some((entry) => entry !== null && typeof entry === "object" && entry.name === "goal");
165
+ }
166
+ function unwrapCommandEntries(listed) {
167
+ if (Array.isArray(listed))
168
+ return listed;
169
+ if (listed !== null && typeof listed === "object") {
170
+ const data = listed.data;
171
+ if (Array.isArray(data))
172
+ return data;
173
+ }
174
+ return null;
175
+ }
package/dist/harness.d.ts CHANGED
@@ -17,7 +17,7 @@
17
17
  * synthetic continuation) and the `session.idle` event net (re-prompt).
18
18
  */
19
19
  import type { BlockStore } from "./block-store.js";
20
- import { type ChangedFileTracker } from "./gate.js";
20
+ import { type ChangedFileTracker, type GateReport } from "./gate.js";
21
21
  import type { RunCommand } from "./host.js";
22
22
  import type { LogFn } from "./logger.js";
23
23
  import type { ResolvedConfig } from "./types.js";
@@ -80,6 +80,45 @@ export interface CompletionDeps {
80
80
  blockCounts: BlockStore;
81
81
  log: LogFn;
82
82
  }
83
+ /**
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`.
88
+ */
89
+ export interface InspectionDeps {
90
+ run: RunCommand;
91
+ config: ResolvedConfig;
92
+ directory: string;
93
+ /** Read-only snapshot of tracker files; never mutated. */
94
+ trackerFiles: string[];
95
+ }
96
+ /**
97
+ * Raw completion report. `ok` is the unadjudicated outcome (gate passed and
98
+ * review satisfied); profiles, block counting, and stand-down are applied by
99
+ * `evaluateCompletion`, and `verifyGate` reports `ok` verbatim as its
100
+ * PASS/FAIL verdict.
101
+ */
102
+ export interface CompletionInspection {
103
+ changedFiles: string[];
104
+ report: GateReport;
105
+ reviewRequired: boolean;
106
+ reviewState: ArtifactState;
107
+ reviewMissing: boolean;
108
+ /** True when the gate short-circuited on `skip_unchanged` with no files. */
109
+ skipped: boolean;
110
+ /** Raw outcome: gate ok AND review satisfied. No profile/policy applied. */
111
+ ok: boolean;
112
+ /** Human- and transcript-readable summary (gate detail or review notice). */
113
+ summary: string;
114
+ }
115
+ /**
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.
120
+ */
121
+ export declare function inspectCompletion(deps: InspectionDeps): Promise<CompletionInspection>;
83
122
  /**
84
123
  * Evaluate the completion gate + review requirement and update block state.
85
124
  * Pure orchestration: both the `experimental.idle` hook and the
package/dist/harness.js CHANGED
@@ -123,21 +123,42 @@ function reviewMissingMessage(changedFiles) {
123
123
  `Investigation-only reviewers: do not ask them to edit product code.`);
124
124
  }
125
125
  /**
126
- * Evaluate the completion gate + review requirement and update block state.
127
- * Pure orchestration: both the `experimental.idle` hook and the
128
- * `session.idle` event net feed their outcome from here so one session's
129
- * block count applies to either lever.
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.
130
130
  */
131
- export async function evaluateCompletion(deps) {
132
- const { run, config, directory, sessionID, tracker, blockCounts } = deps;
131
+ export async function inspectCompletion(deps) {
132
+ const { run, config, directory, trackerFiles } = deps;
133
+ const disabled = {
134
+ changedFiles: [],
135
+ report: {
136
+ ran: false,
137
+ reason: "completion gate disabled",
138
+ steps: [],
139
+ ok: true,
140
+ failedSteps: [],
141
+ },
142
+ reviewRequired: false,
143
+ reviewState: "present",
144
+ reviewMissing: false,
145
+ skipped: false,
146
+ ok: true,
147
+ summary: "completion gate disabled (profile off or no gate section)",
148
+ };
133
149
  if (config.profile === "off" || !config.gate) {
134
- return { decision: "pass", changedFiles: [] };
150
+ return disabled;
135
151
  }
136
- const trackerFiles = tracker.getChangedFiles();
137
152
  const gitFiles = await gitChangedFiles(run, directory);
138
153
  const changedFiles = mergeChangedFiles(trackerFiles, gitFiles);
139
154
  if (config.gate.skip_unchanged && changedFiles.length === 0) {
140
- return { decision: "pass", changedFiles, note: "completion gate skipped: no changed files" };
155
+ return {
156
+ ...disabled,
157
+ changedFiles,
158
+ report: { ran: false, reason: "no changed files", steps: [], ok: true, failedSteps: [] },
159
+ skipped: true,
160
+ summary: "completion gate skipped: no changed files",
161
+ };
141
162
  }
142
163
  const report = await runGate(run, config, changedFiles, { cwd: directory });
143
164
  const gateFailed = report.ran && !report.ok;
@@ -146,18 +167,59 @@ export async function evaluateCompletion(deps) {
146
167
  ? await artifactState(directory, REVIEW_ARTIFACT_REL)
147
168
  : "present";
148
169
  const reviewMissing = reviewRequired && reviewState !== "present";
170
+ const ok = !gateFailed && !reviewMissing;
171
+ const summary = gateFailed
172
+ ? summarizeGate(report)
173
+ : reviewMissing
174
+ ? reviewMissingMessage(changedFiles)
175
+ : report.ran
176
+ ? `completion gate passed\n${summarizeGate(report)}`
177
+ : `completion gate passed (${report.reason ?? "nothing to run"})`;
178
+ return {
179
+ changedFiles,
180
+ report,
181
+ reviewRequired,
182
+ reviewState,
183
+ reviewMissing,
184
+ skipped: false,
185
+ ok,
186
+ summary,
187
+ };
188
+ }
189
+ /**
190
+ * Evaluate the completion gate + review requirement and update block state.
191
+ * Pure orchestration: both the `experimental.idle` hook and the
192
+ * `session.idle` event net feed their outcome from here so one session's
193
+ * block count applies to either lever.
194
+ */
195
+ export async function evaluateCompletion(deps) {
196
+ const { run, config, directory, sessionID, tracker, blockCounts } = deps;
197
+ if (config.profile === "off" || !config.gate) {
198
+ return { decision: "pass", changedFiles: [] };
199
+ }
200
+ const inspection = await inspectCompletion({
201
+ run,
202
+ config,
203
+ directory,
204
+ trackerFiles: tracker.getChangedFiles(),
205
+ });
206
+ const { changedFiles, report } = inspection;
207
+ const gateFailed = report.ran && !report.ok;
208
+ const reviewMissing = inspection.reviewMissing;
149
209
  if (!gateFailed && !reviewMissing) {
150
210
  tracker.clearChangedFiles();
151
211
  await blockCounts.clear(sessionID);
152
212
  return {
153
213
  decision: "pass",
154
214
  changedFiles,
155
- note: report.ran ? `completion gate passed\n${summarizeGate(report)}` : undefined,
215
+ // Preserve the historical note shape: detailed on run, skip note on
216
+ // skip, absent when the gate never ran for any other reason.
217
+ note: report.ran || inspection.skipped ? inspection.summary : undefined,
156
218
  };
157
219
  }
158
220
  // Advisory: report loudly, never block.
159
221
  if (!config.gate.block_on_failure) {
160
- const summary = gateFailed ? summarizeGate(report) : reviewMissingMessage(changedFiles);
222
+ const summary = inspection.summary;
161
223
  await deps.log("error", `completion gate (advisory — not blocking) saw problems:\n${summary}`);
162
224
  return {
163
225
  decision: "pass",
@@ -166,7 +228,7 @@ export async function evaluateCompletion(deps) {
166
228
  };
167
229
  }
168
230
  const reason = gateFailed ? "gate" : "review";
169
- const summary = gateFailed ? summarizeGate(report) : reviewMissingMessage(changedFiles);
231
+ const summary = inspection.summary;
170
232
  const maxBlocks = config.gate.max_blocks ?? 3;
171
233
  const blockCount = await blockCounts.increment(sessionID);
172
234
  if (blockCount > maxBlocks) {
package/dist/index.d.ts 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
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
@@ -30,6 +32,7 @@ import { lintFile, detectPreCommitAvailability, isLintFailure, summarizeLint } f
30
32
  import { createLogger } from "./logger.js";
31
33
  import { checkToolCall, extractFilePath, FILE_TOOLS, toPermissionGuard } from "./protect.js";
32
34
  import { loadConstitution } from "./rules.js";
35
+ import { writeRuntimeStatus } from "./runtime-status.js";
33
36
  let activeState = null;
34
37
  let fallbackLog = async () => { };
35
38
  function safeLog(state, level, message, extra) {
@@ -344,6 +347,9 @@ const plugin = Plugin.define({
344
347
  // `prompt` here — only `synthetic` keeps the same execution.
345
348
  // DEFENSIVE: any-cast because the installed @opencode/plugin may predate
346
349
  // the hook; fires only on builds dispatching it.
350
+ // idleHookVia feeds the runtime-status snapshot (`/df-runtime`): which
351
+ // key the core accepted, so the TUI can report the hook method.
352
+ let idleHookVia = "none";
347
353
  const handleIdleContinuation = async (event) => {
348
354
  if (activeState !== state)
349
355
  return;
@@ -381,6 +387,7 @@ const plugin = Plugin.define({
381
387
  // Pass/stand-down: completed evaluation, nothing to admit.
382
388
  stampIdleHandled(state, sessionID);
383
389
  state.continuationLevel = "idle";
390
+ void writeRuntimeStatus(state.directory, { idleHookVia, continuation: "idle" });
384
391
  return;
385
392
  }
386
393
  // Blocked: admit a synthetic continuation (same execution).
@@ -395,6 +402,7 @@ const plugin = Plugin.define({
395
402
  await ctx.session.synthetic({ sessionID, text: message });
396
403
  stampIdleHandled(state, sessionID);
397
404
  state.continuationLevel = "idle";
405
+ void writeRuntimeStatus(state.directory, { idleHookVia, continuation: "idle" });
398
406
  await safeLog(state, "info", `completion gate continued session ${sessionID} via idle hook`, {
399
407
  sessionID,
400
408
  blockCount: verdict.blockCount,
@@ -418,11 +426,16 @@ const plugin = Plugin.define({
418
426
  trackRegistration(
419
427
  // biome-ignore lint/suspicious/noExplicitAny: defensive idle hook, absent from SessionHooks on older cores
420
428
  await ctx.session.hook(name, handleIdleContinuation));
429
+ if (idleHookVia === "none")
430
+ idleHookVia = name;
421
431
  }
422
432
  catch {
423
433
  await safeLog(state, "warn", `could not register session hook ${name}`, { hook: name });
424
434
  }
425
435
  }
436
+ // Record the registration outcome for `/df-runtime` even before the
437
+ // first dispatch: "armed" is a real state, not a missing one.
438
+ void writeRuntimeStatus(state.directory, { idleHookVia, continuation: "armed" });
426
439
  await safeLog(state, "info", "registered experimental.idle hook (+ idle alias); gate failures continue the same execution via synthetic");
427
440
  // 2a) Native permission layer (Phase 25): `permission.evaluate` fires
428
441
  // with `{action, resources, effect}` (shapes recorded in the 25.1 spike,
@@ -674,7 +687,7 @@ const plugin = Plugin.define({
674
687
  });
675
688
  editor.add({
676
689
  name: "dev_framework_verify",
677
- 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.",
690
+ 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.",
678
691
  input: {
679
692
  type: "object",
680
693
  properties: {
@@ -727,6 +740,51 @@ const plugin = Plugin.define({
727
740
  },
728
741
  });
729
742
  }));
743
+ // 3b) Verified-goal wrapper — server-side `/df-goal` through
744
+ // `ctx.command.transform` (see src/goal.ts for the pure policy). Thin
745
+ // adapter around native `/goal`: probes native capability, checks
746
+ // availability/profile/meaningful-checks, appends the verification
747
+ // addendum verbatim, and delegates exactly once via the flat core
748
+ // `session.command` shape. Defensive like the permission hook: on a
749
+ // core without the command API the wrapper is skipped with a warning
750
+ // and every other layer keeps working.
751
+ try {
752
+ trackRegistration(await ctx.command.transform((editor) => {
753
+ editor.add({
754
+ name: "df-goal",
755
+ 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
+ execute: async (invocation) => {
757
+ if (activeState !== state)
758
+ return;
759
+ await reloadConfigIfChanged(state);
760
+ const { extractObjectiveText, isNativeGoalListed, runGoalCommand } = await import("./goal.js");
761
+ let nativeGoalAvailable = false;
762
+ try {
763
+ nativeGoalAvailable = isNativeGoalListed(await ctx.command.list());
764
+ }
765
+ catch {
766
+ nativeGoalAvailable = false;
767
+ }
768
+ const sessionCommand = ctx.session.command;
769
+ const result = await runGoalCommand({
770
+ config: state.config,
771
+ objective: extractObjectiveText(invocation.prompt),
772
+ sessionID: invocation.sessionID,
773
+ nativeGoalAvailable,
774
+ delegate: (args) => sessionCommand(args),
775
+ });
776
+ if (!result.delegated) {
777
+ throw new Error(result.error);
778
+ }
779
+ },
780
+ });
781
+ }));
782
+ }
783
+ catch (err) {
784
+ await safeLog(state, "warn", "could not register df-goal command; verified goals unavailable", {
785
+ error: String(err),
786
+ });
787
+ }
730
788
  // 4) Event subscription — file tracking + gate enforcement net.
731
789
  // Runs the gate on `session.idle` for the boundaries the §1b hook
732
790
  // skipped (interruption, failure, steer-parked drains) or for builds
@@ -795,8 +853,10 @@ const plugin = Plugin.define({
795
853
  if (wasIdleHandledRecently(state, sessionID))
796
854
  continue;
797
855
  const verdict = await runCompletion(state, sessionID);
798
- if (state.continuationLevel === undefined)
856
+ if (state.continuationLevel === undefined) {
799
857
  state.continuationLevel = "fallback";
858
+ void writeRuntimeStatus(state.directory, { idleHookVia, continuation: "fallback" });
859
+ }
800
860
  const message = await actOnVerdict(state, verdict);
801
861
  if (message === null)
802
862
  continue;
package/dist/lint.d.ts CHANGED
@@ -25,9 +25,11 @@ export interface LintOutcome {
25
25
  export declare function matchExclude(config: ResolvedConfig, filePath: string, directory?: string): string | undefined;
26
26
  /**
27
27
  * Resolve the lint command for a file: the per-extension override wins over
28
- * the default command. The `{file}` token is replaced with the file path;
29
- * commands without the token run as-is. Returns undefined when no lint
30
- * command is configured at all.
28
+ * the default command. The `{file}` token is replaced with the file path and
29
+ * `{dir}` with the file's directory (package context for tools like
30
+ * golangci-lint, which cannot typecheck a lone file); commands with neither
31
+ * token run as-is. Returns undefined when no lint command is configured
32
+ * at all.
31
33
  */
32
34
  export declare function resolveLintCommand(config: ResolvedConfig, filePath: string): string[] | undefined;
33
35
  export declare function resolvePreCommitCommand(filePath: string): string[];
package/dist/lint.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * through an injectable command runner. Pure orchestration — the OpenCode
4
4
  * hook wiring lives in src/index.ts.
5
5
  */
6
- import { basename, extname, isAbsolute, relative } from "node:path";
6
+ import { basename, dirname, extname, isAbsolute, relative } from "node:path";
7
7
  import picomatch from "picomatch";
8
8
  import { normalizeCommandMap, splitCommand } from "./command-utils.js";
9
9
  /** Fallback per-lint timeout (seconds) when the config sets none. */
@@ -33,9 +33,11 @@ export function matchExclude(config, filePath, directory) {
33
33
  }
34
34
  /**
35
35
  * Resolve the lint command for a file: the per-extension override wins over
36
- * the default command. The `{file}` token is replaced with the file path;
37
- * commands without the token run as-is. Returns undefined when no lint
38
- * command is configured at all.
36
+ * the default command. The `{file}` token is replaced with the file path and
37
+ * `{dir}` with the file's directory (package context for tools like
38
+ * golangci-lint, which cannot typecheck a lone file); commands with neither
39
+ * token run as-is. Returns undefined when no lint command is configured
40
+ * at all.
39
41
  */
40
42
  export function resolveLintCommand(config, filePath) {
41
43
  const { default: defaultCommand, byExtension } = normalizeCommandMap(config.commands.lint);
@@ -43,7 +45,8 @@ export function resolveLintCommand(config, filePath) {
43
45
  if (template === undefined) {
44
46
  return undefined;
45
47
  }
46
- return splitCommand(template).map((token) => token.replaceAll("{file}", filePath));
48
+ const dir = dirname(filePath);
49
+ return splitCommand(template).map((token) => token.replaceAll("{file}", filePath).replaceAll("{dir}", dir));
47
50
  }
48
51
  export function resolvePreCommitCommand(filePath) {
49
52
  return ["pre-commit", "run", "--files", filePath];
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Runtime status snapshot: the cross-process bridge between the server
3
+ * plugin (which owns hook registration and gate dispatch state) and the
4
+ * TUI plugin (which can only read the project directory).
5
+ *
6
+ * Written best-effort by the server after hook registration and on every
7
+ * continuation dispatch; read by the TUI `/df-runtime` command. Never
8
+ * throws: a missing, corrupt, or stale snapshot renders as
9
+ * "not reported yet".
10
+ */
11
+ /** Snapshot location, relative to the project directory. */
12
+ export declare const RUNTIME_STATUS_DIR = ".opencode/opencode-dev-framework";
13
+ export declare const RUNTIME_STATUS_FILE = "runtime-status.json";
14
+ /** Which session-hook key the core accepted, or neither. */
15
+ export type IdleHookVia = "experimental.idle" | "idle" | "none";
16
+ /** Dispatch history this session: hook-fired, net-fired, or neither yet. */
17
+ export type ContinuationState = "idle" | "fallback" | "armed";
18
+ export interface RuntimeStatus {
19
+ frameworkVersion: string;
20
+ idleHookVia: IdleHookVia;
21
+ continuation: ContinuationState;
22
+ updatedAt: string;
23
+ }
24
+ export declare function snapshotPath(directory: string): string;
25
+ export declare function writeRuntimeStatus(directory: string, partial: {
26
+ idleHookVia: IdleHookVia;
27
+ continuation: ContinuationState;
28
+ }): Promise<void>;
29
+ export declare function readRuntimeStatus(directory: string): Promise<RuntimeStatus | null>;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Runtime status snapshot: the cross-process bridge between the server
3
+ * plugin (which owns hook registration and gate dispatch state) and the
4
+ * TUI plugin (which can only read the project directory).
5
+ *
6
+ * Written best-effort by the server after hook registration and on every
7
+ * continuation dispatch; read by the TUI `/df-runtime` command. Never
8
+ * throws: a missing, corrupt, or stale snapshot renders as
9
+ * "not reported yet".
10
+ */
11
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
12
+ import { dirname, join } from "node:path";
13
+ import { fileURLToPath } from "node:url";
14
+ /** Snapshot location, relative to the project directory. */
15
+ export const RUNTIME_STATUS_DIR = ".opencode/opencode-dev-framework";
16
+ export const RUNTIME_STATUS_FILE = "runtime-status.json";
17
+ export function snapshotPath(directory) {
18
+ return join(directory, RUNTIME_STATUS_DIR, RUNTIME_STATUS_FILE);
19
+ }
20
+ /** Resolve the plugin version from the installed package.json. Works from
21
+ * both `dist/` (production) and `src/` (vitest) layouts; "unknown" when
22
+ * neither candidate parses. */
23
+ async function resolveFrameworkVersion() {
24
+ const here = dirname(fileURLToPath(import.meta.url));
25
+ const candidates = [join(here, "..", "package.json"), join(here, "..", "..", "package.json")];
26
+ for (const candidate of candidates) {
27
+ try {
28
+ const pkg = JSON.parse(await readFile(candidate, "utf8"));
29
+ if (pkg.name === "opencode-dev-framework" && typeof pkg.version === "string") {
30
+ return pkg.version;
31
+ }
32
+ }
33
+ catch {
34
+ // try the next candidate
35
+ }
36
+ }
37
+ return "unknown";
38
+ }
39
+ export async function writeRuntimeStatus(directory, partial) {
40
+ try {
41
+ const status = {
42
+ frameworkVersion: await resolveFrameworkVersion(),
43
+ ...partial,
44
+ updatedAt: new Date().toISOString(),
45
+ };
46
+ await mkdir(join(directory, RUNTIME_STATUS_DIR), { recursive: true });
47
+ await writeFile(snapshotPath(directory), `${JSON.stringify(status, null, 2)}\n`, "utf8");
48
+ }
49
+ catch {
50
+ // Best-effort only: runtime reporting must never break the gate.
51
+ }
52
+ }
53
+ function isIdleHookVia(value) {
54
+ return value === "experimental.idle" || value === "idle" || value === "none";
55
+ }
56
+ function isContinuationState(value) {
57
+ return value === "idle" || value === "fallback" || value === "armed";
58
+ }
59
+ export async function readRuntimeStatus(directory) {
60
+ try {
61
+ const parsed = JSON.parse(await readFile(snapshotPath(directory), "utf8"));
62
+ if (typeof parsed.frameworkVersion !== "string" || typeof parsed.updatedAt !== "string") {
63
+ return null;
64
+ }
65
+ return {
66
+ frameworkVersion: parsed.frameworkVersion,
67
+ idleHookVia: isIdleHookVia(parsed.idleHookVia) ? parsed.idleHookVia : "none",
68
+ continuation: isContinuationState(parsed.continuation) ? parsed.continuation : "armed",
69
+ updatedAt: parsed.updatedAt,
70
+ };
71
+ }
72
+ catch {
73
+ return null;
74
+ }
75
+ }