opencode-dev-framework 1.9.5 → 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 (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 +16 -6
  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
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Guardrail logic: match tool calls against protected paths and dangerous
3
3
  * shell commands. Pure functions — the OpenCode hook wiring lives in
4
- * src/index.ts.
4
+ * src/adapters/opencode/index.ts, the DSH wiring in src/adapters/dsh/.
5
5
  */
6
6
  import { basename, isAbsolute, relative } from "node:path";
7
7
  import { compileGlobMatchers } from "./command-utils.js";
@@ -52,6 +52,15 @@ export function extractCommand(args) {
52
52
  }
53
53
  return undefined;
54
54
  }
55
+ /**
56
+ * Heredoc span: `<<`/`<<-` marker (not a `<<<` herestring) through the line
57
+ * that is exactly the delimiter. The body is stdin to the command, not shell
58
+ * syntax — scanning it for redirects turns code (`->`, `> 120`) into phantom
59
+ * file targets. Untouched when unterminated. The strip runs on the raw
60
+ * command before tokenizing, so a literal `<<DELIM` inside quoted prose
61
+ * still matches when a later bare `DELIM` line exists — accepted as rare.
62
+ */
63
+ const HEREDOC_RE = /(?<!<)<<-?(?!<)[ \t]*(["']?)(\S+)\1[ \t]*\r?\n[\s\S]*?\n[ \t]*\2[ \t]*(?=\r?$|\r?\n)/g;
55
64
  /**
56
65
  * Extract probable file-write targets from a shell command: filenames after
57
66
  * output redirections (`>`, `>>`, with optional fd/`&` prefixes, glued or
@@ -59,17 +68,22 @@ export function extractCommand(args) {
59
68
  * herestrings (`<<<`) carry input, never a target, so they are ignored.
60
69
  * Token-based and deliberately over-collecting within a command tail: that
61
70
  * is harmless because callers only act on exact artifact matches, while a
62
- * false negative would reopen a write path. Quote-aware.
71
+ * false negative would reopen a write path. Quote-aware: quoted spans are
72
+ * operands, never operators.
63
73
  */
64
74
  export function extractRedirectTargets(command) {
65
75
  const targets = [];
76
+ // Heredoc bodies are stdin, not shell: strip them before tokenizing so
77
+ // code inside (`->`, `> 120`) never becomes a phantom file target.
78
+ const scannable = command.replace(HEREDOC_RE, "");
66
79
  // Operators and separators stay visible as tokens so `tee` is only
67
80
  // honored in command position (not inside quoted prose).
68
81
  const tokens = [];
69
82
  const tokenRe = /"([^"]*)"|'([^']*)'|&&|\|\||[;|&()!<>]+|[^\s;|&<>()!]+/g;
70
- for (let m = tokenRe.exec(command); m !== null; m = tokenRe.exec(command)) {
71
- tokens.push(m[1] ?? m[2] ?? m[0]);
83
+ for (let m = tokenRe.exec(scannable); m !== null; m = tokenRe.exec(scannable)) {
84
+ tokens.push({ text: m[1] ?? m[2] ?? m[0], quoted: m[1] !== undefined || m[2] !== undefined });
72
85
  }
86
+ const tokenText = (t) => t.text;
73
87
  const isSeparator = (t) => /^(?:&&|\|\||[;|&()!<>]+)$/.test(t);
74
88
  const isBareRedirect = (t) => /^(?:\d*>>?\|?|&>>?\|?)$/.test(t);
75
89
  // Wrappers that pass through to the real command: `sudo tee`, `env A=B
@@ -86,7 +100,7 @@ export function extractRedirectTargets(command) {
86
100
  const collectOperands = (from) => {
87
101
  const operands = [];
88
102
  for (let j = from; j < tokens.length; j++) {
89
- const next = tokens[j];
103
+ const next = tokenText(tokens[j]);
90
104
  if (isSeparator(next) || isBareRedirect(next))
91
105
  break;
92
106
  if (!next.startsWith("-") && next !== "")
@@ -95,10 +109,14 @@ export function extractRedirectTargets(command) {
95
109
  return operands;
96
110
  };
97
111
  for (let i = 0; i < tokens.length; i++) {
98
- const token = tokens[i];
99
- const atCommand = i === 0 || isSeparator(tokens[i - 1]) || isBareRedirect(tokens[i - 1]);
112
+ const token = tokenText(tokens[i]);
113
+ const quoted = tokens[i].quoted;
114
+ const prev = i === 0 ? "" : tokenText(tokens[i - 1]);
115
+ // Quoted spans are prose, never operators — but stay eligible as
116
+ // targets/operands below (e.g. `> "my file"`, `tee "a b"`).
117
+ const atCommand = !quoted && (i === 0 || isSeparator(prev) || isBareRedirect(prev));
100
118
  const base = cmdBase(token);
101
- if (base === "tee" && (atCommand || isWrapper(tokens[i - 1] ?? ""))) {
119
+ if (base === "tee" && (atCommand || isWrapper(prev))) {
102
120
  // `tee` writes every non-flag operand that follows it.
103
121
  for (const next of collectOperands(i + 1)) {
104
122
  if (next === "tee")
@@ -116,7 +134,8 @@ export function extractRedirectTargets(command) {
116
134
  }
117
135
  if (atCommand &&
118
136
  base === "sed" &&
119
- tokens.some((t, k) => k > i && (t === "-i" || t === "--in-place" || /^-i./.test(t)))) {
137
+ tokens.some((t, k) => k > i &&
138
+ (tokenText(t) === "-i" || tokenText(t) === "--in-place" || /^-i./.test(tokenText(t))))) {
120
139
  // First non-flag operand is the script; the rest are files.
121
140
  let skippedScript = false;
122
141
  for (const next of collectOperands(i + 1)) {
@@ -128,15 +147,25 @@ export function extractRedirectTargets(command) {
128
147
  }
129
148
  continue;
130
149
  }
131
- if (isBareRedirect(token)) {
150
+ if (!quoted && isBareRedirect(token)) {
132
151
  const next = tokens[i + 1];
133
- if (next !== undefined && next !== "" && !isSeparator(next))
134
- targets.push(next);
152
+ const nextText = next === undefined ? "" : tokenText(next);
153
+ if (nextText !== "" && !isSeparator(nextText))
154
+ targets.push(nextText);
135
155
  continue;
136
156
  }
137
- // Glued forms: `2>file`, `>file`, `&>>file`. Exclude `<<`/`<<<`.
138
- if (token.includes(">") && !token.includes("<")) {
139
- const after = token.replace(/^.*?(?:\d*>>?|&>>?)/, "").replace(/^["']|["']$/g, "");
157
+ // Glued-form backstop: the tokenizer splits every glued operator
158
+ // (`2>file`, `>file`, `&>>file`) into bare-redirect + next-token, so
159
+ // this branch only fires on unforeseen token shapes — never on
160
+ // separators or quoted prose (see guards above). Exclude `<<`/`<<<`.
161
+ // Quoted spans never act as operators (prose like `->` is not a
162
+ // redirect), and separator tokens (`>&` in `2>&1`) carry no target —
163
+ // only real redirections name files.
164
+ if (!quoted && !isSeparator(token) && token.includes(">") && !token.includes("<")) {
165
+ const after = token
166
+ .replace(/^.*?(?:\d*>>?|&>>?)/, "")
167
+ .replace(/^["']|["']$/g, "")
168
+ .trim();
140
169
  if (after !== "")
141
170
  targets.push(after);
142
171
  }
@@ -206,6 +235,43 @@ function enforce(config, reason, matchedPattern) {
206
235
  }
207
236
  return { decision: "warn", reason, matchedPattern };
208
237
  }
238
+ /**
239
+ * Decide a file-path guard without touching tool args (plan 25 slice 4).
240
+ * Harness-agnostic seam: the OpenCode adapter reaches it via `checkToolCall`,
241
+ * the DSH adapter calls it directly with its own envelope extraction
242
+ * (`file_path`, `apply_patch` headers). Same verdicts, same reason text —
243
+ * one logic, two wirings.
244
+ */
245
+ export function decideFileGuard(config, filePath, directory, hostPermissions, tool = "edit") {
246
+ if (config.profile === "off" || config.protect_off) {
247
+ return { decision: "allow" };
248
+ }
249
+ if (hostDenies(tool, hostPermissions)) {
250
+ return { decision: "allow" };
251
+ }
252
+ const pattern = matchProtectedPath(config, filePath, directory);
253
+ if (pattern !== undefined) {
254
+ return enforce(config, `${tool} on protected path "${filePath}" is blocked (matched "${pattern}")`, pattern);
255
+ }
256
+ return { decision: "allow" };
257
+ }
258
+ /**
259
+ * Decide a shell-command guard without touching tool args (plan 25 slice 4).
260
+ * Same sharing contract as `decideFileGuard`.
261
+ */
262
+ export function decideShellGuard(config, command, hostPermissions, tool = "bash") {
263
+ if (config.profile === "off" || config.protect_off) {
264
+ return { decision: "allow" };
265
+ }
266
+ if (hostDenies(tool, hostPermissions)) {
267
+ return { decision: "allow" };
268
+ }
269
+ const dangerous = matchDangerousCommand(command);
270
+ if (dangerous !== undefined) {
271
+ return enforce(config, `${tool} command blocked: ${dangerous.reason}`, dangerous.pattern.source);
272
+ }
273
+ return { decision: "allow" };
274
+ }
209
275
  /**
210
276
  * Evaluate a tool call against the guardrail config.
211
277
  *
@@ -222,35 +288,20 @@ export function checkToolCall(config, tool, args, directory, hostPermissions) {
222
288
  if (filePath === undefined) {
223
289
  return { decision: "allow" };
224
290
  }
225
- // If the host permission model already denies this tool, do not duplicate
226
- // the block here.
227
- if (hostDenies(tool, hostPermissions)) {
228
- return { decision: "allow" };
229
- }
230
- const pattern = matchProtectedPath(config, filePath, directory);
231
- if (pattern !== undefined) {
232
- return enforce(config, `${tool} on protected path "${filePath}" is blocked (matched "${pattern}")`, pattern);
233
- }
234
- return { decision: "allow" };
291
+ return decideFileGuard(config, filePath, directory, hostPermissions, tool);
235
292
  }
236
293
  if (SHELL_TOOLS.has(tool)) {
237
294
  const command = extractCommand(args);
238
295
  if (command === undefined) {
239
296
  return { decision: "allow" };
240
297
  }
241
- if (hostDenies(tool, hostPermissions)) {
242
- return { decision: "allow" };
243
- }
244
- const dangerous = matchDangerousCommand(command);
245
- if (dangerous !== undefined) {
246
- return enforce(config, `bash command blocked: ${dangerous.reason}`, dangerous.pattern.source);
247
- }
298
+ return decideShellGuard(config, command, hostPermissions, tool);
248
299
  }
249
300
  return { decision: "allow" };
250
301
  }
251
302
  /**
252
- * Phase 25: adapt a native `permission.evaluate` event to the guardrail
253
- * verdict. Maps the observed engine shapes (spike 25.1, OpenCode v2.0.26 —
303
+ * Phase 25 (permission spike, items 25.1/25.2): adapt a native
304
+ * `permission.evaluate` event to the guardrail verdict. Maps the observed engine shapes (spike 25.1, OpenCode v2.0.26 —
254
305
  * recorded in docs/plans/08-notes.md, never guessed):
255
306
  * - action `"edit"` (covers edit/write/patch tools) with `resources[0]` =
256
307
  * the target file path (repo-relative).
@@ -1,7 +1,7 @@
1
1
  import type { ChangedFileTracker } from "./gate.js";
2
2
  import type { RunCommand } from "./host.js";
3
3
  import type { LogFn } from "./logger.js";
4
- import type { ResolvedConfig } from "./types.js";
4
+ import type { HostSeams, ResolvedConfig } from "./types.js";
5
5
  /**
6
6
  * OpenCode's native `permission` config is a per-agent, tool-to-mode object
7
7
  * (e.g. `{ edit: "deny", bash: "deny", read: "allow", task: {...} }`), not an
@@ -38,6 +38,14 @@ export interface HookState {
38
38
  * idle re-prompt net has. Absent until either fires. Memory-only: a
39
39
  * reload re-derives it on the next idle boundary. */
40
40
  continuationLevel?: "idle" | "fallback";
41
+ /**
42
+ * Host seam availability (see `HostSeams`), probed once at mount with
43
+ * guarded reads. Rendered by status so a degraded mount reads as
44
+ * degraded, never as silently whole. Unset on hosts whose seams are
45
+ * core-guaranteed (OpenCode leaves this unset; the DSH adapter probes
46
+ * it at mount).
47
+ */
48
+ seams?: HostSeams;
41
49
  }
42
50
  export declare function setBaseDirectory(directory: string): void;
43
51
  export declare function getBaseDirectory(): string | null;
@@ -19,11 +19,11 @@
19
19
  * session changed. Same out-of-scope line — deliberate misnaming
20
20
  * (naming files without reviewing them) is sabotage, not eagerness.
21
21
  *
22
- * The artifact path literal mirrors `REVIEW_ARTIFACT_REL` in
23
- * `harness.ts` (kept inline to avoid a module cycle; both are
24
- * pinned by tests).
22
+ * The artifact path is an alias of `REVIEW_ARTIFACT_REL` from the shared
23
+ * paths module (`paths.ts`), the single owner — no cycle, no second spelling.
25
24
  */
26
- const REVIEW_REL = ".opencode/opencode-dev-framework/review.md";
25
+ import { REVIEW_ARTIFACT_REL } from "./paths.js";
26
+ const REVIEW_REL = REVIEW_ARTIFACT_REL;
27
27
  /** Trimmed-character floor for a substantive review. */
28
28
  export const REVIEW_MIN_CHARS = 200;
29
29
  /** Whitespace-separated-token floor for a substantive review. */
@@ -40,7 +40,12 @@ const TEMPLATE_PATTERNS = [
40
40
  /\bfixme\b/i,
41
41
  /\bxxx\b/i,
42
42
  /lorem ipsum/i,
43
- /placeholder/i,
43
+ // Scaffolding-shaped uses only: ordinary meta-vocabulary such as
44
+ // "an empty placeholder file" is a finding, not an unfinished template.
45
+ /^[ \t]*(?:[-*+]\s+)?[A-Za-z][\w -]*:[ \t]*(?:placeholder\b|<\s*placeholder\s*>)[ \t]*$/im,
46
+ /^[ \t]*(?:[-*+]\s+)?placeholder\s*:/im,
47
+ /^[ \t]*(?:[-*+]\s+)?<\s*placeholder\s*>[ \t]*$/im,
48
+ /^[ \t]*(?:[-*+]\s+)?placeholder\s+(?:text|content|scope|findings?|resolutions?|summary)\b/im,
44
49
  /\[insert/i,
45
50
  /to be (filled|completed|determined)/i,
46
51
  /\bfill in\b/i,
@@ -132,8 +137,11 @@ export function findUncoveredFiles(content, files) {
132
137
  export function staleReviewMessage(changedFiles, uncovered) {
133
138
  const files = changedFiles.map((f) => ` - ${f}`).join("\n");
134
139
  const missing = uncovered.map((f) => ` - ${f}`).join("\n");
140
+ const reason = uncovered.length > 0
141
+ ? `it does not cover this session's changes. Not mentioned:\n${missing}\n\n`
142
+ : "it was not written after the latest session changes, or its freshness could not be established.\n\n";
135
143
  return (`opencode-dev-framework completion gate — the peer-review artifact is substantive ` +
136
- `but stale: it does not cover this session's changes. Not mentioned:\n${missing}\n\n` +
144
+ `but stale: ${reason}` +
137
145
  `This session changed files:\n${files}\n\n` +
138
146
  `Rewrite ${REVIEW_REL} fresh for THIS session's changes — scope, findings, ` +
139
147
  `and resolutions, naming every file above.\n\n` +
@@ -6,7 +6,7 @@ import type { ResolvedConfig } from "./types.js";
6
6
  */
7
7
  export declare const BUNDLED_CONSTITUTION_DIR: string;
8
8
  /** Namespaced directory inside the project for local rule overrides. */
9
- export declare const LOCAL_RULES_DIR = ".opencode/opencode-dev-framework/rules";
9
+ export declare const LOCAL_RULES_DIR: ".dev-framework/rules";
10
10
  /** Default style-guide filenames the plugin auto-discovers. */
11
11
  export declare const STYLE_GUIDE_CANDIDATES: string[];
12
12
  export interface ConstitutionResult {
@@ -25,7 +25,8 @@ export interface ConstitutionResult {
25
25
  * - `rules: { mode: append, files: [...] }` loads the bundled/local rules
26
26
  * first, then the listed files.
27
27
  * - If no explicit `rules` config is set, the plugin auto-discovers
28
- * `.opencode/opencode-dev-framework/rules/*.md` in the project root. If that
28
+ * `.dev-framework/rules/*.md` in the project root (falling back to the
29
+ * previous `.opencode/opencode-dev-framework/rules/*.md`). If that
29
30
  * directory exists and contains markdown files, it replaces the bundled
30
31
  * rules.
31
32
  * - If no local override exists, the bundled `rules/*.md` files are used.
@@ -1,14 +1,15 @@
1
1
  import { readdir, readFile } from "node:fs/promises";
2
2
  import { dirname, isAbsolute, join, resolve } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
+ import { RULES_DIR_RELS } from "./paths.js";
4
5
  /**
5
6
  * Directory containing the constitution bundled with the plugin package.
6
7
  * Built code lives in `dist/`, so `../rules` resolves to the package root at
7
8
  * runtime; during tests (ts source) it resolves the same way relative to `src/`.
8
9
  */
9
- export const BUNDLED_CONSTITUTION_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "rules");
10
+ export const BUNDLED_CONSTITUTION_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "rules");
10
11
  /** Namespaced directory inside the project for local rule overrides. */
11
- export const LOCAL_RULES_DIR = ".opencode/opencode-dev-framework/rules";
12
+ export const LOCAL_RULES_DIR = RULES_DIR_RELS[0];
12
13
  /** Default style-guide filenames the plugin auto-discovers. */
13
14
  export const STYLE_GUIDE_CANDIDATES = [
14
15
  "STYLE.md",
@@ -53,6 +54,20 @@ async function readRuleDir(dir) {
53
54
  return null;
54
55
  }
55
56
  }
57
+ /**
58
+ * Local rule overrides, new home first: `.dev-framework/rules/`, falling
59
+ * back to the previous `.opencode/opencode-dev-framework/rules/` so
60
+ * existing deployments keep their overrides without moving them.
61
+ */
62
+ async function readLocalRules(cwd) {
63
+ for (const rel of RULES_DIR_RELS) {
64
+ const local = await readRuleDir(resolve(cwd, rel));
65
+ if (local !== null) {
66
+ return local;
67
+ }
68
+ }
69
+ return null;
70
+ }
56
71
  async function readRulesFiles(paths, directory) {
57
72
  const parts = [];
58
73
  const warnings = [];
@@ -86,7 +101,8 @@ async function discoverStyleGuide(directory) {
86
101
  * - `rules: { mode: append, files: [...] }` loads the bundled/local rules
87
102
  * first, then the listed files.
88
103
  * - If no explicit `rules` config is set, the plugin auto-discovers
89
- * `.opencode/opencode-dev-framework/rules/*.md` in the project root. If that
104
+ * `.dev-framework/rules/*.md` in the project root (falling back to the
105
+ * previous `.opencode/opencode-dev-framework/rules/*.md`). If that
90
106
  * directory exists and contains markdown files, it replaces the bundled
91
107
  * rules.
92
108
  * - If no local override exists, the bundled `rules/*.md` files are used.
@@ -113,7 +129,7 @@ export async function loadConstitution(config, directory) {
113
129
  }
114
130
  warnings.push(...rulesResult.warnings);
115
131
  if (config.rules.mode === "append") {
116
- const local = await readRuleDir(resolve(cwd, LOCAL_RULES_DIR));
132
+ const local = await readLocalRules(cwd);
117
133
  const bundled = await readRuleDir(BUNDLED_CONSTITUTION_DIR);
118
134
  const base = local ?? bundled;
119
135
  if (base !== null) {
@@ -123,7 +139,7 @@ export async function loadConstitution(config, directory) {
123
139
  }
124
140
  }
125
141
  else {
126
- const local = await readRuleDir(resolve(cwd, LOCAL_RULES_DIR));
142
+ const local = await readLocalRules(cwd);
127
143
  if (local !== null) {
128
144
  parts.push(local);
129
145
  source = "custom";
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Shared hook flow: harness-agnostic hook state and the per-edit / gate
3
+ * evaluation flows that every host adapter drives. Host-specific code
4
+ * (opencode `Plugin.define` registration, DSH Cordis bundle wiring) lives
5
+ * in the adapters and calls into these flows with a populated `HookState`.
6
+ *
7
+ * This module was extracted from the OpenCode adapter
8
+ * (`src/adapters/opencode/index.ts`, formerly `src/index.ts`) with
9
+ * relocation only — plus formatter line-breaks, added explicit types, and
10
+ * a `blockCounts` doc comment. No behavior change; the adapter keeps
11
+ * registration thin.
12
+ */
13
+ import type { BlockStore, StuckSnapshotStore } from "./block-store.js";
14
+ import type { ChangedFileTracker } from "./gate.js";
15
+ import { type CompletionVerdict, type PassCache } from "./harness.js";
16
+ import type { RunCommand } from "./host.js";
17
+ import { type LintLimiter } from "./lint.js";
18
+ import type { LogFn, LogLevel } from "./logger.js";
19
+ import { type IdleHookVia } from "./runtime-status.js";
20
+ import type { HostSeams, ResolvedConfig } from "./types.js";
21
+ import type { EnforceableSnapshot } from "./weakening.js";
22
+ export interface HookState {
23
+ directory: string;
24
+ config: ResolvedConfig;
25
+ /**
26
+ * Session-start enforceable snapshot (plan 17 §2). Compared against the
27
+ * live config at every gate evaluation so mid-session duty reductions
28
+ * surface in the verdict. Never re-baselined — including across
29
+ * `set_profile` — so a profile downgrade reads as the weakening it is.
30
+ */
31
+ initialEnforceable: EnforceableSnapshot;
32
+ log: LogFn;
33
+ run: RunCommand;
34
+ tracker: ChangedFileTracker;
35
+ constitution: string | null;
36
+ /** Per-session count of completion-gate blocks (keyed by sessionID). */
37
+ blockCounts: Map<string, number>;
38
+ /**
39
+ * Persistent block-count store over `ctx.storage`, write-through into
40
+ * `blockCounts` (which stays the live L1 cache for status rendering).
41
+ * Survives plugin reload / session_move / server restart.
42
+ * Note: this `HookState` is intentionally forked from `registry.ts`
43
+ * `HookState` (module state is per-location here, not registry-keyed);
44
+ * `format-status.ts` reads the `blockCounts` Map projection, which the
45
+ * store keeps live on every get/increment/clear.
46
+ */
47
+ blocks: BlockStore;
48
+ /**
49
+ * Last-blocked-evaluation snapshots for no-progress early stand-down
50
+ * (docs/plans/14-stuck-detection.md). Same storage-backed, best-effort pattern as `blocks`;
51
+ * memory-only here (no status projection needed).
52
+ */
53
+ stuckSnapshots: StuckSnapshotStore;
54
+ precommitAvailable?: boolean;
55
+ configMtime?: number;
56
+ /**
57
+ * Shared FIFO limiter bounding concurrent linter subprocesses across
58
+ * per-edit lints and gate lint steps.
59
+ */
60
+ lintLimiter: LintLimiter;
61
+ /** Fingerprint of the last clean gate pass; skips redundant suites. */
62
+ passCache: PassCache;
63
+ /**
64
+ * Host seam availability (see `HostSeams`), probed once at mount with
65
+ * guarded reads. Rendered by status so a degraded mount reads as
66
+ * degraded, never as silently whole. The DSH adapter probes this at
67
+ * mount; OpenCode leaves it unset (its seams are core-guaranteed).
68
+ * Forked from `registry.ts` `HookState` like the stores above.
69
+ */
70
+ seams?: HostSeams;
71
+ /**
72
+ * `Date.now()` of the last config-mtime check. Hook fires are far more
73
+ * frequent than config edits, so mtime stats are throttled to a 1s window.
74
+ */
75
+ lastConfigCheck: number;
76
+ /**
77
+ * Which lever completed a gate evaluation most recently in this process:
78
+ * `"idle"` once the `experimental.idle` hook has (same-execution
79
+ * continuation active), `"fallback"` when only the `event.subscribe`
80
+ * idle re-prompt net has. Absent until either fires. Memory-only: a
81
+ * reload re-derives it on the next idle boundary. `/df-status` renders
82
+ * the active level.
83
+ */
84
+ continuationLevel?: "idle" | "fallback";
85
+ /**
86
+ * Dedup map for the idle-first cutover: sessionID → `Date.now()` at the
87
+ * last COMPLETED hook evaluation (pass, blocked-admitted, and standdown
88
+ * all stamp; throw/early-return paths do not). The `event.subscribe` idle net
89
+ * skips when the stamp is fresh so one boundary never runs the gate
90
+ * twice. Memory-only; worst case on reload is one extra suite run.
91
+ */
92
+ lastIdleHandled: Map<string, number>;
93
+ }
94
+ export declare function getActiveState(): HookState | null;
95
+ export declare function setActiveState(state: HookState | null): void;
96
+ export declare function getFallbackLog(): LogFn;
97
+ export declare function setFallbackLog(log: LogFn): void;
98
+ export declare function safeLog(state: HookState | null, level: LogLevel, message: string, extra?: Record<string, unknown>): Promise<void>;
99
+ export declare function reloadConfigIfChanged(state: HookState): Promise<void>;
100
+ /**
101
+ * Turn a completion verdict into the continuation message fed back to the
102
+ * agent when blocked. Shared by the `experimental.idle` hook (same
103
+ * execution, via synthetic) and the `event.subscribe` idle re-prompt
104
+ * fallback so wording (and block counting) is identical on every
105
+ * enforcement level.
106
+ */
107
+ export declare function continuationMessage(verdict: Extract<CompletionVerdict, {
108
+ decision: "blocked";
109
+ }>): string;
110
+ /** Log pass/standdown verdicts; returns the continuation message when blocked. */
111
+ export declare function actOnVerdict(state: HookState, verdict: CompletionVerdict): Promise<string | null>;
112
+ /**
113
+ * Per-edit lint flow, shared by the `execute.after` hook (primary) and the
114
+ * `filesystem.changed` fallback. Skipped files log at debug; passes at info;
115
+ * failures log loudly at error (the edit already landed, so unlike
116
+ * `execute.before` this never throws — it only reports).
117
+ */
118
+ export declare function runPerEditLint(state: HookState, filePath: string): Promise<void>;
119
+ /** Assemble the completion verdict with the state's live dependencies. */
120
+ export declare function runCompletion(state: HookState, sessionID: string): Promise<CompletionVerdict>;
121
+ /**
122
+ * Record a completed idle-hook evaluation for the dedup map. Stamp ONLY on
123
+ * the completed-evaluation paths (pass, blocked-admitted, standdown);
124
+ * throw/early-return paths must not stamp so the subscriber net retries.
125
+ */
126
+ export declare function stampIdleHandled(state: HookState, sessionID: string): void;
127
+ /**
128
+ * Best-effort runtime snapshot for `/df-runtime`: hook state plus template
129
+ * drift, fire-and-forget (never throws, never blocks the caller).
130
+ */
131
+ export declare function stampRuntimeStatus(directory: string, idleHookVia: IdleHookVia, continuation: "idle" | "fallback" | "armed", skillMirrorRoot?: string): void;
132
+ /**
133
+ * True when the idle hook completed an evaluation for this session inside
134
+ * `windowMs`. The hook itself uses a short window (same-boundary
135
+ * double-fire guard for the dual key registration below); the subscriber
136
+ * net uses the full window (one boundary, one gate run).
137
+ */
138
+ export declare function wasIdleHandledRecently(state: HookState, sessionID: string, windowMs?: number): boolean;