opencode-dev-framework 1.9.4 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +137 -33
  2. package/bin/df +94 -4
  3. package/cordis.patch.yml +17 -0
  4. package/dist/adapters/dsh/extract.d.ts +47 -0
  5. package/dist/adapters/dsh/extract.js +62 -0
  6. package/dist/adapters/dsh/index.d.ts +332 -0
  7. package/dist/adapters/dsh/index.js +1643 -0
  8. package/dist/adapters/opencode/index.d.ts +30 -0
  9. package/dist/{index.js → adapters/opencode/index.js} +138 -251
  10. package/dist/{block-store.d.ts → core/block-store.d.ts} +10 -3
  11. package/dist/{commands.js → core/commands.js} +4 -2
  12. package/dist/{config.d.ts → core/config.d.ts} +16 -4
  13. package/dist/{config.js → core/config.js} +102 -10
  14. package/dist/{format-status.d.ts → core/format-status.d.ts} +13 -2
  15. package/dist/{format-status.js → core/format-status.js} +30 -7
  16. package/dist/{gate.d.ts → core/gate.d.ts} +9 -1
  17. package/dist/{gate.js → core/gate.js} +14 -2
  18. package/dist/{goal.d.ts → core/goal.d.ts} +4 -3
  19. package/dist/{goal.js → core/goal.js} +4 -3
  20. package/dist/{harness.d.ts → core/harness.d.ts} +10 -5
  21. package/dist/{harness.js → core/harness.js} +119 -32
  22. package/dist/{init.d.ts → core/init.d.ts} +18 -1
  23. package/dist/{init.js → core/init.js} +33 -8
  24. package/dist/core/install-dsh.d.ts +67 -0
  25. package/dist/core/install-dsh.js +235 -0
  26. package/dist/{installer.d.ts → core/installer.d.ts} +32 -2
  27. package/dist/{installer.js → core/installer.js} +129 -12
  28. package/dist/{lint.d.ts → core/lint.d.ts} +43 -2
  29. package/dist/{lint.js → core/lint.js} +89 -2
  30. package/dist/{logger.js → core/logger.js} +30 -1
  31. package/dist/core/paths.d.ts +35 -0
  32. package/dist/core/paths.js +41 -0
  33. package/dist/{protect.d.ts → core/protect.d.ts} +18 -4
  34. package/dist/{protect.js → core/protect.js} +85 -34
  35. package/dist/{registry.d.ts → core/registry.d.ts} +36 -15
  36. package/dist/{registry.js → core/registry.js} +66 -52
  37. package/dist/{review.js → core/review.js} +18 -6
  38. package/dist/{rules.d.ts → core/rules.d.ts} +3 -2
  39. package/dist/{rules.js → core/rules.js} +21 -5
  40. package/dist/core/run-hooks.d.ts +138 -0
  41. package/dist/core/run-hooks.js +196 -0
  42. package/dist/{runtime-status.d.ts → core/runtime-status.d.ts} +5 -4
  43. package/dist/{runtime-status.js → core/runtime-status.js} +29 -17
  44. package/dist/{types.d.ts → core/types.d.ts} +17 -0
  45. package/dist/{update.d.ts → core/update.d.ts} +12 -4
  46. package/dist/{update.js → core/update.js} +28 -12
  47. package/dist/{weakening.js → core/weakening.js} +2 -1
  48. package/package.json +16 -6
  49. package/rules/40-delegation.md +13 -2
  50. package/templates/.opencode/agents/style-enforcer.md +1 -1
  51. package/templates/.opencode/agents/test-grounder.md +1 -1
  52. package/templates/.opencode/skills/ground-in-tests/SKILL.md +1 -1
  53. package/templates/.opencode/skills/peer-review/SKILL.md +6 -1
  54. package/templates/.opencode/skills/project-config/SKILL.md +2 -2
  55. package/tui.tsx +6 -6
  56. package/dist/index.d.ts +0 -101
  57. /package/dist/{block-store.js → core/block-store.js} +0 -0
  58. /package/dist/{command-utils.d.ts → core/command-utils.d.ts} +0 -0
  59. /package/dist/{command-utils.js → core/command-utils.js} +0 -0
  60. /package/dist/{commands.d.ts → core/commands.d.ts} +0 -0
  61. /package/dist/{detect.d.ts → core/detect.d.ts} +0 -0
  62. /package/dist/{detect.js → core/detect.js} +0 -0
  63. /package/dist/{host.d.ts → core/host.d.ts} +0 -0
  64. /package/dist/{host.js → core/host.js} +0 -0
  65. /package/dist/{logger.d.ts → core/logger.d.ts} +0 -0
  66. /package/dist/{review.d.ts → core/review.d.ts} +0 -0
  67. /package/dist/{roster.d.ts → core/roster.d.ts} +0 -0
  68. /package/dist/{roster.js → core/roster.js} +0 -0
  69. /package/dist/{types.js → core/types.js} +0 -0
  70. /package/dist/{weakening.d.ts → core/weakening.d.ts} +0 -0
  71. /package/templates/{.opencode/opencode-dev-framework → .dev-framework}/rules/.gitkeep +0 -0
