opencode-dev-framework 0.1.6 → 0.1.12

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 (39) hide show
  1. package/README.md +64 -13
  2. package/bin/df +129 -0
  3. package/dist/config.js +16 -11
  4. package/dist/detect.d.ts +26 -0
  5. package/dist/detect.js +183 -0
  6. package/dist/gate.d.ts +6 -4
  7. package/dist/gate.js +6 -4
  8. package/dist/index.d.ts +20 -5
  9. package/dist/index.js +81 -34
  10. package/dist/installer.d.ts +50 -0
  11. package/dist/installer.js +287 -0
  12. package/dist/lint.d.ts +6 -0
  13. package/dist/lint.js +14 -1
  14. package/dist/logger.d.ts +4 -2
  15. package/dist/logger.js +11 -4
  16. package/dist/registry.d.ts +25 -0
  17. package/dist/registry.js +40 -0
  18. package/dist/rules.d.ts +24 -10
  19. package/dist/rules.js +140 -33
  20. package/dist/tools.d.ts +3 -0
  21. package/dist/tools.js +80 -0
  22. package/dist/types.d.ts +12 -5
  23. package/package.json +7 -3
  24. package/rules/00-activation.md +36 -0
  25. package/rules/10-quality-bar.md +34 -0
  26. package/rules/20-match-existing-patterns.md +41 -0
  27. package/rules/30-testing-discipline.md +41 -0
  28. package/rules/40-delegation.md +50 -0
  29. package/templates/.opencode/agents/pattern-guardian.md +78 -0
  30. package/templates/.opencode/agents/style-enforcer.md +75 -0
  31. package/templates/.opencode/agents/test-grounder.md +71 -0
  32. package/templates/.opencode/commands/df-profile.md +7 -0
  33. package/templates/.opencode/commands/df-verify.md +8 -0
  34. package/templates/.opencode/opencode-dev-framework/rules/.gitkeep +0 -0
  35. package/templates/.opencode/skills/ground-in-tests/SKILL.md +53 -0
  36. package/templates/.opencode/skills/match-patterns/SKILL.md +60 -0
  37. package/templates/.opencode/skills/peer-review/SKILL.md +56 -0
  38. package/commands/df-verify.md +0 -5
  39. package/rules/constitution.md +0 -23
package/dist/index.js CHANGED
@@ -4,44 +4,48 @@
4
4
  * Wired so far:
5
5
  * - tool.execute.before -> protected-path / dangerous-command guardrails
6
6
  * - event (file.edited) -> per-edit lint + changed-file tracking
