opencode-dev-framework 1.9.5 → 1.10.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.
Files changed (70) 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} +120 -235
  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/core/paths.d.ts +35 -0
  31. package/dist/core/paths.js +41 -0
  32. package/dist/{protect.d.ts → core/protect.d.ts} +18 -4
  33. package/dist/{protect.js → core/protect.js} +85 -34
  34. package/dist/{registry.d.ts → core/registry.d.ts} +9 -1
  35. package/dist/{review.js → core/review.js} +14 -6
  36. package/dist/{rules.d.ts → core/rules.d.ts} +3 -2
  37. package/dist/{rules.js → core/rules.js} +21 -5
  38. package/dist/core/run-hooks.d.ts +138 -0
  39. package/dist/core/run-hooks.js +196 -0
  40. package/dist/{runtime-status.d.ts → core/runtime-status.d.ts} +5 -4
  41. package/dist/{runtime-status.js → core/runtime-status.js} +29 -17
  42. package/dist/{types.d.ts → core/types.d.ts} +17 -0
  43. package/dist/{update.d.ts → core/update.d.ts} +12 -4
  44. package/dist/{update.js → core/update.js} +28 -12
  45. package/dist/{weakening.js → core/weakening.js} +2 -1
  46. package/package.json +23 -8
  47. package/rules/40-delegation.md +13 -2
  48. package/templates/.opencode/agents/style-enforcer.md +1 -1
  49. package/templates/.opencode/agents/test-grounder.md +1 -1
  50. package/templates/.opencode/skills/ground-in-tests/SKILL.md +1 -1
  51. package/templates/.opencode/skills/project-config/SKILL.md +2 -2
  52. package/tui.tsx +6 -6
  53. package/dist/index.d.ts +0 -101
  54. /package/dist/{block-store.js → core/block-store.js} +0 -0
  55. /package/dist/{command-utils.d.ts → core/command-utils.d.ts} +0 -0
  56. /package/dist/{command-utils.js → core/command-utils.js} +0 -0
  57. /package/dist/{commands.d.ts → core/commands.d.ts} +0 -0
  58. /package/dist/{detect.d.ts → core/detect.d.ts} +0 -0
  59. /package/dist/{detect.js → core/detect.js} +0 -0
  60. /package/dist/{host.d.ts → core/host.d.ts} +0 -0
  61. /package/dist/{host.js → core/host.js} +0 -0
  62. /package/dist/{logger.d.ts → core/logger.d.ts} +0 -0
  63. /package/dist/{logger.js → core/logger.js} +0 -0
  64. /package/dist/{registry.js → core/registry.js} +0 -0
  65. /package/dist/{review.d.ts → core/review.d.ts} +0 -0
  66. /package/dist/{roster.d.ts → core/roster.d.ts} +0 -0
  67. /package/dist/{roster.js → core/roster.js} +0 -0
  68. /package/dist/{types.js → core/types.js} +0 -0
  69. /package/dist/{weakening.d.ts → core/weakening.d.ts} +0 -0
  70. /package/templates/{.opencode/opencode-dev-framework → .dev-framework}/rules/.gitkeep +0 -0
