opencode-dev-framework 0.1.2

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 opencode-dev-framework contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,116 @@
1
+ # opencode-dev-framework
2
+
3
+ An [OpenCode](https://opencode.ai) plugin that enforces project-specific
4
+ quality gates during AI coding sessions. Inspired by
5
+ [anticomputer/dev-framework](https://github.com/anticomputer/dev-framework),
6
+ reimplemented as an OpenCode-native plugin.
7
+
8
+ ## What it does
9
+
10
+ - **Constitution injection.** Adds a project constitution (quality bar, test
11
+ discipline, focus rules) to the system prompt at session start. Ships with a
12
+ bundled default; point `constitution` at your own Markdown file to override.
13
+ - **Guardrails.** Blocks or warns on edits to protected paths (`.env` files,
14
+ `node_modules`, vendored code, your own globs) and on dangerous shell
15
+ commands (`git push`, `rm -rf`, `git reset --hard`, ...).
16
+ - **Per-edit lint.** Runs your configured linter on each file the agent edits
17
+ and reports failures loudly.
18
+ - **Completion gate.** When the session goes idle, runs typecheck, tests, and
19
+ (optionally) lint on changed files, then reports the result.
20
+ - **`/df-verify` command.** Lets the agent (or you) re-run the verification
21
+ suite on demand.
22
+
23
+ ## Profiles
24
+
25
+ | Profile | Guardrails | Gate failures | Lint on edit | Notes |
26
+ | ---------- | ---------- | ------------- | ------------ | ----- |
27
+ | `off` | disabled | not reported | no | Plugin registers no hooks at all. |
28
+ | `advisory` | warn | warn | yes | Nothing blocks; everything is logged. |
29
+ | `standard` | deny | error | yes | The default when a config file exists. |
30
+ | `strict` | deny | error | yes | Also lints changed files in the gate and throws on per-edit lint failures. |
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ npm install opencode-dev-framework
36
+ ```
37
+
38
+ Then add it to your project's `opencode.json`:
39
+
40
+ ```json
41
+ {
42
+ "plugin": ["opencode-dev-framework"]
43
+ }
44
+ ```
45
+
46
+ ## Configuration
47
+
48
+ Create `.opencode-dev-framework.yml` in your project root:
49
+
50
+ ```yaml
51
+ profile: standard
52
+
53
+ commands:
54
+ typecheck: "go build ./..."
55
+ test: "go test ./..."
56
+ lint:
57
+ ".go": "golangci-lint run {file}"
58
+
59
+ protect:
60
+ - ".env*"
61
+ - "deploy/prod/**"
62
+
63
+ gate:
64
+ run_typecheck: true
65
+ run_tests: true
66
+ block_on_failure: true
67
+
68
+ on_edit:
69
+ lint: true
70
+
71
+ constitution: "TEAM_RULES.md" # optional; bundled default if omitted
72
+ ```
73
+
74
+ The legacy `.dev-framework.yml` flat-key format is read as a fallback for
75
+ compatibility, but the native format above is preferred. See
76
+ [`docs/plans/03-config-spec.md`](docs/plans/03-config-spec.md) for the full
77
+ config reference and [`examples/go-service/`](examples/go-service/) for a
78
+ complete example.
79
+
80
+ ## Limitations
81
+
82
+ - **The completion gate is advisory, not a hard block.** OpenCode has no
83
+ `agentStop` hook, so the gate runs on `session.idle` and reports failures
84
+ loudly (error-level log) but cannot physically prevent the agent from
85
+ stopping. This is an architectural limitation of the plugin API.
86
+ - **Guardrails run inside OpenCode.** The `tool.execute.before` hook runs
87
+ after OpenCode's own permission system; it adds project rules on top, it
88
+ does not replace OpenCode permissions.
89
+ - **Formatting is delegated.** Formatter config is contributed to OpenCode's
90
+ native formatter system rather than reimplemented.
91
+
92
+ ## Development
93
+
94
+ ```bash
95
+ npm install
96
+ npm run format:check
97
+ npm run lint
98
+ npm run lint:md
99
+ npm run typecheck
100
+ npm run test
101
+ npm run build
102
+ ```
103
+
104
+ See `AGENTS.md` and `docs/plans/` for the architecture and implementation
105
+ plan.
106
+
107
+ ## Disclaimer
108
+
109
+ This plugin changes how an AI agent behaves in your repository. Review the
110
+ constitution, protected paths, and gate commands before enabling the
111
+ `standard` or `strict` profiles, and start with `advisory` if you want to
112
+ observe behavior without enforcement.
113
+
114
+ ## License
115
+
116
+ MIT
@@ -0,0 +1,5 @@
1
+ ---
2
+ description: Run the dev-framework completion gate manually
3
+ ---
4
+
5
+ Run the completion gate for this project. Report test, type-check, and lint results. If anything fails, list the failures and suggest fixes.
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Translate resolved framework config into OpenCode-native config fragments.
3
+ *
4
+ * The plugin never rewrites `opencode.json` on disk; these fragments are
5
+ * returned as plain objects so callers (or tests) can inspect or apply them.
6
+ * See docs/plans/02-architecture.md ("Tool guardrails") and the OpenCode
7
+ * permissions/formatters docs.
8
+ */
9
+ import type { CommandMap, ResolvedConfig } from "./types.js";
10
+ export type PermissionAction = "allow" | "ask" | "deny";
11
+ export interface PermissionConfig {
12
+ edit?: Record<string, PermissionAction>;
13
+ bash?: Record<string, PermissionAction>;
14
+ }
15
+ export interface FormatterEntry {
16
+ command: string[];
17
+ extensions?: string[];
18
+ disabled?: boolean;
19
+ }
20
+ export type FormatterConfig = Record<string, FormatterEntry>;
21
+ export interface OpenCodeFragments {
22
+ permission?: PermissionConfig;
23
+ formatter?: FormatterConfig;
24
+ }
25
+ /**
26
+ * Generate an OpenCode `permission` fragment from protected paths.
27
+ *
28
+ * Deny rules are only emitted when protection is active and
29
+ * `protect_mode` is `deny`. In `warn` mode the plugin hook logs a warning
30
+ * instead, since the native permission model has no "warn" action.
31
+ */
32
+ export declare function generatePermission(config: ResolvedConfig): PermissionConfig;
33
+ interface NormalizedCommandMap {
34
+ default?: string;
35
+ byExtension: Record<string, string>;
36
+ }
37
+ export declare function normalizeCommandMap(map: CommandMap | undefined): NormalizedCommandMap;
38
+ /** Split a command string into argv tokens, honoring simple quotes. */
39
+ export declare function splitCommand(command: string): string[];
40
+ /**
41
+ * Generate an OpenCode `formatter` fragment from `commands.format`.
42
+ * Per-extension overrides become named formatter entries scoped to that
43
+ * extension; a plain string becomes a formatter applying to all files.
44
+ */
45
+ export declare function generateFormatter(config: ResolvedConfig): FormatterConfig;
46
+ /**
47
+ * Build all OpenCode-native fragments for a resolved config. Empty
48
+ * fragments are omitted from the result.
49
+ */
50
+ export declare function toOpenCodeFragments(config: ResolvedConfig): OpenCodeFragments;
51
+ export {};
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Translate resolved framework config into OpenCode-native config fragments.
3
+ *
4
+ * The plugin never rewrites `opencode.json` on disk; these fragments are
5
+ * returned as plain objects so callers (or tests) can inspect or apply them.
6
+ * See docs/plans/02-architecture.md ("Tool guardrails") and the OpenCode
7
+ * permissions/formatters docs.
8
+ */
9
+ /**
10
+ * Generate an OpenCode `permission` fragment from protected paths.
11
+ *
12
+ * Deny rules are only emitted when protection is active and
13
+ * `protect_mode` is `deny`. In `warn` mode the plugin hook logs a warning
14
+ * instead, since the native permission model has no "warn" action.
15
+ */
16
+ export function generatePermission(config) {
17
+ if (config.profile === "off" ||
18
+ config.protect_off ||
19
+ config.protect_mode !== "deny" ||
20
+ config.protect.length === 0) {
21
+ return {};
22
+ }
23
+ const edit = { "*": "allow" };
24
+ for (const glob of config.protect) {
25
+ edit[glob] = "deny";
26
+ }
27
+ return { edit };
28
+ }
29
+ export function normalizeCommandMap(map) {
30
+ if (map === undefined) {
31
+ return { byExtension: {} };
32
+ }
33
+ if (typeof map === "string") {
34
+ return { default: map, byExtension: {} };
35
+ }
36
+ // A `default` key inside the map acts as the fallback command; every other
37
+ // key is a per-extension override.
38
+ const { default: defaultCommand, ...byExtension } = map;
39
+ return defaultCommand === undefined ? { byExtension } : { default: defaultCommand, byExtension };
40
+ }
41
+ /** Split a command string into argv tokens, honoring simple quotes. */
42
+ export function splitCommand(command) {
43
+ const tokens = [];
44
+ let current = "";
45
+ let quote;
46
+ for (const ch of command) {
47
+ if (quote !== undefined) {
48
+ if (ch === quote) {
49
+ quote = undefined;
50
+ }
51
+ else {
52
+ current += ch;
53
+ }
54
+ }
55
+ else if (ch === '"' || ch === "'") {
56
+ quote = ch;
57
+ }
58
+ else if (/\s/.test(ch)) {
59
+ if (current !== "") {
60
+ tokens.push(current);
61
+ current = "";
62
+ }
63
+ }
64
+ else {
65
+ current += ch;
66
+ }
67
+ }
68
+ if (current !== "") {
69
+ tokens.push(current);
70
+ }
71
+ return tokens;
72
+ }
73
+ /** Substitute the `{file}` token with OpenCode's `$FILE` placeholder. */
74
+ function substituteFileToken(tokens) {
75
+ return tokens.map((token) => token.replaceAll("{file}", "$FILE"));
76
+ }
77
+ function formatterName(kind, ext) {
78
+ if (ext === undefined) {
79
+ return `dev-framework-${kind}`;
80
+ }
81
+ const suffix = ext.replace(/[^a-zA-Z0-9]/g, "-").replace(/^-+|-+$/g, "");
82
+ return `dev-framework-${kind}-${suffix}`;
83
+ }
84
+ /**
85
+ * Generate an OpenCode `formatter` fragment from `commands.format`.
86
+ * Per-extension overrides become named formatter entries scoped to that
87
+ * extension; a plain string becomes a formatter applying to all files.
88
+ */
89
+ export function generateFormatter(config) {
90
+ const { default: defaultCommand, byExtension } = normalizeCommandMap(config.commands.format);
91
+ const formatter = {};
92
+ for (const [ext, command] of Object.entries(byExtension)) {
93
+ formatter[formatterName("format", ext)] = {
94
+ command: substituteFileToken(splitCommand(command)),
95
+ extensions: [ext],
96
+ };
97
+ }
98
+ if (defaultCommand !== undefined) {
99
+ formatter[formatterName("format")] = {
100
+ command: substituteFileToken(splitCommand(defaultCommand)),
101
+ };
102
+ }
103
+ return formatter;
104
+ }
105
+ /**
106
+ * Build all OpenCode-native fragments for a resolved config. Empty
107
+ * fragments are omitted from the result.
108
+ */
109
+ export function toOpenCodeFragments(config) {
110
+ // The off profile disables the plugin entirely: no native fragments.
111
+ if (config.profile === "off") {
112
+ return {};
113
+ }
114
+ const fragments = {};
115
+ const permission = generatePermission(config);
116
+ if (Object.keys(permission).length > 0) {
117
+ fragments.permission = permission;
118
+ }
119
+ const formatter = generateFormatter(config);
120
+ if (Object.keys(formatter).length > 0) {
121
+ fragments.formatter = formatter;
122
+ }
123
+ return fragments;
124
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Config loader for opencode-dev-framework.
3
+ *
4
+ * Implements the precedence, validation, and profile-default rules from
5
+ * docs/plans/03-config-spec.md.
6
+ */
7
+ import type { Config, ResolvedConfig } from "./types.js";
8
+ /** Config file precedence, highest first. The first file found wins. */
9
+ export declare const CONFIG_FILE_PRECEDENCE: readonly [".opencode-dev-framework.yml", ".opencode-dev-framework.yaml", ".opencode-dev-framework.json", ".dev-framework.yml", ".dev-framework.yaml"];
10
+ /** Sensible default protected paths, used when `protect` is omitted. */
11
+ export declare const DEFAULT_PROTECT: string[];
12
+ /** Find the highest-precedence config file in a directory, if any. */
13
+ export declare function findConfigFile(directory: string): string | undefined;
14
+ /** Split a whitespace-separated glob string (or pass through an array). */
15
+ export declare function splitGlobs(value: unknown): string[];
16
+ /**
17
+ * Map a flat-key `.dev-framework.yml` document onto the native config shape.
18
+ * Unknown keys are ignored. See the compatibility table in
19
+ * docs/plans/03-config-spec.md.
20
+ */
21
+ export declare function mapFlatConfig(flat: Record<string, unknown>): Config;
22
+ /**
23
+ * Apply profile defaults to a validated raw config. Explicit config keys
24
+ * always override profile defaults.
25
+ */
26
+ export declare function resolveConfig(raw: Config, configPath?: string): ResolvedConfig;
27
+ /** Clear the per-session config cache (mainly for tests). */
28
+ export declare function clearConfigCache(): void;
29
+ /**
30
+ * Load and resolve the config for a project directory. Results are cached
31
+ * per directory for the lifetime of the session.
32
+ */
33
+ export declare function loadConfig(directory: string): ResolvedConfig;
package/dist/config.js ADDED
@@ -0,0 +1,325 @@
1
+ /**
2
+ * Config loader for opencode-dev-framework.
3
+ *
4
+ * Implements the precedence, validation, and profile-default rules from
5
+ * docs/plans/03-config-spec.md.
6
+ */
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { basename, join } from "node:path";
9
+ import { parse as parseYaml } from "yaml";
10
+ import { z } from "zod";
11
+ /** Config file precedence, highest first. The first file found wins. */
12
+ export const CONFIG_FILE_PRECEDENCE = [
13
+ ".opencode-dev-framework.yml",
14
+ ".opencode-dev-framework.yaml",
15
+ ".opencode-dev-framework.json",
16
+ ".dev-framework.yml",
17
+ ".dev-framework.yaml",
18
+ ];
19
+ const FALLBACK_FILES = new Set([".dev-framework.yml", ".dev-framework.yaml"]);
20
+ /** Sensible default protected paths, used when `protect` is omitted. */
21
+ export const DEFAULT_PROTECT = [
22
+ ".env",
23
+ ".env.*",
24
+ "**/.env",
25
+ "**/.env.*",
26
+ "**/node_modules/**",
27
+ "**/vendor/**",
28
+ ];
29
+ const commandMapSchema = z.union([z.string(), z.record(z.string(), z.string())]);
30
+ const configSchema = z.object({
31
+ profile: z.enum(["off", "advisory", "standard", "strict"]).optional(),
32
+ commands: z
33
+ .object({
34
+ test: z.string().optional(),
35
+ typecheck: z.string().optional(),
36
+ format: commandMapSchema.optional(),
37
+ lint: commandMapSchema.optional(),
38
+ test_changed: z.string().optional(),
39
+ })
40
+ .optional(),
41
+ protect: z.array(z.string()).optional(),
42
+ protect_mode: z.enum(["warn", "deny"]).optional(),
43
+ protect_off: z.boolean().optional(),
44
+ gate: z
45
+ .object({
46
+ run_typecheck: z.boolean().optional(),
47
+ run_tests: z.boolean().optional(),
48
+ block_on_failure: z.boolean().optional(),
49
+ skip_unchanged: z.boolean().optional(),
50
+ scope: z.enum(["all", "changed"]).optional(),
51
+ lint_changed: z.boolean().optional(),
52
+ timeout: z.number().positive().optional(),
53
+ max_blocks: z.number().int().positive().optional(),
54
+ })
55
+ .optional(),
56
+ on_edit: z
57
+ .object({
58
+ format: z.boolean().optional(),
59
+ lint: z.boolean().optional(),
60
+ })
61
+ .optional(),
62
+ exclude: z.array(z.string()).optional(),
63
+ constitution: z.string().optional(),
64
+ rules: z.array(z.string()).optional(),
65
+ style_guide: z.string().optional(),
66
+ });
67
+ /** Find the highest-precedence config file in a directory, if any. */
68
+ export function findConfigFile(directory) {
69
+ for (const name of CONFIG_FILE_PRECEDENCE) {
70
+ const candidate = join(directory, name);
71
+ if (existsSync(candidate)) {
72
+ return candidate;
73
+ }
74
+ }
75
+ return undefined;
76
+ }
77
+ /** Split a whitespace-separated glob string (or pass through an array). */
78
+ export function splitGlobs(value) {
79
+ if (Array.isArray(value)) {
80
+ return value.map(String);
81
+ }
82
+ if (typeof value === "string") {
83
+ return value.split(/\s+/).filter(Boolean);
84
+ }
85
+ return [];
86
+ }
87
+ function toBoolean(value) {
88
+ if (typeof value === "boolean") {
89
+ return value;
90
+ }
91
+ if (typeof value === "string") {
92
+ const normalized = value.trim().toLowerCase();
93
+ if (normalized === "true" || normalized === "yes" || normalized === "1") {
94
+ return true;
95
+ }
96
+ if (normalized === "false" || normalized === "no" || normalized === "0") {
97
+ return false;
98
+ }
99
+ }
100
+ return undefined;
101
+ }
102
+ function toNumber(value) {
103
+ if (typeof value === "number") {
104
+ return value;
105
+ }
106
+ if (typeof value === "string" && value.trim() !== "") {
107
+ const parsed = Number(value);
108
+ return Number.isNaN(parsed) ? undefined : parsed;
109
+ }
110
+ return undefined;
111
+ }
112
+ /**
113
+ * Map a flat-key `.dev-framework.yml` document onto the native config shape.
114
+ * Unknown keys are ignored. See the compatibility table in
115
+ * docs/plans/03-config-spec.md.
116
+ */
117
+ export function mapFlatConfig(flat) {
118
+ const config = {};
119
+ const commands = {};
120
+ const gate = {};
121
+ const onEdit = {};
122
+ const formatByExt = {};
123
+ const lintByExt = {};
124
+ const assignCommand = (target, keyPrefix, value) => {
125
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
126
+ for (const [ext, cmd] of Object.entries(value)) {
127
+ target[ext] = String(cmd);
128
+ }
129
+ return true;
130
+ }
131
+ if (typeof value === "string") {
132
+ commands[keyPrefix === "format" ? "format" : "lint"] = value;
133
+ return true;
134
+ }
135
+ return false;
136
+ };
137
+ for (const [key, value] of Object.entries(flat)) {
138
+ if (key.startsWith("format.")) {
139
+ const ext = key.slice("format.".length);
140
+ formatByExt[ext.startsWith(".") ? ext : `.${ext}`] = String(value);
141
+ continue;
142
+ }
143
+ if (key.startsWith("lint.")) {
144
+ const ext = key.slice("lint.".length);
145
+ lintByExt[ext.startsWith(".") ? ext : `.${ext}`] = String(value);
146
+ continue;
147
+ }
148
+ switch (key) {
149
+ case "profile":
150
+ config.profile = value;
151
+ break;
152
+ case "test":
153
+ commands.test = String(value);
154
+ break;
155
+ case "typecheck":
156
+ commands.typecheck = String(value);
157
+ break;
158
+ case "format":
159
+ assignCommand(formatByExt, "format", value);
160
+ break;
161
+ case "lint":
162
+ assignCommand(lintByExt, "lint", value);
163
+ break;
164
+ case "test_changed":
165
+ commands.test_changed = String(value);
166
+ break;
167
+ case "precommit":
168
+ // Ignored in MVP.
169
+ break;
170
+ case "format_on_edit":
171
+ onEdit.format = toBoolean(value);
172
+ break;
173
+ case "lint_on_edit":
174
+ onEdit.lint = toBoolean(value);
175
+ break;
176
+ case "gate_run_typecheck":
177
+ gate.run_typecheck = toBoolean(value);
178
+ break;
179
+ case "gate_run_tests":
180
+ gate.run_tests = toBoolean(value);
181
+ break;
182
+ case "gate_block_on_failure":
183
+ gate.block_on_failure = toBoolean(value);
184
+ break;
185
+ case "gate_skip_unchanged":
186
+ gate.skip_unchanged = toBoolean(value);
187
+ break;
188
+ case "gate_scope":
189
+ gate.scope = value === "changed" ? "changed" : value === "all" ? "all" : undefined;
190
+ break;
191
+ case "gate_lint_changed":
192
+ gate.lint_changed = toBoolean(value);
193
+ break;
194
+ case "gate_timeout":
195
+ gate.timeout = toNumber(value);
196
+ break;
197
+ case "gate_max_blocks":
198
+ gate.max_blocks = toNumber(value);
199
+ break;
200
+ case "protect_off":
201
+ config.protect_off = toBoolean(value);
202
+ break;
203
+ case "protect_mode":
204
+ config.protect_mode = value;
205
+ break;
206
+ case "protect":
207
+ config.protect = splitGlobs(value);
208
+ break;
209
+ case "exclude":
210
+ config.exclude = splitGlobs(value);
211
+ break;
212
+ case "constitution":
213
+ config.constitution = String(value);
214
+ break;
215
+ case "rules":
216
+ config.rules = splitGlobs(value);
217
+ break;
218
+ case "style_guide":
219
+ config.style_guide = String(value);
220
+ break;
221
+ default:
222
+ // Unknown flat keys are ignored for forward compatibility.
223
+ break;
224
+ }
225
+ }
226
+ if (Object.keys(formatByExt).length > 0) {
227
+ commands.format = formatByExt;
228
+ }
229
+ if (Object.keys(lintByExt).length > 0) {
230
+ commands.lint = lintByExt;
231
+ }
232
+ if (Object.keys(commands).length > 0) {
233
+ config.commands = commands;
234
+ }
235
+ if (Object.values(gate).some((v) => v !== undefined)) {
236
+ config.gate = gate;
237
+ }
238
+ if (Object.values(onEdit).some((v) => v !== undefined)) {
239
+ config.on_edit = onEdit;
240
+ }
241
+ return config;
242
+ }
243
+ function profileDefaults(profile) {
244
+ return {
245
+ protect_mode: profile === "advisory" ? "warn" : "deny",
246
+ block_on_failure: profile === "standard" || profile === "strict",
247
+ lint_changed: profile === "strict",
248
+ on_edit_format: profile !== "off",
249
+ on_edit_lint: profile !== "off",
250
+ };
251
+ }
252
+ /**
253
+ * Apply profile defaults to a validated raw config. Explicit config keys
254
+ * always override profile defaults.
255
+ */
256
+ export function resolveConfig(raw, configPath) {
257
+ const profile = raw.profile ?? (configPath ? "standard" : "off");
258
+ const defaults = profileDefaults(profile);
259
+ return {
260
+ profile,
261
+ configPath,
262
+ commands: raw.commands ?? {},
263
+ protect: raw.protect ?? DEFAULT_PROTECT,
264
+ protect_mode: raw.protect_mode ?? defaults.protect_mode,
265
+ protect_off: raw.protect_off ?? false,
266
+ gate: {
267
+ run_typecheck: raw.gate?.run_typecheck ?? true,
268
+ run_tests: raw.gate?.run_tests ?? true,
269
+ block_on_failure: raw.gate?.block_on_failure ?? defaults.block_on_failure,
270
+ skip_unchanged: raw.gate?.skip_unchanged ?? true,
271
+ scope: raw.gate?.scope ?? "all",
272
+ lint_changed: raw.gate?.lint_changed ?? defaults.lint_changed,
273
+ timeout: raw.gate?.timeout,
274
+ max_blocks: raw.gate?.max_blocks ?? 3,
275
+ },
276
+ on_edit: {
277
+ format: raw.on_edit?.format ?? defaults.on_edit_format,
278
+ lint: raw.on_edit?.lint ?? defaults.on_edit_lint,
279
+ },
280
+ exclude: raw.exclude ?? [],
281
+ constitution: raw.constitution,
282
+ rules: raw.rules,
283
+ style_guide: raw.style_guide,
284
+ };
285
+ }
286
+ function validateConfig(data, configPath) {
287
+ const result = configSchema.safeParse(data);
288
+ if (!result.success) {
289
+ const issues = result.error.issues
290
+ .map((issue) => ` - ${issue.path.join(".") || "(root)"}: ${issue.message}`)
291
+ .join("\n");
292
+ throw new Error(`Invalid configuration in ${configPath}:\n${issues}`);
293
+ }
294
+ return result.data;
295
+ }
296
+ const configCache = new Map();
297
+ /** Clear the per-session config cache (mainly for tests). */
298
+ export function clearConfigCache() {
299
+ configCache.clear();
300
+ }
301
+ /**
302
+ * Load and resolve the config for a project directory. Results are cached
303
+ * per directory for the lifetime of the session.
304
+ */
305
+ export function loadConfig(directory) {
306
+ const cached = configCache.get(directory);
307
+ if (cached) {
308
+ return cached;
309
+ }
310
+ const configPath = findConfigFile(directory);
311
+ let resolved;
312
+ if (!configPath) {
313
+ resolved = resolveConfig({});
314
+ }
315
+ else {
316
+ const parsed = parseYaml(readFileSync(configPath, "utf8"));
317
+ const asRecord = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
318
+ ? parsed
319
+ : {};
320
+ const mapped = FALLBACK_FILES.has(basename(configPath)) ? mapFlatConfig(asRecord) : asRecord;
321
+ resolved = resolveConfig(validateConfig(mapped, configPath), configPath);
322
+ }
323
+ configCache.set(directory, resolved);
324
+ return resolved;
325
+ }