opencode-dev-framework 1.9.4 → 1.10.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.
Files changed (71) hide show
  1. package/README.md +137 -33
  2. package/bin/df +94 -4
  3. package/cordis.patch.yml +17 -0
  4. package/dist/adapters/dsh/extract.d.ts +47 -0
  5. package/dist/adapters/dsh/extract.js +62 -0
  6. package/dist/adapters/dsh/index.d.ts +332 -0
  7. package/dist/adapters/dsh/index.js +1643 -0
  8. package/dist/adapters/opencode/index.d.ts +30 -0
  9. package/dist/{index.js → adapters/opencode/index.js} +138 -251
  10. package/dist/{block-store.d.ts → core/block-store.d.ts} +10 -3
  11. package/dist/{commands.js → core/commands.js} +4 -2
  12. package/dist/{config.d.ts → core/config.d.ts} +16 -4
  13. package/dist/{config.js → core/config.js} +102 -10
  14. package/dist/{format-status.d.ts → core/format-status.d.ts} +13 -2
  15. package/dist/{format-status.js → core/format-status.js} +30 -7
  16. package/dist/{gate.d.ts → core/gate.d.ts} +9 -1
  17. package/dist/{gate.js → core/gate.js} +14 -2
  18. package/dist/{goal.d.ts → core/goal.d.ts} +4 -3
  19. package/dist/{goal.js → core/goal.js} +4 -3
  20. package/dist/{harness.d.ts → core/harness.d.ts} +10 -5
  21. package/dist/{harness.js → core/harness.js} +119 -32
  22. package/dist/{init.d.ts → core/init.d.ts} +18 -1
  23. package/dist/{init.js → core/init.js} +33 -8
  24. package/dist/core/install-dsh.d.ts +67 -0
  25. package/dist/core/install-dsh.js +235 -0
  26. package/dist/{installer.d.ts → core/installer.d.ts} +32 -2
  27. package/dist/{installer.js → core/installer.js} +129 -12
  28. package/dist/{lint.d.ts → core/lint.d.ts} +43 -2
  29. package/dist/{lint.js → core/lint.js} +89 -2
  30. package/dist/{logger.js → core/logger.js} +30 -1
  31. package/dist/core/paths.d.ts +35 -0
  32. package/dist/core/paths.js +41 -0
  33. package/dist/{protect.d.ts → core/protect.d.ts} +18 -4
  34. package/dist/{protect.js → core/protect.js} +85 -34
  35. package/dist/{registry.d.ts → core/registry.d.ts} +36 -15
  36. package/dist/{registry.js → core/registry.js} +66 -52
  37. package/dist/{review.js → core/review.js} +18 -6
  38. package/dist/{rules.d.ts → core/rules.d.ts} +3 -2
  39. package/dist/{rules.js → core/rules.js} +21 -5
  40. package/dist/core/run-hooks.d.ts +138 -0
  41. package/dist/core/run-hooks.js +196 -0
  42. package/dist/{runtime-status.d.ts → core/runtime-status.d.ts} +5 -4
  43. package/dist/{runtime-status.js → core/runtime-status.js} +29 -17
  44. package/dist/{types.d.ts → core/types.d.ts} +17 -0
  45. package/dist/{update.d.ts → core/update.d.ts} +12 -4
  46. package/dist/{update.js → core/update.js} +28 -12
  47. package/dist/{weakening.js → core/weakening.js} +2 -1
  48. package/package.json +16 -6
  49. package/rules/40-delegation.md +13 -2
  50. package/templates/.opencode/agents/style-enforcer.md +1 -1
  51. package/templates/.opencode/agents/test-grounder.md +1 -1
  52. package/templates/.opencode/skills/ground-in-tests/SKILL.md +1 -1
  53. package/templates/.opencode/skills/peer-review/SKILL.md +6 -1
  54. package/templates/.opencode/skills/project-config/SKILL.md +2 -2
  55. package/tui.tsx +6 -6
  56. package/dist/index.d.ts +0 -101
  57. /package/dist/{block-store.js → core/block-store.js} +0 -0
  58. /package/dist/{command-utils.d.ts → core/command-utils.d.ts} +0 -0
  59. /package/dist/{command-utils.js → core/command-utils.js} +0 -0
  60. /package/dist/{commands.d.ts → core/commands.d.ts} +0 -0
  61. /package/dist/{detect.d.ts → core/detect.d.ts} +0 -0
  62. /package/dist/{detect.js → core/detect.js} +0 -0
  63. /package/dist/{host.d.ts → core/host.d.ts} +0 -0
  64. /package/dist/{host.js → core/host.js} +0 -0
  65. /package/dist/{logger.d.ts → core/logger.d.ts} +0 -0
  66. /package/dist/{review.d.ts → core/review.d.ts} +0 -0
  67. /package/dist/{roster.d.ts → core/roster.d.ts} +0 -0
  68. /package/dist/{roster.js → core/roster.js} +0 -0
  69. /package/dist/{types.js → core/types.js} +0 -0
  70. /package/dist/{weakening.d.ts → core/weakening.d.ts} +0 -0
  71. /package/templates/{.opencode/opencode-dev-framework → .dev-framework}/rules/.gitkeep +0 -0
