opencode-dev-framework 0.4.0 → 0.5.1

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
@@ -11,10 +11,12 @@
11
11
  * - ctx.event.subscribe() -> file tracking + gate enforcement via re-prompt
12
12
  * - ctx.tool.transform(...) -> custom tools
13
13
  *
14
- * Gate enforcement: no synchronous `session.stopping`. On `session.idle`
15
- * / `session.status:idle` we run the gate and if it fails inside budget we
16
- * call `ctx.session.prompt({ sessionID, text: stoppingMessage })` to wake the
17
- * agent — async re-injection preserving the enforcement intent (see docs/plans/08-notes).
14
+ * Gate enforcement: no synchronous pre-stop veto. On `experimental.idle`
15
+ * (same execution) we run the gate and if it fails inside budget we admit
16
+ * `ctx.session.synthetic({ sessionID, text: stoppingMessage })` — the
17
+ * continuation runs before the session goes idle (see
18
+ * docs/plans/12-idle-hook-cutover.md). The `event.subscribe` idle net
19
+ * stays as a deduped fallback for the boundaries the hook skips.
18
20
  */
19
21
  import { Plugin } from "@opencode/plugin";
20
22
  import { stat } from "node:fs/promises";
@@ -28,6 +30,7 @@ import { lintFile, detectPreCommitAvailability, isLintFailure, summarizeLint } f
28
30
  import { createLogger } from "./logger.js";
29
31
  import { checkToolCall, extractFilePath, FILE_TOOLS, toPermissionGuard } from "./protect.js";
30
32
  import { loadConstitution } from "./rules.js";
33
+ import { writeRuntimeStatus } from "./runtime-status.js";
31
34
  let activeState = null;
32
35
  let fallbackLog = async () => { };
33
36
  function safeLog(state, level, message, extra) {
@@ -71,10 +74,10 @@ async function reloadConfigIfChanged(state) {
71
74
  }
72
75
  /**
73
76
  * Turn a completion verdict into the continuation message fed back to the
74
- * agent when blocked. Shared by the `session.stopping` hard-stop path, the
75
- * `experimental.stopping` continuation vote, and the `session.idle`
76
- * re-prompt fallback so wording (and block counting) is identical on every
77
- * core support level.
77
+ * agent when blocked. Shared by the `experimental.idle` hook (same
78
+ * execution, via synthetic) and the `event.subscribe` idle re-prompt
79
+ * fallback so wording (and block counting) is identical on every
80
+ * enforcement level.
78
81
  */
79
82
  function continuationMessage(verdict) {
80
83
  const why = verdict.reason === "review"
@@ -148,17 +151,22 @@ function runCompletion(state, sessionID) {
148
151
  });
149
152
  }
150
153
  /**
151
- * Record that a stopping hook fired at `kind`. Monotonic: the V2
152
- * `experimental.stopping` level outranks the legacy `stopping` probe, so a
153
- * late legacy dispatch never downgrades an already-recorded new-hook level
154
- * (both the in-memory flag and the persisted store upgrade only).
154
+ * Record a completed idle-hook evaluation for the dedup map. Stamp ONLY on
155
+ * the completed-evaluation paths (pass, blocked-admitted, standdown);
156
+ * throw/early-return paths must not stamp so the subscriber net retries.
155
157
  */