@@ -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;
@@ -49,26 +57,39 @@ export declare function updateHookState(directory: string, updates: Partial<Hook
49
57
  export interface SessionParentInfo {
50
58
  parentID?: string | null | undefined;
51
59
  }
60
+ /** Outcome of one ancestry walk: duty verdict plus best-effort depth. */
61
+ export interface ChildSessionResolution {
62
+ isChild: boolean;
63
+ depth: number | null;
64
+ }
65
+ /**
66
+ * Walk the `parentID` chain once, returning the duty verdict and the
67
+ * depth together (depth 0 = top-level, null = unknown). Only a confirmed
68
+ * not-found/deleted hop ends the walk as dead; any lookup failure
69
+ * abandons it as unknown rather than guessing. Fails closed to
70
+ * `{ isChild: false, depth: null }` (top-level): a missing getter (older
71
+ * core), an empty sessionID, or a lookup throw preserves the pre-guard
72
+ * behavior exactly. Results cache per sessionID, but only fully-resolved
73
+ * walks: a throw or a nullish info (unknown to the host) returns
74
+ * top-level WITHOUT caching, so one transient failure can never
75
+ * permanently pin a session. Never throws. A pathological parent cycle
76
+ * terminates via the visited set (the core API cannot currently produce
77
+ * one: no `parentID` mutation, unknown parents rejected at creation).
78
+ */
79
+ export declare function resolveChildSession(sessionID: string, getSession?: (id: string) => Promise<SessionParentInfo | null | undefined>): Promise<ChildSessionResolution>;
52
80
  /**
53
- * True when the session is a child (subagent): its host record carries a
54
- * parentID. Results are cached per sessionID. Fails closed to `false`
55
- * (top-level): a missing getter (older core), an empty sessionID, or a
56
- * lookup throw preserves the pre-guard behavior exactly — the session is
57
- * gated and may write, as before. Never throws.
81
+ * True when the session is a child (subagent): it shares the
82
+ * `resolveChildSession` cache, so pairing this with a depth read costs
83
+ * nothing extra. Same fail-closed contract as the combined resolver.
58
84
  */
59
85
  export declare function resolveIsChildSession(sessionID: string, getSession?: (id: string) => Promise<SessionParentInfo | null | undefined>): Promise<boolean>;
60
86
  /**
61
87
  * Best-effort session-tree depth for the plan-24 tripwire: the number of
62
88
  * `parentID` hops from the session to its top-level root (0 = top-level).
63
- * Logged on child-gated decisions so the first real nesting shows up in
64
- * the log instead of passing silently. Uncapped by policy — the visited
65
- * set only guards against a pathological cycle, which the core API cannot
66
- * currently produce (no `parentID` mutation; creation with an unknown
67
- * parent is rejected). Never throws and never caches: an empty sessionID
68
- * or missing getter yields null (unknown), any lookup failure abandons
69
- * the walk and yields null rather than a misleading partial count, and
70
- * the call sites are rare (idle boundaries, artifact writes) so
71
- * freshness beats memoization.
89
+ * Shares the `resolveChildSession` walk and cache, so pairing a duty
90
+ * check with a depth read costs nothing extra. Same fail-closed contract:
91
+ * empty sessionID, missing getter, or any lookup failure yields null
92
+ * (unknown) rather than a misleading partial count. Never throws.
72
93
  */
73
94
  export declare function resolveSessionDepth(sessionID: string, getSession?: (id: string) => Promise<SessionParentInfo | null | undefined>): Promise<number | null>;
74
95
  export declare function setSessionDirectory(sessionID: string, directory: string): void;
@@ -49,78 +49,92 @@ export function updateHookState(directory, updates) {
49
49
  * session ID can still find their state. */
50
50
  const sessionToDirectory = new Map();
51
51
  /**
52
- * Child-session verdicts: sessionID → true when the session has a parent
53
- * (i.e. it is a subagent and never owns review duty). Populated lazily via
54
- * `resolveIsChildSession` and cleared with everything else in
55
- * `resetRegistry`. Memory-only like the directory map.
52
+ * Child-session resolution: one cached host walk per session lifetime.
53
+ * `isChild` powers the plan-23 duty skip; `depth` is the plan-24 tripwire
54
+ * (null = unknown). Resolved together so child-gated branches never pay
55
+ * for the same lookup twice. Populated lazily and cleared with everything
56
+ * else in `clearSessionDirectory`/`resetRegistry`. Memory-only like the
57
+ * directory map.
56
58
  */
57
59
  const childSessionCache = new Map();
58
60
  /**
59
- * True when the session is a child (subagent): its host record carries a
60
- * parentID. Results are cached per sessionID. Fails closed to `false`
61
- * (top-level): a missing getter (older core), an empty sessionID, or a
62
- * lookup throw preserves the pre-guard behavior exactly — the session is
63
- * gated and may write, as before. Never throws.
61
+ * Walk the `parentID` chain once, returning the duty verdict and the
62
+ * depth together (depth 0 = top-level, null = unknown). Only a confirmed
63
+ * not-found/deleted hop ends the walk as dead; any lookup failure
64
+ * abandons it as unknown rather than guessing. Fails closed to
65
+ * `{ isChild: false, depth: null }` (top-level): a missing getter (older
66
+ * core), an empty sessionID, or a lookup throw preserves the pre-guard
67
+ * behavior exactly. Results cache per sessionID, but only fully-resolved
68
+ * walks: a throw or a nullish info (unknown to the host) returns
69
+ * top-level WITHOUT caching, so one transient failure can never
70
+ * permanently pin a session. Never throws. A pathological parent cycle
71
+ * terminates via the visited set (the core API cannot currently produce
72
+ * one: no `parentID` mutation, unknown parents rejected at creation).
64
73
  */
65
- export async function resolveIsChildSession(sessionID, getSession) {
74
+ export async function resolveChildSession(sessionID, getSession) {
66
75
  if (sessionID === "")
67
- return false;
76
+ return { isChild: false, depth: null };
68
77
  const cached = childSessionCache.get(sessionID);
69
78
  if (cached !== undefined)
70
79
  return cached;
71
- let isChild = false;
80
+ const fallback = { isChild: false, depth: null };
72
81
  if (getSession === undefined)
73
- return false;
82
+ return fallback;
74
83
  try {
75
- const info = await getSession(sessionID);
76
- // Cache only successful lookups that actually resolved a session:
77
- // a throw or a nullish info (unknown to the host) returns top-level
78
- // WITHOUT caching, so one transient failure can never permanently pin
79
- // a child as top-level (which would re-enable the original bug).
80
- if (info !== null && info !== undefined) {
81
- const parent = info.parentID;
82
- isChild = typeof parent === "string" && parent !== "";
83
- childSessionCache.set(sessionID, isChild);
84
+ // An unknown first hop (nullish info) returns top-level WITHOUT
85
+ // caching, so one transient failure can never permanently pin a
86
+ // child as top-level (which would re-enable the original bug).
87
+ const first = await getSession(sessionID);
88
+ if (first === null || first === undefined)
89
+ return fallback;
90
+ const seen = new Set([sessionID]);
91
+ let current = sessionID;
92
+ let parent = first.parentID;
93
+ let depth = 0;
94
+ let isChild = false;
95
+ while (typeof parent === "string" && parent !== "" && !seen.has(parent)) {
96
+ seen.add(parent);
97
+ isChild = true;
98
+ depth++;
99
+ current = parent;
100
+ try {
101
+ parent = (await getSession(current))?.parentID;
102
+ }
103
+ catch {
104
+ // Writer is live (first hop resolved) but deeper ancestry is
105
+ // unknown: keep the duty verdict, abandon the depth, and do NOT
106
+ // cache — the next call re-walks instead of pinning unknown.
107
+ return { isChild: true, depth: null };
108
+ }
84
109
  }
85
- return isChild;
110
+ // Fully-resolved walks cache (top-level `{false, 0}` too: parentage
111
+ // is immutable and deletion evicts via `clearSessionDirectory`).
112
+ const resolved = { isChild, depth };
113
+ childSessionCache.set(sessionID, resolved);
114
+ return resolved;
86
115
  }
87
116
  catch {
88
- return false;
117
+ return fallback;
89
118
  }
90
119
  }
120
+ /**
121
+ * True when the session is a child (subagent): it shares the
122
+ * `resolveChildSession` cache, so pairing this with a depth read costs
123
+ * nothing extra. Same fail-closed contract as the combined resolver.
124
+ */
125
+ export async function resolveIsChildSession(sessionID, getSession) {
126
+ return (await resolveChildSession(sessionID, getSession)).isChild;
127
+ }
91
128
  /**
92
129
  * Best-effort session-tree depth for the plan-24 tripwire: the number of
93
130
  * `parentID` hops from the session to its top-level root (0 = top-level).
94
- * Logged on child-gated decisions so the first real nesting shows up in
95
- * the log instead of passing silently. Uncapped by policy — the visited
96
- * set only guards against a pathological cycle, which the core API cannot
97
- * currently produce (no `parentID` mutation; creation with an unknown
98
- * parent is rejected). Never throws and never caches: an empty sessionID
99
- * or missing getter yields null (unknown), any lookup failure abandons
100
- * the walk and yields null rather than a misleading partial count, and
101
- * the call sites are rare (idle boundaries, artifact writes) so
102
- * freshness beats memoization.
131
+ * Shares the `resolveChildSession` walk and cache, so pairing a duty
132
+ * check with a depth read costs nothing extra. Same fail-closed contract:
133
+ * empty sessionID, missing getter, or any lookup failure yields null
134
+ * (unknown) rather than a misleading partial count. Never throws.
103
135
  */
104
136
  export async function resolveSessionDepth(sessionID, getSession) {
105
- if (sessionID === "" || getSession === undefined)
106
- return null;
107
- const seen = new Set([sessionID]);
108
- let depth = 0;
109
- let current = sessionID;
110
- try {
111
- while (true) {
112
- const parent = (await getSession(current))?.parentID;
113
- if (typeof parent !== "string" || parent === "" || seen.has(parent))
114
- break;
115
- seen.add(parent);
116
- depth++;
117
- current = parent;
118
- }
119
- return depth;
120
- }
121
- catch {
122
- return null;
123
- }
137
+ return (await resolveChildSession(sessionID, getSession)).depth;
124
138
  }
125
139
  export function setSessionDirectory(sessionID, directory) {
126
140
  sessionToDirectory.set(sessionID, directory);
@@ -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,
@@ -71,6 +76,10 @@ function reviewCadenceReminder() {
71
76
  `fail without the change, commands that actually pass), and code-reviewer / pattern-guardian ` +
72
77
  `for correctness and drift. Resolve every blocking finding, then write a summary of the ` +
73
78
  `review findings and their resolution to ${REVIEW_REL}.\n\n` +
79
+ `Scope the battery to the change: product code gets the full battery above. ` +
80
+ `Docs-only changes (no product code) get markdown lint instead of specialists — ` +
81
+ `run lint:md on the changed files and record scope plus result in the review. ` +
82
+ `That is the entire docs cadence.\n\n` +
74
83
  `Do not re-run a specialist whose scope has not changed since its last report — ` +
75
84
  `reuse that report and only re-run what your fixes invalidate.\n\n` +
76
85
  `Investigation-only reviewers: do not ask them to edit product code.`);
@@ -128,8 +137,11 @@ export function findUncoveredFiles(content, files) {
128
137
  export function staleReviewMessage(changedFiles, uncovered) {
129
138
  const files = changedFiles.map((f) => ` - ${f}`).join("\n");
130
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";
131
143
  return (`opencode-dev-framework completion gate — the peer-review artifact is substantive ` +
132
- `but stale: it does not cover this session's changes. Not mentioned:\n${missing}\n\n` +
144
+ `but stale: ${reason}` +
133
145
  `This session changed files:\n${files}\n\n` +
134
146
  `Rewrite ${REVIEW_REL} fresh for THIS session's changes — scope, findings, ` +
135
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";