@@ -28,164 +28,27 @@
28
28
  import { stat } from "node:fs/promises";
29
29
  import { join } from "node:path";
30
30
  import { Plugin } from "@opencode/plugin";
31
- import { createBlockStore, createStuckSnapshotStore, } from "./block-store.js";
32
- import { clearConfigCache, loadConfig } from "./config.js";
33
- import { createChangedFileTracker } from "./gate.js";
34
- import { artifactState, childArtifactDenial, createPassCache, evaluateCompletion, isReviewArtifact, PREFLIGHT_ARTIFACT_REL, preflightBlockReason, } from "./harness.js";
35
- import { runCommand } from "./host.js";
36
- import { createLintLimiter, detectPreCommitAvailability, isLintFailure, lintFile, summarizeLint, } from "./lint.js";
37
- import { createLogger } from "./logger.js";
38
- import { checkToolCall, extractCommand, extractFilePath, extractRedirectTargets, FILE_TOOLS, SHELL_TOOLS, toPermissionGuard, } from "./protect.js";
39
- import { clearSessionDirectory, hasSeenSessionStart, markSessionStartSeen, resolveIsChildSession, resolveSessionDepth, } from "./registry.js";
40
- import { findRosterIndex, renderDutyRoster, rosterPresent } from "./roster.js";
41
- import { constitutionPresent, loadConstitution } from "./rules.js";
42
- import { writeRuntimeStatus } from "./runtime-status.js";
43
- import { checkTemplateUpdates, driftMentionLine, summarizeDrift } from "./update.js";
44
- import { snapshotEnforceable } from "./weakening.js";
45
- let activeState = null;
46
- let fallbackLog = async () => { };
47
- /**
48
- * Minimum interval between config-mtime checks. Every hook fire calls
49
- * `reloadConfigIfChanged`, but the config file almost never changes
50
- * mid-session, so a 1s staleness window is invisible.
51
- */
52
- const CONFIG_RELOAD_MIN_INTERVAL_MS = 1000;
53
- function safeLog(state, level, message, extra) {
54
- const fn = state && typeof state.log === "function" ? state.log : fallbackLog;
55
- return fn(level, message, extra);
56
- }
57
- async function reloadConfigIfChanged(state) {
58
- // Throttle mtime checks: every hook fire calls this, but the config file
59
- // almost never changes mid-session. A 1s staleness window is invisible.
60
- const now = Date.now();
61
- if (now - state.lastConfigCheck < CONFIG_RELOAD_MIN_INTERVAL_MS) {
62
- return;
63
- }
64
- state.lastConfigCheck = now;
65
- const primary = join(state.directory, ".opencode-dev-framework.yml");
66
- const fallback = join(state.directory, ".dev-framework.yml");
67
- // check both names; stat whichever exists
68
- let configPath = null;
69
- let mtime;
70
- for (const p of [primary, fallback]) {
71
- try {
72
- const s = await stat(p);
73
- configPath = p;
74
- mtime = s.mtimeMs;
75
- break;
76
- }
77
- catch {
78
- // continue
79
- }
80
- }
81
- if (!configPath || mtime === undefined) {
82
- return;
83
- }
84
- if (state.configMtime !== undefined && state.configMtime === mtime) {
85
- return;
86
- }
87
- try {
88
- clearConfigCache();
89
- const next = loadConfig(state.directory);
90
- const { constitution } = await loadConstitution(next, state.directory);
91
- state.config = next;
92
- state.constitution = constitution;
93
- state.configMtime = mtime;
94
- }
95
- catch {
96
- // keep current state on read failure
97
- }
98
- }
99
- /**
100
- * Turn a completion verdict into the continuation message fed back to the
101
- * agent when blocked. Shared by the `experimental.idle` hook (same
102
- * execution, via synthetic) and the `event.subscribe` idle re-prompt
103
- * fallback so wording (and block counting) is identical on every
104
- * enforcement level.
105
- */
106
- function continuationMessage(verdict) {
107
- const why = verdict.reason === "review"
108
- ? "the peer-review requirement is unmet"
109
- : verdict.reason === "weakened"
110
- ? "the completion contract was weakened mid-session"
111
- : "the repo's checks are failing";
112
- return (`opencode-dev-framework completion gate blocked you from finishing because ${why} ` +
113
- `(block ${verdict.blockCount}/${verdict.maxBlocks}).\n\n${verdict.summary}\n\n` +
114
- `Fix the underlying cause and continue. Do NOT disable, skip, or weaken these checks to ` +
115
- `get past the gate. If a failure is pre-existing and unrelated to your work, prove it ` +
116
- `(show it fails on a clean tree) and report it to the user.`);
117
- }
118
- /** Log pass/standdown verdicts; returns the continuation message when blocked. */
119
- async function actOnVerdict(state, verdict) {
120
- if (verdict.decision === "pass") {
121
- if (verdict.note) {
122
- await safeLog(state, "info", verdict.note, { changedFiles: verdict.changedFiles });
123
- }
124
- return null;
125
- }
126
- if (verdict.decision === "standdown") {
127
- // evaluateCompletion already logged the stand-down loudly.
128
- return null;
129
- }
130
- return continuationMessage(verdict);
131
- }
132
- /**
133
- * Per-edit lint flow, shared by the `execute.after` hook (primary) and the
134
- * `filesystem.changed` fallback. Skipped files log at debug; passes at info;
135
- * failures log loudly at error (the edit already landed, so unlike
136
- * `execute.before` this never throws — it only reports).
137
- */
138
- async function runPerEditLint(state, filePath) {
139
- if (!state.config.on_edit.lint)
140
- return;
141
- if (state.config.precommit === "auto" && state.precommitAvailable === undefined) {
142
- state.precommitAvailable = await detectPreCommitAvailability(state.run, state.directory);
143
- }
144
- const outcome = await state.lintLimiter.run(() => lintFile(state.run, state.config, filePath, {
145
- cwd: state.directory,
146
- timeout: state.config.gate?.timeout,
147
- precommitAvailable: state.precommitAvailable,
148
- }));
149
- if (outcome.skipped) {
150
- await safeLog(state, "debug", summarizeLint(outcome), {
151
- filePath,
152
- reason: outcome.reason,
153
- });
154
- return;
155
- }
156
- if (!isLintFailure(outcome)) {
157
- await safeLog(state, "info", summarizeLint(outcome), { filePath });
158
- return;
159
- }
160
- await safeLog(state, "error", summarizeLint(outcome), {
161
- filePath,
162
- command: outcome.command?.join(" "),
163
- stdout: outcome.result?.stdout,
164
- stderr: outcome.result?.stderr,
165
- });
166
- }
167
- /** Assemble the completion verdict with the state's live dependencies. */
168
- function runCompletion(state, sessionID) {
169
- return evaluateCompletion({
170
- run: state.run,
171
- config: state.config,
172
- directory: state.directory,
173
- sessionID,
174
- tracker: state.tracker,
175
- blockCounts: state.blocks,
176
- stuckSnapshots: state.stuckSnapshots,
177
- lintLimiter: state.lintLimiter,
178
- passCache: state.passCache,
179
- baseline: state.initialEnforceable,
180
- log: (level, message, extra) => safeLog(state, level, message, extra),
181
- });
182
- }
31
+ import { createBlockStore, createStuckSnapshotStore } from "../../core/block-store.js";
32
+ import { CONFIG_FILE_PRECEDENCE, loadConfig } from "../../core/config.js";
33
+ import { createChangedFileTracker } from "../../core/gate.js";
34
+ import { artifactStateFirst, childArtifactDenial, createPassCache, isReviewArtifact, preflightBlockReason, } from "../../core/harness.js";
35
+ import { runCommand } from "../../core/host.js";
36
+ import { createLintLimiter } from "../../core/lint.js";
37
+ import { createLogger } from "../../core/logger.js";
38
+ import { PREFLIGHT_ARTIFACT_REL, PREFLIGHT_RELS } from "../../core/paths.js";
39
+ import { checkToolCall, extractCommand, extractFilePath, extractRedirectTargets, FILE_TOOLS, SHELL_TOOLS, toPermissionGuard, } from "../../core/protect.js";
40
+ import { clearSessionDirectory, hasSeenSessionStart, markSessionStartSeen, resolveChildSession, } from "../../core/registry.js";
41
+ import { findRosterIndex, renderDutyRoster, rosterPresent } from "../../core/roster.js";
42
+ import { constitutionPresent, loadConstitution } from "../../core/rules.js";
43
+ import { actOnVerdict, getActiveState, reloadConfigIfChanged, runCompletion, runPerEditLint, safeLog, setActiveState, setFallbackLog, stampIdleHandled, stampRuntimeStatus, wasIdleHandledRecently, } from "../../core/run-hooks.js";
44
+ import { checkTemplateUpdates, driftMentionLine } from "../../core/update.js";
45
+ import { snapshotEnforceable } from "../../core/weakening.js";
183
46
  /**
184
47
  * Build the host session lookup for child detection, defensively: older
185
48
  * cores (and stub contexts in tests) may not expose `session.get`, in
186
49
  * 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.
50
+ * The lookup is cached per sessionID inside `resolveChildSession`, so the
51
+ * steady state pays one walk per session lifetime.
189
52
  */
