@bakers-build/conductor 0.5.1-next.849 → 0.5.1-next.851

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.
@@ -2,8 +2,8 @@ import { type ConfigInventoryOptions, type ConfigReport } from '@bakers-build/co
2
2
  import { type ConnectionAuthType } from './config-templates.js';
3
3
  export interface ConfigPlanOptions extends ConfigInventoryOptions {
4
4
  inputs?: {
5
- machineId?: string;
6
- userId?: string;
5
+ /** Machine display label; the machine UUID is always generated. */
6
+ label?: string;
7
7
  maxParallel?: number;
8
8
  baseUrl?: string;
9
9
  clientId?: string;
@@ -5,25 +5,16 @@ import { createRequire } from 'node:module';
5
5
  import { dirname } from 'node:path';
6
6
  import { configRecheckCommand, finalizeConfigReport, inspectConfigSource, inventoryConfig, shellQuote, } from '@bakers-build/core';
7
7
  import { applyMigrations, BB_CONFIG_SCHEMA_VERSION } from './config-schema.js';
8
- import { ConfigSourceEditor, redactConfigSource, sameValue, } from './config-source-edit.js';
9
- import { configImportExpression, DEFAULT_CONDUCTOR_AGENT_ADDONS, renderCommittedConfig, renderGlobalConnection, renderHostMachine, } from './config-templates.js';
10
- import { CONDUCTOR_ADDON_SLOTS, validateConfigSources, } from './config-validation.js';
11
- import { migrateAddonNames } from './migrate-addon-names.js';
8
+ import { ConfigSourceEditor, redactConfigSource, } from './config-source-edit.js';
9
+ import { renderCommittedConfig, renderGlobalConnection, renderHostMachine, } from './config-templates.js';
10
+ import { validateConfigSources } from './config-validation.js';
11
+ // Every config file restarted at schema v1; no migration step exists.
12
12
  const CURRENT = {
13
- machine: 3,
14
- // v1 is the first versioned conductor shape: the conductor owns only
15
- // remote/executor/workspace and declares no agent addons. Zero was the
16
- // implicit pre-versioned state (no @bakers-schema-version marker present).
13
+ machine: 1,
17
14
  conductor: 1,
18
- connection: 4,
19
- 'project-connection': 4,
15
+ connection: 1,
16
+ 'project-connection': 1,
20
17
  };
21
- const CONNECTION_KEYS = [
22
- 'base_url',
23
- 'client_id',
24
- 'client_secret',
25
- 'workspace_id',
26
- ];
27
18
  function fingerprint(text) {
28
19
  return `sha256:${createHash('sha256').update(text).digest('hex')}`;
29
20
  }
@@ -67,7 +58,6 @@ export function planConfig(options = {}) {
67
58
  const files = report.files;
68
59
  const machine = files.find((f) => f.kind === 'machine');
69
60
  const connection = files.find((f) => f.kind === 'connection');
70
- const local = files.find((f) => f.kind === 'local');
71
61
  if (options.operation === 'check') {
72
62
  const validated = validateConfigSources(inventoryOptions, new Map(original), files);
73
63
  return {
@@ -78,7 +68,9 @@ export function planConfig(options = {}) {
78
68
  }
79
69
  const errors = report.findings.filter((f) => (['scope', 'syntax', 'inventory'].includes(f.stage) &&
80
70
  f.code !== 'missing_required_file') ||
81
- ['future_schema_version', 'version_marker_disagreement'].includes(f.code));
71
+ // An old machine file is rewritten below, keeping its machine_id.
72
+ (f.code === 'unsupported_schema_version' && f.path !== machine?.path) ||
73
+ f.code === 'version_marker_disagreement');
82
74
  const recheck = configRecheckCommand((options.scope ?? 'all'), report.roots.project) +
83
75
  (options.machinePath
84
76
  ? ` --machine-path ${shellQuote(options.machinePath)}`
@@ -110,7 +102,7 @@ export function planConfig(options = {}) {
110
102
  };
111
103
  const protectedFile = (file) => errors.some((e) => e.path === file.path &&
112
104
  [
113
- 'future_schema_version',
105
+ 'unsupported_schema_version',
114
106
  'version_marker_disagreement',
115
107
  'syntax_error',
116
108
  'unreadable_file',
@@ -130,50 +122,13 @@ export function planConfig(options = {}) {
130
122
  (!p || (p.staticallyDetermined && (p.value === '' || p.value === null))))
131
123
  e.set(key, JSON.stringify(value));
132
124
  };
133
- const move = (from, key, to, target) => {
134
- const source = editors.get(from.path);
135
- const p = source?.property(key);
136
- if (!p || !source)
137
- return;
138
- if (!from.selected && !to.selected)
139
- return;
140
- if (!from.selected || !to.selected) {
141
- problem(from, 'out_of_scope_write_required', key, 'Both source and destination are selected writable layers.', [{ path: to.path, key: target }]);
142
- return;
143
- }
144
- if (protectedFile(from) || protectedFile(to))
145
- return;
146
- const dest = editor(to);
147
- const existing = dest.property(target);
148
- if (!p.staticallyDetermined || p.value === undefined) {
149
- problem(from, 'unknown_value', key, 'The moved value must be a known literal.', [{ path: to.path, key: target }]);
150
- return;
151
- }
152
- if (existing && !sameValue(p, existing)) {
153
- problem(from, 'conflicting_values', key, 'Source and destination values agree.', [
154
- {
155
- path: to.path,
156
- key: target,
157
- line: existing.line,
158
- column: existing.column,
159
- },
160
- ]);
161
- return;
162
- }
163
- if (!existing)
164
- dest.set(target, source.expression(key));
165
- source.remove(key);
166
- };
167
125
  if (!machine || !connection)
168
126
  return { report, writes: [], fingerprints: new Map() };
169
- if (machine.selected &&
170
- !editors.has(machine.path) &&
171
- options.inputs?.machineId &&
172
- options.inputs?.userId)
127
+ if (machine.selected && !editors.has(machine.path))
173
128
  editors.set(machine.path, new ConfigSourceEditor(renderHostMachine({
174
- machineId: options.inputs.machineId,
175
- userId: options.inputs.userId,
176
- maxParallel: options.inputs.maxParallel ?? 1,
129
+ machineId: randomUUID(),
130
+ ...(options.inputs?.label ? { label: options.inputs.label } : {}),
131
+ maxParallel: options.inputs?.maxParallel ?? 1,
177
132
  })));
178
133
  const authType = options.inputs?.authType ?? 'oauth2_client_credentials';
179
134
  if (connection.selected &&
@@ -493,45 +448,6 @@ export function planConfig(options = {}) {
493
448
  migrateCatalog(file, source);
494
449
  deriveMachineDefault();
495
450
  }
496
- if (editors.has(connection.path) &&
497
- connection.selected &&
498
- !protectedFile(connection) &&
499
- !protectedFile(machine))
500
- replaceGeneratedMachineWiring(editor(connection), editor(machine), connection, options.inputs, problem);
501
- // Machine connection values must move atomically with their connection destinations.
502
- for (const key of CONNECTION_KEYS) {
503
- const target = key === 'base_url'
504
- ? 'site.base_url'
505
- : key === 'workspace_id'
506
- ? key
507
- : `plugins[0].with.${key}`;
508
- const e = editors.get(machine.path);
509
- if (!e?.property(key))
510
- continue;
511
- if (!machine.selected || !connection.selected) {
512
- problem(machine, 'out_of_scope_write_required', key, 'Machine and connection scopes are both required.', [{ path: connection.path, key: target }]);
513
- continue;
514
- }
515
- if (protectedFile(machine) || protectedFile(connection))
516
- continue;
517
- const conn = editor(connection);
518
- // Generated v1-v3 wiring is resolved only from the recognized machine literal.
519
- if (key === 'client_id' || key === 'client_secret') {
520
- let prefix = oauthPrefix(conn);
521
- if (!prefix) {
522
- if (!conn.property('plugins'))
523
- conn.set('plugins', "[{ plugin: '@bakers-build/addon-essentials' }, { plugin: '@dropsh/plugin-oauth2', export: 'oauth2Plugin', with: { id: 'bakers', default: true, type: 'oauth2_client_credentials', scope: 'bb:session' } }]");
524
- prefix = oauthPrefix(conn);
525
- }
526
- if (!prefix) {
527
- problem(connection, 'unsupported_source_shape', 'plugins', 'A statically known OAuth provider accepts migrated credentials.');
528
- continue;
529
- }
530
- move(machine, key, connection, `${prefix}.with.${key}`);
531
- }
532
- else
533
- move(machine, key, connection, target);
534
- }
535
451
  for (const file of files) {
536
452
  if (protectedFile(file) || !file.selected)
537
453
  continue;
@@ -542,66 +458,11 @@ export function planConfig(options = {}) {
542
458
  }
543
459
  try {
544
460
  if (file.kind === 'machine') {
545
- fill(file, 'machine_id', options.inputs?.machineId);
546
- fill(file, 'user_id', options.inputs?.userId);
461
+ editor(file).remove('user_id');
462
+ fill(file, 'machine_id', randomUUID());
463
+ fill(file, 'label', options.inputs?.label);
547
464
  fill(file, 'max_parallel', options.inputs?.maxParallel);
548
- e = editors.get(file.path);
549
- // Addon settings live only in the top-level addons[]: move the retired
550
- // `agents.addons` and `ports` keys there first.
551
- // Entries moved from agents.addons are the operator's harnesses; an
552
- // empty list names none, so it seeds like a missing one.
553
- const agentAddons = e?.property('agents.addons');
554
- const hadAgentAddons = !!agentAddons && agentAddons.arrayLength !== 0;
555
- if (e)
556
- migrateMachineAddons(e);
557
- // Machine 2 → 3: seed agent harnesses into addons[] when the machine
558
- // lists no harness (isHarness). Source: harness packages found in the
559
- // project conductor.config.js addons[], or a known default set when no
560
- // conductor config is available.
561
- const machineAddons = e?.property('addons');
562
- if (e &&
563
- !hadAgentAddons &&
564
- (!machineAddons || machineAddons.nodeType === 'ArrayExpression') &&
565
- arrayEntries(e, 'addons').every((x) => typeof x.pkg === 'string' && !isHarness(x.pkg))) {
566
- const conductorFile = files.find((f) => f.kind === 'conductor');
567
- const conductorEditor = conductorFile
568
- ? editors.get(conductorFile.path)
569
- : undefined;
570
- let agentAddonsExpression;
571
- if (conductorEditor) {
572
- const agentEntries = [...conductorEditor.source.properties]
573
- .filter(([key]) => /^addons\[\d+\](?:\.use)?$/.test(key))
574
- .map(([, property]) => property.value)
575
- .filter((value) => typeof value === 'string' && isHarness(value));
576
- if (agentEntries.length > 0)
577
- agentAddonsExpression = `[${agentEntries.map((pkg) => `{ use: ${JSON.stringify(pkg)} }`).join(', ')}]`;
578
- }
579
- if (!agentAddonsExpression) {
580
- // No conductor config or no agent entries found — seed a known default
581
- // set and surface a warning so the operator can review it.
582
- agentAddonsExpression = `['@bakers-build/addon-claude', '@bakers-build/addon-codex', '@bakers-build/addon-grok']`;
583
- report.findings.push({
584
- code: 'missing_required_file',
585
- severity: 'warning',
586
- stage: 'planning',
587
- path: file.path,
588
- key: 'addons',
589
- expected: 'addons seeded with a default set of agent harnesses; review it and adjust to match your installed agent packages.',
590
- observed: null,
591
- owner: file.layer,
592
- related: [],
593
- statically_determined: true,
594
- remediation: `Edit ${file.path} to set addons to the packages you want, then run ${recheck}.`,
595
- recheck,
596
- });
597
- }
598
- const listed = arrayEntries(e, 'addons').map((x) => x.text);
599
- e.set('addons', listed.length
600
- ? `[${[...listed, agentAddonsExpression.slice(1, -1)].join(', ')}]`
601
- : agentAddonsExpression);
602
- }
603
- if (e)
604
- e.stamp(3);
465
+ editor(file).stamp(1);
605
466
  }
606
467
  if (file.kind === 'conductor' || file.kind === 'local') {
607
468
  if ((!e || e.text.trim() === 'export default {};') &&
@@ -620,67 +481,6 @@ export function planConfig(options = {}) {
620
481
  continue;
621
482
  if (file.kind === 'conductor') {
622
483
  e = editor(file);
623
- const legacyProject = e.property('project');
624
- const legacyWorkspace = e.property('bb_workspace');
625
- const nestedBb = e.property('bakers');
626
- const nestedExpression = e.expression('bakers');
627
- const nestedHasSpread = nestedExpression
628
- ? new ConfigSourceEditor(`export default ${nestedExpression};`)
629
- .source.unknownKeys
630
- : false;
631
- let projectExpression = e.expression('project');
632
- if (projectExpression === 'project' &&
633
- /const project\s*=\s*local\.project\s*\?\?\s*([^;]+);/.test(e.text)) {
634
- const fallback = /const project\s*=\s*local\.project\s*\?\?\s*([^;]+);/
635
- .exec(e.text)?.[1]
636
- ?.trim();
637
- const literal = fallback
638
- ? new ConfigSourceEditor(`export default { value: ${fallback} };`).property('value')
639
- : undefined;
640
- if (literal?.staticallyDetermined &&
641
- typeof literal.value === 'string') {
642
- projectExpression = fallback;
643
- e.text = e.text.replace(/const project\s*=\s*local\.project\s*\?\?\s*[^;]+;/, `const project = ${fallback};`);
644
- }
645
- }
646
- const staticProject = projectExpression
647
- ? new ConfigSourceEditor(`export default { value: ${projectExpression} };`).property('value')
648
- : undefined;
649
- if (nestedBb &&
650
- (nestedBb.nodeType !== 'ObjectExpression' ||
651
- !nestedBb.staticallyDetermined ||
652
- nestedHasSpread))
653
- problem(file, 'unsupported_source_shape', 'bakers', 'A literal bakers object is required.');
654
- else if (legacyProject &&
655
- (!staticProject?.staticallyDetermined ||
656
- typeof staticProject.value !== 'string'))
657
- problem(file, 'unknown_value', 'project', 'A literal project name is required for migration.');
658
- else if (legacyWorkspace &&
659
- (!legacyWorkspace.staticallyDetermined ||
660
- typeof legacyWorkspace.value !== 'string'))
661
- problem(file, 'unknown_value', 'bb_workspace', 'A literal workspace name is required for migration.');
662
- else if (legacyProject || legacyWorkspace) {
663
- const existingProject = e.property('bakers.project');
664
- const existingWorkspace = e.property('bakers.workspace');
665
- if (legacyProject &&
666
- existingProject &&
667
- (!existingProject.staticallyDetermined ||
668
- existingProject.value !== staticProject?.value))
669
- problem(file, 'conflicting_values', 'project', 'Legacy and nested project names must agree.');
670
- else if (legacyWorkspace &&
671
- existingWorkspace &&
672
- (!existingWorkspace.staticallyDetermined ||
673
- existingWorkspace.value !== legacyWorkspace.value))
674
- problem(file, 'conflicting_values', 'bb_workspace', 'Legacy and nested workspace names must agree.');
675
- else {
676
- if (legacyProject && !existingProject)
677
- e.set('bakers.project', projectExpression);
678
- if (legacyWorkspace && !existingWorkspace)
679
- e.set('bakers.workspace', e.expression('bb_workspace'));
680
- e.remove('project');
681
- e.remove('bb_workspace');
682
- }
683
- }
684
484
  fill(file, 'bakers.project', options.project);
685
485
  const canonical = new ConfigSourceEditor(renderCommittedConfig({
686
486
  project: options.project ?? 'project',
@@ -707,106 +507,11 @@ export function planConfig(options = {}) {
707
507
  continue;
708
508
  e.set(slot, canonical.expression(slot));
709
509
  }
710
- // Only seed default agent addons into an unversioned conductor config.
711
- // A versioned config (schema v1+) has already been migrated: agents
712
- // belong to machine.config.js and the conductor addons[] must not be
713
- // repopulated with the old agent harnesses on re-run.
714
- if (!e.property('agent') &&
715
- !e.property('addons') &&
716
- !(file.version.effective ?? 0))
717
- e.set('addons', DEFAULT_CONDUCTOR_AGENT_ADDONS);
718
510
  if (options.operation === 'init' &&
719
511
  options.inputs?.workspace &&
720
512
  !e.property('bakers.workspace'))
721
513
  e.set('bakers.workspace', JSON.stringify(options.inputs.workspace));
722
- if (!e.property('conductor_id') && !e.property('machine_id')) {
723
- const machineEditor = editors.get(machine.path);
724
- const machineId = machineEditor?.property('machine_id');
725
- const userId = machineEditor?.property('user_id');
726
- const project = e.property('bakers.project');
727
- if (typeof machineId?.value === 'string' &&
728
- typeof userId?.value === 'string' &&
729
- typeof project?.value === 'string')
730
- e.set('conductor_id', JSON.stringify(`${userId.value}-${machineId.value}-${project.value}`));
731
- }
732
- }
733
- for (const key of ['max_parallel', 'conductor.max_parallel'])
734
- move(file, key, machine, 'max_parallel');
735
- const old = e.property('machine_id');
736
- const current = e.property('conductor_id');
737
- if (old) {
738
- if (current &&
739
- !sameValue(old, current) &&
740
- e.expression('machine_id') !== e.expression('conductor_id'))
741
- problem(file, 'conflicting_values', 'machine_id', 'The deprecated and current conductor identity must agree.', [
742
- {
743
- path: file.path,
744
- key: 'conductor_id',
745
- line: current.line,
746
- column: current.column,
747
- },
748
- ]);
749
- else if (current)
750
- e.remove('machine_id');
751
- else
752
- e.rename('machine_id', 'conductor_id');
753
- }
754
- if (file.kind === 'conductor' &&
755
- e.text.includes('async function loadMachine()'))
756
- // The committed conductor config never names this machine's path
757
- // (AC 4): the replacement is the same portable BB_HOME/HOME
758
- // expression init renders, not a serialised file:// URL. The match
759
- // is widened past a single backtick pair so it also catches the
760
- // nested-backtick form the current template emits.
761
- e.text = e.text.replace(/import\(`(?:[^`\\]|\\.|`[^`]*`)*\/(?:machine\.config\.js|conductor\.config\.machine\.js)`\)/g, `import(${configImportExpression('machine.config.js')})`);
762
- e.text = migrateAddonNames(e.text, 'engine').text;
763
- if (file.kind === 'conductor') {
764
- // Conductor 0 → 1: remove agent-addon entries from addons[], leaving
765
- // only remote/executor/workspace provider packages (and any spread
766
- // expressions such as `...(local.agent_addons ?? [])`). If addons[]
767
- // becomes empty, remove the key. Idempotent: a file already at v1
768
- // (effective version set) is left entirely unchanged on re-run.
769
- // Agent packages are those NOT in the canonical non-agent provider set
770
- // (same definition as the conductor slot-filling heuristic).
771
- if (!(file.version.effective ?? 0)) {
772
- const NON_AGENT_PACKAGES = new Set([
773
- '@bakers-build/addon-remote-drupal',
774
- '@bakers-build/addon-herdr',
775
- '@bakers-build/addon-fake',
776
- '@bakers-build/addon-workspace-git',
777
- ]);
778
- const addonsProperty = e.property('addons');
779
- if (addonsProperty?.staticallyDetermined &&
780
- addonsProperty.nodeType === 'ArrayExpression') {
781
- const length = addonsProperty.arrayLength ?? 0;
782
- const kept = [];
783
- for (let i = 0; i < length; i++) {
784
- const entryKey = `addons[${i}]`;
785
- const entry = e.property(entryKey);
786
- // Keep non-statically-known entries (e.g. spread) and entries
787
- // whose package is a known non-agent provider.
788
- const useProperty = e.property(`${entryKey}.use`) ??
789
- e.property(`${entryKey}.name`);
790
- const pkg = entry?.staticallyDetermined && typeof entry.value === 'string'
791
- ? entry.value
792
- : useProperty?.staticallyDetermined &&
793
- typeof useProperty.value === 'string'
794
- ? useProperty.value
795
- : undefined;
796
- if (pkg === undefined || NON_AGENT_PACKAGES.has(pkg)) {
797
- const expr = e.expression(entryKey);
798
- if (expr !== undefined)
799
- kept.push(expr);
800
- }
801
- }
802
- if (kept.length === 0)
803
- e.remove('addons');
804
- else if (kept.length < length)
805
- e.set('addons', `[${kept.join(', ')}]`);
806
- }
807
- // Stamp v1 so subsequent runs skip this block (idempotent).
808
- e.stamp(1);
809
- }
514
+ e.stamp(1);
810
515
  }
811
516
  }
812
517
  }
@@ -849,29 +554,10 @@ export function planConfig(options = {}) {
849
554
  e.set(`${prefix}.with.token_url`, JSON.stringify(`${url.replace(/\/$/, '')}/oauth/token`));
850
555
  }
851
556
  }
852
- if (file.kind === 'project-connection')
853
- migrateGeneratedProject(e);
854
557
  const version = file.version.effective ?? 1;
855
558
  if (version < BB_CONFIG_SCHEMA_VERSION)
856
559
  e.text = applyMigrations(e.text, version, BB_CONFIG_SCHEMA_VERSION);
857
- e.text = migrateAddonNames(e.text, 'connection').text;
858
- if (file.kind === 'project-connection' && local) {
859
- const prefix = oauthPrefix(e);
860
- const secret = prefix
861
- ? e.property(`${prefix}.with.client_secret`)
862
- : undefined;
863
- if (secret?.staticallyDetermined && secret.value) {
864
- move(file, `${prefix}.with.client_secret`, local, 'oauth.client_secret');
865
- if (!e.property(`${prefix}.with.client_secret`)) {
866
- e.set(`${prefix}.with.client_secret`, 'local.oauth?.client_secret');
867
- if (!/const local\s*=|let local\s*=/.test(e.text))
868
- e.text =
869
- "let local = {};\ntry { local = (await import('./conductor.config.local.js')).default; } catch (error) { if (error.code !== 'ERR_MODULE_NOT_FOUND') throw error; }\n" +
870
- e.text;
871
- }
872
- }
873
- }
874
- e.stamp(4);
560
+ e.stamp(BB_CONFIG_SCHEMA_VERSION);
875
561
  }
876
562
  catch {
877
563
  problem(file, 'unsupported_source_shape', null, 'The supported connection migration chain completes safely.');
@@ -914,15 +600,7 @@ export function planConfig(options = {}) {
914
600
  path: file.path,
915
601
  layer: file.layer,
916
602
  before_version: file.version.effective,
917
- after_version: after === null
918
- ? null
919
- : file.kind === 'machine'
920
- ? 3
921
- : ['connection', 'project-connection'].includes(file.kind)
922
- ? 4
923
- : file.kind === 'conductor'
924
- ? 1
925
- : null,
603
+ after_version: after === null || file.kind === 'local' ? null : CURRENT[file.kind],
926
604
  diff: `--- ${file.path}\n+++ ${file.path}\n${before === null
927
605
  ? ''
928
606
  : redactConfigSource(before)
@@ -940,171 +618,12 @@ export function planConfig(options = {}) {
940
618
  finalizeConfigReport(report);
941
619
  return { report, writes, fingerprints };
942
620
  }
943
- const PORTS_ADDON = '@bakers-build/addon-ports';
944
- /** A package known to fill no agent slot is not a harness; an unknown one may be. */
945
- function isHarness(pkg) {
946
- return CONDUCTOR_ADDON_SLOTS[pkg]?.includes('agent') ?? true;
947
- }
948
- /**
949
- * Source text, package and alias of each element of the array at `key`; the
950
- * alias is '' when absent and undefined when not a literal.
951
- */
952
- function arrayEntries(e, key) {
953
- const length = e.property(key)?.arrayLength ?? 0;
954
- return Array.from({ length }, (_, i) => {
955
- const item = `${key}[${i}]`;
956
- const alias = e.property(`${item}.alias`);
957
- return {
958
- text: e.expression(item) ?? '',
959
- pkg: e.property(item)?.value ??
960
- e.property(`${item}.use`)?.value ??
961
- e.property(`${item}.name`)?.value,
962
- alias: !alias ? '' : alias.staticallyDetermined ? alias.value : undefined,
963
- };
964
- });
965
- }
966
- /**
967
- * Move the retired machine keys into the top-level `addons[]`: each
968
- * `agents.addons` entry not already listed with the same text, and `ports`
969
- * as the `@bakers-build/addon-ports` entry's `with`. Only literal arrays/objects
970
- * move; an opaque value stays for `bakers config check` to report.
971
- */
972
- function migrateMachineAddons(e) {
973
- const addons = e.property('addons');
974
- if (addons && addons.nodeType !== 'ArrayExpression')
975
- return;
976
- // A spread has no element span to carry over; rebuilding would drop it.
977
- const opaque = (key) => arrayEntries(e, key).some((x) => !x.text);
978
- if (opaque('addons') || opaque('agents.addons'))
979
- return;
980
- const agentAddons = e.property('agents.addons');
981
- if (agentAddons?.nodeType === 'ArrayExpression') {
982
- const listed = arrayEntries(e, 'addons');
983
- const merged = [...listed];
984
- for (const x of arrayEntries(e, 'agents.addons')) {
985
- if (merged.some((y) => y.text === x.text))
986
- continue;
987
- // Possibly the same package as a listed entry under a possibly equal
988
- // alias but other text: moving would drop or override settings, so leave
989
- // it for `bakers config check`. A variable package may be any harness; two
990
- // variables still move, as distinct entries. Entries of agents.addons
991
- // already stood together, so they are not compared with each other.
992
- const clash = listed.some((y) => (typeof x.pkg === 'string' && typeof y.pkg === 'string'
993
- ? x.pkg === y.pkg
994
- : typeof x.pkg === 'string'
995
- ? isHarness(x.pkg)
996
- : typeof y.pkg === 'string' && isHarness(y.pkg)) &&
997
- (x.alias === undefined ||
998
- y.alias === undefined ||
999
- x.alias === y.alias));
1000
- if (clash)
1001
- return movePorts(e);
1002
- merged.push(x);
1003
- }
1004
- e.set('addons', `[${merged.map((x) => x.text).join(', ')}]`);
1005
- e.remove('agents.addons');
1006
- const agents = e.property('agents');
1007
- if (agents?.nodeType === 'ObjectExpression' &&
1008
- ![...e.source.properties.keys()].some((k) => k.startsWith('agents.')))
1009
- e.remove('agents');
1010
- }
1011
- movePorts(e);
1012
- }
1013
- function movePorts(e) {
1014
- const ports = e.property('ports');
1015
- if (ports?.nodeType !== 'ObjectExpression')
1016
- return;
1017
- const settings = e.expression('ports');
1018
- const listed = arrayEntries(e, 'addons');
1019
- const at = listed.findIndex((x) => x.pkg === PORTS_ADDON);
1020
- const entry = `{ use: '${PORTS_ADDON}', with: ${settings} }`;
1021
- if (at < 0) {
1022
- e.set('addons', `[${[...listed.map((x) => x.text), entry].join(', ')}]`);
1023
- }
1024
- else if (e.property(`addons[${at}]`)?.nodeType === 'Literal') {
1025
- e.set(`addons[${at}]`, entry);
1026
- }
1027
- else if (!e.property(`addons[${at}].with`)) {
1028
- e.set(`addons[${at}].with`, settings);
1029
- }
1030
- else
1031
- return; // both set: leave `ports` for the check to report
1032
- e.remove('ports');
1033
- }
1034
621
  function oauthPrefix(e) {
1035
622
  return [...e.source.properties]
1036
623
  .find(([key, p]) => /^plugins\[\d+\]\.plugin$/.test(key) &&
1037
624
  p.value === '@dropsh/plugin-oauth2')?.[0]
1038
625
  .replace(/\.plugin$/, '');
1039
626
  }
1040
- function replaceGeneratedMachineWiring(e, machine, file, inputs, problem) {
1041
- if (!e.text.includes('async function loadMachine()'))
1042
- return;
1043
- const mappings = {
1044
- baseUrl: 'base_url',
1045
- clientId: 'client_id',
1046
- clientSecret: 'client_secret',
1047
- workspaceId: 'workspace_id',
1048
- };
1049
- const resolved = new Map();
1050
- for (const [name, key] of Object.entries(mappings)) {
1051
- const declaration = new RegExp(`const ${name} = ([^;]+);`).exec(e.text);
1052
- if (!declaration)
1053
- continue;
1054
- const literal = new ConfigSourceEditor(`export default {value:${declaration[1]}};`).property('value');
1055
- if (literal?.staticallyDetermined && literal.value !== undefined)
1056
- resolved.set(name, JSON.stringify(literal.value));
1057
- else if (new RegExp(`^(?:local\\.[^;]+\\?\\? )?machine\\.${key}(?: \\?\\? 'bakers-agent')?$`).test(declaration[1] ?? '')) {
1058
- // The retired home-local sibling is absent (inventory refuses otherwise),
1059
- // so a generated `local.x ??` prefix evaluates to the machine value.
1060
- const p = machine.property(key);
1061
- const input = key === 'workspace_id' ? inputs?.workspaceId : undefined;
1062
- const value = p?.staticallyDetermined && p.value != null
1063
- ? p.value
1064
- : (input ?? (key === 'client_id' ? 'bakers-agent' : undefined));
1065
- if (value !== undefined)
1066
- resolved.set(name, JSON.stringify(value));
1067
- }
1068
- }
1069
- for (const key of [...e.source.properties.keys()]) {
1070
- const expr = e.expression(key);
1071
- const value = expr ? resolved.get(expr) : undefined;
1072
- if (value !== undefined)
1073
- e.set(key, value);
1074
- }
1075
- for (const [name, value] of resolved)
1076
- e.text = e.text.replace(new RegExp(`const ${name} = [^;]+;`), `const ${name} = ${value};`);
1077
- if ([...e.source.properties.keys()].some((key) => Object.hasOwn(mappings, e.expression(key) ?? ''))) {
1078
- problem(file, 'unknown_value', null, 'Generated connection values require known inputs before removing machine ownership.');
1079
- return;
1080
- }
1081
- if ([...e.source.properties.keys()].some((key) => /\bmachine\./.test(e.expression(key) ?? '')))
1082
- return;
1083
- e.text = e.text
1084
- .replace(/async function loadMachine\(\) \{[\s\S]*?\n\}\n/, '')
1085
- .replace(/const machine = await loadMachine\(\);\n?/, '');
1086
- }
1087
- function migrateGeneratedProject(e) {
1088
- if (!e.text.includes('async function loadMachine()'))
1089
- return;
1090
- if ([...e.source.properties.keys()].some((key) => /\bmachine\./.test(e.expression(key) ?? '')))
1091
- return;
1092
- if (!e.property('workspace_id'))
1093
- e.set('workspace_id', 'local.workspace_id ?? connection.workspace_id');
1094
- // Both imports land in a COMMITTED file, so neither may carry this machine's
1095
- // path — the connection import leaks ~/.bakers just as the machine one does.
1096
- e.text = e.text
1097
- .replace(/async function loadMachine\(\) \{[\s\S]*?\n\}\n/, `async function loadConnection() { return (await import(${configImportExpression('bakers.config.js')})).default; }\n`)
1098
- .replace('const machine = await loadMachine();', "const connection = await loadConnection();\nconst auth = connection.plugins.find(entry => entry.plugin === '@dropsh/plugin-oauth2')?.with;")
1099
- .replace(/machine\.base_url/g, 'connection.site.base_url')
1100
- .replace(/machine\.client_id(?: \?\? 'bakers-agent')?/g, 'auth?.client_id')
1101
- .replace(/machine\.client_secret/g, 'auth?.client_secret')
1102
- .replace(/machine\.workspace_id/g, 'connection.workspace_id');
1103
- if (/\bmachine\.(?:user_id|machine_id)/.test(e.text))
1104
- e.text =
1105
- `const machine = (await import(${configImportExpression('machine.config.js')})).default;\n` +
1106
- e.text;
1107
- }
1108
627
  /** Fingerprints are checked for the whole inventory before creating any backup. */
1109
628
  /**
1110
629
  * Best-effort pretty-print of a written `.js` config through biome. The planner