opencode-dev-framework 1.9.0 → 1.9.2

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/README.md CHANGED
@@ -155,7 +155,7 @@ How each layer is enforced, and what it honestly cannot do:
155
155
  | `/df-profile` | Instant modal picker (or `/df-profile <name>`): switches profile now, written to config. |
156
156
  | `/df-verify` | Runs the verification suite manually; pass/fail summary in a modal. |
157
157
  | `/df-init` | Server-side command: scaffolds templates, writes the detected config, trial-runs it, hands the brief to the agent. |
158
- | `/df-update` | Server-side command: diffs installed templates against shipped, refresh/add each with user approval (detection only, never writes). |
158
+ | `/df-update` | Server-side command: diffs installed templates against shipped, refresh/add each with user approval (detection only, never writes). Drift is also mentioned once at session startup. |
159
159
  | `/df-goal <objective>` | Server-side command: starts a **verified** native goal (requires native `/goal`, a blocking profile, and at least one real check). |
160
160
 
161
161
  The TUI commands open instantly and never feed the LLM; `/df-init`,
@@ -1,6 +1,12 @@
1
1
  import type { HookState } from "./registry.js";
2
- import type { RuntimeStatus } from "./runtime-status.js";
2
+ import type { RuntimeStatus, TemplateState } from "./runtime-status.js";
3
3
  import type { ResolvedConfig } from "./types.js";
4
+ /**
5
+ * One-line template drift state for `/df-runtime`: up to date, drifted
6
+ * (run `/df-update`), or nothing installed (run `/df-init`). Absent
7
+ * state (older snapshot) renders as unknown, never as current.
8
+ */
9
+ export declare function renderTemplateState(templates: TemplateState | undefined): string;
4
10
  /**
5
11
  * Render the config-only portion of the status summary.
6
12
  *
@@ -21,8 +27,9 @@ export declare function renderHelp(): string;
21
27
  export declare function renderStatus(config: ResolvedConfig, state?: HookState | null): string;
22
28
  /**
23
29
  * Render the runtime snapshot for the TUI `/df-runtime` command: plugin
24
- * version, which session-hook method the core accepted, and dispatch
25
- * history. A null snapshot (server hasn't reported yet) renders as such —
26
- * never as a negative claim about the hook.
30
+ * version, which session-hook method the core accepted, dispatch
31
+ * history, and template drift state. A null snapshot (server hasn't
32
+ * reported yet) renders as such — never as a negative claim about the
33
+ * hook. A snapshot without template state (older server) says unknown.
27
34
  */
28
35
  export declare function renderRuntimeStatus(snapshot: RuntimeStatus | null): string;
