@bakers-build/core 0.7.1-next.7 → 0.8.1-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/src/cli/bakers-dir.d.ts +8 -8
  2. package/dist/src/cli/bakers-dir.js +30 -33
  3. package/dist/src/cli/config-inventory.d.ts +2 -0
  4. package/dist/src/cli/config-inventory.js +45 -72
  5. package/dist/src/cli/config-report.d.ts +2 -2
  6. package/dist/src/cli/config-source.js +1 -1
  7. package/dist/src/cli/config-validate.d.ts +49 -0
  8. package/dist/src/cli/config-validate.js +400 -0
  9. package/dist/src/cli/import-config.d.ts +2 -2
  10. package/dist/src/cli/import-config.js +5 -5
  11. package/dist/src/cli/load-bakers-config.d.ts +2 -2
  12. package/dist/src/cli/load-bakers-config.js +20 -49
  13. package/dist/src/cli/machine-context.d.ts +8 -12
  14. package/dist/src/cli/machine-context.js +12 -18
  15. package/dist/src/cli/version-check.d.ts +1 -1
  16. package/dist/src/cli/version-check.js +1 -1
  17. package/dist/src/config-types.generated.d.ts +173 -0
  18. package/dist/src/config-types.generated.js +3 -0
  19. package/dist/src/core/logger.d.ts +3 -3
  20. package/dist/src/core/logger.js +5 -5
  21. package/dist/src/core/proc.d.ts +1 -1
  22. package/dist/src/core/proc.js +8 -5
  23. package/dist/src/index.d.ts +3 -1
  24. package/dist/src/index.js +2 -3
  25. package/dist/src/plugins/discover-addons.d.ts +2 -2
  26. package/dist/src/plugins/discover-addons.js +9 -9
  27. package/dist/src/plugins/preset.d.ts +9 -20
  28. package/dist/src/plugins/preset.js +6 -6
  29. package/dist/src/plugins/scoped-addons.d.ts +5 -14
  30. package/dist/src/plugins/scoped-addons.js +11 -36
  31. package/package.json +5 -3
  32. package/schema/connection.schema.json +57 -0
  33. package/schema/harness-options.schema.json +46 -0
  34. package/schema/machine.schema.json +77 -0
  35. package/schema/project.schema.json +262 -0