156
- async function recordStopLevel(state, kind) {
157
- if (state.stopHookKind !== "experimental.stopping") {
158
- state.stopHookKind = kind;
159
- }
160
- state.stopHookSupported = true;
161
- await state.blocks.setStopSupported(kind);
158
+ function stampIdleHandled(state, sessionID) {
159
+ state.lastIdleHandled.set(sessionID, Date.now());
160
+ }
161
+ /**
162
+ * True when the idle hook completed an evaluation for this session inside
163
+ * `windowMs`. The hook itself uses a short window (same-boundary
164
+ * double-fire guard for the dual key registration below); the subscriber
165
+ * net uses the full window (one boundary, one gate run).
166
+ */
167
+ function wasIdleHandledRecently(state, sessionID, windowMs = 5_000) {
168
+ const at = state.lastIdleHandled.get(sessionID);
169
+ return at !== undefined && Date.now() - at < windowMs;
162
170
  }
163
171
  // Helpers to normalize V2 event shapes (data vs properties vs direct)
164
172
  function getEventSessionID(event) {
@@ -259,14 +267,13 @@ const plugin = Plugin.define({
259
267
  blockCounts,
260
268
  blocks,
261
269
  configMtime,
270
+ lastIdleHandled: new Map(),
262
271
  };
263
272
  activeState = state;
264
- // Hydrate the hard-stop probe level: a previous setup may have seen core
265
- // dispatch `stopping` or `experimental.stopping`. A storage failure
266
- // degrades to in-memory counts (pre-Phase-23 behavior) and is logged,
267
- // never thrown.
268
- state.stopHookKind = (await blocks.getStopKind()) ?? undefined;
269
- state.stopHookSupported = state.stopHookKind !== undefined;
273
+ // Surface a broken storage backend early (best-effort, never thrown).
274
+ // With the stop-level hydration gone there is no setup-time storage
275
+ // read left, so this rarely fires here — the store still degrades
276
+ // lazily on first use and reports via isDegraded().
270
277
  if (blocks.isDegraded()) {
271
278
  await log("warn", "ctx.storage is unavailable; gate block counts are in-memory only and reset on reload", { directory });
272
279
  }
@@ -324,122 +331,110 @@ const plugin = Plugin.define({
324
331
  event.system.push({ type: "text", text: constitution });
325
332
  }));
326
333
  }
327
- // 1b) Hard-stop completion gate — `session.stopping` (OpenCode PR #44712).
328
- // Fires before the agent loop breaks on natural exit: a blocked verdict
329
- // sets stop=false + message and the loop re-enters, so gate failures
330
- // physically prevent completion. Registered defensively: on builds
331
- // without core support the hook is simply never dispatched, and the
332
- // session.idle fallback below provides re-prompt enforcement instead.
333
- // The first invocation flips `stopHookSupported` so /df-status can show
334
- // which enforcement level is active.
335
- // DEFENSIVE: "stopping" is not in SessionHooks as of 2.0.x; fires only
336
- // if a future core dispatches it (see PR #44712). One of two any-casts
337
- // in src/ (this probe + the `experimental.stopping` probe in §1c) —
338
- // all other hooks are fully typed so the compiler guards future SDK
339
- // upgrades.
340
- try {
341
- trackRegistration(
342
- // biome-ignore lint/suspicious/noExplicitAny: defensive stopping probe, not in SessionHooks (PR #44712)
343
- await ctx.session.hook("stopping",
344
- // biome-ignore lint/suspicious/noExplicitAny: core may dispatch (input, output) or a single mutable event
345
- async (input, output) => {
346
- if (activeState !== state)
334
+ // 1b) Idle-first completion gate — `experimental.idle` (landed upstream
335
+ // via anomalyco/opencode#59437; see docs/plans/12-idle-hook-cutover.md).
336
+ // Fires where a session would otherwise go idle, inside the same
337
+ // execution: a blocked verdict admits a synthetic continuation and the
338
+ // runner re-checks the inbox instead of idling. Pass/stand-down admit
339
+ // nothing. Registered defensively: on builds without core support the
340
+ // hook is simply never dispatched, and the session.idle event net below
341
+ // provides re-prompt enforcement instead (deduped via lastIdleHandled).
342
+ // Both the current `experimental.idle` key and the unprefixed `idle`
343
+ // alias are registered so a future stabilization rename is a non-event;
344
+ // the same-boundary double-fire guard below makes that safe. Never
345
+ // `prompt` here — only `synthetic` keeps the same execution.
346
+ // DEFENSIVE: any-cast because the installed @opencode/plugin may predate
347
+ // the hook; fires only on builds dispatching it.
348
+ // idleHookVia feeds the runtime-status snapshot (`/df-runtime`): which
349
+ // key the core accepted, so the TUI can report the hook method.
350
+ let idleHookVia = "none";
351
+ const handleIdleContinuation = async (event) => {
352
+ if (activeState !== state)
353
+ return;
354
+ if (event === null || typeof event !== "object")
355
+ return;
356
+ // Never let a gate failure escape into core: an uncaught throw fails
357
+ // the drain (Failed terminal), it does NOT fail open to idle. So on
358
+ // any error — including a hostile event shape blowing up sessionID
359
+ // resolution — abstain (admit nothing) and leave unstamped; the
360
+ // subscriber net retries at the next idle.
361
+ let sessionID;
362
+ try {
363
+ sessionID =
364
+ (typeof event.sessionID === "string" &&
365
+ event.sessionID) ||
366
+ getEventSessionID(event);
367
+ if (!sessionID)
347
368
  return;
348
- const out = output ?? input ?? {};
349
- const sessionID = input?.sessionID ??
350
- out.sessionID ??
351
- getEventSessionID(input) ??
352
- "unknown";
353
- await recordStopLevel(state, "stopping");
354
369
  await reloadConfigIfChanged(state);
355
370
  if (state.config.profile === "off")
356
371
  return;
372
+ if (!state.config.gate) {
373
+ await safeLog(state, "warn", "plugin config is incomplete (missing gate section), skipping completion gate", { directory: state.directory });
374
+ return;
375
+ }
376
+ // Same-boundary double-fire guard for the dual key registration
377
+ // above (a future core dispatching both names for one boundary).
378
+ // Short window on purpose: any legitimate re-fire needs a full
379
+ // model round-trip first, which never lands inside a second.
380
+ if (wasIdleHandledRecently(state, sessionID, 1_000))
381
+ return;
357
382
  const verdict = await runCompletion(state, sessionID);
358
383
  const message = await actOnVerdict(state, verdict);
359
- if (message !== null) {
360
- out.stop = false;
361
- out.message = message;
362
- }
363
- }));
364
- await safeLog(state, "info", "registered session.stopping hook; if this OpenCode build dispatches it, gate failures become hard stops before loop exit");
365
- }
366
- catch {
367
- await safeLog(state, "warn", "could not register session.stopping hook; using session.idle re-prompt fallback only");
368
- }
369
- // 1c) V2 pre-terminal continuation vote — `experimental.stopping`.
370
- // Same verdict mapping as §1b, in the new contract shape: gate fail →
371
- // `decision = { shouldContinue: true, text: message }` (core admits it
372
- // as a synthetic steer and continues the turn); gate pass/stand-down →
373
- // leave the fail-closed default (abstain). Registered ALONGSIDE the
374
- // legacy probe, not replacing it — the same dist keeps working on
375
- // mainline builds that lack the new core. No provider scoping: the
376
- // event carries no model, so a providerID option would never fire.
377
- // `event.continuations` is the pre-increment grant count (core caps at
378
- // 2 and goes silent past it without calling voters); local policy stays
379
- // tighter-or-equal via the verdict runner's own max_blocks/stand-down,
380
- // never fighting the core cap — expect silence after 2 grants.
381
- // DEFENSIVE: "experimental.stopping" is not in SessionHooks on released
382
- // cores; fires only on builds dispatching it. Same any-cast pattern as
383
- // §1b (the only two in src/).
384
- try {
385
- trackRegistration(
386
- // biome-ignore lint/suspicious/noExplicitAny: defensive stopping probe, not in SessionHooks on released cores
387
- await ctx.session.hook("experimental.stopping",
388
- // biome-ignore lint/suspicious/noExplicitAny: core dispatches a single mutable event
389
- async (event) => {
390
- if (activeState !== state)
384
+ if (message === null || verdict.decision !== "blocked") {
385
+ // Pass/stand-down: completed evaluation, nothing to admit.
386
+ stampIdleHandled(state, sessionID);
387
+ state.continuationLevel = "idle";
388
+ void writeRuntimeStatus(state.directory, { idleHookVia, continuation: "idle" });
391
389
  return;
392
- // Core always dispatches a single mutable event object; a
393
- // non-object would leave the grant with nowhere to land, so bail
394
- // (fail-closed is the core's job on malformed dispatch).
395
- if (event === null || typeof event !== "object")
390
+ }
391
+ // Blocked: admit a synthetic continuation (same execution).
392
+ // `background` is intentionally ignored — the gate evaluates the
393
+ // working tree, it never waits on running work.
394
+ if (typeof ctx.session.synthetic !== "function") {
395
+ await safeLog(state, "warn", "gate blocked but no session.synthetic API available", {
396
+ sessionID,
397
+ });
396
398
  return;
397
- const vote = event;
398
- const sessionID = (typeof vote.sessionID === "string" && vote.sessionID) ||
399
- getEventSessionID(event) ||
400
- "unknown";
401
- // Never let a voter failure escape into core: on any error
402
- // abstain (leave the fail-closed default) instead of losing the
403
- // turn to an undefined core reaction. A throwing voter stops the
404
- // turn per the contract — that decision belongs to core, not to
405
- // a logging or gate-backend failure inside this probe.
399
+ }
400
+ await ctx.session.synthetic({ sessionID, text: message });
401
+ stampIdleHandled(state, sessionID);
402
+ state.continuationLevel = "idle";
403
+ void writeRuntimeStatus(state.directory, { idleHookVia, continuation: "idle" });
404
+ await safeLog(state, "info", `completion gate continued session ${sessionID} via idle hook`, {
405
+ sessionID,
406
+ blockCount: verdict.blockCount,
407
+ maxBlocks: verdict.maxBlocks,
408
+ });
409
+ }
410
+ catch (error) {
406
411
  try {
407
- await recordStopLevel(state, "experimental.stopping");
408
- await reloadConfigIfChanged(state);
409
- if (state.config.profile === "off")
410
- return;
411
- const verdict = await runCompletion(state, sessionID);
412
- const message = await actOnVerdict(state, verdict);
413
- await safeLog(state, "info", "experimental.stopping vote", {
412
+ await safeLog(state, "warn", "idle continuation failed; abstaining (subscriber net retries)", {
414
413
  sessionID,
415
- step: vote.step,
416
- continuations: vote.continuations,
417
- decision: verdict.decision,
414
+ error: error instanceof Error ? error.message : String(error),
418
415
  });
419
- if (message !== null) {
420
- event.decision = {
421
- shouldContinue: true,
422
- text: message,
423
- };
424
- }
425
416
  }
426
- catch (error) {
427
- try {
428
- await safeLog(state, "warn", "experimental.stopping vote failed; abstaining", {
429
- sessionID,
430
- error: error instanceof Error ? error.message : String(error),
431
- });
432
- }
433
- catch {
434
- // best-effort only — the abstain itself must not throw
435
- }
417
+ catch {
418
+ // best-effort only — the abstain itself must not throw
436
419
  }
437
- }));
438
- await safeLog(state, "info", "registered experimental.stopping hook; if this OpenCode build dispatches it, gate failures continue the turn with steer text");
439
- }
440
- catch {
441
- await safeLog(state, "warn", "could not register experimental.stopping hook; legacy stopping probe and session.idle re-prompt remain");
420
+ }
421
+ };
422
+ for (const name of ["experimental.idle", "idle"]) {
423
+ try {
424
+ trackRegistration(
425
+ // biome-ignore lint/suspicious/noExplicitAny: defensive idle hook, absent from SessionHooks on older cores
426
+ await ctx.session.hook(name, handleIdleContinuation));
427
+ if (idleHookVia === "none")
428
+ idleHookVia = name;
429
+ }
430
+ catch {
431
+ await safeLog(state, "warn", `could not register session hook ${name}`, { hook: name });
432
+ }
442
433
  }
434
+ // Record the registration outcome for `/df-runtime` even before the
435
+ // first dispatch: "armed" is a real state, not a missing one.
436
+ void writeRuntimeStatus(state.directory, { idleHookVia, continuation: "armed" });
437
+ await safeLog(state, "info", "registered experimental.idle hook (+ idle alias); gate failures continue the same execution via synthetic");
443
438
  // 2a) Native permission layer (Phase 25): `permission.evaluate` fires
444
439
  // with `{action, resources, effect}` (shapes recorded in the 25.1 spike,
445
440
  // docs/plans/08-notes.md — never guessed: action "edit" covers
@@ -743,9 +738,12 @@ const plugin = Plugin.define({
743
738
  },
744
739
  });
745
740
  }));
746
- // 4) Event subscription — file tracking + gate enforcement (V1: event hook)
747
- // Keeps the completion gate intent without session.stopping: on idle, run gate;
748
- // on failure inside budget, re-prompt the session (async block).
741
+ // 4) Event subscription — file tracking + gate enforcement net.
742
+ // Runs the gate on `session.idle` for the boundaries the §1b hook
743
+ // skipped (interruption, failure, steer-parked drains) or for builds
744
+ // without the hook. Skips when the hook just handled the same boundary
745
+ // (dedup map). Synthetic-first admit: after the execution ended, a
746
+ // synthetic message is the quietest wake; prompt is the fallback.
749
747
  const controller = new AbortController();
750
748
  const eventLoop = (async () => {
751
749
  try {
@@ -758,10 +756,12 @@ const plugin = Plugin.define({
758
756
  const type = event.type;
759
757
  if (isSessionDeletedEvent(type)) {
760
758
  // session.deleted: cleanup block counts (memory + storage) and
761
- // forget the session's directory mapping if present.
759
+ // the idle dedup stamp for the session.
762
760
  const sid = getEventSessionID(event);
763
- if (sid)
761
+ if (sid) {
764
762
  await state.blocks.clear(sid);
763
+ state.lastIdleHandled.delete(sid);
764
+ }
765
765
  continue;
766
766
  }
767
767
  if (isFilesystemChangedEvent(type)) {
@@ -799,23 +799,33 @@ const plugin = Plugin.define({
799
799
  const sessionID = getEventSessionID(event);
800
800
  if (!sessionID)
801
801
  continue;
802
+ // The §1b hook completed an evaluation for this boundary — one
803
+ // boundary, one gate run. (Deliberately not stamped here: only
804
+ // the hook stamps, so a hook that never fires can never be
805
+ // starved by the net.)
806
+ if (wasIdleHandledRecently(state, sessionID))
807
+ continue;
802
808
  const verdict = await runCompletion(state, sessionID);
809
+ if (state.continuationLevel === undefined) {
810
+ state.continuationLevel = "fallback";
811
+ void writeRuntimeStatus(state.directory, { idleHookVia, continuation: "fallback" });
812
+ }
803
813
  const message = await actOnVerdict(state, verdict);
804
814
  if (message === null)
805
815
  continue;
806
816
  const blockInfo = verdict.decision === "blocked"
807
817
  ? ` (block ${verdict.blockCount}/${verdict.maxBlocks})`
808
818
  : "";
809
- // blocked -> re-prompt the session (fallback when session.stopping
810
- // is not dispatched by this OpenCode build)
819
+ // blocked -> admit a continuation (net for the boundaries the
820
+ // hook skipped: interruption, failure, steer-parked drains).
811
821
  try {
812
- // Prefer prompt (creates a user turn and wakes the agent); fallback to synthetic if prompt not available
813
- if (typeof ctx.session.prompt === "function") {
814
- await ctx.session.prompt({ sessionID, text: message });
815
- }
816
- else if (typeof ctx.session.synthetic === "function") {
822
+ // Prefer synthetic (quiet wake, no user turn); fallback to prompt if synthetic not available
823
+ if (typeof ctx.session.synthetic === "function") {
817
824
  await ctx.session.synthetic({ sessionID, text: message });
818
825
  }
826
+ else if (typeof ctx.session.prompt === "function") {
827
+ await ctx.session.prompt({ sessionID, text: message });
828
+ }
819
829
  else {
820
830
  await safeLog(state, "error", `gate blocked but no session prompt API available: ${message}`);
821
831
  }
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];
@@ -1,4 +1,3 @@
1
- import type { StopHookKind } from "./block-store.js";
2
1
  import type { ChangedFileTracker } from "./gate.js";
3
2
  import type { RunCommand } from "./host.js";
4
3
  import type { LogFn } from "./logger.js";
@@ -33,14 +32,12 @@ export interface HookState {
33
32
  /** mtime (ms) of the config file at last load; used to detect out-of-process
34
33
  * edits (e.g. a `/df-profile` change made from the TUI module). */
35
34
  configMtime?: number;
36
- /** True once core has actually dispatched a stopping hook (hard stops active). */
37
- stopHookSupported?: boolean;
38
- /**
39
- * Which hook fired: the legacy `stopping` probe or the V2
40
- * `experimental.stopping` contract. The new hook outranks the old; absent
41
- * until either fires (idle re-prompt fallback is the active level).
42
- */
43
- stopHookKind?: StopHookKind;
35
+ /** Which lever completed a gate evaluation most recently in this process:
36
+ * `"idle"` once the `experimental.idle` hook has (same-execution
37
+ * continuation active), `"fallback"` when only the `event.subscribe`
38
+ * idle re-prompt net has. Absent until either fires. Memory-only: a
39
+ * reload re-derives it on the next idle boundary. */
40
+ continuationLevel?: "idle" | "fallback";
44
41
  }
45
42
  export declare function setBaseDirectory(directory: string): void;
46
43
  export declare function getBaseDirectory(): string | null;
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-dev-framework",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "OpenCode plugin that enforces project-specific quality gates during AI coding sessions",
5
5
  "license": "MIT",
6
6
  "type": "module",