@@ -1,3 +1,21 @@
1
+ /**
2
+ * One-line template drift state for `/df-runtime`: up to date, drifted
3
+ * (run `/df-update`), or nothing installed (run `/df-init`). Absent
4
+ * state (older snapshot) renders as unknown, never as current.
5
+ */
6
+ export function renderTemplateState(templates) {
7
+ if (templates === undefined) {
8
+ return "Templates: state unknown (no report yet)";
9
+ }
10
+ if (templates.state === "empty") {
11
+ return "Templates: not installed — run /df-init";
12
+ }
13
+ if (templates.state === "current") {
14
+ return `Templates: up to date (${templates.current}/${templates.total} match)`;
15
+ }
16
+ return (`Templates: drifted (${templates.refresh} to refresh, ${templates.add} to add) ` +
17
+ "— run /df-update");
18
+ }
1
19
  function formatCommandMap(map, indent) {
2
20
  if (map === undefined) {
3
21
  return `${indent}(not configured)`;
@@ -159,9 +177,10 @@ export function renderStatus(config, state) {
159
177
  }
160
178
  /**
161
179
  * Render the runtime snapshot for the TUI `/df-runtime` command: plugin
162
- * version, which session-hook method the core accepted, and dispatch
163
- * history. A null snapshot (server hasn't reported yet) renders as such —
164
- * never as a negative claim about the hook.
180
+ * version, which session-hook method the core accepted, dispatch
181
+ * history, and template drift state. A null snapshot (server hasn't
182
+ * reported yet) renders as such — never as a negative claim about the
183
+ * hook. A snapshot without template state (older server) says unknown.
165
184
  */
166
185
  export function renderRuntimeStatus(snapshot) {
167
186
  const lines = ["dev-framework runtime", ""];
@@ -171,6 +190,7 @@ export function renderRuntimeStatus(snapshot) {
171
190
  return lines.join("\n");
172
191
  }
173
192
  lines.push(`Framework: v${snapshot.frameworkVersion} (snapshot as of ${snapshot.updatedAt})`);
193
+ lines.push(renderTemplateState(snapshot.templates));
174
194
  lines.push(snapshot.idleHookVia === "none"
175
195
  ? "Idle hook: not registered — event-subscribe fallback only"
176
196
  : `Idle hook: registered via ${snapshot.idleHookVia}`);
package/dist/harness.d.ts CHANGED
@@ -26,6 +26,21 @@ import type { ResolvedConfig } from "./types.js";
26
26
  import { type EnforceableSnapshot } from "./weakening.js";
27
27
  /** Project-relative path of the peer-review artifact the agent must produce. */
28
28
  export declare const REVIEW_ARTIFACT_REL = ".opencode/opencode-dev-framework/review.md";
29
+ /**
30
+ * True when a tool-call target is the review artifact. Normalizes like the
31
+ * guardrail path matcher (absolute paths resolve against the project
32
+ * directory) plus `normalize`, so non-canonical spellings (`a/../b`,
33
+ * `././x`) compare by where they resolve, not how they are spelled.
34
+ * Matches the exact artifact only — never a prefix or a similarly-named
35
+ * file.
36
+ */
37
+ export declare function isReviewArtifact(filePath: string, directory?: string): boolean;
38
+ /**
39
+ * Shared denial text for the child-session artifact guard (plan 23): one
40
+ * spelling, referenced from both enforcement layers so a wording fix can
41
+ * never update one site and miss the other.
42
+ */
43
+ export declare function childArtifactDenial(): string;
29
44
  /** Project-relative path of the pre-flight artifact the agent must produce. */
30
45
  export declare const PREFLIGHT_ARTIFACT_REL = ".opencode/opencode-dev-framework/preflight.md";
31
46
  /**
package/dist/harness.js CHANGED
@@ -17,13 +17,38 @@
17
17
  * synthetic continuation) and the `session.idle` event net (re-prompt).
18
18
  */
19
19
  import { readFile, stat } from "node:fs/promises";
20
- import { join } from "node:path";
20
+ import { isAbsolute, join, normalize, relative } from "node:path";
21
21
  import { runGate, summarizeGate } from "./gate.js";
22
22
  import { assessReviewContent, findUncoveredFiles, normalizeReviewPath, staleReviewMessage, templateReviewMessage, thinReviewMessage, } from "./review.js";
23
23
  import { RUNTIME_STATUS_DIR, RUNTIME_STATUS_FILE } from "./runtime-status.js";
24
24
  import { diffWeakening } from "./weakening.js";
25
25
  /** Project-relative path of the peer-review artifact the agent must produce. */
26
26
  export const REVIEW_ARTIFACT_REL = ".opencode/opencode-dev-framework/review.md";
27
+ /**
28
+ * True when a tool-call target is the review artifact. Normalizes like the
29
+ * guardrail path matcher (absolute paths resolve against the project
30
+ * directory) plus `normalize`, so non-canonical spellings (`a/../b`,
31
+ * `././x`) compare by where they resolve, not how they are spelled.
32
+ * Matches the exact artifact only — never a prefix or a similarly-named
33
+ * file.
34
+ */
35
+ export function isReviewArtifact(filePath, directory) {
36
+ let candidate = filePath;
37
+ if (directory !== undefined && isAbsolute(filePath)) {
38
+ candidate = relative(directory, filePath);
39
+ }
40
+ return normalize(candidate) === normalize(REVIEW_ARTIFACT_REL);
41
+ }
42
+ /**
43
+ * Shared denial text for the child-session artifact guard (plan 23): one
44
+ * spelling, referenced from both enforcement layers so a wording fix can
45
+ * never update one site and miss the other.
46
+ */
47
+ export function childArtifactDenial() {
48
+ return (`child sessions never write ${REVIEW_ARTIFACT_REL}: the review duty belongs ` +
49
+ `to the top-level session — report back as text and let the orchestrator ` +
50
+ `write the artifact`);
51
+ }
27
52
  /** Project-relative path of the pre-flight artifact the agent must produce. */
28
53
  export const PREFLIGHT_ARTIFACT_REL = ".opencode/opencode-dev-framework/preflight.md";
29
54
  /**
package/dist/index.js CHANGED
@@ -25,20 +25,22 @@
25
25
  * docs/plans/12-idle-hook-cutover.md). The `event.subscribe` idle net
26
26
  * stays as a deduped fallback for the boundaries the hook skips.
27
27
  */
28
- import { Plugin } from "@opencode/plugin";
29
28
  import { stat } from "node:fs/promises";
30
29
  import { join } from "node:path";
30
+ import { Plugin } from "@opencode/plugin";
31
31
  import { createBlockStore, createStuckSnapshotStore, } from "./block-store.js";
32
32
  import { clearConfigCache, loadConfig } from "./config.js";
33
33
  import { createChangedFileTracker } from "./gate.js";
34
- import { artifactState, createPassCache, evaluateCompletion, PREFLIGHT_ARTIFACT_REL, preflightBlockReason, } from "./harness.js";
34
+ import { artifactState, childArtifactDenial, createPassCache, evaluateCompletion, isReviewArtifact, PREFLIGHT_ARTIFACT_REL, preflightBlockReason, } from "./harness.js";
35
35
  import { runCommand } from "./host.js";
36
36
  import { createLintLimiter, detectPreCommitAvailability, isLintFailure, lintFile, summarizeLint, } from "./lint.js";
37
37
  import { createLogger } from "./logger.js";
38
- import { checkToolCall, extractFilePath, FILE_TOOLS, toPermissionGuard } from "./protect.js";
39
- import { constitutionPresent, loadConstitution } from "./rules.js";
38
+ import { checkToolCall, extractCommand, extractFilePath, extractRedirectTargets, FILE_TOOLS, SHELL_TOOLS, toPermissionGuard, } from "./protect.js";
39
+ import { clearSessionDirectory, hasSeenSessionStart, markSessionStartSeen, resolveIsChildSession, } from "./registry.js";
40
40
  import { findRosterIndex, renderDutyRoster, rosterPresent } from "./roster.js";
41
+ import { constitutionPresent, loadConstitution } from "./rules.js";
41
42
  import { writeRuntimeStatus } from "./runtime-status.js";
43
+ import { checkTemplateUpdates, driftMentionLine, summarizeDrift } from "./update.js";
42
44
  import { snapshotEnforceable } from "./weakening.js";
43
45
  let activeState = null;
44
46
  let fallbackLog = async () => { };
@@ -178,6 +180,21 @@ function runCompletion(state, sessionID) {
178
180
  log: (level, message, extra) => safeLog(state, level, message, extra),
179
181
  });
180
182
  }
183
+ /**
184
+ * Build the host session lookup for child detection, defensively: older
185
+ * cores (and stub contexts in tests) may not expose `session.get`, in
186
+ * which case every session reads as top-level and behavior is unchanged.
187
+ * The lookup is cached per sessionID inside `resolveIsChildSession`, so the
188
+ * steady state pays one call per session lifetime.
189
+ */
190
+ function childSessionGetter(ctx) {
191
+ const session = ctx.session;
192
+ if (typeof session.get !== "function")
193
+ return undefined;
194
+ // Called as a method so the receiver is preserved (a detached `get`
195
+ // could throw on `this`-dependent adapters and fail open to top-level).
196
+ return (id) => session.get({ sessionID: id });
197
+ }
181
198
  /**
182
199
  * Record a completed idle-hook evaluation for the dedup map. Stamp ONLY on
183
200
  * the completed-evaluation paths (pass, blocked-admitted, standdown);
@@ -186,6 +203,22 @@ function runCompletion(state, sessionID) {
186
203
  function stampIdleHandled(state, sessionID) {
187
204
  state.lastIdleHandled.set(sessionID, Date.now());
188
205
  }
206
+ /**
207
+ * Best-effort runtime snapshot for `/df-runtime`: hook state plus template
208
+ * drift, fire-and-forget (never throws, never blocks the caller).
209
+ */
210
+ function stampRuntimeStatus(directory, idleHookVia, continuation) {
211
+ void (async () => {
212
+ let templates;
213
+ try {
214
+ templates = summarizeDrift(await checkTemplateUpdates(directory));
215
+ }
216
+ catch {
217
+ // Best-effort: the snapshot renders without template state.
218
+ }
219
+ await writeRuntimeStatus(directory, { idleHookVia, continuation, templates });
220
+ })();
221
+ }
189
222
  /**
190
223
  * True when the idle hook completed an evaluation for this session inside
191
224
  * `windowMs`. The hook itself uses a short window (same-boundary
@@ -304,6 +337,10 @@ const plugin = Plugin.define({
304
337
  lastIdleHandled: new Map(),
305
338
  };
306
339
  activeState = state;
340
+ // Child-session detection for the review-duty guard (plan 23 phase 1):
341
+ // one cached host lookup per session lifetime; undefined on older
342
+ // cores, where every session reads as top-level (behavior unchanged).
343
+ const sessionGetter = childSessionGetter(ctx);
307
344
  // Surface a broken storage backend early (best-effort, never thrown).
308
345
  // With the stop-level hydration gone there is no setup-time storage
309
346
  // read left, so this rarely fires here — the store still degrades
@@ -360,6 +397,27 @@ const plugin = Plugin.define({
360
397
  await safeLog(state, "debug", "duty roster injected into system prompt");
361
398
  }
362
399
  }
400
+ // 1a) Startup template-drift mention — once per session, best-effort.
401
+ // First `context` sighting of a sessionID is session startup (plugin
402
+ // `setup()` has no session to mention into). Drifted installs get one
403
+ // line pointing at `/df-update`; current and empty trees stay silent.
404
+ // Never throws into prompt assembly; never writes.
405
+ const startupID = getEventSessionID(event);
406
+ if (startupID !== undefined && !hasSeenSessionStart(startupID)) {
407
+ markSessionStartSeen(startupID);
408
+ try {
409
+ const line = driftMentionLine(await checkTemplateUpdates(state.directory));
410
+ if (line !== null) {
411
+ event.system.push({ type: "text", text: line });
412
+ await safeLog(state, "debug", "template drift mentioned at session startup");
413
+ }
414
+ }
415
+ catch (error) {
416
+ await safeLog(state, "debug", "startup drift check failed silently", {
417
+ error: String(error),
418
+ });
419
+ }
420
+ }
363
421
  }));
364
422
  // Also hook other request kinds so the reminder is not missed on title/generate
365
423
  // (no-op if model doesn't need it; cheap)
@@ -413,6 +471,16 @@ const plugin = Plugin.define({
413
471
  getEventSessionID(event);
414
472
  if (!sessionID)
415
473
  return;
474
+ // Child sessions owe no review duty (plan 23 phase 1): the review
475
+ // artifact belongs to the top-level session, so a child idling on
476
+ // a dirty tree must never be blocked or told to write it. Skip
477
+ // before any gate work; both levers share this predicate.
478
+ if (await resolveIsChildSession(sessionID, sessionGetter)) {
479
+ await safeLog(state, "debug", "completion gate skipped: child session owes no review duty", {
480
+ sessionID,
481
+ });
482
+ return;
483
+ }
416
484
  await reloadConfigIfChanged(state);
417
485
  if (state.config.profile === "off")
418
486
  return;
@@ -432,7 +500,7 @@ const plugin = Plugin.define({
432
500
  // Pass/stand-down: completed evaluation, nothing to admit.
433
501
  stampIdleHandled(state, sessionID);
434
502
  state.continuationLevel = "idle";
435
- void writeRuntimeStatus(state.directory, { idleHookVia, continuation: "idle" });
503
+ stampRuntimeStatus(state.directory, idleHookVia, "idle");
436
504
  return;
437
505
  }
438
506
  // Blocked: admit a synthetic continuation (same execution).
@@ -447,7 +515,7 @@ const plugin = Plugin.define({
447
515
  await ctx.session.synthetic({ sessionID, text: message });
448
516
  stampIdleHandled(state, sessionID);
449
517
  state.continuationLevel = "idle";
450
- void writeRuntimeStatus(state.directory, { idleHookVia, continuation: "idle" });
518
+ stampRuntimeStatus(state.directory, idleHookVia, "idle");
451
519
  await safeLog(state, "info", `completion gate continued session ${sessionID} via idle hook`, {
452
520
  sessionID,
453
521
  blockCount: verdict.blockCount,
@@ -480,7 +548,7 @@ const plugin = Plugin.define({
480
548
  }
481
549
  // Record the registration outcome for `/df-runtime` even before the
482
550
  // first dispatch: "armed" is a real state, not a missing one.
483
- void writeRuntimeStatus(state.directory, { idleHookVia, continuation: "armed" });
551
+ stampRuntimeStatus(state.directory, idleHookVia, "armed");
484
552
  await safeLog(state, "info", "registered experimental.idle hook (+ idle alias); gate failures continue the same execution via synthetic");
485
553
  // 2a) Native permission layer (Phase 25): `permission.evaluate` fires
486
554
  // with `{action, resources, effect}` (shapes recorded in the 25.1 spike,
@@ -542,6 +610,35 @@ const plugin = Plugin.define({
542
610
  return;
543
611
  }
544
612
  }
613
+ // Child sessions never write the parent's review artifact (plan 23
614
+ // phase 1, defense-in-depth behind execute.before). Checked before
615
+ // guardrails so the specific duty message wins and a future
616
+ // pipeline reorder cannot strand this check behind a guardrail
617
+ // early-return. Consulted only for artifact targets.
618
+ {
619
+ let resourceHitsArtifact = false;
620
+ if (action === "edit") {
621
+ resourceHitsArtifact = event.resources.some((r) => r !== undefined && isReviewArtifact(r, state.directory));
622
+ }
623
+ else if (action === "shell" && event.resources[0] !== undefined) {
624
+ resourceHitsArtifact = extractRedirectTargets(event.resources[0]).some((t) => isReviewArtifact(t, state.directory));
625
+ }
626
+ if (resourceHitsArtifact) {
627
+ const childID = typeof event.sessionID === "string" ? event.sessionID : "";
628
+ if (await resolveIsChildSession(childID, sessionGetter)) {
629
+ const reason = childArtifactDenial();
630
+ if (state.config.profile === "advisory") {
631
+ await safeLog(state, "debug", reason, { ...baseExtra });
632
+ }
633
+ else {
634
+ event.effect = "deny";
635
+ event.message = reason;
636
+ await safeLog(state, "error", reason, { ...baseExtra });
637
+ }
638
+ return;
639
+ }
640
+ }
641
+ }
545
642
  const verdict = toPermissionGuard(state.config, action, event.resources, state.directory);
546
643
  if (verdict === null) {
547
644
  await safeLog(state, "debug", `permission.evaluate action=${action} effect=${event.effect} (no guardrail verdict; engine default wins)`, { ...baseExtra, effect: event.effect });
@@ -585,6 +682,31 @@ const plugin = Plugin.define({
585
682
  const toolName = event.tool;
586
683
  const input = event.input;
587
684
  const sessionID = event.sessionID;
685
+ // Child sessions never write the parent's review artifact (plan 23
686
+ // phase 1). Checked only for artifact targets so ordinary calls pay
687
+ // zero lookup cost. Covers edit tools by target path and shell tools
688
+ // by redirect/`tee` target: a bare mention of the path in a command
689
+ // (grep, cat without redirect) is not a write and stays allowed.
690
+ const editTarget = extractFilePath(input);
691
+ const writesArtifact = (editTarget !== undefined &&
692
+ FILE_TOOLS.has(toolName) &&
693
+ isReviewArtifact(editTarget, state.directory)) ||
694
+ (SHELL_TOOLS.has(toolName) &&
695
+ extractRedirectTargets(extractCommand(input) ?? "").some((t) => isReviewArtifact(t, state.directory)));
696
+ if (writesArtifact) {
697
+ const childID = typeof sessionID === "string" ? sessionID : "";
698
+ if (await resolveIsChildSession(childID, sessionGetter)) {
699
+ const reason = childArtifactDenial();
700
+ const extra = { tool: toolName, sessionID };
701
+ if (state.config.profile === "advisory") {
702
+ await safeLog(state, "warn", reason, extra);
703
+ }
704
+ else {
705
+ await safeLog(state, "error", reason, extra);
706
+ throw new Error(`[opencode-dev-framework] ${reason}`);
707
+ }
708
+ }
709
+ }
588
710
  // Pre-flight harness: when `preflight:` tasks are configured, file
589
711
  // edits are denied (standard/strict) until the pre-flight artifact
590
712
  // exists. This is a true hard gate — it runs before the edit lands.
@@ -851,7 +973,7 @@ const plugin = Plugin.define({
851
973
  "(teardown or reload raced the command); retry /df-init.");
852
974
  }
853
975
  const { runInitCommand } = await import("./init.js");
854
- await runInitCommand({
976
+ const delivered = await runInitCommand({
855
977
  directory: state.directory,
856
978
  run: state.run,
857
979
  delivery: invocation.delivery,
@@ -890,6 +1012,9 @@ const plugin = Plugin.define({
890
1012
  await safeLog(state, level, message, extra);
891
1013
  },
892
1014
  });
1015
+ if (!delivered) {
1016
+ await safeLog(state, "info", "df-init: already configured and clean, staying silent (no handoff)");
1017
+ }
893
1018
  },
894
1019
  });
895
1020
  }));
@@ -916,7 +1041,7 @@ const plugin = Plugin.define({
916
1041
  "(teardown or reload raced the command); retry /df-update.");
917
1042
  }
918
1043
  const { runUpdateCommand } = await import("./update.js");
919
- await runUpdateCommand({
1044
+ const delivered = await runUpdateCommand({
920
1045
  directory: state.directory,
921
1046
  delivery: invocation.delivery,
922
1047
  checkAlive: () => {
@@ -933,6 +1058,9 @@ const plugin = Plugin.define({
933
1058
  });
934
1059
  },
935
1060
  });
1061
+ if (!delivered) {
1062
+ await safeLog(state, "info", "df-update: templates current, staying silent (no handoff)");
1063
+ }
936
1064
  },
937
1065
  });
938
1066
  }));
@@ -960,12 +1088,14 @@ const plugin = Plugin.define({
960
1088
  const type = event.type;
961
1089
  if (isSessionDeletedEvent(type)) {
962
1090
  // session.deleted: cleanup block counts + stuck snapshots
963
- // (memory + storage) and the idle dedup stamp for the session.
1091
+ // (memory + storage), the idle dedup stamp, and the startup
1092
+ // registries (directory mapping + drift-mention seen-set).
964
1093
  const sid = getEventSessionID(event);
965
1094
  if (sid) {
966
1095
  await state.blocks.clear(sid);
967
1096
  await state.stuckSnapshots.clear(sid);
968
1097
  state.lastIdleHandled.delete(sid);
1098
+ clearSessionDirectory(sid);
969
1099
  }
970
1100
  continue;
971
1101
  }
@@ -1004,6 +1134,12 @@ const plugin = Plugin.define({
1004
1134
  const sessionID = getEventSessionID(event);
1005
1135
  if (!sessionID)
1006
1136
  continue;
1137
+ // Same child-session skip as the hook lever above: no duty, no
1138
+ // verdict, no re-prompt — the parent answers for the tree.
1139
+ if (await resolveIsChildSession(sessionID, sessionGetter)) {
1140
+ await safeLog(state, "debug", "completion gate skipped: child session owes no review duty", { sessionID });
1141
+ continue;
1142
+ }
1007
1143
  // The §1b hook completed an evaluation for this boundary — one
1008
1144
  // boundary, one gate run. (Deliberately not stamped here: only
1009
1145
  // the hook stamps, so a hook that never fires can never be
@@ -1013,7 +1149,7 @@ const plugin = Plugin.define({
1013
1149
  const verdict = await runCompletion(state, sessionID);
1014
1150
  if (state.continuationLevel === undefined) {
1015
1151
  state.continuationLevel = "fallback";
1016
- void writeRuntimeStatus(state.directory, { idleHookVia, continuation: "fallback" });
1152
+ stampRuntimeStatus(state.directory, idleHookVia, "fallback");
1017
1153
  }
1018
1154
  const message = await actOnVerdict(state, verdict);
1019
1155
  if (message === null)
package/dist/init.d.ts CHANGED
@@ -25,6 +25,15 @@ export interface InitScaffold {
25
25
  /** True when this run changed anything (templates or config). */
26
26
  fresh: boolean;
27
27
  }