@@ -0,0 +1,400 @@
1
+ // One JSON Schema per configuration file kind, applied by the loaders to the
2
+ // imported value and by `config check` to the literal values parsed from the
3
+ // source without running it.
4
+ import { readFileSync } from 'node:fs';
5
+ import { createRequire } from 'node:module';
6
+ import { parse, } from 'acorn';
7
+ import { Ajv2020 } from 'ajv/dist/2020.js';
8
+ import { resolveModuleEslintStyle } from './resolve-module.js';
9
+ const require = createRequire(import.meta.url);
10
+ /** A schema file shipped in `@bakers-build/core/schema/`. */
11
+ export function coreSchemaPath(name) {
12
+ return require.resolve(`@bakers-build/core/schema/${name}`);
13
+ }
14
+ function readSchema(name) {
15
+ return JSON.parse(readFileSync(coreSchemaPath(name), 'utf8'));
16
+ }
17
+ let ajvInstance;
18
+ /** The shared ajv instance: core and harness schemas registered, `function` keyword added. */
19
+ export function configAjv() {
20
+ if (ajvInstance)
21
+ return ajvInstance;
22
+ const ajv = new Ajv2020({ allErrors: true, strict: false, verbose: true });
23
+ ajv.addKeyword({
24
+ keyword: 'function',
25
+ schemaType: 'boolean',
26
+ validate: (schema, data) => !schema || typeof data === 'function',
27
+ errors: false,
28
+ });
29
+ for (const name of [
30
+ 'project.schema.json',
31
+ 'machine.schema.json',
32
+ 'connection.schema.json',
33
+ 'harness-options.schema.json',
34
+ ])
35
+ ajv.addSchema(readSchema(name));
36
+ ajvInstance = ajv;
37
+ return ajv;
38
+ }
39
+ const validators = new Map();
40
+ function validatorFor(id) {
41
+ let validate = validators.get(id);
42
+ if (!validate) {
43
+ validate = configAjv().getSchema(id);
44
+ validators.set(id, validate);
45
+ }
46
+ return validate;
47
+ }
48
+ /** Drop `undefined` properties, as an absent key; leave non-plain objects untouched. */
49
+ function withoutUndefined(value, seen = new WeakSet()) {
50
+ if (typeof value !== 'object' || value === null || seen.has(value))
51
+ return value;
52
+ seen.add(value);
53
+ if (Array.isArray(value))
54
+ return value.map((item) => withoutUndefined(item, seen));
55
+ if (Object.getPrototypeOf(value) !== Object.prototype)
56
+ return value;
57
+ return Object.fromEntries(Object.entries(value)
58
+ .filter(([, v]) => v !== undefined)
59
+ .map(([k, v]) => [k, withoutUndefined(v, seen)]));
60
+ }
61
+ function keyOf(instancePath, child) {
62
+ let key = '';
63
+ for (const raw of instancePath.split('/').slice(1)) {
64
+ const segment = raw.replace(/~1/g, '/').replace(/~0/g, '~');
65
+ key = /^\d+$/.test(segment)
66
+ ? `${key}[${segment}]`
67
+ : key
68
+ ? `${key}.${segment}`
69
+ : segment;
70
+ }
71
+ if (child === undefined)
72
+ return key;
73
+ return key ? `${key}.${child}` : child;
74
+ }
75
+ function messageOf(error) {
76
+ const params = error.params;
77
+ switch (error.keyword) {
78
+ case 'enum':
79
+ return `must be one of ${params.allowedValues.join(', ')}`;
80
+ case 'const':
81
+ return `must be ${JSON.stringify(params.allowedValue)}`;
82
+ case 'type':
83
+ return `must be ${String(params.type).replace(',', ' or ')}`;
84
+ case 'minimum':
85
+ return `must be >= ${String(params.limit)}`;
86
+ case 'minLength':
87
+ case 'minProperties':
88
+ return 'must not be empty';
89
+ case 'pattern':
90
+ return params.pattern === '\\S'
91
+ ? 'must not be empty'
92
+ : `must be ${error.parentSchema?.description ?? `match ${String(params.pattern)}`}`;
93
+ case 'function':
94
+ return 'must be a function';
95
+ case 'anyOf':
96
+ return `must be ${error.schema
97
+ .map((branch) => branch.type ?? 'another shape')
98
+ .join(' or ')}`;
99
+ default:
100
+ return error.message ?? 'is invalid';
101
+ }
102
+ }
103
+ const under = (key, ancestor) => ancestor === '' ||
104
+ key.startsWith(`${ancestor}.`) ||
105
+ key.startsWith(`${ancestor}[`);
106
+ /** Convert ajv errors into one problem per key and code. */
107
+ function problemsOf(errors) {
108
+ const anyOfKeys = errors
109
+ .filter((e) => e.keyword === 'anyOf')
110
+ .map((e) => keyOf(e.instancePath));
111
+ const problems = new Map();
112
+ for (const error of errors) {
113
+ if (error.keyword === 'if')
114
+ continue;
115
+ const params = error.params;
116
+ let problem;
117
+ if (error.keyword === 'additionalProperties' ||
118
+ error.keyword === 'unevaluatedProperties') {
119
+ const key = keyOf(error.instancePath, params.additionalProperty ?? params.unevaluatedProperty);
120
+ problem = {
121
+ key,
122
+ code: 'unknown_key',
123
+ severity: 'error',
124
+ message: 'unknown key',
125
+ };
126
+ }
127
+ else if (error.keyword === 'required') {
128
+ problem = {
129
+ key: keyOf(error.instancePath, params.missingProperty),
130
+ code: 'missing_required_key',
131
+ severity: 'error',
132
+ message: 'is required',
133
+ };
134
+ }
135
+ else {
136
+ const key = keyOf(error.instancePath);
137
+ if (error.keyword !== 'anyOf' &&
138
+ anyOfKeys.some((k) => k === key || under(key, k)))
139
+ continue;
140
+ problem = {
141
+ key,
142
+ code: 'invalid_value',
143
+ severity: 'error',
144
+ message: messageOf(error),
145
+ };
146
+ }
147
+ const id = `${problem.code}\0${problem.key}`;
148
+ if (!problems.has(id))
149
+ problems.set(id, problem);
150
+ }
151
+ return [...problems.values()];
152
+ }
153
+ /** Validate one file's value against its schema. Problems sorted by key. */
154
+ export function validateConfig(kind, value, opts = {}) {
155
+ const data = withoutUndefined(value);
156
+ const validate = validatorFor(`https://bakers.build/schema/${kind}.schema.json`);
157
+ validate(data);
158
+ const computed = [...(opts.computed ?? [])];
159
+ const partial = [...(opts.partial ?? [])];
160
+ const schema = problemsOf(validate.errors ?? []).filter((problem) => {
161
+ if (computed.some((c) => under(problem.key, c) ||
162
+ (c === problem.key && problem.code !== 'unknown_key')))
163
+ return false;
164
+ if (problem.code === 'missing_required_key' &&
165
+ partial.includes(problem.key.replace(/\.?[^.[\]]+$/, '')))
166
+ return false;
167
+ return true;
168
+ });
169
+ // The loader reads `project` without running the file (BAKERS_PROJECT may
170
+ // replace the name), so a computed or spread identity never loads.
171
+ const identity = kind === 'project'
172
+ ? [...computed, ...partial].filter((key) => key === 'project' || under(key, 'project'))
173
+ : [];
174
+ const identityProblems = identity.map((key) => ({
175
+ key,
176
+ code: 'invalid_value',
177
+ severity: 'error',
178
+ message: 'must be a literal: the conductor reads project without running the file (BAKERS_PROJECT overrides the name)',
179
+ }));
180
+ const notChecked = [...computed, ...partial]
181
+ .filter((key) => !identity.includes(key))
182
+ .map((key) => ({
183
+ key,
184
+ code: 'not_checked',
185
+ severity: 'warning',
186
+ message: computed.includes(key)
187
+ ? 'value is computed; it is checked when the conductor loads the file'
188
+ : 'object has a spread; its keys are checked when the conductor loads the file',
189
+ }));
190
+ return [...schema, ...identityProblems, ...notChecked].sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
191
+ }
192
+ /** Throw one error naming the file and every error-level problem; warn the rest. */
193
+ export function assertValidConfig(kind, value, path, warn = (m) => console.warn(m)) {
194
+ const problems = validateConfig(kind, value);
195
+ for (const p of problems.filter((p) => p.severity === 'warning'))
196
+ warn(`warning: ${path}: ${p.key ? `${p.key}: ` : ''}${p.message}`);
197
+ const errors = problems.filter((p) => p.severity === 'error');
198
+ if (errors.length)
199
+ throw new Error(`${path}: ${errors
200
+ .map((p) => `${p.key || '(file)'} ${p.message}`)
201
+ .join('; ')}`);
202
+ }
203
+ const join = (prefix, name) => prefix ? `${prefix}.${name}` : name;
204
+ /** Read the default-export object literal without evaluating anything. */
205
+ export function staticConfig(text) {
206
+ let program;
207
+ try {
208
+ program = parse(text, {
209
+ ecmaVersion: 'latest',
210
+ sourceType: 'module',
211
+ locations: true,
212
+ });
213
+ }
214
+ catch {
215
+ return undefined;
216
+ }
217
+ const declaration = program.body.find((node) => node.type === 'ExportDefaultDeclaration');
218
+ if (declaration?.type !== 'ExportDefaultDeclaration' ||
219
+ declaration.declaration.type !== 'ObjectExpression')
220
+ return undefined;
221
+ const result = {
222
+ value: {},
223
+ computed: new Set(),
224
+ partial: new Set(),
225
+ locations: new Map(),
226
+ };
227
+ const locate = (key, node) => {
228
+ if (node.loc)
229
+ result.locations.set(key, {
230
+ line: node.loc.start.line,
231
+ column: node.loc.start.column + 1,
232
+ });
233
+ };
234
+ const COMPUTED = Symbol('computed');
235
+ const read = (node, key) => {
236
+ switch (node.type) {
237
+ case 'Literal':
238
+ if (node.value === null ||
239
+ ['string', 'number', 'boolean'].includes(typeof node.value))
240
+ return node.value;
241
+ break;
242
+ case 'UnaryExpression':
243
+ if ((node.operator === '-' || node.operator === '+') &&
244
+ node.argument.type === 'Literal' &&
245
+ typeof node.argument.value === 'number')
246
+ return node.operator === '-'
247
+ ? -node.argument.value
248
+ : node.argument.value;
249
+ break;
250
+ case 'TemplateLiteral':
251
+ if (node.expressions.length === 0)
252
+ return node.quasis[0]?.value.cooked ?? '';
253
+ break;
254
+ case 'ArrowFunctionExpression':
255
+ case 'FunctionExpression':
256
+ return () => undefined;
257
+ case 'ObjectExpression':
258
+ return readObject(node, key);
259
+ case 'ArrayExpression': {
260
+ const items = [];
261
+ for (const [index, element] of node.elements.entries()) {
262
+ if (!element || element.type === 'SpreadElement')
263
+ return COMPUTED;
264
+ locate(`${key}[${index}]`, element);
265
+ const item = read(element, `${key}[${index}]`);
266
+ if (item === COMPUTED)
267
+ result.computed.add(`${key}[${index}]`);
268
+ items.push(item === COMPUTED ? undefined : item);
269
+ }
270
+ return items;
271
+ }
272
+ }
273
+ return COMPUTED;
274
+ };
275
+ const readObject = (node, prefix) => {
276
+ const object = {};
277
+ for (const entry of node.properties) {
278
+ if (entry.type === 'SpreadElement' || entry.computed) {
279
+ result.partial.add(prefix);
280
+ continue;
281
+ }
282
+ const name = entry.key.type === 'Identifier'
283
+ ? entry.key.name
284
+ : entry.key.type === 'Literal'
285
+ ? String(entry.key.value)
286
+ : undefined;
287
+ if (name === undefined)
288
+ continue;
289
+ const key = join(prefix, name);
290
+ // A later duplicate key replaces the earlier value whole.
291
+ for (const stale of [...result.computed])
292
+ if (stale === key || under(stale, key))
293
+ result.computed.delete(stale);
294
+ locate(key, entry);
295
+ const value = entry.kind !== 'init' || entry.shorthand
296
+ ? COMPUTED
297
+ : entry.method
298
+ ? () => undefined
299
+ : read(entry.value, key);
300
+ if (value === COMPUTED) {
301
+ result.computed.add(key);
302
+ object[name] = null;
303
+ }
304
+ else
305
+ object[name] = value;
306
+ }
307
+ return object;
308
+ };
309
+ result.value = readObject(declaration.declaration, '');
310
+ return result;
311
+ }
312
+ /** The validator of an addon's shipped `options.schema.json`, read as JSON only. */
313
+ function addonOptionsValidator(spec, bases) {
314
+ const path = resolveModuleEslintStyle(`${spec}/options.schema.json`, bases);
315
+ if (!path)
316
+ return undefined;
317
+ const schema = JSON.parse(readFileSync(path, 'utf8'));
318
+ const ajv = configAjv();
319
+ const existing = schema.$id ? ajv.getSchema(schema.$id) : undefined;
320
+ return existing ?? ajv.compile(schema);
321
+ }
322
+ /**
323
+ * Check each literal `with` of the `addons[]` entries (and, on a machine, the
324
+ * `agents.catalog[]` entries) against the addon's own options schema. Addon
325
+ * code never runs; an addon without a schema leaves its options not checked.
326
+ */
327
+ export function addonOptionProblems(kind, parsed, bases) {
328
+ const entries = [];
329
+ const list = (key, specKey) => {
330
+ const items = key
331
+ .split('.')
332
+ .reduce((node, name) => node && typeof node === 'object'
333
+ ? node[name]
334
+ : undefined, parsed.value);
335
+ if (!Array.isArray(items) || parsed.computed.has(key))
336
+ return;
337
+ items.forEach((item, index) => {
338
+ if (item && typeof item === 'object' && 'with' in item)
339
+ entries.push({
340
+ key: `${key}[${index}]`,
341
+ spec: item[specKey],
342
+ options: item.with,
343
+ });
344
+ });
345
+ };
346
+ if (kind !== 'connection')
347
+ list('addons', 'use');
348
+ if (kind === 'machine')
349
+ list('agents.catalog', 'harness');
350
+ const problems = [];
351
+ for (const { key, spec, options } of entries) {
352
+ const withKey = `${key}.with`;
353
+ if (typeof spec !== 'string' ||
354
+ [...parsed.computed].some((c) => c === withKey || under(withKey, c)))
355
+ continue;
356
+ let validate;
357
+ try {
358
+ validate = addonOptionsValidator(spec, bases);
359
+ }
360
+ catch {
361
+ validate = undefined;
362
+ }
363
+ if (!validate) {
364
+ problems.push({
365
+ key: withKey,
366
+ code: 'options_not_checked',
367
+ severity: 'warning',
368
+ message: `options not checked: ${spec} ships no options.schema.json resolvable from this file`,
369
+ });
370
+ continue;
371
+ }
372
+ validate(withoutUndefined(options));
373
+ for (const problem of problemsOf(validate.errors ?? []))
374
+ problems.push({
375
+ ...problem,
376
+ key: problem.key ? `${withKey}.${problem.key}` : withKey,
377
+ });
378
+ }
379
+ return problems;
380
+ }
381
+ /** `config check`'s offline field check of one file's source text. */
382
+ export function checkConfigText(kind, text, opts = {}) {
383
+ const parsed = staticConfig(text);
384
+ if (!parsed)
385
+ return [];
386
+ return [
387
+ ...validateConfig(kind, parsed.value, parsed),
388
+ ...(opts.bases ? addonOptionProblems(kind, parsed, opts.bases) : []),
389
+ ].map((problem) => {
390
+ let key = problem.key;
391
+ let location = parsed.locations.get(key);
392
+ while (!location && key) {
393
+ key = key.replace(/(\.[^.[]+|\[\d+\])$/, '');
394
+ if (key === problem.key)
395
+ break;
396
+ location = parsed.locations.get(key);
397
+ }
398
+ return location ? { ...problem, ...location } : problem;
399
+ });
400
+ }
@@ -2,10 +2,10 @@ export declare function homeBbDirInline(): string;
2
2
  /**
3
3
  * Recognises the computed `import()` expression `configImportExpression()`
4
4
  * (`conductor/src/cli/config-templates.ts`) renders for the home-inherited
5
- * `bakers.config.js`/`machine.config.js` imports. Exported so a cross-package
5
+ * connection file/`machine.config.js` imports. Exported so a cross-package
6
6
  * test can pin the renderer against this recogniser directly, rather than
7
7
  * the two drifting independently. An alternation, not a replacement: every
8
- * config generated before the renderer moved to the `BB_HOME`-aware form
8
+ * config generated before the renderer moved to the `BAKERS_HOME`-aware form
9
9
  * still carries the plain `${process.env.HOME}/.bakers/…` shape on disk, and
10
10
  * that shape must stay recognised alongside the new one.
11
11
  */
@@ -4,25 +4,25 @@ import { homedir } from 'node:os';
4
4
  import { dirname, isAbsolute, join, resolve } from 'node:path';
5
5
  import { fileURLToPath, pathToFileURL } from 'node:url';
6
6
  import { parse } from 'acorn';
7
- // Mirrors homeBbDir()'s BB_HOME precedence (bakers-dir.ts) without importing
7
+ // Mirrors homeBbDir()'s BAKERS_HOME precedence (bakers-dir.ts) without importing
8
8
  // it: this file is spawned directly as a `.ts` entry point by tests (no
9
9
  // transpiler resolving `.js`-suffixed relative imports back to `.ts`
10
10
  // sources), so a same-package import here would break that execution path.
11
11
  export function homeBbDirInline() {
12
- const override = process.env.BB_HOME;
12
+ const override = process.env.BAKERS_HOME;
13
13
  return override ? resolve(override) : join(homedir(), '.bakers');
14
14
  }
15
15
  /**
16
16
  * Recognises the computed `import()` expression `configImportExpression()`
17
17
  * (`conductor/src/cli/config-templates.ts`) renders for the home-inherited
18
- * `bakers.config.js`/`machine.config.js` imports. Exported so a cross-package
18
+ * connection file/`machine.config.js` imports. Exported so a cross-package
19
19
  * test can pin the renderer against this recogniser directly, rather than
20
20
  * the two drifting independently. An alternation, not a replacement: every
21
- * config generated before the renderer moved to the `BB_HOME`-aware form
21
+ * config generated before the renderer moved to the `BAKERS_HOME`-aware form
22
22
  * still carries the plain `${process.env.HOME}/.bakers/…` shape on disk, and
23
23
  * that shape must stay recognised alongside the new one.
24
24
  */
25
- export const HOME_IMPORT_EXPRESSION_PATTERN = /^`\$\{process\.env\.BB_HOME \?\? `\$\{process\.env\.HOME\}\/\.bakers`\}\/(bakers\.config\.js|machine\.config\.js)`$|^`\$\{process\.env\.HOME\}\/\.bakers\/(bakers\.config\.js|machine\.config\.js)`$/;
25
+ export const HOME_IMPORT_EXPRESSION_PATTERN = /^`\$\{process\.env\.BAKERS_HOME \?\? `\$\{process\.env\.HOME\}\/\.bakers`\}\/(bakers\.config\.js|machine\.config\.js)`$|^`\$\{process\.env\.HOME\}\/\.bakers\/(bakers\.config\.js|machine\.config\.js)`$/;
26
26
  /** Import configuration as a fresh module graph without writing transient secret files.
27
27
  * Local literal imports are refreshed recursively; package imports retain normal
28
28
  * Node resolution. Preserve import.meta.url so relative resource access still
@@ -38,7 +38,7 @@ export interface BbConnectionConfig {
38
38
  /** The selected named connection, or `default` for the global connection. */
39
39
  connection_id: string | undefined;
40
40
  /** Which user-facing selector chose the connection. */
41
- selection_source: ConfigSourceKind | 'project-file' | 'default' | 'legacy-project';
41
+ selection_source: ConfigSourceKind | 'default' | 'legacy-project';
42
42
  /** Current resolution never chooses a historical engine connection. */
43
43
  legacy: boolean;
44
44
  /**
@@ -77,7 +77,7 @@ export interface BbConnectionLoadOptions {
77
77
  export interface BbConnectionSelection {
78
78
  path: string;
79
79
  connectionId: string | undefined;
80
- selectionSource: ConfigSourceKind | 'project-file' | 'default' | 'legacy-project';
80
+ selectionSource: ConfigSourceKind | 'default' | 'legacy-project';
81
81
  source: BbConfigSource;
82
82
  fallback: boolean;
83
83
  legacy: boolean;
@@ -4,11 +4,12 @@ import { pathToFileURL } from 'node:url';
4
4
  import { resolveConfigSource, resolveConnectionsDir, } from 'dropsh/plugin';
5
5
  import { shellQuote } from '../core/shell.js';
6
6
  import { discoverAddons } from '../plugins/discover-addons.js';
7
- import { findConfigProjectBbDir, homeBbDir, resolveBbConfigPath, } from './bakers-dir.js';
7
+ import { homeBbDir, resolveBbConfigPath, } from './bakers-dir.js';
8
8
  import { inspectConfigSource } from './config-source.js';
9
+ import { assertValidConfig } from './config-validate.js';
9
10
  import { importConfig } from './import-config.js';
10
11
  import { machineUiConfigPath, projectConductorConfigPath, readUiEntryLayers, } from './layered-ui-entries.js';
11
- import { assertSchemaVersion1, warnIgnoredMaxParallel, } from './machine-context.js';
12
+ import { assertSchemaVersion } from './machine-context.js';
12
13
  import { resolveModuleEslintStyle } from './resolve-module.js';
13
14
  /**
14
15
  * A connection config that was RESOLVED but is not usable — a missing
@@ -92,51 +93,20 @@ export async function reportLoadedBbConfigFields(path) {
92
93
  visit(key, value, 0);
93
94
  return fields;
94
95
  }
95
- function projectConnectionSelection(cwd, home) {
96
- const bakersDir = findConfigProjectBbDir(cwd, home);
97
- if (!bakersDir)
98
- return undefined;
99
- const path = join(bakersDir, 'connection.config.local.js');
100
- if (!existsSync(path))
101
- return undefined;
102
- const inspected = inspectConfigSource(readFileSync(path, 'utf8'));
103
- const topLevel = inspected.propertyOccurrences.filter((property) => !property.key.includes('.') && !property.key.includes('['));
104
- const unknown = topLevel.find((property) => property.key !== 'connection');
105
- if (unknown)
106
- throw new BbConnectionConfigError(`Unknown key '${unknown.key}' in ${path}; only 'connection' is allowed.`);
107
- const connection = inspected.properties.get('connection');
108
- if (inspected.syntax !== 'valid' ||
109
- inspected.shape !== 'object' ||
110
- inspected.unknownKeys ||
111
- !connection?.staticallyDetermined ||
112
- typeof connection.value !== 'string' ||
113
- connection.value.trim() === '')
114
- throw new BbConnectionConfigError(`${path} must default-export one literal string key: connection.`);
115
- return connection.value.trim();
116
- }
117
96
  /** Resolve the connection source without importing or executing it. */
118
97
  export async function resolveBbConnectionSelection(opts = {}) {
119
98
  const env = opts.env ?? process.env;
120
99
  const connectionsDir = resolveConnectionsDir({
121
100
  flag: join(homeBbDir(opts.home), 'connections'),
122
101
  });
123
- let projectConnection;
124
- let projectConnectionRead = false;
102
+ // A project selects a named connection with BAKERS_CONNECTION or --connection.
125
103
  const dropshEnv = {
126
104
  ...env,
127
- ...(env.BB_CONFIG ? { DROPSH_CONFIG: env.BB_CONFIG } : {}),
105
+ ...(env.BAKERS_CONFIG ? { DROPSH_CONFIG: env.BAKERS_CONFIG } : {}),
106
+ ...(env.BAKERS_CONNECTION
107
+ ? { DROPSH_CONNECTION: env.BAKERS_CONNECTION }
108
+ : {}),
128
109
  };
129
- Object.defineProperty(dropshEnv, 'DROPSH_CONNECTION', {
130
- enumerable: true,
131
- get() {
132
- const environmentConnection = env.BB_CONNECTION || env.DROPSH_CONNECTION;
133
- if (environmentConnection)
134
- return environmentConnection;
135
- projectConnectionRead = true;
136
- projectConnection = projectConnectionSelection(opts.cwd ?? process.cwd(), opts.home);
137
- return projectConnection;
138
- },
139
- });
140
110
  const defaultResolution = resolveBbConfigPath({
141
111
  ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
142
112
  explicit: undefined,
@@ -150,11 +120,7 @@ export async function resolveBbConnectionSelection(opts = {}) {
150
120
  env: dropshEnv,
151
121
  ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
152
122
  });
153
- let selectionSource = selected.source === 'env-connection' &&
154
- projectConnectionRead &&
155
- projectConnection !== undefined
156
- ? 'project-file'
157
- : selected.source;
123
+ let selectionSource = selected.source;
158
124
  const usesDefaultConfig = selected.source === 'cwd' || selected.source === 'default-config';
159
125
  const resolution = usesDefaultConfig
160
126
  ? defaultResolution
@@ -207,7 +173,7 @@ function withGlobals(globals, own) {
207
173
  async function loadDescriptor(entry, bases, globals) {
208
174
  const resolved = resolveModuleEslintStyle(entry.plugin, bases);
209
175
  if (resolved === undefined) {
210
- throw new Error(`bakers.config.js cannot resolve plugin '${entry.plugin}'`);
176
+ throw new Error(`connection config cannot resolve plugin '${entry.plugin}'`);
211
177
  }
212
178
  const mod = (await import(pathToFileURL(resolved).href));
213
179
  let factory;
@@ -258,8 +224,13 @@ export async function loadBbConnectionBootstrap(host, opts = {}) {
258
224
  if (!isRecord(raw)) {
259
225
  throw new Error(`bakers connection config default export must be an object (${configPath})`);
260
226
  }
261
- assertSchemaVersion1(configPath, raw);
262
- warnIgnoredMaxParallel(configPath, raw);
227
+ assertSchemaVersion(configPath, raw);
228
+ try {
229
+ assertValidConfig('connection', raw, configPath);
230
+ }
231
+ catch (error) {
232
+ throw new BbConnectionConfigError(error.message);
233
+ }
263
234
  const site = isRecord(raw.site) ? raw.site : {};
264
235
  const baseUrl = typeof site.base_url === 'string' ? site.base_url : '';
265
236
  if (baseUrl.trim() === '') {
@@ -303,15 +274,15 @@ export async function loadBbConnectionBootstrap(host, opts = {}) {
303
274
  const warn = (message) => {
304
275
  console.warn(message);
305
276
  };
306
- // The `.bakers` root is core's decision (BB_HOME), not this function's: an
277
+ // The `.bakers` root is core's decision (BAKERS_HOME), not this function's: an
307
278
  // absent `opts.home` must reach `homeBbDir()`'s resolver rather than
308
- // collapsing to the OS home here first, or BB_HOME never relocates
279
+ // collapsing to the OS home here first, or BAKERS_HOME never relocates
309
280
  // `machine.config.js` for this layer.
310
281
  const machineBbDir = homeBbDir(opts.home);
311
282
  // The project root is the SELECTED connection config's own directory only
312
283
  // when that config actually sits in A PROJECT's `.bakers/` dir — `configPath`
313
284
  // is `<project root>/.bakers/<file>` — whether resolved by walk-up or given
314
- // explicitly. The home connection (`<home>/.bakers/bakers.config.js`, BB-218's
285
+ // explicitly. The home connection (`<home>/.bakers/connection file`, BB-218's
315
286
  // canonical engine-only shape) and a named connection
316
287
  // (`<home>/.bakers/connections/<id>.js`) both fail that test — the first
317
288
  // because its `.bakers/` dir IS the home one, the second because its parent
@@ -4,14 +4,13 @@ export interface MachineAgentEntry {
4
4
  alias?: string;
5
5
  with?: unknown;
6
6
  }
7
- /** Normalized named state-to-agent routes. `default` is the automatic route. */
7
+ /** Named state-to-agent routes. `default` is the automatic route; `'*'` matches any state. */
8
8
  export type AgentRoutes = Record<string, Record<string, string>>;
9
9
  /** Optional host-local overlays and selection policy for addon-derived agents. */
10
10
  export interface MachineAgentPolicy {
11
11
  catalog?: MachineAgentEntry[];
12
12
  enabled?: string[];
13
13
  disabled?: string[];
14
- default_agent?: string;
15
14
  routes?: AgentRoutes;
16
15
  }
17
16
  /** Local host identity, display label and shared capacity. */
@@ -45,25 +44,22 @@ export interface MachineContext {
45
44
  */
46
45
  executor?: unknown;
47
46
  }
48
- /**
49
- * Warn once that a leftover `max_parallel` in a config file is ignored: the
50
- * run budget is set on the machine in the backend.
51
- */
52
- export declare function warnIgnoredMaxParallel(path: string, raw: object): void;
53
- /** Canonical machine-context path: `<BB_HOME or ~/.bakers>/machine.config.js`. */
47
+ /** Canonical machine-context path: `<BAKERS_HOME or ~/.bakers>/machine.config.js`. */
54
48
  export declare function machineContextPath(): string;
55
49
  /** Resolve explicit or canonical current host context. */
56
50
  export declare function resolveMachineContextPath(path?: string): string;
51
+ /** The configuration schema version every file kind is at. */
52
+ export declare const CONFIG_SCHEMA_VERSION = 1;
57
53
  /**
58
54
  * Every config file (machine, connection, project) is at schema version 1.
59
55
  * Any other version, in the `schema_version` field or the
60
- * `@bakers-schema-version` header, predates the fresh start and is refused.
56
+ * `@bakers-schema-version` header, is refused.
61
57
  */
62
- export declare function assertSchemaVersion1(path: string, raw: Record<string, unknown>, remedy?: string): void;
58
+ export declare function assertSchemaVersion(path: string, raw: Record<string, unknown>): void;
63
59
  /**
64
60
  * Import an existing context module's default export, or `{}` if absent/broken.
65
- * An old file (`user_id`, a schema version other than 1) throws, naming
66
- * `bakers init`, which rewrites it in place. An existing machine keeps its
61
+ * A file at another schema version, or one the machine schema rejects,
62
+ * throws naming the file and every problem. An existing machine keeps its
67
63
  * `machine_id` as it is; only a UUID is normalised to lowercase.
68
64
  */
69
65
  export declare function readMachineContext(path?: string): Promise<Partial<MachineContext>>;