@@ -0,0 +1,1643 @@
1
+ /**
2
+ * DSH adapter (plan 25 slice 4, packaged promotion of the slice-3 dogfood).
3
+ *
4
+ * One logic, two wirings: every verdict, reason string, and gate evaluation
5
+ * comes from core (`decideFileGuard`/`decideShellGuard`, `formatFile`/
6
+ * `lintFile`, `runCompletion`/`actOnVerdict`). This module is only wiring:
7
+ * Cordis event registration, `ctx.subprocess` transport, `ctx.logger`
8
+ * logging, and `dsh-commands` slash registration.
9
+ *
10
+ * Seams touched: `commands` (slash registration at load) and `subprocess`
11
+ * (lint/format/gate execution). Events (`ctx.on`) and `ctx.logger` are
12
+ * ambient on the verified DSH build (`0.2.2-rc.3`) and need no declaration —
13
+ * re-probe `inject` if a future host tightens seams.
14
+ *
15
+ * Directory: `ODF_WORKDIR` env override, else `process.cwd()`. No throw on
16
+ * unset env (safe default); the resolved directory is the config source and
17
+ * the `cwd` for every subprocess.
18
+ */
19
+ import { randomUUID } from "node:crypto";
20
+ import { readFile, stat } from "node:fs/promises";
21
+ import { join } from "node:path";
22
+ import { createBlockStore, createStuckSnapshotStore } from "../../core/block-store.js";
23
+ import { changeProfile, verifyGate } from "../../core/commands.js";
24
+ import { CONFIG_FILE_PRECEDENCE, clearConfigCache, loadConfig } from "../../core/config.js";
25
+ import { renderHelp, renderRuntimeStatus, renderStatus } from "../../core/format-status.js";
26
+ import { createChangedFileTracker } from "../../core/gate.js";
27
+ import { buildVerifiedObjective, checkGoalAvailability, isNativeGoalListed, } from "../../core/goal.js";
28
+ import { artifactStateFirst, childArtifactDenial, createPassCache, isReviewArtifact, preflightBlockReason, } from "../../core/harness.js";
29
+ import { runInitCommand, runInitScaffold, scaffoldReportLines } from "../../core/init.js";
30
+ import { DSH_SKILL_ROOTS } from "../../core/installer.js";
31
+ import { createLintLimiter, detectPreCommitAvailability, formatFile, isFormatFailure, isLintFailure, lintFile, summarizeFormat, summarizeLint, } from "../../core/lint.js";
32
+ import { PREFLIGHT_RELS } from "../../core/paths.js";
33
+ import { decideFileGuard, decideShellGuard, extractRedirectTargets, } from "../../core/protect.js";
34
+ import { renderDutyRoster } from "../../core/roster.js";
35
+ import { loadConstitution } from "../../core/rules.js";
36
+ import { actOnVerdict, getActiveState, getFallbackLog, reloadConfigIfChanged, runCompletion, safeLog, setActiveState, setFallbackLog, stampRuntimeStatus, } from "../../core/run-hooks.js";
37
+ import { readRuntimeStatus } from "../../core/runtime-status.js";
38
+ import { checkTemplateUpdates, composeUpdatePrompt, driftMentionLine, needsAgentHandoff, runUpdateCommand, } from "../../core/update.js";
39
+ import { snapshotEnforceable } from "../../core/weakening.js";
40
+ import { extractDshCommand, extractDshPaths, } from "./extract.js";
41
+ export const name = "opencode-dev-framework-dsh";
42
+ /** Seams this adapter touches: slash registration + subprocess transport. */
43
+ export const inject = ["commands", "subprocess"];
44
+ /** Cap on collected subprocess output per stream (bytes). */
45
+ const COLLECT_MAX_BYTES = 1024 * 1024;
46
+ /**
47
+ * Formatter attribution for DSH status surfaces: the adapter (not host
48
+ * core) runs format-then-lint in post-execute. One site (the `df-status`
49
+ * command) passes `formatOwner: "adapter"`; the agent-tool status path
50
+ * renders through the same handler shape.
51
+ */
52
+ const DSH_FORMAT_OWNER = "adapter";
53
+ /** Grace period before a subprocess abort escalates (ms). */
54
+ const SUBPROCESS_GRACE_MS = 2000;
55
+ /** Stable identity stamped on every ODF denial so host diagnostics can attribute it. */
56
+ function odfInfo(code) {
57
+ return { name: "opencode-dev-framework", code };
58
+ }
59
+ /** Resolve the project directory: explicit env override, else process cwd. */
60
+ export function resolveDshDirectory(env = process.env) {
61
+ const override = env["ODF_WORKDIR"];
62
+ if (typeof override === "string" && override !== "") {
63
+ return override;
64
+ }
65
+ return process.cwd();
66
+ }
67
+ /** `RunCommand` over `ctx.subprocess`: the `(string[], {cwd, timeout})` shape core expects. */
68
+ function runOverSubprocess(ctx, directory) {
69
+ return async (command, options = {}) => {
70
+ const controller = new AbortController();
71
+ const timeoutMs = (options.timeout ?? 60) * 1000;
72
+ let timedOut = false;
73
+ const timer = setTimeout(() => {
74
+ timedOut = true;
75
+ controller.abort();
76
+ }, timeoutMs);
77
+ const collect = (maxBytes) => ({ maxBytes, spill: { maxBytes } });
78
+ try {
79
+ const handle = ctx.subprocess.spawn({
80
+ argv: command,
81
+ cwd: options.cwd ?? directory,
82
+ stdio: {
83
+ stdin: "ignore",
84
+ stdout: collect(COLLECT_MAX_BYTES),
85
+ stderr: collect(COLLECT_MAX_BYTES),
86
+ },
87
+ graceMs: SUBPROCESS_GRACE_MS,
88
+ signal: controller.signal,
89
+ });
90
+ const outcome = await handle.done;
91
+ const stdout = handle.collected.stdout?.readFrom(0).text ?? "";
92
+ const stderr = handle.collected.stderr?.readFrom(0).text ?? "";
93
+ return { stdout, stderr, exitCode: outcome.exitCode ?? 1, timedOut };
94
+ }
95
+ catch (error) {
96
+ return {
97
+ stdout: "",
98
+ stderr: String(error?.message ?? error),
99
+ exitCode: 127,
100
+ timedOut,
101
+ };
102
+ }
103
+ finally {
104
+ clearTimeout(timer);
105
+ }
106
+ };
107
+ }
108
+ /**
109
+ * Register one agent-invokable tool, isolated: a host that rejects one
110
+ * definition (shape drift, name clash) still gets the rest, and a host
111
+ * without a tool service keeps every command. The definition is built in
112
+ * the host's compiled `defineTool` shape (see `DshToolDefinition`) so no
113
+ * host-internal import is needed.
114
+ */
115
+ function registerDshTool(ctx, state, def) {
116
+ // The host throws on reading a non-injected service (rather than
117
+ // yielding undefined), so the read itself is guarded: a host without
118
+ // the service keeps every command, exactly as documented. The service
119
+ // object (not the bare method) is captured so the `register` call
120
+ // keeps its receiver — the host implementation reads `this`.
121
+ let tools;
122
+ try {
123
+ tools = ctx.tools;
124
+ }
125
+ catch {
126
+ tools = undefined;
127
+ }
128
+ if (typeof tools?.register !== "function") {
129
+ void safeLog(state, "warn", `tool service unavailable; skipping agent tool ${def.name}`);
130
+ return;
131
+ }
132
+ try {
133
+ tools.register({
134
+ name: def.name,
135
+ description: def.description,
136
+ parameters: def.parameters,
137
+ output: {
138
+ schema: { type: "string" },
139
+ render: (_args, value) => [
140
+ { type: "text", text: typeof value === "string" ? value : String(value) },
141
+ ],
142
+ },
143
+ ...(def.isConcurrencySafe === undefined ? {} : { isConcurrencySafe: def.isConcurrencySafe }),
144
+ execute: (args, exec) => {
145
+ // Review duty belongs to the top-level session (plan 23): a child
146
+ // that invokes a gate tool gets a denial with the redirect, never
147
+ // a gate evaluation for the shared tree. Investigation-only by
148
+ // construction, even where the child roster lists these tools.
149
+ const agent = exec?.agent;
150
+ if (isChildAgent(agent)) {
151
+ const denial = `Child sessions may not invoke ${def.name}: the review duty belongs ` +
152
+ "to the top-level session — report findings back as text and let the " +
153
+ "parent run the gate.";
154
+ void safeLog(state, "warn", denial, { tool: def.name });
155
+ return Promise.resolve(denial);
156
+ }
157
+ return def.execute(args);
158
+ },
159
+ });
160
+ }
161
+ catch (error) {
162
+ void safeLog(state, "warn", `agent tool ${def.name} rejected by host; commands still work`, {
163
+ error: String(error?.message ?? error),
164
+ });
165
+ }
166
+ }
167
+ /**
168
+ * Whether a host service exposes a given method. Guarded read (same idiom
169
+ * as every other seam probe): the host throws without inject, and absence
170
+ * degrades to false. Used once at mount for the status seams snapshot.
171
+ */
172
+ function hasServiceMethod(read, method) {
173
+ try {
174
+ const service = read();
175
+ return typeof service?.[method] === "function";
176
+ }
177
+ catch {
178
+ return false;
179
+ }
180
+ }
181
+ /**
182
+ * Whether a guard `warn` can reach the human as an `ask` decision. Guarded
183
+ * read (same idiom as the tool/goal services): the host throws without
184
+ * inject, and absence means allow+log. Child sessions never ask — a child
185
+ * reports back and the parent decides (the host rejects child questions
186
+ * anyway); the caller ANDs this with `!isChildAgent(exec.agent)`.
187
+ */
188
+ function canAskUser(ctx) {
189
+ try {
190
+ // Services are objects here (`subprocess`, `commands`, `tools`,
191
+ // `goals`); accept a callable too so a future function-shaped mount
192
+ // still reaches the human instead of silently degrading.
193
+ const approval = ctx.approval;
194
+ return approval !== null && (typeof approval === "object" || typeof approval === "function");
195
+ }
196
+ catch {
197
+ return false;
198
+ }
199
+ }
200
+ function toPreDecision(result, askAvailable) {
201
+ // Intent over mechanism: a `warn` is the framework asking the human, not
202
+ // a log line. Where the host exposes a user-approval seam (the
203
+ // interactive TUI mounts it with human answerers), emit `ask` so the
204
+ // human actually gets the question. Where the seam is absent (agent-run
205
+ // headless: the read throws without inject), allow with a warn log —
206
+ // exactly like the OpenCode adapter. Emitting `ask` with no answerers
207
+ // would fail closed and convert advisory warnings into blocks, the
208
+ // opposite of the warn contract. (`cancel` stays unused: nothing in the
209
+ // framework asks the model to stand down, only the human to decide.)
210
+ if (result.decision !== "deny") {
211
+ if (result.decision === "warn" && askAvailable) {
212
+ // Fallback literal mirrors the deny armor below: core `enforce()`
213
+ // always sets `reason`, but a reason-less `ask` must still read
214
+ // as a request, never as an empty prompt.
215
+ return { kind: "ask", reason: result.reason ?? "review requested by guardrails" };
216
+ }
217
+ return { kind: "allow" };
218
+ }
219
+ // Fallback literal is unreachable armor: core `enforce()` always sets
220
+ // `reason` on deny, so the deny path carries one.
221
+ return {
222
+ kind: "deny",
223
+ reason: result.reason ?? "blocked by guardrails",
224
+ info: odfInfo("guard-deny"),
225
+ };
226
+ }
227
+ /**
228
+ * What a guard *evaluation failure* (not a verdict — an exception) does.
229
+ * Profile-dependent like every other enforcement decision: advisory and
230
+ * off report and allow; standard/strict fail closed (unknown =
231
+ * untrusted). Pure for testability. (`off` never reaches evaluation —
232
+ * the kill switch returns first — but mapping it to allow keeps the
233
+ * helper safe under any future call ordering.)
234
+ */
235
+ export function guardErrorDecision(profile) {
236
+ return profile === "advisory" || profile === "off" ? "allow" : "deny";
237
+ }
238
+ /** Cap for the linter-output body in one feedback line (the `lint failed for…` header adds a little more). */
239
+ const MAX_LINT_FEEDBACK_CHARS = 4000;
240
+ /** Maximum fault lines in one block decision; the tail names the rest. */
241
+ const MAX_LINT_BLOCK_LINES = 5;
242
+ /** Suffix marking truncated feedback; the char cap is exact by construction. */
243
+ const TRUNCATED_SUFFIX = "… (truncated)";
244
+ /**
245
+ * Model-fault lint failures for a post-execute `block` decision.
246
+ * A finding blames the edit, so the model sees it as a failed tool call
247
+ * and fixes it in the same turn — stronger than the OpenCode
248
+ * `execute.after`, which can only log after the edit lands. A finding
249
+ * means: nonzero exit, no timeout, not the 127 command-not-found
250
+ * convention, and the linter actually printed something. Everything else
251
+ * (timeouts, spawn failures, missing binaries, silent crashes and silent
252
+ * nonzero exits) is infra the model cannot fix by editing: accept +
253
+ * error-log, file still tracked, gate re-checks. Pure for testability.
254
+ */
255
+ export function lintBlockLines(outcomes) {
256
+ const faults = [];
257
+ for (const outcome of outcomes) {
258
+ if (outcome.skipped || outcome.result === undefined) {
259
+ continue;
260
+ }
261
+ if (outcome.result.timedOut || outcome.result.exitCode === 0) {
262
+ continue;
263
+ }
264
+ // Exit 127 is the command-not-found convention (shells and the
265
+ // adapter's own spawn transport both use it): the linter never ran.
266
+ if (outcome.result.exitCode === 127) {
267
+ continue;
268
+ }
269
+ const output = [outcome.result.stdout, outcome.result.stderr]
270
+ .map((part) => part.trim())
271
+ .filter((part) => part !== "")
272
+ .join("\n");
273
+ // A nonzero exit with no output anywhere is infra noise, not evidence:
274
+ // a linter with real findings prints them. The gate re-runs the same
275
+ // command and surfaces whatever it says.
276
+ if (output === "") {
277
+ continue;
278
+ }
279
+ const capped = output.length > MAX_LINT_FEEDBACK_CHARS
280
+ ? `${output.slice(0, MAX_LINT_FEEDBACK_CHARS - TRUNCATED_SUFFIX.length)}${TRUNCATED_SUFFIX}`
281
+ : output;
282
+ faults.push({
283
+ filePath: outcome.filePath,
284
+ line: `lint failed for ${outcome.filePath} (exit ${outcome.result.exitCode}):\n${capped}`,
285
+ });
286
+ }
287
+ if (faults.length <= MAX_LINT_BLOCK_LINES) {
288
+ return faults.map((fault) => fault.line);
289
+ }
290
+ // Name the omitted files instead of asserting gate coverage: under the
291
+ // default `standard` profile the gate does not re-lint, so the tail is
292
+ // the only place the model learns which files still need attention.
293
+ const shown = faults.slice(0, MAX_LINT_BLOCK_LINES);
294
+ const omitted = faults.slice(MAX_LINT_BLOCK_LINES).map((fault) => fault.filePath);
295
+ return [
296
+ ...shown.map((fault) => fault.line),
297
+ `(findings omitted for ${omitted.length} more files: ${omitted.join(", ")})`,
298
+ ];
299
+ }
300
+ function dshUserMessage(text) {
301
+ return {
302
+ role: "user",
303
+ content: [{ type: "text", text }],
304
+ source: { kind: "user" },
305
+ id: randomUUID(),
306
+ };
307
+ }
308
+ /** Warn when an apply_patch envelope carries no recognizable file headers. */
309
+ function warnApplyPatchSkip(state, exec, rawInput, paths) {
310
+ if (exec.name === "apply_patch" &&
311
+ typeof rawInput === "string" &&
312
+ rawInput !== "" &&
313
+ paths.length === 0) {
314
+ void safeLog(state, "warn", "apply_patch with no recognized file headers — hooks skipping", {
315
+ tool: exec.name,
316
+ });
317
+ }
318
+ }
319
+ /** Closed-vocabulary `df-status` rendering for a continuity state. */
320
+ function renderContinuity(state) {
321
+ if (state === "clean") {
322
+ return "Continuity (this session): clean — session log shows no interrupted turn";
323
+ }
324
+ if (state === "resumed-interrupted") {
325
+ return ("Continuity (this session): resumed after interruption — prior gate state " +
326
+ "is unknown; the gate re-verifies from scratch");
327
+ }
328
+ return ("Continuity (this session): unknown — continuity could not be established; " +
329
+ "the gate re-verifies from scratch");
330
+ }
331
+ /**
332
+ * Resolve the session-history query service without a bundle inject
333
+ * change: the sandbox facade's optional `get` never throws for absent
334
+ * services, and the guarded property read covers hosts that inject it
335
+ * directly. Returns null when the seam is unavailable — never throws.
336
+ */
337
+ function readSessionQuery(ctx) {
338
+ try {
339
+ if (typeof ctx.get === "function") {
340
+ const viaGet = ctx.get("sessionQuery");
341
+ if (viaGet !== null && viaGet !== undefined) {
342
+ return viaGet;
343
+ }
344
+ }
345
+ }
346
+ catch {
347
+ // Fall through to the property read below.
348
+ }
349
+ try {
350
+ const direct = ctx.sessionQuery;
351
+ if (direct !== null && direct !== undefined) {
352
+ return direct;
353
+ }
354
+ }
355
+ catch {
356
+ // Absent seam: the caller reports unknown.
357
+ }
358
+ return null;
359
+ }
360
+ /** True when a raw session-log event closes a turn as interrupted. */
361
+ function isInterruptedTurnEnd(event) {
362
+ if (event === null || typeof event !== "object")
363
+ return false;
364
+ const record = event;
365
+ if (record.type !== "turn/end")
366
+ return false;
367
+ const data = record.data;
368
+ const reason = data?.reason;
369
+ return reason?.kind === "interrupted";
370
+ }
371
+ /**
372
+ * Probe continuity once per session per process (plan 27). Fallback
373
+ * turn-number identities carry no session to query, so they report
374
+ * unknown without touching the seam. Every failure — absent seam,
375
+ * throwing query, uninterpretable log — reports unknown and logs at
376
+ * debug. Never throws; never changes a gate verdict.
377
+ */
378
+ async function probeContinuity(ctx, state, sessionID) {
379
+ if (sessionID.startsWith("turn-")) {
380
+ return "unknown";
381
+ }
382
+ const query = readSessionQuery(ctx);
383
+ if (query === null || typeof query.readSession !== "function") {
384
+ await safeLog(state, "debug", "continuity probe skipped: no sessionQuery seam", {
385
+ sessionID,
386
+ });
387
+ return "unknown";
388
+ }
389
+ try {
390
+ const snapshot = (await query.readSession(sessionID));
391
+ if (!Array.isArray(snapshot?.events)) {
392
+ // A malformed payload is neither an empty log nor evidence: the
393
+ // spec's uninterpretable-log rule reports unknown.
394
+ await safeLog(state, "debug", "continuity probe uninterpretable (unknown)", {
395
+ sessionID,
396
+ });
397
+ return "unknown";
398
+ }
399
+ const interrupted = snapshot.events.some(isInterruptedTurnEnd);
400
+ const result = interrupted ? "resumed-interrupted" : "clean";
401
+ await safeLog(state, "debug", `continuity probe: ${result}`, { sessionID });
402
+ return result;
403
+ }
404
+ catch (error) {
405
+ await safeLog(state, "debug", `continuity probe failed (unknown): ${error?.message ?? error}`, {
406
+ sessionID,
407
+ });
408
+ return "unknown";
409
+ }
410
+ }
411
+ /** Best-effort session identity for gate block accounting. */
412
+ function sessionOf(agent, turn) {
413
+ const headerId = agent.session?.header?.id;
414
+ if (typeof headerId === "string" && headerId !== "") {
415
+ return headerId;
416
+ }
417
+ if (typeof agent.id === "string" && agent.id !== "") {
418
+ return agent.id;
419
+ }
420
+ return `turn-${typeof turn === "number" ? turn : "unknown"}`;
421
+ }
422
+ /** True when the session is fully off (no gates of any kind). */
423
+ function isProfileOff(state) {
424
+ return state.config.profile === "off";
425
+ }
426
+ /**
427
+ * Child-session predicate for the review-duty guard. DSH-native shape:
428
+ * the host attaches the session header to the agent, so parentage is a
429
+ * synchronous header read — no session lookup, no cache, no walk (all of
430
+ * that is OpenCode's problem, where the event carries no parentage).
431
+ * The rule mirrors the host's own classification: `parentSession` names
432
+ * the direct creator, but historical ordinary forks may retain it, so a
433
+ * child is `origin === "subagent"` *with* a creator id (cf. the host's
434
+ * `archive-admission` walk condition). An absent agent or header reads
435
+ * as top-level — the pre-existing behavior, never a new block.
436
+ */
437
+ export function isChildAgent(agent) {
438
+ const header = agent?.session?.header;
439
+ if (header?.origin !== "subagent") {
440
+ return false;
441
+ }
442
+ return typeof header.parentSession === "string" && header.parentSession !== "";
443
+ }
444
+ /**
445
+ * Specialist dispatch (plan 26). The read-only reviewers dispatched at
446
+ * review-blocks: pattern-guardian first (slice 26.2), style-enforcer and
447
+ * code-reviewer joining in 26.3. test-grounder stays a lead duty — it
448
+ * executes the project's own verify commands, which needs an
449
+ * execution-capable context, not a read-only child.
450
+ */
451
+ const SPECIALIST_KINDS = ["pattern-guardian", "style-enforcer", "code-reviewer"];
452
+ /** Name stems for adapter-spawned specialist children (host limit: ≤32 chars). */
453
+ const SPECIALIST_NAME_STEMS = {
454
+ "pattern-guardian": "odf-pattern-guardian",
455
+ "style-enforcer": "odf-style-enforcer",
456
+ "code-reviewer": "odf-code-reviewer",
457
+ };
458
+ /**
459
+ * Read-only reviewer preset (plan 26.3): the exact toolset every
460
+ * specialist child runs under. Registered by the adapter itself at
461
+ * apply time — no profile-owner step. Reads + search only: no writes,
462
+ * no exec, no delegation (a child can neither edit nor spawn).
463
+ */
464
+ const REVIEWER_PRESET_ID = "odf-reviewer";
465
+ function reviewerPresetDefinition() {
466
+ return {
467
+ id: REVIEWER_PRESET_ID,
468
+ name: "ODF Reviewer",
469
+ description: "Read-only review tools for ODF specialist children: filesystem reads and search. No writes, no exec, no delegation.",
470
+ plugins: [
471
+ {
472
+ id: "odf-reviewer-fs",
473
+ name: "@deepseek-ai/dsh-tool-fs",
474
+ config: { read: true, readImage: true, write: false, edit: false, applyPatch: false },
475
+ },
476
+ {
477
+ id: "odf-reviewer-search",
478
+ name: "@deepseek-ai/dsh-tool-fs-search",
479
+ config: { sampleOverCapGlobResults: false },
480
+ },
481
+ ],
482
+ };
483
+ }
484
+ /**
485
+ * Completion-notice shape, verified live (plan 26 slice 26.1): the
486
+ * delivery-to-parent notice names the finished child and quotes its
487
+ * closing message.
488
+ */
489
+ const SPECIALIST_NOTICE_RE = /Background subagent ([a-z0-9][a-z0-9-]*) finished[\s\S]*?[Ii]ts closing message:\s*([\s\S]*?)\s*$/;
490
+ /** Read-only investigation brief when the agent file is unreadable. */
491
+ const SPECIALIST_FALLBACK_BRIEF = "You are the pattern-guardian: check the changed files below against the " +
492
+ "codebase's existing patterns (duplication, re-invented helpers, divergent " +
493
+ "conventions, unjustified new dependencies). Report findings as text; do " +
494
+ "not edit anything.";
495
+ /** Brief source chain (plan 26.3): neutral override first so a DSH-only
496
+ * project never needs OpenCode's home; the shipped OpenCode home second
497
+ * (single source both harnesses edit); embedded fallback last. Never throws. */
498
+ const SPECIALIST_BRIEF_RELS = [".dev-framework/agents", ".opencode/agents"];
499
+ /** Load the specialist brief: neutral override, OpenCode home, fallback. */
500
+ async function loadSpecialistBrief(kind, directory) {
501
+ for (const rel of SPECIALIST_BRIEF_RELS) {
502
+ try {
503
+ return await readFile(join(directory, rel, `${kind}.md`), "utf8");
504
+ }
505
+ catch {
506
+ // Next brief source.
507
+ }
508
+ }
509
+ return SPECIALIST_FALLBACK_BRIEF;
510
+ }
511
+ /** Best-effort text of one entering message (any shape, never throws). */
512
+ function enteringMessageText(message) {
513
+ if (typeof message !== "object" || message === null) {
514
+ return null;
515
+ }
516
+ const content = message.content;
517
+ if (!Array.isArray(content)) {
518
+ return null;
519
+ }
520
+ const parts = [];
521
+ for (const part of content) {
522
+ if (typeof part === "object" &&
523
+ part !== null &&
524
+ part.type === "text" &&
525
+ typeof part.text === "string") {
526
+ parts.push(part.text);
527
+ }
528
+ }
529
+ return parts.length > 0 ? parts.join("\n") : null;
530
+ }
531
+ /**
532
+ * Register the ODF gates on a DSH Cordis context. Synchronous like every
533
+ * DSH plugin `apply`. A project without (or with a broken) config gets no
534
+ * hooks at all — error-logged, never throwing: failing the whole host
535
+ * mount for one project's missing yml would brick unrelated sessions
536
+ * (mirror of the OpenCode adapter's setup behavior).
537
+ */
538
+ export function apply(ctx) {
539
+ const directory = resolveDshDirectory();
540
+ let log = getFallbackLog();
541
+ try {
542
+ const hostLogger = ctx.logger;
543
+ log = async (level, message, extra) => {
544
+ hostLogger[level](`[odf] ${message}`, extra);
545
+ };
546
+ }
547
+ catch {
548
+ // Keep the fallback logger when the host logger is unavailable.
549
+ }
550
+ setFallbackLog(log);
551
+ let config;
552
+ try {
553
+ config = loadConfig(directory);
554
+ }
555
+ catch (error) {
556
+ void log("error", `loadConfig(${directory}) failed: ${error?.message ?? error} — ODF gates disabled`);
557
+ return;
558
+ }
559
+ const run = runOverSubprocess(ctx, directory);
560
+ const blockCounts = new Map();
561
+ const state = {
562
+ directory,
563
+ config,
564
+ initialEnforceable: snapshotEnforceable(config),
565
+ log,
566
+ run,
567
+ tracker: createChangedFileTracker(),
568
+ constitution: null,
569
+ blockCounts,
570
+ blocks: createBlockStore(undefined, blockCounts),
571
+ stuckSnapshots: createStuckSnapshotStore(undefined),
572
+ lintLimiter: createLintLimiter(),
573
+ passCache: createPassCache(),
574
+ lastConfigCheck: 0,
575
+ lastIdleHandled: new Map(),
576
+ // Probed once at mount so `df-status` reads degraded mounts as
577
+ // degraded. Never throws: every seam degrades to false.
578
+ seams: {
579
+ tools: hasServiceMethod(() => ctx.tools, "register"),
580
+ goals: hasServiceMethod(() => ctx.goals, "create"),
581
+ approval: canAskUser(ctx),
582
+ subagents: hasServiceMethod(() => ctx.subagents, "startActivation"),
583
+ agentPresets: hasServiceMethod(() => ctx.agentPresets, "register"),
584
+ sessionQuery: hasServiceMethod(() => readSessionQuery(ctx), "readSession"),
585
+ },
586
+ };
587
+ setActiveState(state);
588
+ // Runtime snapshot for `df-runtime` (fire-and-forget, never throws):
589
+ // "armed" until a gate evaluation reports otherwise.
590
+ stampRuntimeStatus(state.directory, "turn-stopping", "armed", DSH_SKILL_ROOTS[0]);
591
+ // Re-entrancy guard: `formatFile` mutates, so it re-fires `post-execute`.
592
+ // The guard lives here, never in core (plan 25 §Risks).
593
+ const inflight = new Set();
594
+ // Sessions that already received the constitution prepend, mapped to the
595
+ // config mtime it was built from: a mid-session config change refreshes
596
+ // the injection on the next step (mirror of the OpenCode per-request
597
+ // injection; history already admitted keeps the old text on both hosts).
598
+ // The marker is a number, never a config reference, so old configs are
599
+ // not pinned in memory for the host's lifetime. Keys come from
600
+ // `sessionOf`: stable host ids in production, turn-number fallback in
601
+ // id-less contexts (test stubs).
602
+ const injectedSessions = new Map();
603
+ // Continuity probe results (plan 27): one entry per session per
604
+ // process, holding the in-flight promise so concurrent callers share
605
+ // it. A fresh process re-verifies from scratch, so the map only ever
606
+ // names what this process observed — never a durable receipt.
607
+ const continuityBySession = new Map();
608
+ /**
609
+ * Lazily assess continuity for a session, memoizing per session id.
610
+ * The memoized unit is the in-flight promise, so concurrent callers
611
+ * (a stopping evaluation racing a status check) share one query.
612
+ * Total: even a throwing logger degrades to unknown instead of
613
+ * rejecting into the stopping path or the status handler.
614
+ */
615
+ async function ensureContinuity(sessionID) {
616
+ // Fallback identities name no session: report without memoizing, so
617
+ // id-less call sites neither accumulate entries nor share results.
618
+ if (sessionID.startsWith("turn-")) {
619
+ return "unknown";
620
+ }
621
+ const known = continuityBySession.get(sessionID);
622
+ if (known !== undefined) {
623
+ return known;
624
+ }
625
+ const pending = probeContinuity(ctx, state, sessionID).catch(() => "unknown");
626
+ continuityBySession.set(sessionID, pending);
627
+ return pending;
628
+ }
629
+ // Specialist dispatch (plan 26): children the adapter spawned per
630
+ // session and kind (at most one pending per kind — a new block while
631
+ // one is outstanding reuses it instead of fanning out) and findings
632
+ // collected per session. Findings fold into the next gate steer
633
+ // exactly once, then clear, so a later block never steers a stale copy.
634
+ const dispatchedSpecialists = new Map();
635
+ const specialistFindings = new Map();
636
+ let specialistCounter = 0;
637
+ // Whether the read-only reviewer preset registered (plan 26.3). Set
638
+ // asynchronously at apply; spawn reads it at dispatch time, so an
639
+ // early block simply spawns preset-less and degrades gracefully.
640
+ let reviewerPresetReady = false;
641
+ // Fire-and-forget: the adapter ships its own reviewer preset — no
642
+ // profile-owner step. Duplicate registration means our deterministic
643
+ // definition is already live (HMR re-apply), which also counts as
644
+ // ready. Any other failure degrades to preset-less spawning.
645
+ void (async () => {
646
+ let presets;
647
+ try {
648
+ presets = ctx.agentPresets;
649
+ }
650
+ catch (error) {
651
+ await safeLog(state, "debug", `reviewer preset skipped (no agentPresets seam): ${error?.message ?? error}`);
652
+ return;
653
+ }
654
+ if (typeof presets?.register !== "function") {
655
+ await safeLog(state, "debug", "reviewer preset skipped: agentPresets.register unavailable");
656
+ return;
657
+ }
658
+ try {
659
+ await presets.register(reviewerPresetDefinition());
660
+ reviewerPresetReady = true;
661
+ await safeLog(state, "info", `reviewer preset registered: ${REVIEWER_PRESET_ID}`);
662
+ }
663
+ catch (error) {
664
+ const message = String(error?.message ?? error);
665
+ if (message.includes("Duplicate agent preset")) {
666
+ reviewerPresetReady = true;
667
+ await safeLog(state, "debug", `reviewer preset already live: ${REVIEWER_PRESET_ID}`);
668
+ }
669
+ else {
670
+ await safeLog(state, "warn", `reviewer preset unavailable (prompt-level restriction only): ${message}`);
671
+ }
672
+ }
673
+ })();
674
+ function pendingSpecialist(sessionKey, kind) {
675
+ return dispatchedSpecialists.get(sessionKey)?.get(kind);
676
+ }
677
+ function trackSpecialist(sessionKey, kind, name) {
678
+ let kinds = dispatchedSpecialists.get(sessionKey);
679
+ if (kinds === undefined) {
680
+ kinds = new Map();
681
+ dispatchedSpecialists.set(sessionKey, kinds);
682
+ }
683
+ kinds.set(kind, name);
684
+ }
685
+ /** Dispatch one specialist child; null when the seam is absent/fails. */
686
+ async function spawnSpecialist(sessionKey, kind, agent, changedFiles, gateSummary, signal) {
687
+ let subagents;
688
+ try {
689
+ subagents = ctx.subagents;
690
+ }
691
+ catch {
692
+ subagents = undefined;
693
+ }
694
+ if (typeof subagents?.startActivation !== "function") {
695
+ return null;
696
+ }
697
+ try {
698
+ specialistCounter += 1;
699
+ const name = `${SPECIALIST_NAME_STEMS[kind]}-${specialistCounter}`;
700
+ const brief = await loadSpecialistBrief(kind, state.directory);
701
+ const prompt = `${brief}\n\nYou are investigating, not implementing: report findings ` +
702
+ `as text, do not edit anything.\nChanged files under review:\n` +
703
+ `${changedFiles.map((file) => `- ${file}`).join("\n")}\n\n` +
704
+ `Gate summary for this block:\n${gateSummary}`;
705
+ const activation = await subagents.startActivation({
706
+ provider: "spawn",
707
+ label: `odf specialist review (${kind})`,
708
+ name,
709
+ prompt: [{ type: "text", text: prompt }],
710
+ parent: agent,
711
+ ...(reviewerPresetReady ? { agentPreset: REVIEWER_PRESET_ID } : {}),
712
+ ...(signal !== undefined ? { signal } : {}),
713
+ delivery: "parent",
714
+ });
715
+ trackSpecialist(sessionKey, kind, activation.name);
716
+ await safeLog(state, "info", `specialist dispatched: ${activation.name}`, {
717
+ sessionID: sessionKey,
718
+ });
719
+ return activation.name;
720
+ }
721
+ catch (error) {
722
+ await safeLog(state, "warn", `specialist spawn failed (inline review continues): ${error?.message ?? error}`);
723
+ return null;
724
+ }
725
+ }
726
+ ctx.on("tools/pre-execute", async (exec, next) => {
727
+ try {
728
+ await reloadConfigIfChanged(state);
729
+ // Fully off means no gates of any kind. `protect_off` only stands
730
+ // down the *guardrails* — pre-flight below still fires under it,
731
+ // mirroring the OpenCode `execute.before` (bail on profile-off only).
732
+ if (isProfileOff(state)) {
733
+ return next();
734
+ }
735
+ const paths = extractDshPaths(exec);
736
+ const rawInput = typeof exec.arguments === "object" && exec.arguments !== null
737
+ ? exec.arguments["input"]
738
+ : undefined;
739
+ warnApplyPatchSkip(state, exec, rawInput, paths);
740
+ // Children never write the parent's review artifact. Not a
741
+ // guardrail — it fires under `protect_off` too — so it sits above
742
+ // both pre-flight and the guard tiers, where the specific duty
743
+ // message wins. File tools by target path, shell tools by redirect
744
+ // target; a bare mention (grep, cat without redirect) stays
745
+ // allowed. Top-level sessions pass through: the duty is theirs.
746
+ {
747
+ const command = extractDshCommand(exec);
748
+ const candidates = command === undefined ? paths : [...paths, ...extractRedirectTargets(command)];
749
+ if (candidates.some((p) => isReviewArtifact(p, state.directory))) {
750
+ if (isChildAgent(exec.agent)) {
751
+ const reason = childArtifactDenial();
752
+ if (state.config.profile === "advisory") {
753
+ await safeLog(state, "warn", reason, { tool: exec.name });
754
+ }
755
+ else {
756
+ await safeLog(state, "error", reason, { tool: exec.name });
757
+ return {
758
+ kind: "deny",
759
+ reason,
760
+ info: odfInfo("child-artifact-deny"),
761
+ };
762
+ }
763
+ }
764
+ }
765
+ }
766
+ // Pre-flight harness (mirror of the OpenCode `execute.before` order:
767
+ // pre-flight before guardrails, advisory warns and continues). Only
768
+ // file-tool paths are gated — shell tools fall through to the guard
769
+ // tiers below, exactly like `preflightBlockReason` returning null for
770
+ // non-file tools on the OpenCode side. DSH names its patch tool
771
+ // `apply_patch`; core knows it as `patch` — map the envelope
772
+ // vocabulary before calling in, the same normalization `extractDshPaths`
773
+ // already performs for paths.
774
+ if (state.config.preflight.length > 0) {
775
+ const preflightTool = exec.name === "apply_patch" ? "patch" : exec.name;
776
+ const artifact = await artifactStateFirst(state.directory, PREFLIGHT_RELS);
777
+ for (const filePath of paths) {
778
+ const reason = preflightBlockReason(state.config, preflightTool, filePath, artifact, state.directory);
779
+ if (reason !== null) {
780
+ if (state.config.profile === "advisory") {
781
+ await safeLog(state, "warn", reason, { tool: exec.name, filePath });
782
+ }
783
+ else {
784
+ await safeLog(state, "error", reason, { tool: exec.name, filePath });
785
+ return {
786
+ kind: "deny",
787
+ reason,
788
+ info: odfInfo("preflight-deny"),
789
+ };
790
+ }
791
+ }
792
+ }
793
+ }
794
+ // `protect_off` stands down the guardrails only — pre-flight above
795
+ // already fired. (Profile-off bailed at the top: no gates at all.)
796
+ if (state.config.protect_off === true) {
797
+ return next();
798
+ }
799
+ const command = extractDshCommand(exec);
800
+ if (command !== undefined) {
801
+ const verdict = decideShellGuard(state.config, command, undefined, exec.name);
802
+ if (verdict.decision !== "allow") {
803
+ await safeLog(state, "warn", verdict.reason ?? "shell call blocked", { tool: exec.name });
804
+ return toPreDecision(verdict, canAskUser(ctx) && !isChildAgent(exec.agent));
805
+ }
806
+ for (const target of extractRedirectTargets(command)) {
807
+ const fileVerdict = decideFileGuard(state.config, target, state.directory, undefined, exec.name);
808
+ if (fileVerdict.decision !== "allow") {
809
+ await safeLog(state, "warn", fileVerdict.reason ?? "redirect target blocked", {
810
+ tool: exec.name,
811
+ target,
812
+ });
813
+ return toPreDecision(fileVerdict, canAskUser(ctx) && !isChildAgent(exec.agent));
814
+ }
815
+ }
816
+ }
817
+ for (const filePath of paths) {
818
+ const verdict = decideFileGuard(state.config, filePath, state.directory, undefined, exec.name);
819
+ if (verdict.decision !== "allow") {
820
+ await safeLog(state, "warn", verdict.reason ?? "file call blocked", {
821
+ tool: exec.name,
822
+ filePath,
823
+ });
824
+ return toPreDecision(verdict, canAskUser(ctx) && !isChildAgent(exec.agent));
825
+ }
826
+ }
827
+ }
828
+ catch (error) {
829
+ // Evaluation failure (not a verdict): profile-dependent, like every
830
+ // other enforcement decision. Advisory reports and allows;
831
+ // standard/strict fail closed — a guard that cannot evaluate must not
832
+ // silently permit. (Post-execute stays fail-open under every profile:
833
+ // the edit already landed, so there is nothing left to gate.)
834
+ const message = `pre-execute guard error: ${error?.message ?? error}`;
835
+ if (guardErrorDecision(state.config.profile) === "deny") {
836
+ await safeLog(state, "error", message);
837
+ return {
838
+ kind: "deny",
839
+ reason: message,
840
+ info: odfInfo("guard-error"),
841
+ };
842
+ }
843
+ await safeLog(state, "warn", message);
844
+ }
845
+ return next();
846
+ });
847
+ ctx.on("tools/post-execute", async (exec, result, next) => {
848
+ try {
849
+ await reloadConfigIfChanged(state);
850
+ // Only a fully-off profile skips tracking and lint: `protect_off`
851
+ // stands down guardrails, not the per-edit evidence the gate reads —
852
+ // mirroring the OpenCode `execute.after`.
853
+ if (isProfileOff(state)) {
854
+ return next();
855
+ }
856
+ const command = extractDshCommand(exec);
857
+ const redirectTargets = command !== undefined ? extractRedirectTargets(command) : [];
858
+ const paths = [...new Set([...extractDshPaths(exec), ...redirectTargets])];
859
+ if (paths.length === 0) {
860
+ return next();
861
+ }
862
+ // Track first, like the OpenCode `execute.after`: a failed tool call
863
+ // may still have partially applied its write, and the gate must see it.
864
+ // Only format/lint are skipped on error.
865
+ for (const filePath of paths) {
866
+ state.tracker.add(filePath, state.directory);
867
+ }
868
+ if (result.isError) {
869
+ return next();
870
+ }
871
+ const execArgs = exec.arguments;
872
+ const rawInput = typeof execArgs === "object" && execArgs !== null
873
+ ? execArgs["input"]
874
+ : undefined;
875
+ warnApplyPatchSkip(state, exec, rawInput, paths);
876
+ if (state.config.precommit === "auto" && state.precommitAvailable === undefined) {
877
+ state.precommitAvailable = await detectPreCommitAvailability(run, state.directory);
878
+ }
879
+ const timeout = state.config.gate?.timeout;
880
+ const reports = [];
881
+ const lintOutcomes = [];
882
+ for (const filePath of paths) {
883
+ if (inflight.has(filePath)) {
884
+ continue;
885
+ }
886
+ inflight.add(filePath);
887
+ try {
888
+ await state.lintLimiter.run(async () => {
889
+ // Format-then-lint: a formatter that rewrites must run before the
890
+ // linter reads, so the linter never flags what the formatter fixes.
891
+ // Skips stay at debug (core `runPerEditLint` contract) — only real
892
+ // outcomes reach `reports` and the agent context.
893
+ if (state.config.on_edit.format === true) {
894
+ const formatted = await formatFile(run, state.config, filePath, {
895
+ cwd: state.directory,
896
+ timeout,
897
+ });
898
+ if (formatted.skipped) {
899
+ await safeLog(state, "debug", summarizeFormat(formatted), { filePath });
900
+ }
901
+ else {
902
+ reports.push(summarizeFormat(formatted));
903
+ }
904
+ if (isFormatFailure(formatted)) {
905
+ await safeLog(state, "error", summarizeFormat(formatted), {
906
+ filePath,
907
+ command: formatted.command?.join(" "),
908
+ stdout: formatted.result?.stdout,
909
+ stderr: formatted.result?.stderr,
910
+ });
911
+ }
912
+ }
913
+ if (state.config.on_edit.lint === true) {
914
+ const linted = await lintFile(run, state.config, filePath, {
915
+ cwd: state.directory,
916
+ timeout,
917
+ precommitAvailable: state.precommitAvailable,
918
+ });
919
+ if (linted.skipped) {
920
+ await safeLog(state, "debug", summarizeLint(linted), { filePath });
921
+ }
922
+ else {
923
+ reports.push(summarizeLint(linted));
924
+ lintOutcomes.push(linted);
925
+ }
926
+ if (!linted.skipped) {
927
+ await safeLog(state, isLintFailure(linted) ? "error" : "info", summarizeLint(linted), { filePath });
928
+ }
929
+ }
930
+ });
931
+ }
932
+ finally {
933
+ inflight.delete(filePath);
934
+ }
935
+ }
936
+ // Model-fault lint findings fail the tool call itself (`block` turns
937
+ // the result into a model-facing error): the agent fixes its edit in
938
+ // the same turn instead of sailing on to be caught at the gate. The
939
+ // OpenCode `execute.after` cannot do this — a landed edit can only be
940
+ // logged. Advisory never blocks; format outcomes never block (the
941
+ // formatter is fix-up, and its nonzero exits are ambiguous infra);
942
+ // infra-looking lint outcomes (timeouts, 127, silent exits) stay
943
+ // accept + error-log with the file tracked for the gate.
944
+ const faults = lintBlockLines(lintOutcomes);
945
+ if (faults.length > 0 && state.config.profile !== "advisory") {
946
+ await safeLog(state, "error", `post-execute lint blocks ${paths.join(", ")}`, {
947
+ faults: faults.length,
948
+ });
949
+ return {
950
+ kind: "block",
951
+ feedback: [
952
+ {
953
+ type: "text",
954
+ text: `[odf post-execute] your edit introduced lint findings; fix them and retry:\n${faults.join("\n")}`,
955
+ },
956
+ ],
957
+ info: odfInfo("lint-block"),
958
+ };
959
+ }
960
+ if (reports.length > 0) {
961
+ return {
962
+ kind: "accept",
963
+ additionalContexts: [dshUserMessage(`[odf post-execute]\n${reports.join("\n")}`)],
964
+ };
965
+ }
966
+ }
967
+ catch (error) {
968
+ await safeLog(state, "warn", `post-execute error (fail-open): ${error?.message ?? error}`);
969
+ }
970
+ return next();
971
+ });
972
+ ctx.on("agent/pre-step", async ({ agent, messages, turn }, next) => {
973
+ try {
974
+ await reloadConfigIfChanged(state);
975
+ // Fully off means no instruction either — mirroring the OpenCode
976
+ // context hook, which returns before touching the system prompt.
977
+ if (isProfileOff(state)) {
978
+ return next();
979
+ }
980
+ // Nothing proposed, nothing to prepend to (mirror of the Codex
981
+ // pre-step guard in the host tree).
982
+ if (messages.length === 0) {
983
+ return next();
984
+ }
985
+ const key = sessionOf(agent, turn);
986
+ // Specialist findings (plan 26): a completion notice for a child
987
+ // this adapter dispatched carries its closing message as review
988
+ // evidence. Collect per session; the next gate block folds the
989
+ // findings into its steer and clears them. Notices for children
990
+ // the adapter did not dispatch are ignored. Scanned before the
991
+ // injection early-return: findings arrive on later steps, after
992
+ // the session is already injected.
993
+ {
994
+ const pending = dispatchedSpecialists.get(key);
995
+ if (pending !== undefined && pending.size > 0) {
996
+ for (const message of messages) {
997
+ const text = enteringMessageText(message);
998
+ if (text === null) {
999
+ continue;
1000
+ }
1001
+ const match = SPECIALIST_NOTICE_RE.exec(text);
1002
+ if (match === null) {
1003
+ continue;
1004
+ }
1005
+ const finished = match[1];
1006
+ if (![...pending.values()].includes(finished)) {
1007
+ continue;
1008
+ }
1009
+ // The child finished: consume its kind slot whether or not
1010
+ // it reported anything, so a silent child never wedges
1011
+ // future blocks. Empty closings fold nothing.
1012
+ for (const [kind, childName] of pending) {
1013
+ if (childName === finished) {
1014
+ pending.delete(kind);
1015
+ }
1016
+ }
1017
+ const finding = (match[2] ?? "").trim();
1018
+ if (finding !== "") {
1019
+ const collected = specialistFindings.get(key) ?? [];
1020
+ collected.push(`[${finished}] ${finding}`);
1021
+ specialistFindings.set(key, collected);
1022
+ await safeLog(state, "info", `specialist findings collected: ${finished}`, {
1023
+ sessionID: key,
1024
+ });
1025
+ }
1026
+ else {
1027
+ await safeLog(state, "debug", `specialist finished silent: ${finished}`, {
1028
+ sessionID: key,
1029
+ });
1030
+ }
1031
+ }
1032
+ }
1033
+ }
1034
+ // Already injected under the current config: pass through (the
1035
+ // once-per-session rule; admitted history keeps its copy, exactly
1036
+ // like system text already admitted on the OpenCode side).
1037
+ if (injectedSessions.get(key) === state.configMtime) {
1038
+ return next();
1039
+ }
1040
+ if (state.constitution === null) {
1041
+ const loaded = await loadConstitution(state.config, state.directory);
1042
+ state.constitution = loaded.constitution;
1043
+ if (loaded.warning !== undefined) {
1044
+ await safeLog(state, "warn", loaded.warning);
1045
+ }
1046
+ }
1047
+ const prepend = [];
1048
+ if (state.constitution !== null) {
1049
+ prepend.push(dshUserMessage(state.constitution));
1050
+ }
1051
+ const roster = renderDutyRoster(state.config);
1052
+ if (roster !== null) {
1053
+ prepend.push(dshUserMessage(roster));
1054
+ await safeLog(state, "debug", "duty roster prepended at session start");
1055
+ }
1056
+ // Startup template-drift mention — once per session, best-effort.
1057
+ // First pre-step of a session is session startup (mount has no
1058
+ // session to mention into). Never throws into step assembly.
1059
+ try {
1060
+ const line = driftMentionLine(await checkTemplateUpdates(state.directory, DSH_SKILL_ROOTS[0]));
1061
+ if (line !== null) {
1062
+ prepend.push(dshUserMessage(line));
1063
+ await safeLog(state, "debug", "template drift mentioned at session startup");
1064
+ }
1065
+ }
1066
+ catch (error) {
1067
+ await safeLog(state, "debug", "startup drift check failed silently", {
1068
+ error: String(error),
1069
+ });
1070
+ }
1071
+ if (prepend.length === 0) {
1072
+ return next();
1073
+ }
1074
+ injectedSessions.set(key, state.configMtime);
1075
+ await safeLog(state, "info", "constitution injected at session start");
1076
+ return { kind: "enter", messages: [...prepend, ...messages] };
1077
+ }
1078
+ catch (error) {
1079
+ // Injection is advisory by nature (the gates still enforce): never
1080
+ // let a load failure break step assembly.
1081
+ await safeLog(state, "warn", `pre-step inject error (fail-open): ${error?.message ?? error}`);
1082
+ return next();
1083
+ }
1084
+ });
1085
+ ctx.on("agent/turn-stopping", async ({ agent, turn, signal }) => {
1086
+ try {
1087
+ // Children owe no review duty: the artifact belongs to the
1088
+ // top-level session, so a child idling on a dirty tree must never
1089
+ // be steered into the review loop. Skip before any gate work — no
1090
+ // verdict, no steer, no stamp. The parent answers for the shared
1091
+ // tree at its own boundary.
1092
+ if (isChildAgent(agent)) {
1093
+ await safeLog(state, "debug", "completion gate skipped: child session owes no review duty");
1094
+ return;
1095
+ }
1096
+ await reloadConfigIfChanged(state);
1097
+ const sessionID = sessionOf(agent, turn);
1098
+ // Continuity probe (plan 27): assessed once per session, before any
1099
+ // gate work, in every profile including off — it reports, never
1100
+ // gates. Awaited here (not fire-and-forget) so the first `df-status`
1101
+ // after a turn boundary already names the state.
1102
+ await ensureContinuity(sessionID);
1103
+ // Only a fully-off profile skips the gate: `protect_off` stands
1104
+ // down guardrails, not the completion contract — mirroring the
1105
+ // OpenCode idle gate, which never consults `protect_off`.
1106
+ if (isProfileOff(state)) {
1107
+ return;
1108
+ }
1109
+ const verdict = await runCompletion(state, sessionID);
1110
+ const message = await actOnVerdict(state, verdict);
1111
+ // Refresh the `df-runtime` snapshot: a block prevents termination and
1112
+ // continues the same turn ("idle" = gate failures continue the same
1113
+ // execution); pass and standdown leave the gate armed for the next turn.
1114
+ stampRuntimeStatus(state.directory, "turn-stopping", message === null ? "armed" : "idle", DSH_SKILL_ROOTS[0]);
1115
+ if (message === null) {
1116
+ return;
1117
+ }
1118
+ // Fold collected specialist findings (plan 26), then clear: each
1119
+ // finding steers exactly one block, never a stale copy.
1120
+ let steerText = message;
1121
+ const collected = specialistFindings.get(sessionID);
1122
+ if (collected !== undefined && collected.length > 0) {
1123
+ specialistFindings.delete(sessionID);
1124
+ steerText +=
1125
+ "\n\nSpecialist findings (incorporate before writing the review artifact):\n" +
1126
+ collected.join("\n");
1127
+ }
1128
+ // Dispatch specialists on review-blocks only (plan 26.3): the tree
1129
+ // is green and only the review duty is unmet — exactly the
1130
+ // reviewers' job. Gate-blocks (failing tests) need the lead to fix
1131
+ // code first; reviewing a red tree would burn child runs for
1132
+ // findings the gate already reports. Weakened blocks steer text
1133
+ // only. Advisory never dispatches — it warns instead of blocking.
1134
+ // At most one pending child per kind per session: a new block
1135
+ // while one is outstanding reuses the slot instead of fanning out.
1136
+ // Absent seam or spawn failure degrades to the inline steer.
1137
+ let specialistLine = "";
1138
+ if (verdict.decision === "blocked" &&
1139
+ verdict.reason === "review" &&
1140
+ (state.config.profile === "standard" || state.config.profile === "strict") &&
1141
+ state.seams?.subagents === true) {
1142
+ const dispatched = [];
1143
+ for (const kind of SPECIALIST_KINDS) {
1144
+ if (pendingSpecialist(sessionID, kind) !== undefined) {
1145
+ continue;
1146
+ }
1147
+ const name = await spawnSpecialist(sessionID, kind, agent, state.tracker.getChangedFiles(), message, signal);
1148
+ if (name !== null) {
1149
+ dispatched.push(name);
1150
+ }
1151
+ }
1152
+ if (dispatched.length > 0) {
1153
+ specialistLine =
1154
+ `\n\nSpecialist review dispatched (${dispatched.join(", ")}): their ` +
1155
+ "completion notices will arrive shortly — incorporate their findings " +
1156
+ "alongside this summary before writing the review artifact.";
1157
+ }
1158
+ }
1159
+ // Blocked: prevent termination by steering the gate summary into the
1160
+ // same turn. This is DSH's behavioral equivalent of the original
1161
+ // framework's stop-hook `decision: block`: the host awaits listeners,
1162
+ // then re-reads its inbox, and non-empty next-step work means the turn
1163
+ // cannot close. `followup` is only a degraded fallback when steering
1164
+ // is unavailable. Budget exhaustion is already a core `standdown`
1165
+ // verdict (no steer) — the adapter never counts blocks itself.
1166
+ const followup = dshUserMessage(steerText + specialistLine);
1167
+ try {
1168
+ // Single abort check immediately before steering: an abort landing
1169
+ // between gate evaluation and this line must not wake a new turn
1170
+ // with stale feedback (host `send` reroutes waking input after
1171
+ // abort). Nothing that touches the inbox runs between check and
1172
+ // steer, so the window is closed. The log keeps the evidence.
1173
+ if (signal?.aborted === true) {
1174
+ await safeLog(state, "debug", "turn-stopping gate blocked but turn aborted; steer dropped", {
1175
+ sessionID,
1176
+ });
1177
+ }
1178
+ else if (typeof agent.steer === "function") {
1179
+ agent.steer(followup);
1180
+ }
1181
+ else if (typeof agent.followup === "function") {
1182
+ agent.followup(followup);
1183
+ }
1184
+ else {
1185
+ await safeLog(state, "warn", "turn-stopping blocked but agent has no steer/followup seam");
1186
+ }
1187
+ }
1188
+ catch (error) {
1189
+ await safeLog(state, "warn", `turn-stopping steer failed (seam gap): ${error?.message ?? error}`);
1190
+ }
1191
+ }
1192
+ catch (error) {
1193
+ await safeLog(state, "warn", `turn-stopping error: ${error?.message ?? error}`);
1194
+ }
1195
+ });
1196
+ ctx.commands.register({
1197
+ name: "df-status",
1198
+ description: "Show opencode-dev-framework gate status (profile, config, enforcement level) plus session continuity.",
1199
+ handler: async (invocation) => {
1200
+ // Continuity is session-scoped and the invoking agent names the
1201
+ // session; without an invocation there is nothing to assess.
1202
+ const agent = invocation?.agent;
1203
+ const continuity = agent === undefined ? "unknown" : await ensureContinuity(sessionOf(agent, undefined));
1204
+ return {
1205
+ kind: "success",
1206
+ text: `${renderStatus(state.config, state, {
1207
+ formatOwner: DSH_FORMAT_OWNER,
1208
+ })}\n\n${renderContinuity(continuity)}`,
1209
+ };
1210
+ },
1211
+ });
1212
+ // Runtime snapshot: hook registration, gate continuation posture, and
1213
+ // template drift — the console-text shape of the TUI `/df-runtime`
1214
+ // modal (a DSH host has no dialog surface; the text IS the surface).
1215
+ // The snapshot is stamped by `apply()` ("armed") and refreshed by every
1216
+ // turn-stopping evaluation; absent until the first stamp lands.
1217
+ ctx.commands.register({
1218
+ name: "df-runtime",
1219
+ description: "Show plugin version and live hook/gate runtime state (hook registration, continuation posture, template drift).",
1220
+ handler: async () => {
1221
+ try {
1222
+ await reloadConfigIfChanged(state);
1223
+ const snapshot = await readRuntimeStatus(state.directory);
1224
+ return { kind: "success", text: renderRuntimeStatus(snapshot) };
1225
+ }
1226
+ catch (error) {
1227
+ return { kind: "error", text: `df-runtime failed: ${error?.message ?? error}` };
1228
+ }
1229
+ },
1230
+ });
1231
+ // Command list: the `renderHelp` text is the DSH surface where the
1232
+ // OpenCode TUI would render the `/df-help` modal.
1233
+ ctx.commands.register({
1234
+ name: "df-help",
1235
+ description: "List the opencode-dev-framework commands.",
1236
+ handler: () => ({ kind: "success", text: renderHelp() }),
1237
+ });
1238
+ // Verified goal: availability check + pure verified-objective build, then
1239
+ // delegate to the host goal service (`ctx.goals.create`, the DSH-native
1240
+ // equivalent of opencode's `session.command` delegation). Same contract
1241
+ // as opencode's `/df-goal`: blocking profile required, native goal
1242
+ // required, objective wrapped exactly once, no unverified fallback.
1243
+ ctx.commands.register({
1244
+ name: "df-goal",
1245
+ description: "Start a verified native goal: appends a dev_framework_verify contract to the objective and creates the host goal exactly once. Requires native /goal and a blocking profile.",
1246
+ input: { hint: "<objective>" },
1247
+ handler: async (invocation) => {
1248
+ try {
1249
+ invocation.signal?.throwIfAborted();
1250
+ await reloadConfigIfChanged(state);
1251
+ const objective = invocation.rawInput.trim();
1252
+ let nativeGoalAvailable = false;
1253
+ try {
1254
+ // Core tolerates bare-array and `{data: [...]}`-wrapped
1255
+ // listings alike; anything unrecognized fails closed.
1256
+ nativeGoalAvailable =
1257
+ typeof ctx.commands.list === "function"
1258
+ ? isNativeGoalListed(await ctx.commands.list(invocation.agent))
1259
+ : false;
1260
+ }
1261
+ catch {
1262
+ nativeGoalAvailable = false;
1263
+ }
1264
+ const availability = checkGoalAvailability(state.config, nativeGoalAvailable);
1265
+ if (!availability.ok) {
1266
+ return { kind: "error", text: availability.error };
1267
+ }
1268
+ const built = buildVerifiedObjective(objective);
1269
+ if (!built.ok) {
1270
+ return { kind: "error", text: built.error };
1271
+ }
1272
+ // The host throws on reading a non-injected service, so the
1273
+ // read itself is guarded (same as the agent-tool registration).
1274
+ // The service object (not the bare method) is captured so the
1275
+ // `create` call keeps its receiver.
1276
+ let goals;
1277
+ try {
1278
+ goals = ctx.goals;
1279
+ }
1280
+ catch {
1281
+ goals = undefined;
1282
+ }
1283
+ if (typeof goals?.create !== "function") {
1284
+ return {
1285
+ kind: "error",
1286
+ text: "Cannot start a verified goal: the host goal service is not available on this core. Run the objective without verification where a goal service exists.",
1287
+ };
1288
+ }
1289
+ await goals.create(invocation.agent, { objective: built.text });
1290
+ return {
1291
+ kind: "success",
1292
+ text: `Verified goal created via native /goal${built.alreadyWrapped ? " (objective already wrapped, reused verbatim)" : ""}.\n` +
1293
+ `Objective (with verification contract):\n${built.text}`,
1294
+ };
1295
+ }
1296
+ catch (error) {
1297
+ return { kind: "error", text: `df-goal failed: ${error?.message ?? error}` };
1298
+ }
1299
+ },
1300
+ });
1301
+ // On-demand gate: same full completion contract as the turn-stopping gate,
1302
+ // run when asked instead of at the boundary. Fills the slot the missing
1303
+ // TUI `/df-verify` leaves on DSH.
1304
+ ctx.commands.register({
1305
+ name: "df-verify",
1306
+ description: "Run the full completion gate on demand (typecheck, tests, lint, review state) and report PASS/FAIL. Side-effect-free: never retries, never steers.",
1307
+ handler: async () => {
1308
+ try {
1309
+ await reloadConfigIfChanged(state);
1310
+ const result = await verifyGate(run, state.directory, state.config, state.tracker.getChangedFiles());
1311
+ return { kind: "success", text: result.summary };
1312
+ }
1313
+ catch (error) {
1314
+ return { kind: "error", text: `df-verify failed: ${error?.message ?? error}` };
1315
+ }
1316
+ },
1317
+ });
1318
+ // Profile switch: same `changeProfile` core as the TUI modal and the
1319
+ // `dev_framework_set_profile` custom tool on OpenCode. The adapter
1320
+ // picks the new profile up on the next tool call / gate run.
1321
+ ctx.commands.register({
1322
+ name: "df-profile",
1323
+ description: "Change the enforcement profile (off, advisory, standard, strict).",
1324
+ input: { hint: "<off|advisory|standard|strict>" },
1325
+ handler: async (invocation) => {
1326
+ try {
1327
+ const raw = invocation.rawInput.trim().toLowerCase();
1328
+ if (raw !== "off" && raw !== "advisory" && raw !== "standard" && raw !== "strict") {
1329
+ return {
1330
+ kind: "error",
1331
+ text: `Unknown profile "${invocation.rawInput.trim()}". Use one of: off, advisory, standard, strict.`,
1332
+ };
1333
+ }
1334
+ await reloadConfigIfChanged(state);
1335
+ const text = await changeProfile(state.directory, raw);
1336
+ return { kind: "success", text };
1337
+ }
1338
+ catch (error) {
1339
+ return { kind: "error", text: `df-profile failed: ${error?.message ?? error}` };
1340
+ }
1341
+ },
1342
+ });
1343
+ // Project setup: deterministic half in code (scaffold templates,
1344
+ // detected config, trial-run, wizard brief), judgment half handed to
1345
+ // the agent via `followup` — the DSH-native shape of opencode's
1346
+ // `session.prompt` handoff (same pattern as operator-memory's
1347
+ // `operator-project-init`). Safe to re-run; reports status when
1348
+ // already configured.
1349
+ ctx.commands.register({
1350
+ name: "df-init",
1351
+ 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.",
1352
+ handler: async (invocation) => {
1353
+ try {
1354
+ invocation.signal?.throwIfAborted();
1355
+ await reloadConfigIfChanged(state);
1356
+ const delivered = await runInitCommand({
1357
+ directory: state.directory,
1358
+ run,
1359
+ delivery: undefined,
1360
+ // Setup intent: the scaffold must leave the agent able to load
1361
+ // the shipped skills through the host `skill` tool, so mirror
1362
+ // them into a scanned root and word the brief for host-native
1363
+ // tools (`skill` + `ask_user_question`).
1364
+ skillMirrorRoot: DSH_SKILL_ROOTS[0],
1365
+ skillAccess: "tool",
1366
+ checkAlive: () => invocation.signal?.throwIfAborted(),
1367
+ reload: async () => {
1368
+ clearConfigCache();
1369
+ const newConfig = loadConfig(state.directory);
1370
+ const { constitution: newConstitution } = await loadConstitution(newConfig, state.directory);
1371
+ state.config = newConfig;
1372
+ state.constitution = newConstitution;
1373
+ for (const name of CONFIG_FILE_PRECEDENCE) {
1374
+ try {
1375
+ const mtimeMs = (await stat(join(state.directory, name))).mtimeMs;
1376
+ if (state.configMtime === undefined || mtimeMs > state.configMtime) {
1377
+ state.configMtime = mtimeMs;
1378
+ }
1379
+ }
1380
+ catch {
1381
+ // name absent
1382
+ }
1383
+ }
1384
+ },
1385
+ deliver: async (text) => {
1386
+ // Receiver-preserving method call: a bare-function
1387
+ // extraction would drop a `this`-dependent host
1388
+ // implementation (same class as the tools.register fix).
1389
+ const agent = invocation.agent;
1390
+ if (typeof agent.followup !== "function") {
1391
+ // Core converts a delivery throw into a precise
1392
+ // scaffold-succeeded-but-handoff-failed error (init.ts).
1393
+ throw new Error("df-init: the host agent has no followup seam; setup brief could not be handed off");
1394
+ }
1395
+ agent.followup(dshUserMessage(text));
1396
+ },
1397
+ note: async (level, message, extra) => {
1398
+ await safeLog(state, level, message, extra);
1399
+ },
1400
+ });
1401
+ if (!delivered) {
1402
+ return { kind: "success", text: "df-init: project already configured and clean." };
1403
+ }
1404
+ return {
1405
+ kind: "success",
1406
+ text: "df-init: scaffold complete; setup brief handed to the session.",
1407
+ };
1408
+ }
1409
+ catch (error) {
1410
+ return { kind: "error", text: `df-init failed: ${error?.message ?? error}` };
1411
+ }
1412
+ },
1413
+ });
1414
+ // Template refresh: drift check (read-only), handoff when drift needs
1415
+ // an agent. Mirrors opencode's `/df-update` with a `followup` handoff
1416
+ // instead of `session.prompt`.
1417
+ ctx.commands.register({
1418
+ name: "df-update",
1419
+ description: "Check for template drift between the deployed project files and the shipped set; hands the refresh list to the agent when drift needs attention. Read-only; safe to re-run.",
1420
+ handler: async (invocation) => {
1421
+ try {
1422
+ invocation.signal?.throwIfAborted();
1423
+ await reloadConfigIfChanged(state);
1424
+ const delivered = await runUpdateCommand({
1425
+ directory: state.directory,
1426
+ delivery: undefined,
1427
+ // The init-time mirror is maintained, not fire-and-forget: a
1428
+ // missing or edited-out-of-sync skill copy reads as drift.
1429
+ skillMirrorRoot: DSH_SKILL_ROOTS[0],
1430
+ checkAlive: () => invocation.signal?.throwIfAborted(),
1431
+ deliver: async (text) => {
1432
+ // Receiver-preserving method call: a bare-function
1433
+ // extraction would drop a `this`-dependent host
1434
+ // implementation (same class as the tools.register fix).
1435
+ const agent = invocation.agent;
1436
+ if (typeof agent.followup !== "function") {
1437
+ // Core converts a delivery throw into a precise
1438
+ // refreshed-but-handoff-failed error (update.ts).
1439
+ throw new Error("df-update: the host agent has no followup seam; refresh handoff could not be delivered");
1440
+ }
1441
+ agent.followup(dshUserMessage(text));
1442
+ },
1443
+ });
1444
+ if (!delivered) {
1445
+ return { kind: "success", text: "df-update: templates current, nothing to do." };
1446
+ }
1447
+ return {
1448
+ kind: "success",
1449
+ text: "df-update: drift detected; refresh list handed to the session.",
1450
+ };
1451
+ }
1452
+ catch (error) {
1453
+ return { kind: "error", text: `df-update failed: ${error?.message ?? error}` };
1454
+ }
1455
+ },
1456
+ });
1457
+ // Agent-invokable tools: the same `dev_framework_*` tools the
1458
+ // OpenCode adapter installs (verify, profile, status, init, update,
1459
+ // runtime), over the same core functions. Definitions
1460
+ // are plain objects in the host's compiled `defineTool` shape (JSON
1461
+ // Schema parameters, canonical string value schema with a text
1462
+ // renderer) — see `DshToolDefinition`. Each registration is isolated:
1463
+ // a host that rejects one definition still gets the rest.
1464
+ registerDshTool(ctx, state, {
1465
+ name: "dev_framework_verify",
1466
+ description: "Run the full opencode-dev-framework completion contract now (typecheck, tests, changed-file lint, peer-review state) and return the summary. The first line is DEV_FRAMEWORK_VERDICT: PASS or FAIL, reporting the raw inspection outcome. Use for a mid-session gate check without waiting for turn-stopping; unlike the gate this never steers, it only reports.",
1467
+ parameters: {
1468
+ type: "object",
1469
+ properties: {
1470
+ directory: {
1471
+ type: "string",
1472
+ description: "Project directory (defaults to current project)",
1473
+ },
1474
+ },
1475
+ additionalProperties: false,
1476
+ },
1477
+ isConcurrencySafe: () => true,
1478
+ execute: async (input) => {
1479
+ const args = input;
1480
+ const targetDir = args.directory ?? state.directory;
1481
+ const liveState = getActiveState();
1482
+ const live = liveState !== null && liveState.directory === targetDir ? liveState : null;
1483
+ const own = state.directory === targetDir ? state : null;
1484
+ const holder = live ?? own;
1485
+ // Live tracker's changed files beat the empty default: a mid-session
1486
+ // verify scopes `changed` steps to real edits (mirror of opencode).
1487
+ const cfg = holder?.config ?? loadConfig(targetDir);
1488
+ const changed = holder !== null ? holder.tracker.getChangedFiles() : [];
1489
+ const { summary } = await verifyGate(run, targetDir, cfg, changed);
1490
+ return summary;
1491
+ },
1492
+ });
1493
+ registerDshTool(ctx, state, {
1494
+ name: "dev_framework_set_profile",
1495
+ description: "Change the opencode-dev-framework profile (off, advisory, standard, strict) for the current project and apply it immediately.",
1496
+ parameters: {
1497
+ type: "object",
1498
+ properties: {
1499
+ profile: {
1500
+ type: "string",
1501
+ description: "New profile: off, advisory, standard, or strict",
1502
+ },
1503
+ directory: {
1504
+ type: "string",
1505
+ description: "Project directory (defaults to current project)",
1506
+ },
1507
+ },
1508
+ required: ["profile"],
1509
+ additionalProperties: false,
1510
+ },
1511
+ execute: async (input) => {
1512
+ const args = input;
1513
+ const targetDir = args.directory ?? state.directory;
1514
+ const profile = args.profile.trim().toLowerCase();
1515
+ const valid = ["off", "advisory", "standard", "strict"];
1516
+ if (!valid.includes(profile)) {
1517
+ return `Invalid profile "${args.profile}". Valid values: ${valid.join(", ")}.`;
1518
+ }
1519
+ const message = await changeProfile(targetDir, profile);
1520
+ clearConfigCache();
1521
+ const newConfig = loadConfig(targetDir);
1522
+ const { constitution: newConstitution } = await loadConstitution(newConfig, targetDir);
1523
+ if (state.directory === targetDir) {
1524
+ state.config = newConfig;
1525
+ state.constitution = newConstitution;
1526
+ }
1527
+ const liveState = getActiveState();
1528
+ if (liveState !== null && liveState !== state && liveState.directory === targetDir) {
1529
+ liveState.config = newConfig;
1530
+ liveState.constitution = newConstitution;
1531
+ }
1532
+ return `${message} Change applied immediately.`;
1533
+ },
1534
+ });
1535
+ registerDshTool(ctx, state, {
1536
+ name: "dev_framework_status",
1537
+ description: "Show the current opencode-dev-framework state for the project: active profile, guardrails, completion gate, on-edit behavior, tracked changed files, and block counts.",
1538
+ parameters: {
1539
+ type: "object",
1540
+ properties: {
1541
+ directory: {
1542
+ type: "string",
1543
+ description: "Project directory (defaults to current project)",
1544
+ },
1545
+ },
1546
+ additionalProperties: false,
1547
+ },
1548
+ isConcurrencySafe: () => true,
1549
+ execute: async (input) => {
1550
+ const args = input;
1551
+ const targetDir = args.directory ?? state.directory;
1552
+ const liveState = getActiveState();
1553
+ const live = liveState !== null && liveState.directory === targetDir ? liveState : null;
1554
+ const own = state.directory === targetDir ? state : null;
1555
+ const holder = live ?? own;
1556
+ const cfg = holder?.config ?? loadConfig(targetDir);
1557
+ // Nullable like the OpenCode tool: a foreign directory renders
1558
+ // config-only instead of misattributing our tracker data to it.
1559
+ return renderStatus(cfg, holder, {
1560
+ formatOwner: DSH_FORMAT_OWNER,
1561
+ });
1562
+ },
1563
+ });
1564
+ registerDshTool(ctx, state, {
1565
+ name: "dev_framework_init",
1566
+ description: "Scaffold opencode-dev-framework project files (agents, skills, commands, default config) into the current project, mirroring skills into the host-scanned skill root. Missing files are created; existing files are skipped unless overwrite is true. With wizard:true, appends a wizard brief (detection, trial-run, Makefile targets, open questions) when the scaffold changed anything, or a status note when already configured.",
1567
+ parameters: {
1568
+ type: "object",
1569
+ properties: {
1570
+ directory: {
1571
+ type: "string",
1572
+ description: "Target project directory (defaults to current project)",
1573
+ },
1574
+ overwrite: {
1575
+ type: "boolean",
1576
+ description: "Overwrite existing files that differ from templates",
1577
+ },
1578
+ wizard: {
1579
+ type: "boolean",
1580
+ description: "Append a wizard brief for agent-led handoff to the project-config skill",
1581
+ },
1582
+ },
1583
+ additionalProperties: false,
1584
+ },
1585
+ execute: async (input) => {
1586
+ const args = input;
1587
+ const targetDir = args.directory ?? state.directory;
1588
+ const scaffold = await runInitScaffold(targetDir, run, {
1589
+ wizard: args.wizard,
1590
+ overwrite: args.overwrite,
1591
+ // Same kick-start contract as the `df-init` command: the agent
1592
+ // must be able to load the skills through the host `skill` tool.
1593
+ skillMirrorRoot: DSH_SKILL_ROOTS[0],
1594
+ });
1595
+ return scaffoldReportLines(scaffold, targetDir).join("\n");
1596
+ },
1597
+ });
1598
+ registerDshTool(ctx, state, {
1599
+ name: "dev_framework_update",
1600
+ description: "Check the framework deployment for drift (bundled templates and the host-scanned skill mirror) 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.",
1601
+ parameters: {
1602
+ type: "object",
1603
+ properties: {
1604
+ directory: {
1605
+ type: "string",
1606
+ description: "Target project directory (defaults to current project)",
1607
+ },
1608
+ },
1609
+ additionalProperties: false,
1610
+ },
1611
+ isConcurrencySafe: () => true,
1612
+ execute: async (input) => {
1613
+ const args = input;
1614
+ const targetDir = args.directory ?? state.directory;
1615
+ const drift = await checkTemplateUpdates(targetDir, DSH_SKILL_ROOTS[0]);
1616
+ if (!needsAgentHandoff(drift)) {
1617
+ return "templates current";
1618
+ }
1619
+ return composeUpdatePrompt(drift, targetDir);
1620
+ },
1621
+ });
1622
+ registerDshTool(ctx, state, {
1623
+ name: "dev_framework_runtime",
1624
+ 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.",
1625
+ parameters: {
1626
+ type: "object",
1627
+ properties: {
1628
+ directory: {
1629
+ type: "string",
1630
+ description: "Target project directory (defaults to current project)",
1631
+ },
1632
+ },
1633
+ additionalProperties: false,
1634
+ },
1635
+ isConcurrencySafe: () => true,
1636
+ execute: async (input) => {
1637
+ const args = input;
1638
+ const targetDir = args.directory ?? state.directory;
1639
+ const snapshot = await readRuntimeStatus(targetDir);
1640
+ return renderRuntimeStatus(snapshot);
1641
+ },
1642
+ });
1643
+ }