28
+ /**
29
+ * Whether the scaffold result needs an agent handoff (a turn). Fresh
30
+ * scaffolds do (the agent must resolve the brief); re-runs with warnings
31
+ * do (reload/trial failures the user came to fix must be relayed). A clean
32
+ * re-run stays silent: the server command API returns void, so any
33
+ * delivery costs a full agent turn, and an "already configured" turn is
34
+ * pure waste.
35
+ */
36
+ export declare function initNeedsHandoff(scaffold: InitScaffold, warnings?: string[]): boolean;
28
37
  export declare function runInitScaffold(directory: string, run: RunCommand, options?: InitScaffoldOptions): Promise<InitScaffold>;
29
38
  export declare function scaffoldReportLines(scaffold: InitScaffold, directory: string): string[];
30
39
  /**
@@ -53,10 +62,14 @@ export interface InitCommandDeps {
53
62
  * Execute the `/df-init` command with injected dependencies (pure policy,
54
63
  * testable without a plugin context). Scaffold first, re-check liveness
55
64
  * across the long await (file IO + trial-runs), reload the just-written
56
- * config, then deliver the handoff. A reload failure degrades to a
65
+ * config, then deliver the handoff — but only when it needs an agent
66
+ * handoff (fresh scaffold, or warnings). A clean re-run returns `false`
67
+ * without delivering: the server command API returns void, so any
68
+ * delivery costs a full agent turn. A reload failure degrades to a
57
69
  * warning inside the prompt — `/df-init` is the command you run to fix
58
70
  * a broken setup, so it must not fail on exactly the broken setups.
59
71
  * A delivery failure throws: the scaffold succeeded, only the handoff
60
- * back failed, and the message says how to recover.
72
+ * back failed, and the message says how to recover. Returns whether the
73
+ * handoff was delivered.
61
74
  */