7
- * - event (session.idle) -> completion gate (advisory: reports loudly, cannot block)
8
- * - experimental.chat.system.transform -> constitution injection
7
+ * - event (session.idle) -> completion gate fallback (advisory logging)
8
+ * - experimental.chat.system.transform -> constitution injection + session mapping
9
+ * - experimental.session.stopping -> blocking completion gate (OpenCode >= PR #41811)
10
+ * - tool -> dev_framework_init / dev_framework_set_profile custom tools
9
11
  */
10
12
  import { loadConfig } from "./config.js";
11
13
  import { createChangedFileTracker, runGate, summarizeGate, } from "./gate.js";
12
14
  import { runCommand } from "./host.js";
13
- import { isLintFailure, lintFile, summarizeLint } from "./lint.js";
15
+ import { detectPreCommitAvailability, isLintFailure, lintFile, summarizeLint } from "./lint.js";
14
16
  import { createLogger } from "./logger.js";
15
17
  import { checkToolCall } from "./protect.js";
18
+ import { clearSessionDirectory, getDirectoryForSession, getHookState, setHookState, setSessionDirectory, } from "./registry.js";
16
19
  import { injectConstitution, loadConstitution } from "./rules.js";
20
+ import { buildTools } from "./tools.js";
17
21
  /**
18
- * Per-directory hook state registry. OpenCode's effect runtime can strip
19
- * closure variables when invoking hooks asynchronously, so we store the state
20
- * in module-level maps and look it up at call time.
21
- */
22
- const hookRegistry = new Map();
23
- let activeDirectory = null;
24
- function getHookState(directoryHint) {
25
- const directory = directoryHint ?? activeDirectory;
26
- if (!directory) {
27
- return null;
28
- }
29
- return hookRegistry.get(directory) ?? null;
30
- }
31
- /**
32
- * Build the plugin's hooks. Exported (rather than inlined in the plugin) so
33
- * tests can inject a stubbed command runner and tracker.
22
+ * Build the plugin's hooks and custom tools. Exported (rather than inlined in
23
+ * the plugin) so tests can inject a stubbed command runner and tracker.
34
24
  */
35
25
  export function buildHooks(ctx, config, log, run = runCommand, tracker = createChangedFileTracker(), constitution = null) {
36
- const directory = ctx.directory;
37
- hookRegistry.set(directory, { config, log, run, tracker, constitution });
38
- activeDirectory = directory;
26
+ // All hook state — including the project directory — lives in the registry
27
+ // and is looked up at call time. OpenCode's Effect runtime stripped closure
28
+ // captures in production (config/log/run came back undefined), so hooks must
29
+ // not rely on variables from this scope.
30
+ setHookState(ctx.directory, {
31
+ directory: ctx.directory,
32
+ config,
33
+ log,
34
+ run,
35
+ tracker,
36
+ constitution,
37
+ blockCounts: new Map(),
38
+ });
39
39
  return {
40
- "experimental.chat.system.transform": async (_input, output) => {
40
+ tool: buildTools(ctx),
41
+ "experimental.chat.system.transform": async (input, output) => {
41
42
  const state = getHookState();
42
43
  if (!state) {
43
44
  return;
44
45
  }
46
+ if (input.sessionID) {
47
+ setSessionDirectory(input.sessionID, state.directory);
48
+ }
45
49
  const next = injectConstitution(output.system, state.constitution);
46
50
  if (next !== output.system) {
47
51
  await state.log("info", "constitution injected into system prompt");
@@ -49,11 +53,11 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
49
53
  }
50
54
  },
51
55
  "tool.execute.before": async (input, output) => {
52
- const state = getHookState();
56
+ const state = getHookState(getDirectoryForSession(input.sessionID) ?? undefined);
53
57
  if (!state) {
54
58
  return;
55
59
  }
56
- const result = checkToolCall(state.config, input.tool, output.args, activeDirectory ?? undefined);
60
+ const result = checkToolCall(state.config, input.tool, output.args, state.directory);
57
61
  if (result.decision === "allow") {
58
62
  return;
59
63
  }
@@ -70,20 +74,62 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
70
74
  await state.log("error", message, extra);
71
75
  throw new Error(`[opencode-dev-framework] ${message}`);
72
76
  },
77
+ "experimental.session.stopping": async (input, output) => {
78
+ const state = getHookState(getDirectoryForSession(input.sessionID) ?? undefined);
79
+ if (!state?.config.gate || state.config.profile === "off") {
80
+ return;
81
+ }
82
+ const changedFiles = state.tracker.getChangedFiles();
83
+ const report = await runGate(state.run, state.config, changedFiles, { cwd: state.directory });
84
+ if (!report.ran || report.ok) {
85
+ state.tracker.clearChangedFiles();
86
+ state.blockCounts.delete(input.sessionID);
87
+ return;
88
+ }
89
+ const maxBlocks = state.config.gate.max_blocks ?? 3;
90
+ const blockCount = (state.blockCounts.get(input.sessionID) ?? 0) + 1;
91
+ state.blockCounts.set(input.sessionID, blockCount);
92
+ if (blockCount > maxBlocks) {
93
+ // Standing down: clear the tracker so the session.idle fallback does
94
+ // not re-run the same failing gate commands a second time.
95
+ state.tracker.clearChangedFiles();
96
+ await state.log("warn", `completion gate has blocked ${maxBlocks} times; standing down but checks are still failing`, { failedSteps: report.failedSteps.map((step) => step.name) });
97
+ return;
98
+ }
99
+ const summary = summarizeGate(report);
100
+ await state.log("error", summary, {
101
+ failedSteps: report.failedSteps.map((step) => step.name),
102
+ });
103
+ output.context.push(`opencode-dev-framework completion gate blocked you from finishing (block ${blockCount}/${maxBlocks}). ` +
104
+ `The following checks failed:\n\n${summary}\n\n` +
105
+ `Fix the underlying cause and continue. Do NOT disable, skip, or weaken these checks to make them pass.`);
106
+ },
73
107
  event: async ({ event }) => {
74
- const state = getHookState();
108
+ // session.deleted must run even without hook state so the session map
109
+ // does not grow unboundedly.
110
+ if (event.type === "session.deleted") {
111
+ clearSessionDirectory(event.properties.info.id);
112
+ return;
113
+ }
114
+ const state = getHookState(event.type === "session.idle"
115
+ ? (getDirectoryForSession(event.properties.sessionID) ?? undefined)
116
+ : undefined);
75
117
  if (!state) {
76
118
  return;
77
119
  }
78
120
  if (event.type === "file.edited") {
79
121
  const filePath = event.properties.file;
80
- state.tracker.add(filePath, activeDirectory ?? undefined);
122
+ state.tracker.add(filePath, state.directory);
81
123
  if (!state.config.on_edit.lint) {
82
124
  return;
83
125
  }
126
+ if (state.config.precommit === "auto" && state.precommitAvailable === undefined) {
127
+ state.precommitAvailable = await detectPreCommitAvailability(state.run, state.directory);
128
+ }
84
129
  const outcome = await lintFile(state.run, state.config, filePath, {
85
- cwd: activeDirectory ?? undefined,
130
+ cwd: state.directory,
86
131
  timeout: state.config.gate?.timeout,
132
+ precommitAvailable: state.precommitAvailable,
87
133
  });
88
134
  if (outcome.skipped) {
89
135
  await state.log("debug", summarizeLint(outcome), { filePath, reason: outcome.reason });
@@ -109,15 +155,16 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
109
155
  return;
110
156
  }
111
157
  if (event.type === "session.idle") {
158
+ if (state.config.profile === "off") {
159
+ return;
160
+ }
112
161
  if (!state.config.gate) {
113
- await state.log("warn", "plugin config is incomplete (missing gate section), skipping completion gate", {
114
- directory: activeDirectory ?? undefined,
115
- });
162
+ await state.log("warn", "plugin config is incomplete (missing gate section), skipping completion gate", { directory: state.directory });
116
163
  return;
117
164
  }
118
165
  const changedFiles = state.tracker.getChangedFiles();
119
166
  const report = await runGate(state.run, state.config, changedFiles, {
120
- cwd: activeDirectory ?? undefined,
167
+ cwd: state.directory,
121
168
  });
122
169
  state.tracker.clearChangedFiles();
123
170
  const summary = summarizeGate(report);
@@ -129,8 +176,8 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
129
176
  await state.log("info", summary);
130
177
  return;
131
178
  }
132
- // The gate cannot physically block (session.idle fires after the turn
133
- // ends), so failure visibility is the enforcement mechanism.
179
+ // The gate cannot physically block on session.idle (the turn already
180
+ // ended), so failure visibility is the enforcement mechanism.
134
181
  const level = state.config.gate.block_on_failure ? "error" : "warn";
135
182
  await state.log(level, summary, {
136
183
  failedSteps: report.failedSteps.map((step) => ({
@@ -0,0 +1,50 @@
1
+ import type { Profile } from "./types.js";
2
+ /** Directory containing the project templates shipped with the package. */
3
+ export declare const TEMPLATES_DIR: string;
4
+ export type OverwriteDecision = "overwrite" | "skip" | "overwrite-all" | "skip-all";
5
+ export type PromptFn = (relativePath: string) => Promise<OverwriteDecision>;
6
+ export interface InstallOptions {
7
+ /** How to handle files that already exist with different content. */
8
+ overwriteExisting?: boolean;
9
+ /** Non-interactive mode: never prompt. Defaults to skip when false. */
10
+ skipExisting?: boolean;
11
+ /** Custom prompt function for interactive installs. */
12
+ prompt?: PromptFn;
13
+ }
14
+ export interface InstallResult {
15
+ created: string[];
16
+ skipped: string[];
17
+ overwritten: string[];
18
+ }
19
+ export interface TemplateStatus {
20
+ missing: string[];
21
+ present: string[];
22
+ different: string[];
23
+ }
24
+ /** List all template files relative to TEMPLATES_DIR. */
25
+ export declare function listTemplateFiles(): Promise<string[]>;
26
+ /**
27
+ * Install all bundled templates into a target project directory.
28
+ * Returns lists of created, skipped, and overwritten files (relative paths).
29
+ */
30
+ export declare function installTemplates(targetDir: string, options?: InstallOptions): Promise<InstallResult>;
31
+ /**
32
+ * Compare the target project against the bundled templates.
33
+ */
34
+ export declare function statusTemplates(targetDir: string): Promise<TemplateStatus>;
35
+ export interface ConfigWriteResult {
36
+ action: "created" | "skipped" | "overwritten";
37
+ }
38
+ /**
39
+ * Write a project-level `.opencode-dev-framework.yml` based on detected
40
+ * tooling. Respects the same overwrite/skip flags and prompt as
41
+ * `installTemplates`.
42
+ */
43
+ export declare function writeDetectedConfig(targetDir: string, options?: InstallOptions): Promise<ConfigWriteResult>;
44
+ /** Resolve a user-supplied directory (default cwd) to an absolute path. */
45
+ export declare function resolveTargetDir(dir?: string): string;
46
+ /**
47
+ * Set the top-level `profile:` key in a config file. Edits the raw text
48
+ * instead of re-serializing the YAML so user comments and formatting survive.
49
+ */
50
+ export declare function setProfileInFile(configPath: string, profile: Profile): Promise<void>;
@@ -0,0 +1,287 @@
1
+ import { promises as fs } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { createInterface } from "node:readline";
5
+ import { detectProject } from "./detect.js";
6
+ /** Directory containing the project templates shipped with the package. */
7
+ export const TEMPLATES_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "templates");
8
+ /** List all template files relative to TEMPLATES_DIR. */
9
+ export async function listTemplateFiles() {
10
+ const files = [];
11
+ async function walk(dir, prefix) {
12
+ const entries = await fs.readdir(dir, { withFileTypes: true });
13
+ for (const entry of entries) {
14
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
15
+ if (entry.isDirectory()) {
16
+ await walk(join(dir, entry.name), relative);
17
+ }
18
+ else if (entry.isFile()) {
19
+ files.push(relative);
20
+ }
21
+ }
22
+ }
23
+ await walk(TEMPLATES_DIR, "");
24
+ return files.sort();
25
+ }
26
+ async function fileExists(path) {
27
+ try {
28
+ await fs.access(path);
29
+ return true;
30
+ }
31
+ catch {
32
+ return false;
33
+ }
34
+ }
35
+ async function readFileSafe(path) {
36
+ try {
37
+ return await fs.readFile(path, "utf8");
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ }
43
+ async function defaultPrompt(relativePath) {
44
+ if (!process.stdin.isTTY) {
45
+ return "skip";
46
+ }
47
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
48
+ try {
49
+ const answer = await new Promise((resolve) => {
50
+ rl.question(`File exists with different content: ${relativePath}\nOverwrite? [o]verwrite / [s]kip / [a]ll / [n]one: `, resolve);
51
+ });
52
+ const normalized = answer.trim().toLowerCase();
53
+ if (normalized === "o" || normalized === "overwrite") {
54
+ return "overwrite";
55
+ }
56
+ if (normalized === "s" || normalized === "skip") {
57
+ return "skip";
58
+ }
59
+ if (normalized === "a" || normalized === "all") {
60
+ return "overwrite-all";
61
+ }
62
+ if (normalized === "n" || normalized === "none") {
63
+ return "skip-all";
64
+ }
65
+ return "skip";
66
+ }
67
+ finally {
68
+ rl.close();
69
+ }
70
+ }
71
+ /**
72
+ * Install all bundled templates into a target project directory.
73
+ * Returns lists of created, skipped, and overwritten files (relative paths).
74
+ */
75
+ export async function installTemplates(targetDir, options = {}) {
76
+ const result = { created: [], skipped: [], overwritten: [] };
77
+ const files = await listTemplateFiles();
78
+ const prompt = options.prompt ?? defaultPrompt;
79
+ /** Sticky decision set when the user answers "all" or "none". */
80
+ let stickyDecision = null;
81
+ for (const relative of files) {
82
+ const source = join(TEMPLATES_DIR, relative);
83
+ const destination = join(targetDir, relative);
84
+ const sourceContent = await readFileSafe(source);
85
+ if (sourceContent === null) {
86
+ continue;
87
+ }
88
+ if (!(await fileExists(destination))) {
89
+ await fs.mkdir(dirname(destination), { recursive: true });
90
+ await fs.writeFile(destination, sourceContent, "utf8");
91
+ result.created.push(relative);
92
+ continue;
93
+ }
94
+ const existing = await readFileSafe(destination);
95
+ if (existing === sourceContent) {
96
+ result.skipped.push(relative);
97
+ continue;
98
+ }
99
+ let decision;
100
+ if (stickyDecision !== null) {
101
+ decision = stickyDecision;
102
+ }
103
+ else if (options.skipExisting) {
104
+ decision = "skip";
105
+ }
106
+ else if (options.overwriteExisting) {
107
+ decision = "overwrite";
108
+ }
109
+ else {
110
+ decision = await prompt(relative);
111
+ }
112
+ if (decision === "overwrite-all") {
113
+ stickyDecision = "overwrite";
114
+ decision = "overwrite";
115
+ }
116
+ else if (decision === "skip-all") {
117
+ stickyDecision = "skip";
118
+ decision = "skip";
119
+ }
120
+ if (decision === "overwrite") {
121
+ await fs.writeFile(destination, sourceContent, "utf8");
122
+ result.overwritten.push(relative);
123
+ }
124
+ else {
125
+ result.skipped.push(relative);
126
+ }
127
+ }
128
+ return result;
129
+ }
130
+ /**
131
+ * Compare the target project against the bundled templates.
132
+ */
133
+ export async function statusTemplates(targetDir) {
134
+ const files = await listTemplateFiles();
135
+ const status = { missing: [], present: [], different: [] };
136
+ for (const relative of files) {
137
+ const source = join(TEMPLATES_DIR, relative);
138
+ const destination = join(targetDir, relative);
139
+ const sourceContent = await readFileSafe(source);
140
+ const existing = await readFileSafe(destination);
141
+ if (existing === null) {
142
+ status.missing.push(relative);
143
+ }
144
+ else if (existing === sourceContent) {
145
+ status.present.push(relative);
146
+ }
147
+ else {
148
+ status.different.push(relative);
149
+ }
150
+ }
151
+ return status;
152
+ }
153
+ const DEFAULT_PROTECT = [".env*", "**/.env*", "**/node_modules/**", "**/vendor/**"];
154
+ function buildDefaultConfigYaml(language, commands, hasPreCommitConfig) {
155
+ const lines = ["# opencode-dev-framework configuration"];
156
+ lines.push("# Edit the commands to match your project's toolchain.");
157
+ lines.push("");
158
+ lines.push("profile: standard");
159
+ if (language !== null) {
160
+ lines.push(`# Detected language: ${language}`);
161
+ }
162
+ if (Object.keys(commands).length > 0) {
163
+ lines.push("commands:");
164
+ if (commands.test !== undefined)
165
+ lines.push(` test: ${commands.test}`);
166
+ if (commands.typecheck !== undefined)
167
+ lines.push(` typecheck: ${commands.typecheck}`);
168
+ if (commands.format !== undefined) {
169
+ if (typeof commands.format === "string") {
170
+ lines.push(` format: ${commands.format}`);
171
+ }
172
+ else {
173
+ lines.push(" format:");
174
+ for (const [ext, cmd] of Object.entries(commands.format)) {
175
+ lines.push(` ${ext}: ${cmd}`);
176
+ }
177
+ }
178
+ }
179
+ if (commands.lint !== undefined) {
180
+ if (typeof commands.lint === "string") {
181
+ lines.push(` lint: ${commands.lint}`);
182
+ }
183
+ else {
184
+ lines.push(" lint:");
185
+ for (const [ext, cmd] of Object.entries(commands.lint)) {
186
+ lines.push(` ${ext}: ${cmd}`);
187
+ }
188
+ }
189
+ }
190
+ if (commands.test_changed !== undefined)
191
+ lines.push(` test_changed: ${commands.test_changed}`);
192
+ }
193
+ if (hasPreCommitConfig) {
194
+ lines.push("");
195
+ lines.push("# Pre-commit config detected; use it for per-file linting.");
196
+ lines.push("precommit: auto");
197
+ }
198
+ lines.push("");
199
+ lines.push("protect:");
200
+ for (const pattern of DEFAULT_PROTECT) {
201
+ lines.push(` - "${pattern}"`);
202
+ }
203
+ lines.push("");
204
+ lines.push("exclude: []");
205
+ lines.push("");
206
+ lines.push("gate:");
207
+ lines.push(" run_typecheck: true");
208
+ lines.push(" run_tests: true");
209
+ lines.push(" block_on_failure: true");
210
+ lines.push(" skip_unchanged: true");
211
+ lines.push(" scope: all");
212
+ lines.push(" lint_changed: false");
213
+ lines.push(" timeout: 300");
214
+ lines.push(" max_blocks: 3");
215
+ lines.push("");
216
+ lines.push("on_edit:");
217
+ lines.push(" format: true");
218
+ lines.push(" lint: true");
219
+ return lines.join("\n");
220
+ }
221
+ /**
222
+ * Write a project-level `.opencode-dev-framework.yml` based on detected
223
+ * tooling. Respects the same overwrite/skip flags and prompt as
224
+ * `installTemplates`.
225
+ */
226
+ export async function writeDetectedConfig(targetDir, options = {}) {
227
+ const { language, commands, hasPreCommitConfig } = detectProject(targetDir);
228
+ const content = buildDefaultConfigYaml(language, commands, hasPreCommitConfig);
229
+ const destination = join(targetDir, ".opencode-dev-framework.yml");
230
+ const relativePath = ".opencode-dev-framework.yml";
231
+ const exists = await fileExists(destination);
232
+ if (!exists) {
233
+ await fs.writeFile(destination, content, "utf8");
234
+ return { action: "created" };
235
+ }
236
+ const existing = await readFileSafe(destination);
237
+ if (existing === content) {
238
+ return { action: "skipped" };
239
+ }
240
+ const prompt = options.prompt ?? defaultPrompt;
241
+ let decision;
242
+ if (options.skipExisting) {
243
+ decision = "skip";
244
+ }
245
+ else if (options.overwriteExisting) {
246
+ decision = "overwrite";
247
+ }
248
+ else {
249
+ decision = await prompt(relativePath);
250
+ }
251
+ if (decision === "overwrite-all") {
252
+ decision = "overwrite";
253
+ }
254
+ else if (decision === "skip-all") {
255
+ decision = "skip";
256
+ }
257
+ if (decision === "overwrite") {
258
+ await fs.writeFile(destination, content, "utf8");
259
+ return { action: "overwritten" };
260
+ }
261
+ return { action: "skipped" };
262
+ }
263
+ /** Resolve a user-supplied directory (default cwd) to an absolute path. */
264
+ export function resolveTargetDir(dir) {
265
+ return resolve(dir ?? process.cwd());
266
+ }
267
+ /**
268
+ * Set the top-level `profile:` key in a config file. Edits the raw text
269
+ * instead of re-serializing the YAML so user comments and formatting survive.
270
+ */
271
+ export async function setProfileInFile(configPath, profile) {
272
+ let content = "";
273
+ try {
274
+ content = await fs.readFile(configPath, "utf8");
275
+ }
276
+ catch {
277
+ // File does not exist yet; it will be created below.
278
+ }
279
+ const line = `profile: ${profile}`;
280
+ if (/^profile\s*:/m.test(content)) {
281
+ content = content.replace(/^profile\s*:.*$/m, line);
282
+ }
283
+ else {
284
+ content = content.trim() === "" ? `${line}\n` : `${content.trimEnd()}\n${line}\n`;
285
+ }
286
+ await fs.writeFile(configPath, content, "utf8");
287
+ }
package/dist/lint.d.ts CHANGED
@@ -30,6 +30,11 @@ export declare function matchExclude(config: ResolvedConfig, filePath: string, d
30
30
  * command is configured at all.
31
31
  */
32
32
  export declare function resolveLintCommand(config: ResolvedConfig, filePath: string): string[] | undefined;
33
+ export declare function resolvePreCommitCommand(filePath: string): string[];
34
+ /**
35
+ * Check whether the `pre-commit` binary is available in the project.
36
+ */
37
+ export declare function detectPreCommitAvailability(run: RunCommand, directory?: string): Promise<boolean>;
33
38
  /**
34
39
  * Lint a single file. Excluded files and file types without a configured
35
40
  * linter are skipped; everything else runs through the injected runner.
@@ -37,6 +42,7 @@ export declare function resolveLintCommand(config: ResolvedConfig, filePath: str
37
42
  export declare function lintFile(run: RunCommand, config: ResolvedConfig, filePath: string, options?: {
38
43
  cwd?: string;
39
44
  timeout?: number;
45
+ precommitAvailable?: boolean;
40
46
  }): Promise<LintOutcome>;
41
47
  /** True when a lint outcome represents a failure (non-zero exit or timeout). */
42
48
  export declare function isLintFailure(outcome: LintOutcome): boolean;
package/dist/lint.js CHANGED
@@ -45,6 +45,16 @@ export function resolveLintCommand(config, filePath) {
45
45
  }
46
46
  return splitCommand(template).map((token) => token.replaceAll("{file}", filePath));
47
47
  }
48
+ export function resolvePreCommitCommand(filePath) {
49
+ return ["pre-commit", "run", "--files", filePath];
50
+ }
51
+ /**
52
+ * Check whether the `pre-commit` binary is available in the project.
53
+ */
54
+ export async function detectPreCommitAvailability(run, directory) {
55
+ const result = await run(["pre-commit", "--version"], { cwd: directory, timeout: 10 });
56
+ return result.exitCode === 0;
57
+ }
48
58
  /**
49
59
  * Lint a single file. Excluded files and file types without a configured
50
60
  * linter are skipped; everything else runs through the injected runner.
@@ -54,7 +64,10 @@ export async function lintFile(run, config, filePath, options) {
54
64
  if (excluded !== undefined) {
55
65
  return { skipped: true, reason: `excluded by "${excluded}"`, filePath };
56
66
  }
57
- const command = resolveLintCommand(config, filePath);
67
+ const usePreCommit = config.precommit === "auto" && options?.precommitAvailable === true;
68
+ const command = usePreCommit
69
+ ? resolvePreCommitCommand(filePath)
70
+ : resolveLintCommand(config, filePath);
58
71
  if (command === undefined) {
59
72
  return { skipped: true, reason: "no lint command configured for this file type", filePath };
60
73
  }
package/dist/logger.d.ts CHANGED
@@ -6,7 +6,9 @@ export type LogLevel = "debug" | "info" | "warn" | "error";
6
6
  export declare const LOG_SERVICE = "opencode-dev-framework";
7
7
  export type LogFn = (level: LogLevel, message: string, extra?: Record<string, unknown>) => Promise<void>;
8
8
  /**
9
- * Create a logger bound to the OpenCode client. Logging failures are
10
- * swallowed — logging must never break the plugin or a tool call.
9
+ * Create a logger bound to the OpenCode client. Logging never throws:
10
+ * `app.log` failures fall back to stderr so the failure stays visible
11
+ * (a total swallow made production debugging painful during development),
12
+ * and even stderr failures are ignored as a last resort.
11
13
  */
12
14
  export declare function createLogger(client: PluginInput["client"]): LogFn;
package/dist/logger.js CHANGED
@@ -3,16 +3,23 @@
3
3
  */
4
4
  export const LOG_SERVICE = "opencode-dev-framework";
5
5
  /**
6
- * Create a logger bound to the OpenCode client. Logging failures are
7
- * swallowed — logging must never break the plugin or a tool call.
6
+ * Create a logger bound to the OpenCode client. Logging never throws:
7
+ * `app.log` failures fall back to stderr so the failure stays visible
8
+ * (a total swallow made production debugging painful during development),
9
+ * and even stderr failures are ignored as a last resort.
8
10
  */
9
11
  export function createLogger(client) {
10
12
  return async (level, message, extra) => {
11
13
  try {
12
14
  await client.app.log({ body: { service: LOG_SERVICE, level, message, extra } });
13
15
  }
14
- catch {
15
- // Intentionally ignored: logging is best-effort.
16
+ catch (error) {
17
+ try {
18
+ process.stderr.write(`[${LOG_SERVICE}] ${level} ${message} (app.log failed: ${String(error)})\n`);
19
+ }
20
+ catch {
21
+ // Even stderr may be unavailable; truly ignore.
22
+ }
16
23
  }
17
24
  };
18
25
  }
@@ -0,0 +1,25 @@
1
+ import type { ChangedFileTracker } from "./gate.js";
2
+ import type { RunCommand } from "./host.js";
3
+ import type { LogFn } from "./logger.js";
4
+ import type { ResolvedConfig } from "./types.js";
5
+ export interface HookState {
6
+ /** Project directory this state belongs to. Stored here (rather than
7
+ * closure-captured by hooks) so every hook invocation is self-contained. */
8
+ directory: string;
9
+ config: ResolvedConfig;
10
+ log: LogFn;
11
+ run: RunCommand;
12
+ tracker: ChangedFileTracker;
13
+ constitution: string | null;
14
+ /** Per-session count of completion-gate blocks (keyed by sessionID). */
15
+ blockCounts: Map<string, number>;
16
+ /** Cached result of checking whether `pre-commit` is available. */
17
+ precommitAvailable?: boolean;
18
+ }
19
+ export declare function setHookState(directory: string, state: HookState): void;
20
+ export declare function getHookState(directoryHint?: string): HookState | null;
21
+ export declare function updateHookState(directory: string, updates: Partial<HookState>): HookState | null;
22
+ export declare function setSessionDirectory(sessionID: string, directory: string): void;
23
+ export declare function getDirectoryForSession(sessionID: string): string | null;
24
+ /** Forget a session's directory mapping (called on `session.deleted`). */
25
+ export declare function clearSessionDirectory(sessionID: string): void;