190
53
  function childSessionGetter(ctx) {
191
54
  const session = ctx.session;
@@ -195,40 +58,6 @@ function childSessionGetter(ctx) {
195
58
  // could throw on `this`-dependent adapters and fail open to top-level).
196
59
  return (id) => session.get({ sessionID: id });
197
60
  }
198
- /**
199
- * Record a completed idle-hook evaluation for the dedup map. Stamp ONLY on
200
- * the completed-evaluation paths (pass, blocked-admitted, standdown);
201
- * throw/early-return paths must not stamp so the subscriber net retries.
202
- */
203
- function stampIdleHandled(state, sessionID) {
204
- state.lastIdleHandled.set(sessionID, Date.now());
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
- }
222
- /**
223
- * True when the idle hook completed an evaluation for this session inside
224
- * `windowMs`. The hook itself uses a short window (same-boundary
225
- * double-fire guard for the dual key registration below); the subscriber
226
- * net uses the full window (one boundary, one gate run).
227
- */
228
- function wasIdleHandledRecently(state, sessionID, windowMs = 5_000) {
229
- const at = state.lastIdleHandled.get(sessionID);
230
- return at !== undefined && Date.now() - at < windowMs;
231
- }
232
61
  // Helpers to normalize V2 event shapes (data vs properties vs direct)
233
62
  function getEventSessionID(event) {
234
63
  const e = event;
@@ -289,7 +118,7 @@ const plugin = Plugin.define({
289
118
  id: "opencode-dev-framework",
290
119
  async setup(ctx) {
291
120
  const log = createLogger();
292
- fallbackLog = log;
121
+ setFallbackLog(log);
293
122
  const directory = ctx.location.directory;
294
123
  let config;
295
124
  try {
@@ -306,13 +135,15 @@ const plugin = Plugin.define({
306
135
  await log("warn", warning);
307
136
  }
308
137
  let configMtime;
309
- for (const name of [".opencode-dev-framework.yml", ".dev-framework.yml"]) {
138
+ for (const name of CONFIG_FILE_PRECEDENCE) {
310
139
  try {
311
- configMtime = (await stat(join(directory, name))).mtimeMs;
312
- break;
140
+ const mtimeMs = (await stat(join(directory, name))).mtimeMs;
141
+ if (configMtime === undefined || mtimeMs > configMtime) {
142
+ configMtime = mtimeMs;
143
+ }
313
144
  }
314
145
  catch {
315
- // continue
146
+ // name absent
316
147
  }
317
148
  }
318
149
  const tracker = createChangedFileTracker();
@@ -336,7 +167,7 @@ const plugin = Plugin.define({
336
167
  lastConfigCheck: 0,
337
168
  lastIdleHandled: new Map(),
338
169
  };
339
- activeState = state;
170
+ setActiveState(state);
340
171
  // Child-session detection for the review-duty guard (plan 23 phase 1):
341
172
  // one cached host lookup per session lifetime; undefined on older
342
173
  // cores, where every session reads as top-level (behavior unchanged).
@@ -367,7 +198,7 @@ const plugin = Plugin.define({
367
198
  // while the global may be cleared). See issue #1 follow-up.
368
199
  // 1) Constitution injection — per model request (V1: experimental.chat.system.transform -> V2: session.hook("context", ...))
369
200
  trackRegistration(await ctx.session.hook("context", async (event) => {
370
- if (activeState !== state)
201
+ if (getActiveState() !== state)
371
202
  return;
372
203
  await reloadConfigIfChanged(state);
373
204
  if (state.config.profile === "off")
@@ -400,7 +231,7 @@ const plugin = Plugin.define({
400
231
  // 1a) Startup template-drift mention — once per session, best-effort.
401
232
  // First `context` sighting of a sessionID is session startup (plugin
402
233
  // `setup()` has no session to mention into). Drifted installs get one
403
- // line pointing at `/df-update`; current and empty trees stay silent.
234
+ // line pointing at `dev_framework_update`; current and empty trees stay silent.
404
235
  // Never throws into prompt assembly; never writes.
405
236
  const startupID = getEventSessionID(event);
406
237
  if (startupID !== undefined && !hasSeenSessionStart(startupID)) {
@@ -423,7 +254,7 @@ const plugin = Plugin.define({
423
254
  // (no-op if model doesn't need it; cheap)
424
255
  for (const kind of ["generate", "compaction", "title"]) {
425
256
  trackRegistration(await ctx.session.hook(kind, async (event) => {
426
- if (activeState !== state)
257
+ if (getActiveState() !== state)
427
258
  return;
428
259
  const constitution = state.constitution;
429
260
  if (state.config.profile === "off" || !constitution)
@@ -454,7 +285,7 @@ const plugin = Plugin.define({
454
285
  // key the core accepted, so the TUI can report the hook method.
455
286
  let idleHookVia = "none";
456
287
  const handleIdleContinuation = async (event) => {
457
- if (activeState !== state)
288
+ if (getActiveState() !== state)
458
289
  return;
459
290
  if (event === null || typeof event !== "object")
460
291
  return;
@@ -474,16 +305,18 @@ const plugin = Plugin.define({
474
305
  // Child sessions owe no review duty (plan 23 phase 1): the review
475
306
  // artifact belongs to the top-level session, so a child idling on
476
307
  // 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)) {
308
+ // before any gate work; both levers share this predicate. The
309
+ // tripwire depth (plan 24) rides the same walk, so this costs one
310
+ // cached lookup per session lifetime — never two.
311
+ const child = await resolveChildSession(sessionID, sessionGetter);
312
+ if (child.isChild) {
479
313
  // Tripwire (plan 24): log the chain depth on every child-gated
480
314
  // decision. Depth 1 is the entire world at core's default
481
315
  // `experimental.subagent_depth`; anything deeper means nesting
482
316
  // arrived via a raised limit or a non-tool creation path.
483
- const depth = await resolveSessionDepth(sessionID, sessionGetter);
484
317
  await safeLog(state, "debug", "completion gate skipped: child session owes no review duty", {
485
318
  sessionID,
486
- depth,
319
+ depth: child.depth,
487
320
  });
488
321
  return;
489
322
  }
@@ -572,7 +405,7 @@ const plugin = Plugin.define({
572
405
  // already warned for the same call.
573
406
  try {
574
407
  trackRegistration(await ctx.permission.hook("evaluate", async (event) => {
575
- if (activeState !== state)
408
+ if (getActiveState() !== state)
576
409
  return;
577
410
  await reloadConfigIfChanged(state);
578
411
  if (state.config.profile === "off")
@@ -594,7 +427,7 @@ const plugin = Plugin.define({
594
427
  // Pre-flight (mirrors execute.before; the artifact itself stays
595
428
  // writable). Deny/warn per profile, exactly like the backstop.
596
429
  if (state.config.preflight.length > 0 && action === "edit") {
597
- const artifact = await artifactState(state.directory, PREFLIGHT_ARTIFACT_REL);
430
+ const artifact = await artifactStateFirst(state.directory, PREFLIGHT_RELS);
598
431
  const reason = preflightBlockReason(state.config, "edit", target, artifact);
599
432
  if (reason !== null) {
600
433
  if (state.config.profile === "advisory") {
@@ -631,16 +464,16 @@ const plugin = Plugin.define({
631
464
  }
632
465
  if (resourceHitsArtifact) {
633
466
  const childID = typeof event.sessionID === "string" ? event.sessionID : "";
634
- if (await resolveIsChildSession(childID, sessionGetter)) {
467
+ const child = await resolveChildSession(childID, sessionGetter);
468
+ if (child.isChild) {
635
469
  const reason = childArtifactDenial();
636
- const depth = await resolveSessionDepth(childID, sessionGetter);
637
470
  if (state.config.profile === "advisory") {
638
- await safeLog(state, "debug", reason, { ...baseExtra, depth });
471
+ await safeLog(state, "debug", reason, { ...baseExtra, depth: child.depth });
639
472
  }
640
473
  else {
641
474
  event.effect = "deny";
642
475
  event.message = reason;
643
- await safeLog(state, "error", reason, { ...baseExtra, depth });
476
+ await safeLog(state, "error", reason, { ...baseExtra, depth: child.depth });
644
477
  }
645
478
  return;
646
479
  }
@@ -676,8 +509,8 @@ const plugin = Plugin.define({
676
509
  // captured `state` throughout also closes the teardown race where the
677
510
  // global is cleared between awaits. See issue #1.
678
511
  trackRegistration(await ctx.tool.hook("execute.before", async (event) => {
679
- if (activeState !== state) {
680
- if (activeState === null) {
512
+ if (getActiveState() !== state) {
513
+ if (getActiveState() === null) {
681
514
  await safeLog(null, "warn", "[opencode-dev-framework] plugin state is not available; allowing tool call (fail-open after teardown)", { tool: event.tool });
682
515
  }
683
516
  return;
@@ -702,10 +535,10 @@ const plugin = Plugin.define({
702
535
  extractRedirectTargets(extractCommand(input) ?? "").some((t) => isReviewArtifact(t, state.directory)));
703
536
  if (writesArtifact) {
704
537
  const childID = typeof sessionID === "string" ? sessionID : "";
705
- if (await resolveIsChildSession(childID, sessionGetter)) {
538
+ const child = await resolveChildSession(childID, sessionGetter);
539
+ if (child.isChild) {
706
540
  const reason = childArtifactDenial();
707
- const depth = await resolveSessionDepth(childID, sessionGetter);
708
- const extra = { tool: toolName, sessionID, depth };
541
+ const extra = { tool: toolName, sessionID, depth: child.depth };
709
542
  if (state.config.profile === "advisory") {
710
543
  await safeLog(state, "warn", reason, extra);
711
544
  }
@@ -719,8 +552,8 @@ const plugin = Plugin.define({
719
552
  // edits are denied (standard/strict) until the pre-flight artifact
720
553
  // exists. This is a true hard gate — it runs before the edit lands.
721
554
  if (state.config.preflight.length > 0) {
722
- const artifact = await artifactState(state.directory, PREFLIGHT_ARTIFACT_REL);
723
- const reason = preflightBlockReason(state.config, toolName, extractFilePath(input), artifact);
555
+ const artifact = await artifactStateFirst(state.directory, PREFLIGHT_RELS);
556
+ const reason = preflightBlockReason(state.config, toolName, extractFilePath(input), artifact, state.directory);
724
557
  if (reason !== null) {
725
558
  const extra = { tool: toolName, sessionID, artifact: PREFLIGHT_ARTIFACT_REL };
726
559
  if (state.config.profile === "advisory") {
@@ -752,7 +585,7 @@ const plugin = Plugin.define({
752
585
  // is nothing reliable to lint); read-only tools never touch the tracker.
753
586
  // The edit already landed, so this hook only reports — it never throws.
754
587
  trackRegistration(await ctx.tool.hook("execute.after", async (event) => {
755
- if (activeState !== state)
588
+ if (getActiveState() !== state)
756
589
  return;
757
590
  await reloadConfigIfChanged(state);
758
591
  if (state.config.profile === "off")
@@ -762,7 +595,10 @@ const plugin = Plugin.define({
762
595
  return;
763
596
  if (!FILE_TOOLS.has(event.tool))
764
597
  return;
765
- state.tracker.add(filePath, state.directory);
598
+ // Out-of-tree absolute paths (sibling repos, home dir) are outside
599
+ // the gate's jurisdiction: not tracked, not linted.
600
+ if (!state.tracker.add(filePath, state.directory))
601
+ return;
766
602
  if (event.status !== "completed") {
767
603
  await safeLog(state, "debug", `tracked ${filePath} from failed ${event.tool} call (lint skipped)`, { tool: event.tool, sessionID: event.sessionID, filePath });
768
604
  return;
@@ -793,7 +629,7 @@ const plugin = Plugin.define({
793
629
  additionalProperties: false,
794
630
  },
795
631
  async execute(input) {
796
- const { runInitScaffold, scaffoldReportLines } = await import("./init.js");
632
+ const { runInitScaffold, scaffoldReportLines } = await import("../../core/init.js");
797
633
  const args = input;
798
634
  const targetDir = args.directory ?? directory;
799
635
  const scaffold = await runInitScaffold(targetDir, state.run, {
@@ -822,9 +658,9 @@ const plugin = Plugin.define({
822
658
  additionalProperties: false,
823
659
  },
824
660
  async execute(input) {
825
- const { clearConfigCache: ccc, loadConfig: lc } = await import("./config.js");
826
- const { changeProfile } = await import("./commands.js");
827
- const { loadConstitution: lc2 } = await import("./rules.js");
661
+ const { clearConfigCache: ccc, loadConfig: lc } = await import("../../core/config.js");
662
+ const { changeProfile } = await import("../../core/commands.js");
663
+ const { loadConstitution: lc2 } = await import("../../core/rules.js");
828
664
  const args = input;
829
665
  const targetDir = args.directory ?? directory;
830
666
  const profile = args.profile.trim().toLowerCase();
@@ -842,9 +678,10 @@ const plugin = Plugin.define({
842
678
  state.config = newConfig;
843
679
  state.constitution = newConstitution;
844
680
  }
845
- if (activeState && activeState !== state && activeState.directory === targetDir) {
846
- activeState.config = newConfig;
847
- activeState.constitution = newConstitution;
681
+ const liveState = getActiveState();
682
+ if (liveState && liveState !== state && liveState.directory === targetDir) {
683
+ liveState.config = newConfig;
684
+ liveState.constitution = newConstitution;
848
685
  }
849
686
  return { content: `${message} Change applied immediately.` };
850
687
  },
@@ -863,10 +700,11 @@ const plugin = Plugin.define({
863
700
  additionalProperties: false,
864
701
  },
865
702
  async execute(input) {
866
- const { verifyGate } = await import("./commands.js");
703
+ const { verifyGate } = await import("../../core/commands.js");
867
704
  const args = input;
868
705
  const targetDir = args.directory ?? directory;
869
- const live = activeState && activeState.directory === targetDir ? activeState : null;
706
+ const liveState = getActiveState();
707
+ const live = liveState && liveState.directory === targetDir ? liveState : null;
870
708
  const own = state.directory === targetDir ? state : null;
871
709
  const holder = live ?? own;
872
710
  // Live tracker's changed files beat the TUI's empty default: a
@@ -891,10 +729,11 @@ const plugin = Plugin.define({
891
729
  additionalProperties: false,
892
730
  },
893
731
  async execute(input) {
894
- const { renderStatus } = await import("./format-status.js");
732
+ const { renderStatus } = await import("../../core/format-status.js");
895
733
  const args = input;
896
734
  const targetDir = args.directory ?? directory;
897
- const live = activeState && activeState.directory === targetDir ? activeState : null;
735
+ const liveState = getActiveState();
736
+ const live = liveState && liveState.directory === targetDir ? liveState : null;
898
737
  const own = state.directory === targetDir ? state : null;
899
738
  const cfg = (live ?? own)?.config ?? loadConfig(targetDir);
900
739
  // renderStatus expects HookState? pass live ?? own (may be null for other dirs)
@@ -903,6 +742,52 @@ const plugin = Plugin.define({
903
742
  };
904
743
  },
905
744
  });
745
+ editor.add({
746
+ name: "dev_framework_update",
747
+ description: "Check the framework deployment for drift (bundled templates, including the skill set) and return the per-file refresh/add brief. Use when the setup may be stale; present each file for review before editing, exactly like /df-update, and never commit unreviewed.",
748
+ input: {
749
+ type: "object",
750
+ properties: {
751
+ directory: {
752
+ type: "string",
753
+ description: "Project directory (defaults to current project)",
754
+ },
755
+ },
756
+ additionalProperties: false,
757
+ },
758
+ async execute(input) {
759
+ const { checkTemplateUpdates, composeUpdatePrompt, needsAgentHandoff } = await import("../../core/update.js");
760
+ const args = input;
761
+ const targetDir = args.directory ?? directory;
762
+ const drift = await checkTemplateUpdates(targetDir);
763
+ if (!needsAgentHandoff(drift)) {
764
+ return { content: "templates current" };
765
+ }
766
+ return { content: composeUpdatePrompt(drift, targetDir) };
767
+ },
768
+ });
769
+ editor.add({
770
+ name: "dev_framework_runtime",
771
+ description: "Show the live framework runtime snapshot for the project (hook registration, gate continuation posture, template drift). Read-only; use to inspect gate state mid-session.",
772
+ input: {
773
+ type: "object",
774
+ properties: {
775
+ directory: {
776
+ type: "string",
777
+ description: "Project directory (defaults to current project)",
778
+ },
779
+ },
780
+ additionalProperties: false,
781
+ },
782
+ async execute(input) {
783
+ const { renderRuntimeStatus } = await import("../../core/format-status.js");
784
+ const { readRuntimeStatus } = await import("../../core/runtime-status.js");
785
+ const args = input;
786
+ const targetDir = args.directory ?? directory;
787
+ const snapshot = await readRuntimeStatus(targetDir);
788
+ return { content: renderRuntimeStatus(snapshot) };
789
+ },
790
+ });
906
791
  }));
907
792
  // 3b) Verified-goal wrapper — server-side `/df-goal` through
908
793
  // `ctx.command.transform` (see src/goal.ts for the pure policy). Thin
@@ -918,12 +803,12 @@ const plugin = Plugin.define({
918
803
  name: "df-goal",
919
804
  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.",
920
805
  execute: async (invocation) => {
921
- if (activeState !== state) {
806
+ if (getActiveState() !== state) {
922
807
  throw new Error("Cannot start a verified goal: the plugin session state changed " +
923
808
  "(teardown or reload raced the command); retry /df-goal.");
924
809
  }
925
810
  await reloadConfigIfChanged(state);
926
- const { extractObjectiveText, isNativeGoalListed, runGoalCommand } = await import("./goal.js");
811
+ const { extractObjectiveText, isNativeGoalListed, runGoalCommand } = await import("../../core/goal.js");
927
812
  let nativeGoalAvailable = false;
928
813
  try {
929
814
  nativeGoalAvailable = isNativeGoalListed(await ctx.command.list());
@@ -976,36 +861,38 @@ const plugin = Plugin.define({
976
861
  name: "df-init",
977
862
  description: "Set up opencode-dev-framework for the current project: scaffold templates, write the detected config, trial-run it, and hand the brief to the agent. Safe to re-run; reports status when already configured.",
978
863
  execute: async (invocation) => {
979
- if (activeState !== state) {
864
+ if (getActiveState() !== state) {
980
865
  throw new Error("Cannot start project setup: the plugin session state changed " +
981
866
  "(teardown or reload raced the command); retry /df-init.");
982
867
  }
983
- const { runInitCommand } = await import("./init.js");
868
+ const { runInitCommand } = await import("../../core/init.js");
984
869
  const delivered = await runInitCommand({
985
870
  directory: state.directory,
986
871
  run: state.run,
987
872
  delivery: invocation.delivery,
988
873
  checkAlive: () => {
989
- if (activeState !== state) {
874
+ if (getActiveState() !== state) {
990
875
  throw new Error("Project setup was superseded mid-scaffold (teardown or reload raced the command); " +
991
876
  "retry /df-init — a re-run reports status without touching anything.");
992
877
  }
993
878
  },
994
879
  reload: async () => {
995
- const { clearConfigCache: ccc, loadConfig: lc } = await import("./config.js");
996
- const { loadConstitution: lc2 } = await import("./rules.js");
880
+ const { clearConfigCache: ccc, loadConfig: lc } = await import("../../core/config.js");
881
+ const { loadConstitution: lc2 } = await import("../../core/rules.js");
997
882
  ccc();
998
883
  const newConfig = lc(state.directory);
999
884
  const { constitution: newConstitution } = await lc2(newConfig, state.directory);
1000
885
  state.config = newConfig;
1001
886
  state.constitution = newConstitution;
1002
- for (const name of [".opencode-dev-framework.yml", ".dev-framework.yml"]) {
887
+ for (const name of CONFIG_FILE_PRECEDENCE) {
1003
888
  try {
1004
- state.configMtime = (await stat(join(state.directory, name))).mtimeMs;
1005
- break;
889
+ const mtimeMs = (await stat(join(state.directory, name))).mtimeMs;
890
+ if (state.configMtime === undefined || mtimeMs > state.configMtime) {
891
+ state.configMtime = mtimeMs;
892
+ }
1006
893
  }
1007
894
  catch {
1008
- // continue to fallback name
895
+ // name absent
1009
896
  }
1010
897
  }
1011
898
  },
@@ -1044,16 +931,16 @@ const plugin = Plugin.define({
1044
931
  name: "df-update",
1045
932
  description: "Check the project's installed templates against the shipped set and hand the drift to the agent: refresh differing files, add missing ones, each with user approval. Detection only, never writes.",
1046
933
  execute: async (invocation) => {
1047
- if (activeState !== state) {
934
+ if (getActiveState() !== state) {
1048
935
  throw new Error("Cannot check for updates: the plugin session state changed " +
1049
936
  "(teardown or reload raced the command); retry /df-update.");
1050
937
  }
1051
- const { runUpdateCommand } = await import("./update.js");
938
+ const { runUpdateCommand } = await import("../../core/update.js");
1052
939
  const delivered = await runUpdateCommand({
1053
940
  directory: state.directory,
1054
941
  delivery: invocation.delivery,
1055
942
  checkAlive: () => {
1056
- if (activeState !== state) {
943
+ if (getActiveState() !== state) {
1057
944
  throw new Error("Update check was superseded mid-run (teardown or reload raced the command); " +
1058
945
  "retry /df-update — it only reads, never writes.");
1059
946
  }
@@ -1090,7 +977,7 @@ const plugin = Plugin.define({
1090
977
  for await (const rawEvent of ctx.event.subscribe({ signal: controller.signal })) {
1091
978
  // Stale-loop guard: a previous setup's loop must exit rather than
1092
979
  // hijack a newer setup's state (duplicate gate re-prompts / lint).
1093
- if (activeState !== state)
980
+ if (getActiveState() !== state)
1094
981
  return;
1095
982
  const event = rawEvent;
1096
983
  const type = event.type;
@@ -1108,7 +995,7 @@ const plugin = Plugin.define({
1108
995
  continue;
1109
996
  }
1110
997
  if (isFilesystemChangedEvent(type)) {
1111
- if (activeState !== state)
998
+ if (getActiveState() !== state)
1112
999
  return;
1113
1000
  await reloadConfigIfChanged(state);
1114
1001
  if (state.config.profile === "off")
@@ -1128,7 +1015,7 @@ const plugin = Plugin.define({
1128
1015
  continue;
1129
1016
  }
1130
1017
  if (isIdleEvent(event)) {
1131
- if (activeState !== state)
1018
+ if (getActiveState() !== state)
1132
1019
  return;
1133
1020
  await reloadConfigIfChanged(state);
1134
1021
  if (state.config.profile === "off")
@@ -1144,9 +1031,9 @@ const plugin = Plugin.define({
1144
1031
  continue;
1145
1032
  // Same child-session skip as the hook lever above: no duty, no
1146
1033
  // verdict, no re-prompt — the parent answers for the tree.
1147
- if (await resolveIsChildSession(sessionID, sessionGetter)) {
1148
- const depth = await resolveSessionDepth(sessionID, sessionGetter);
1149
- await safeLog(state, "debug", "completion gate skipped: child session owes no review duty", { sessionID, depth });
1034
+ const child = await resolveChildSession(sessionID, sessionGetter);
1035
+ if (child.isChild) {
1036
+ await safeLog(state, "debug", "completion gate skipped: child session owes no review duty", { sessionID, depth: child.depth });
1150
1037
  continue;
1151
1038
  }
1152
1039
  // The §1b hook completed an evaluation for this boundary — one
@@ -1204,7 +1091,7 @@ const plugin = Plugin.define({
1204
1091
  // Unregister every hook/transform registered by this setup() so a
1205
1092
  // teardown/reload (e.g. session_move into a worktree) does not leave
1206
1093
  // stale closures alive. Disposal failures are ignored — the
1207
- // stale-hook guard (`activeState !== state` → no-op / fail-open) keeps
1094
+ // stale-hook guard (`getActiveState() !== state` → no-op / fail-open) keeps
1208
1095
  // the session usable regardless.
1209
1096
  for (const registration of registrations) {
1210
1097
  try {
@@ -1216,8 +1103,8 @@ const plugin = Plugin.define({
1216
1103
  }
1217
1104
  // Only clear the singleton if it is still ours; a newer setup() may
1218
1105
  // already have replaced it (reload race).
1219
- if (activeState === state) {
1220
- activeState = null;
1106
+ if (getActiveState() === state) {
1107
+ setActiveState(null);
1221
1108
  }
1222
1109
  };
1223
1110
  },