62
- export declare function runInitCommand(deps: InitCommandDeps): Promise<void>;
75
+ export declare function runInitCommand(deps: InitCommandDeps): Promise<boolean>;
package/dist/init.js CHANGED
@@ -11,6 +11,17 @@
11
11
  */
12
12
  import { detectProject } from "./detect.js";
13
13
  import { buildWizardBrief, formatBriefSkipped, formatTrialRun, formatWizardBrief, installTemplates, trialRunDetectedCommands, writeDetectedConfig, } from "./installer.js";
14
+ /**
15
+ * Whether the scaffold result needs an agent handoff (a turn). Fresh
16
+ * scaffolds do (the agent must resolve the brief); re-runs with warnings
17
+ * do (reload/trial failures the user came to fix must be relayed). A clean
18
+ * re-run stays silent: the server command API returns void, so any
19
+ * delivery costs a full agent turn, and an "already configured" turn is
20
+ * pure waste.
21
+ */
22
+ export function initNeedsHandoff(scaffold, warnings = []) {
23
+ return scaffold.fresh || warnings.length > 0;
24
+ }
14
25
  export async function runInitScaffold(directory, run, options = {}) {
15
26
  const overwrite = options.overwrite ?? false;
16
27
  const io = { overwriteExisting: overwrite, skipExisting: !overwrite };
@@ -110,11 +121,15 @@ export function composeInitPrompt(scaffold, directory, warnings = []) {
110
121
  * Execute the `/df-init` command with injected dependencies (pure policy,
111
122
  * testable without a plugin context). Scaffold first, re-check liveness
112
123
  * across the long await (file IO + trial-runs), reload the just-written
113
- * config, then deliver the handoff. A reload failure degrades to a
124
+ * config, then deliver the handoff — but only when it needs an agent
125
+ * handoff (fresh scaffold, or warnings). A clean re-run returns `false`
126
+ * without delivering: the server command API returns void, so any
127
+ * delivery costs a full agent turn. A reload failure degrades to a
114
128
  * warning inside the prompt — `/df-init` is the command you run to fix
115
129
  * a broken setup, so it must not fail on exactly the broken setups.
116
130
  * A delivery failure throws: the scaffold succeeded, only the handoff
117
- * back failed, and the message says how to recover.
131
+ * back failed, and the message says how to recover. Returns whether the
132
+ * handoff was delivered.
118
133
  */
119
134
  export async function runInitCommand(deps) {
120
135
  const scaffold = await runInitScaffold(deps.directory, deps.run, { wizard: true });
@@ -131,6 +146,9 @@ export async function runInitCommand(deps) {
131
146
  error: detail,
132
147
  });
133
148
  }
149
+ if (!initNeedsHandoff(scaffold, warnings)) {
150
+ return false;
151
+ }
134
152
  const text = composeInitPrompt(scaffold, deps.directory, warnings);
135
153
  try {
136
154
  await deps.deliver(text, deps.delivery);
@@ -140,4 +158,5 @@ export async function runInitCommand(deps) {
140
158
  throw new Error(`df-init scaffolded ${scaffold.created.length} file(s) (config ${scaffold.configAction}) ` +
141
159
  `but the handoff back to the session failed (${detail}); retry /df-init — a re-run reports status without touching anything.`);
142
160
  }
161
+ return true;
143
162
  }
package/dist/installer.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import { dirname, join, resolve } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
3
  import { createInterface } from "node:readline";
4
+ import { fileURLToPath } from "node:url";
5
5
  import { splitCommand } from "./command-utils.js";
6
6
  import { checkConfigEnforceable, DEFAULT_PROTECT, resolveConfig } from "./config.js";
7
7
  import { detectProject } from "./detect.js";
package/dist/protect.d.ts CHANGED
@@ -26,6 +26,16 @@ export declare const DANGEROUS_COMMANDS: DangerousCommand[];
26
26
  export declare function extractFilePath(args: unknown): string | undefined;
27
27
  /** Extract the shell command from tool args, if present. */
28
28
  export declare function extractCommand(args: unknown): string | undefined;
29
+ /**
30
+ * Extract probable file-write targets from a shell command: filenames after
31
+ * output redirections (`>`, `>>`, with optional fd/`&` prefixes, glued or
32
+ * spaced) and operands of `tee` in command position. Heredocs (`<<`) and
33
+ * herestrings (`<<<`) carry input, never a target, so they are ignored.
34
+ * Token-based and deliberately over-collecting within a command tail: that
35
+ * is harmless because callers only act on exact artifact matches, while a
36
+ * false negative would reopen a write path. Quote-aware.
37
+ */
38
+ export declare function extractRedirectTargets(command: string): string[];
29
39
  /**
30
40
  * Check a file path against the protected globs. Returns the matching
31
41
  * pattern, or undefined. Patterns without a slash also match basenames at
package/dist/protect.js CHANGED
@@ -52,6 +52,97 @@ export function extractCommand(args) {
52
52
  }
53
53
  return undefined;
54
54
  }
55
+ /**
56
+ * Extract probable file-write targets from a shell command: filenames after
57
+ * output redirections (`>`, `>>`, with optional fd/`&` prefixes, glued or
58
+ * spaced) and operands of `tee` in command position. Heredocs (`<<`) and
59
+ * herestrings (`<<<`) carry input, never a target, so they are ignored.
60
+ * Token-based and deliberately over-collecting within a command tail: that
61
+ * is harmless because callers only act on exact artifact matches, while a
62
+ * false negative would reopen a write path. Quote-aware.
63
+ */
64
+ export function extractRedirectTargets(command) {
65
+ const targets = [];
66
+ // Operators and separators stay visible as tokens so `tee` is only
67
+ // honored in command position (not inside quoted prose).
68
+ const tokens = [];
69
+ const tokenRe = /"([^"]*)"|'([^']*)'|&&|\|\||[;|&()!<>]+|[^\s;|&<>()!]+/g;
70
+ for (let m = tokenRe.exec(command); m !== null; m = tokenRe.exec(command)) {
71
+ tokens.push(m[1] ?? m[2] ?? m[0]);
72
+ }
73
+ const isSeparator = (t) => /^(?:&&|\|\||[;|&()!<>]+)$/.test(t);
74
+ const isBareRedirect = (t) => /^(?:\d*>>?\|?|&>>?\|?)$/.test(t);
75
+ // Wrappers that pass through to the real command: `sudo tee`, `env A=B
76
+ // tee`, `VAR=val tee`, `/usr/bin/tee`. A bare `tee` elsewhere (prose,
77
+ // array contents) is not a command.
78
+ const isWrapper = (t) => /^(?:sudo|command|env|nice|nohup|stdbuf|time|xargs)$/.test(t) ||
79
+ /^[A-Za-z_][A-Za-z0-9_]*=/.test(t);
80
+ const cmdBase = (t) => t.split("/").pop() ?? t;
81
+ // A few shell commands take plain argv paths as write targets (no
82
+ // redirect involved): `cp`/`mv`/`install` write their last operand,
83
+ // `sed -i` rewrites every file operand, `ed`/`ex` edit their first.
84
+ const ARG_WRITERS_LAST = new Set(["cp", "mv", "install"]);
85
+ const ARG_WRITERS_FIRST = new Set(["ed", "ex"]);
86
+ const collectOperands = (from) => {
87
+ const operands = [];
88
+ for (let j = from; j < tokens.length; j++) {
89
+ const next = tokens[j];
90
+ if (isSeparator(next) || isBareRedirect(next))
91
+ break;
92
+ if (!next.startsWith("-") && next !== "")
93
+ operands.push(next);
94
+ }
95
+ return operands;
96
+ };
97
+ for (let i = 0; i < tokens.length; i++) {
98
+ const token = tokens[i];
99
+ const atCommand = i === 0 || isSeparator(tokens[i - 1]) || isBareRedirect(tokens[i - 1]);
100
+ const base = cmdBase(token);
101
+ if (base === "tee" && (atCommand || isWrapper(tokens[i - 1] ?? ""))) {
102
+ // `tee` writes every non-flag operand that follows it.
103
+ for (const next of collectOperands(i + 1)) {
104
+ if (next === "tee")
105
+ break;
106
+ targets.push(next);
107
+ }
108
+ continue;
109
+ }
110
+ if (atCommand && (ARG_WRITERS_LAST.has(base) || ARG_WRITERS_FIRST.has(base))) {
111
+ const operands = collectOperands(i + 1);
112
+ const pick = ARG_WRITERS_LAST.has(base) ? operands.at(-1) : operands[0];
113
+ if (pick !== undefined)
114
+ targets.push(pick);
115
+ continue;
116
+ }
117
+ if (atCommand &&
118
+ base === "sed" &&
119
+ tokens.some((t, k) => k > i && (t === "-i" || t === "--in-place" || /^-i./.test(t)))) {
120
+ // First non-flag operand is the script; the rest are files.
121
+ let skippedScript = false;
122
+ for (const next of collectOperands(i + 1)) {
123
+ if (!skippedScript) {
124
+ skippedScript = true;
125
+ continue;
126
+ }
127
+ targets.push(next);
128
+ }
129
+ continue;
130
+ }
131
+ if (isBareRedirect(token)) {
132
+ const next = tokens[i + 1];
133
+ if (next !== undefined && next !== "" && !isSeparator(next))
134
+ targets.push(next);
135
+ continue;
136
+ }
137
+ // Glued forms: `2>file`, `>file`, `&>>file`. Exclude `<<`/`<<<`.
138
+ if (token.includes(">") && !token.includes("<")) {
139
+ const after = token.replace(/^.*?(?:\d*>>?|&>>?)/, "").replace(/^["']|["']$/g, "");
140
+ if (after !== "")
141
+ targets.push(after);
142
+ }
143
+ }
144
+ return targets;
145
+ }
55
146
  /**
56
147
  * Check a file path against the protected globs. Returns the matching
57
148
  * pattern, or undefined. Patterns without a slash also match basenames at
@@ -45,10 +45,24 @@ export declare function setHookState(directory: string, state: HookState): void;
45
45
  export declare function getHookState(directoryHint?: string): HookState | null;
46
46
  export declare function getStateForSession(sessionID: string | undefined): HookState | null;
47
47
  export declare function updateHookState(directory: string, updates: Partial<HookState>): HookState | null;
48
+ /** Structural parent link returned by the host session lookup. */
49
+ export interface SessionParentInfo {
50
+ parentID?: string | null | undefined;
51
+ }
52
+ /**
53
+ * True when the session is a child (subagent): its host record carries a
54
+ * parentID. Results are cached per sessionID. Fails closed to `false`
55
+ * (top-level): a missing getter (older core), an empty sessionID, or a
56
+ * lookup throw preserves the pre-guard behavior exactly — the session is
57
+ * gated and may write, as before. Never throws.
58
+ */
59
+ export declare function resolveIsChildSession(sessionID: string, getSession?: (id: string) => Promise<SessionParentInfo | null | undefined>): Promise<boolean>;
48
60
  export declare function setSessionDirectory(sessionID: string, directory: string): void;
49
61
  export declare function getDirectoryForSession(sessionID: string): string | null;
50
62
  /** Forget a session's directory mapping (called on `session.deleted`). */
51
63
  export declare function clearSessionDirectory(sessionID: string): void;
64
+ export declare function hasSeenSessionStart(sessionID: string): boolean;
65
+ export declare function markSessionStartSeen(sessionID: string): void;
52
66
  /** Reset all in-memory registries. Intended for test cleanup between
53
67
  * test runs so stale session-to-directory mappings do not bleed
54
68
  * `getStateForSession` into the next test. */
package/dist/registry.js CHANGED
@@ -48,21 +48,78 @@ export function updateHookState(directory, updates) {
48
48
  /** Map session IDs to their project directory so hooks that only receive a
49
49
  * session ID can still find their state. */
50
50
  const sessionToDirectory = new Map();
51
+ /**
52
+ * Child-session verdicts: sessionID → true when the session has a parent
53
+ * (i.e. it is a subagent and never owns review duty). Populated lazily via
54
+ * `resolveIsChildSession` and cleared with everything else in
55
+ * `resetRegistry`. Memory-only like the directory map.
56
+ */
57
+ const childSessionCache = new Map();
58
+ /**
59
+ * True when the session is a child (subagent): its host record carries a
60
+ * parentID. Results are cached per sessionID. Fails closed to `false`
61
+ * (top-level): a missing getter (older core), an empty sessionID, or a
62
+ * lookup throw preserves the pre-guard behavior exactly — the session is
63
+ * gated and may write, as before. Never throws.
64
+ */
65
+ export async function resolveIsChildSession(sessionID, getSession) {
66
+ if (sessionID === "")
67
+ return false;
68
+ const cached = childSessionCache.get(sessionID);
69
+ if (cached !== undefined)
70
+ return cached;
71
+ let isChild = false;
72
+ if (getSession === undefined)
73
+ return false;
74
+ try {
75
+ const info = await getSession(sessionID);
76
+ // Cache only successful lookups that actually resolved a session:
77
+ // a throw or a nullish info (unknown to the host) returns top-level
78
+ // WITHOUT caching, so one transient failure can never permanently pin
79
+ // a child as top-level (which would re-enable the original bug).
80
+ if (info !== null && info !== undefined) {
81
+ const parent = info.parentID;
82
+ isChild = typeof parent === "string" && parent !== "";
83
+ childSessionCache.set(sessionID, isChild);
84
+ }
85
+ return isChild;
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ }
51
91
  export function setSessionDirectory(sessionID, directory) {
52
92
  sessionToDirectory.set(sessionID, directory);
53
93
  }
54
94
  export function getDirectoryForSession(sessionID) {
55
95
  return sessionToDirectory.get(sessionID) ?? null;
56
96
  }
97
+ /** Session IDs already given their startup mention. In-memory like the
98
+ * directory map, so an opencode restart/reload naturally re-arms it. */
99
+ const sessionStartSeen = new Set();
57
100
  /** Forget a session's directory mapping (called on `session.deleted`). */
58
101
  export function clearSessionDirectory(sessionID) {
59
102
  sessionToDirectory.delete(sessionID);
103
+ sessionStartSeen.delete(sessionID);
104
+ // A deleted session's verdict must never outlive it: IDs are unique per
105
+ // session, so this is just hygiene against unbounded growth — but a stale
106
+ // `true` here would wrongly exempt, and a stale `false` wrongly gate, a
107
+ // hypothetical ID reuse. Match the existing per-session eviction contract.
108
+ childSessionCache.delete(sessionID);
109
+ }
110
+ export function hasSeenSessionStart(sessionID) {
111
+ return sessionStartSeen.has(sessionID);
112
+ }
113
+ export function markSessionStartSeen(sessionID) {
114
+ sessionStartSeen.add(sessionID);
60
115
  }
61
116
  /** Reset all in-memory registries. Intended for test cleanup between
62
117
  * test runs so stale session-to-directory mappings do not bleed
63
118
  * `getStateForSession` into the next test. */
64
119
  export function resetRegistry() {
65
120
  sessionToDirectory.clear();
121
+ sessionStartSeen.clear();
122
+ childSessionCache.clear();
66
123
  hookRegistry.clear();
67
124
  activeDirectory = null;
68
125
  }
@@ -15,15 +15,31 @@ export declare const RUNTIME_STATUS_FILE = "runtime-status.json";
15
15
  export type IdleHookVia = "experimental.idle" | "idle" | "none";
16
16
  /** Dispatch history this session: hook-fired, net-fired, or neither yet. */
17
17
  export type ContinuationState = "idle" | "fallback" | "armed";
18
+ /** Template drift state for the TUI `/df-runtime` command: up to date,
19
+ * drifted (run `/df-update`), or nothing installed (run `/df-init`). */
20
+ export interface TemplateState {
21
+ state: "current" | "drifted" | "empty";
22
+ /** Shipped files matching the deployed set. */
23
+ current: number;
24
+ /** Total shipped files. */
25
+ total: number;
26
+ /** Deployed files differing from shipped (refresh candidates). */
27
+ refresh: number;
28
+ /** Shipped files absent (add candidates). */
29
+ add: number;
30
+ }
18
31
  export interface RuntimeStatus {
19
32
  frameworkVersion: string;
20
33
  idleHookVia: IdleHookVia;
21
34
  continuation: ContinuationState;
35
+ /** Absent on snapshots written before template reporting existed. */
36
+ templates?: TemplateState;
22
37
  updatedAt: string;
23
38
  }
24
39
  export declare function snapshotPath(directory: string): string;
25
40
  export declare function writeRuntimeStatus(directory: string, partial: {
26
41
  idleHookVia: IdleHookVia;
27
42
  continuation: ContinuationState;
43
+ templates?: TemplateState;
28
44
  }): Promise<void>;
29
45
  export declare function readRuntimeStatus(directory: string): Promise<RuntimeStatus | null>;
@@ -56,6 +56,16 @@ function isIdleHookVia(value) {
56
56
  function isContinuationState(value) {
57
57
  return value === "idle" || value === "fallback" || value === "armed";
58
58
  }
59
+ function isTemplateState(value) {
60
+ if (typeof value !== "object" || value === null)
61
+ return false;
62
+ const t = value;
63
+ return ((t.state === "current" || t.state === "drifted" || t.state === "empty") &&
64
+ typeof t.current === "number" &&
65
+ typeof t.total === "number" &&
66
+ typeof t.refresh === "number" &&
67
+ typeof t.add === "number");
68
+ }
59
69
  export async function readRuntimeStatus(directory) {
60
70
  try {
61
71
  const parsed = JSON.parse(await readFile(snapshotPath(directory), "utf8"));
@@ -66,6 +76,7 @@ export async function readRuntimeStatus(directory) {
66
76
  frameworkVersion: parsed.frameworkVersion,
67
77
  idleHookVia: isIdleHookVia(parsed.idleHookVia) ? parsed.idleHookVia : "none",
68
78
  continuation: isContinuationState(parsed.continuation) ? parsed.continuation : "armed",
79
+ ...(isTemplateState(parsed.templates) ? { templates: parsed.templates } : {}),
69
80
  updatedAt: parsed.updatedAt,
70
81
  };
71
82
  }
package/dist/update.d.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  * path by construction. The user config (`.opencode-dev-framework.yml`) is
9
9
  * structurally out of scope: it was never in the template set.
10
10
  */
11
+ import type { TemplateState } from "./runtime-status.js";
11
12
  export interface TemplateDrift {
12
13
  /** Shipped files present and identical. */
13
14
  current: string[];
@@ -26,6 +27,29 @@ export declare function checkTemplateUpdates(directory: string): Promise<Templat
26
27
  * standing instructions (present per file, apply only what is approved).
27
28
  */
28
29
  export declare function composeUpdatePrompt(drift: TemplateDrift, directory: string): string;
30
+ /**
31
+ * Summarize drift for the runtime snapshot (`/df-runtime` renders one of
32
+ * three states: up to date, drifted, nothing installed). Pure; counts
33
+ * only, no file lists.
34
+ */
35
+ export declare function summarizeDrift(drift: TemplateDrift): TemplateState;
36
+ /**
37
+ * Whether the drift needs an agent handoff (a turn). Drifted trees do
38
+ * (the agent must diff, present per file, and get approval), and empty
39
+ * trees do too (the `/df-init` redirect guides someone who just invoked
40
+ * the command while exploring — silence would leave zero feedback that
41
+ * anything ran). Current trees ("nothing to do") stay silent: an empty
42
+ * tree's missing files already read as `add`, so the two length checks
43
+ * below cover all three cases with no special-casing.
44
+ */
45
+ export declare function needsAgentHandoff(drift: TemplateDrift): boolean;
46
+ /**
47
+ * One-line startup mention for template drift, or null when there is
48
+ * nothing to say. Installed-but-current and empty trees stay silent: the
49
+ * mention covers drift only (an empty tree is `/df-init` territory, and
50
+ * the command itself already redirects there — no new nag is invented).
51
+ */
52
+ export declare function driftMentionLine(drift: TemplateDrift): string | null;
29
53
  export interface UpdateCommandDeps {
30
54
  directory: string;
31
55
  delivery: unknown;
@@ -37,7 +61,11 @@ export interface UpdateCommandDeps {
37
61
  /**
38
62
  * Execute the `/df-update` command with injected dependencies (pure policy,
39
63
  * testable without a plugin context). Check, re-check liveness across the
40
- * await, then deliver. A delivery failure throws: the check succeeded, only
41
- * the handoff back failed, and the message says how to recover.
64
+ * await, then deliver — but only when the drift needs an agent handoff.
65
+ * A current tree returns `false` without delivering: the server command
66
+ * API returns void, so any delivery costs a full agent turn, and a
67
+ * "nothing to do" turn is pure waste. A delivery failure throws: the check
68
+ * succeeded, only the handoff back failed, and the message says how to
69
+ * recover. Returns whether the handoff was delivered.
42
70
  */
43
- export declare function runUpdateCommand(deps: UpdateCommandDeps): Promise<void>;
71
+ export declare function runUpdateCommand(deps: UpdateCommandDeps): Promise<boolean>;
package/dist/update.js CHANGED
@@ -58,15 +58,75 @@ export function composeUpdatePrompt(drift, directory) {
58
58
  "Report what was applied and what was left alone.");
59
59
  return lines.join("\n");
60
60
  }
61
+ /**
62
+ * Summarize drift for the runtime snapshot (`/df-runtime` renders one of
63
+ * three states: up to date, drifted, nothing installed). Pure; counts
64
+ * only, no file lists.
65
+ */
66
+ export function summarizeDrift(drift) {
67
+ const total = drift.current.length + drift.refresh.length + drift.add.length;
68
+ if (drift.empty) {
69
+ return { state: "empty", current: 0, total, refresh: 0, add: drift.add.length };
70
+ }
71
+ if (drift.refresh.length === 0 && drift.add.length === 0) {
72
+ return { state: "current", current: drift.current.length, total, refresh: 0, add: 0 };
73
+ }
74
+ return {
75
+ state: "drifted",
76
+ current: drift.current.length,
77
+ total,
78
+ refresh: drift.refresh.length,
79
+ add: drift.add.length,
80
+ };
81
+ }
82
+ /**
83
+ * Whether the drift needs an agent handoff (a turn). Drifted trees do
84
+ * (the agent must diff, present per file, and get approval), and empty
85
+ * trees do too (the `/df-init` redirect guides someone who just invoked
86
+ * the command while exploring — silence would leave zero feedback that
87
+ * anything ran). Current trees ("nothing to do") stay silent: an empty
88
+ * tree's missing files already read as `add`, so the two length checks
89
+ * below cover all three cases with no special-casing.
90
+ */
91
+ export function needsAgentHandoff(drift) {
92
+ return drift.refresh.length > 0 || drift.add.length > 0;
93
+ }
94
+ /**
95
+ * One-line startup mention for template drift, or null when there is
96
+ * nothing to say. Installed-but-current and empty trees stay silent: the
97
+ * mention covers drift only (an empty tree is `/df-init` territory, and
98
+ * the command itself already redirects there — no new nag is invented).
99
+ */
100
+ export function driftMentionLine(drift) {
101
+ if (drift.empty || (drift.refresh.length === 0 && drift.add.length === 0)) {
102
+ return null;
103
+ }
104
+ const parts = [];
105
+ if (drift.refresh.length > 0) {
106
+ parts.push(`${drift.refresh.length} to refresh`);
107
+ }
108
+ if (drift.add.length > 0) {
109
+ parts.push(`${drift.add.length} to add`);
110
+ }
111
+ return (`opencode-dev-framework templates have drifted (${parts.join(", ")}). ` +
112
+ "Run /df-update to review each file with approval.");
113
+ }
61
114
  /**
62
115
  * Execute the `/df-update` command with injected dependencies (pure policy,
63
116
  * testable without a plugin context). Check, re-check liveness across the
64
- * await, then deliver. A delivery failure throws: the check succeeded, only
65
- * the handoff back failed, and the message says how to recover.
117
+ * await, then deliver — but only when the drift needs an agent handoff.
118
+ * A current tree returns `false` without delivering: the server command
119
+ * API returns void, so any delivery costs a full agent turn, and a
120
+ * "nothing to do" turn is pure waste. A delivery failure throws: the check
121
+ * succeeded, only the handoff back failed, and the message says how to
122
+ * recover. Returns whether the handoff was delivered.
66
123
  */
67
124
  export async function runUpdateCommand(deps) {
68
125
  const drift = await checkTemplateUpdates(deps.directory);
69
126
  deps.checkAlive();
127
+ if (!needsAgentHandoff(drift)) {
128
+ return false;
129
+ }
70
130
  const text = composeUpdatePrompt(drift, deps.directory);
71
131
  try {
72
132
  await deps.deliver(text, deps.delivery);
@@ -76,4 +136,5 @@ export async function runUpdateCommand(deps) {
76
136
  throw new Error(`df-update detected drift (${drift.refresh.length} to refresh, ${drift.add.length} to add) ` +
77
137
  `but the handoff back to the session failed (${detail}); retry /df-update — it only reads, never writes.`);
78
138
  }
139
+ return true;
79
140
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-dev-framework",
3
- "version": "1.9.0",
3
+ "version": "1.9.2",
4
4
  "description": "OpenCode plugin that enforces project-specific quality gates during AI coding sessions",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -39,6 +39,8 @@
39
39
  "pretest": "npm run build",
40
40
  "lint": "biome lint .",
41
41
  "lint:fix": "biome lint --write .",
42
+ "check": "biome check .",
43
+ "check:fix": "biome check --write .",
42
44
  "format:check": "biome format .",
43
45
  "format:fix": "biome format --write .",
44
46
  "lint:md": "markdownlint-cli2 \"**/*.md\"",
@@ -22,7 +22,10 @@ whenever the user asks for a review of the current changes.
22
22
 
23
23
  These steps are the orchestrator's. If you are running as one of the
24
24
  specialist subagents below, do only your assigned step and report back —
25
- never consolidate, fix, or re-run anything.
25
+ never consolidate, fix, or re-run anything. Only the orchestrator writes
26
+ the review artifact: as a specialist you never write files, your report
27
+ text is your entire output. This overrides any session duty telling you
28
+ to write the review file.
26
29
 
27
30
  1. **Scope the change.** Determine exactly what changed:
28
31