Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
presets: share the composite lookup, derive markers from the registries, one write per link (#7565)
[._.]/ Adam Eivy5c50e2bd3f96
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex cb48c4c07b..fb1d65580c 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -806,12 +806,10 @@ export function createProviderService(config = {}) {...(providerData.tuiIdleTimeoutMs != null ? { tuiIdleTimeoutMs: providerData.tuiIdleTimeoutMs } : {}),// Preset structure (#7565) — only persisted when named, so every record// created without it stays byte-identical and reads as a legacy preset.- ...(typeof providerData.harnessId === 'string' && providerData.harnessId ? { harnessId: providerData.harnessId } : {}),- ...(typeof providerData.method === 'string' && providerData.method ? { method: providerData.method } : {}),- ...(typeof providerData.serviceId === 'string' && providerData.serviceId ? { serviceId: providerData.serviceId } : {}),- ...(Array.isArray(providerData.catalogNarrowing) ? { catalogNarrowing: [...providerData.catalogNarrowing] } : {}),- ...(typeof providerData.credentialBootstrapId === 'string' && providerData.credentialBootstrapId- ? { credentialBootstrapId: providerData.credentialBootstrapId } : {})+ ...Object.fromEntries(['harnessId', 'method', 'serviceId', 'credentialBootstrapId']+ .filter((key) => typeof providerData[key] === 'string' && providerData[key])+ .map((key) => [key, providerData[key]])),+ ...(Array.isArray(providerData.catalogNarrowing) ? { catalogNarrowing: [...providerData.catalogNarrowing] } : {})};return provider;diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.jsindex 4a309df4ea..43ef82d15c 100644--- a/server/lib/aiToolkit/validation.js+++ b/server/lib/aiToolkit/validation.js@@ -78,6 +78,9 @@ export function sanitizeScreenshotRefs(screenshots) {return { safe, rejected };}+/** A service or bootstrap slug on a preset (#7565): the same alphabet as a record id, clearable with `null`. */+const presetSlugField = z.string().regex(PRESET_ID_RE, 'must be a slug (lowercase alphanumeric with hyphens)').max(64).nullable().optional();+export const providerSchema = z.object({// Sample providers post a stable id (e.g. 'codex') so the server can adopt// them verbatim rather than slugifying the display name (which would turn@@ -259,13 +262,13 @@ export const providerSchema = z.object({// slugs rather than enums because this directory stays self-contained.harnessId: z.string().regex(/^[a-z0-9-]+$/, 'harnessId must be a harness id').max(64).nullable().optional(),method: z.enum(['cli', 'tui', 'api']).nullable().optional(),- serviceId: z.string().regex(PRESET_ID_RE, 'serviceId must be a service slug').max(64).nullable().optional(),+ serviceId: presetSlugField,// The subset of the service catalog this preset offers; `null` = the whole catalog.catalogNarrowing: z.array(z.string().trim().min(1).max(512)).max(1000).nullable().optional(),// The configured credential-bootstrap app (`settings.credentialBootstraps`// slug) a derived cli/tui preset spawns through; materialization writes the// inline `credentialBootstrap` object from it.- credentialBootstrapId: z.string().regex(PRESET_ID_RE, 'credentialBootstrapId must be a bootstrap slug').max(64).nullable().optional(),+ credentialBootstrapId: presetSlugField,});/**diff --git a/server/lib/providerGraphRecords.js b/server/lib/providerGraphRecords.jsindex 408333bd95..a7296f6bb3 100644--- a/server/lib/providerGraphRecords.js+++ b/server/lib/providerGraphRecords.js@@ -16,6 +16,7 @@ import {import { routeSettingsRevision, routeSettingsSchema } from './providerRouteSettings.js';import { CREATABLE_CONNECTION_KINDS, connectionKindLabel } from './providerRouteRecipes.js';import { SERVICE_CREDENTIAL_VIAS, SERVICE_PLANS } from './serviceDefinitions.js';+import { isNonBlankStr } from './textUtils.js';// `PROVIDER_GRAPH_SCHEMA_VERSION` is deliberately NOT re-exported: it is one// wire version shared with the preview, and two flat `export *` modules in this@@ -411,11 +412,8 @@ export const importGraphFromProviders = (data, mintId = randomUUID) =>* `providerPresets.js`, which imports this module) because reconciliation is* the first reader.*/-export const isDerivedPreset = (record) => Boolean(record)- && typeof record === 'object'- && typeof record.harnessId === 'string' && record.harnessId !== ''- && typeof record.method === 'string' && record.method !== ''- && typeof record.serviceId === 'string' && record.serviceId !== '';+export const isDerivedPreset = (record) => Boolean(record) && typeof record === 'object'+ && [record.harnessId, record.method, record.serviceId].every(isNonBlankStr);/*** Whether a derived preset DECLARES it sits on this connection — its@@ -438,8 +436,7 @@ export const presetDeclaresConnection = (record, connection) =>* A declared preset whose profile the preview isolates (a reason on it) gets* no route row, exactly as any other isolated record.*/-function importDeclaredPresets(records, graph, mintId) {- const bySlug = new Map(graph.connections.filter((connection) => connection.slug).map((connection) => [connection.slug, connection]));+function importDeclaredPresets(records, graph, bySlug, mintId) {const byId = new Map(records.map((record) => [record.id, record]));const fragment = importGraphFromProviders({ providers: records }, mintId);const variantKey = (connectionId, harnessId, key) => JSON.stringify([connectionId, harnessId ?? null, key]);@@ -627,17 +624,17 @@ export function planGraphReconciliation(graph, providers, { mintId = randomUUIDconst unmapped = [...records.values()].filter((provider) => !mapped.has(provider.id));// A derived preset naming an existing instance is imported ONTO it (#7565);// everything else is its own fragment, never auto-linked.- const slugs = new Set(graph.connections.map((connection) => connection.slug).filter(Boolean));- const declared = unmapped.filter((provider) => isDerivedPreset(provider) && slugs.has(provider.serviceId));- const fragments = unmapped.filter((provider) => !declared.includes(provider));+ const bySlug = new Map(graph.connections.filter((connection) => connection.slug).map((connection) => [connection.slug, connection]));+ const declared = [];+ const fragments = [];+ for (const provider of unmapped) {+ (isDerivedPreset(provider) && bySlug.has(provider.serviceId) ? declared : fragments).push(provider);+ }if (fragments.length > 0) plan.imports = importGraphFromProviders({ providers: fragments }, mintId);if (declared.length > 0) {- const onto = importDeclaredPresets(declared, graph, mintId);- plan.imports = {- connections: plan.imports.connections,- bindings: [...plan.imports.bindings, ...onto.bindings],- routes: [...plan.imports.routes, ...onto.routes],- };+ const onto = importDeclaredPresets(declared, graph, bySlug, mintId);+ plan.imports.bindings.push(...onto.bindings);+ plan.imports.routes.push(...onto.routes);}return plan;diff --git a/server/lib/providerPresets.js b/server/lib/providerPresets.jsindex 8bd55dbf94..0d5d98d15e 100644--- a/server/lib/providerPresets.js+++ b/server/lib/providerPresets.js@@ -1,9 +1,9 @@import { isDeepStrictEqual } from 'node:util';import { isDerivedPreset } from './providerGraphRecords.js';-import { providerConnectionProfile } from './providerConnections.js';+import { providerConnectionProfile, withoutConnectionOwnedFields } from './providerConnections.js';import { harnessForProvider } from './providerHarnesses.js';import { parseOpencodeConfigContent } from './providerModels.js';-import { materializeRouteOutcome } from './providerRouteRecipes.js';+import { BACKEND_MARKER_KEYS, materializeRouteOutcome } from './providerRouteRecipes.js';import { applyServicePlanFilter, instanceForConnection } from './providerServiceInstances.js';/**@@ -33,9 +33,6 @@ import { applyServicePlanFilter, instanceForConnection } from './providerService/** The additive keys that make a record a derived preset (plus its two per-preset choices). */export const PRESET_STRUCTURAL_KEYS = Object.freeze(['harnessId', 'method', 'serviceId', 'catalogNarrowing', 'credentialBootstrapId']);-/** The backend markers a service definition writes (`serviceMarkers` in providerRouteRecipes.js). */-const BACKEND_MARKER_KEYS = Object.freeze(['ollamaBacked', 'lmstudioBacked', 'mtplxBacked', 'llamaBacked', 'vllmBacked', 'sglangBacked', 'gatewayBacked', 'orcarouterBacked']);-/*** The record keys the SERVICE owns on a derived preset — written by* materialization, refused as a direct edit (`refusedDerivedEdits`). `envVars`@@ -55,15 +52,26 @@ export const presetKind = (record) => (isDerivedPreset(record) ? 'derived' : 'le* with no isolation reason. The conversion itself still has to prove the* fixpoint against the service — this is the editor's "offer the button" test.*/+/**+ * Whether the record spawns the recipe's own binary. A path-configured+ * `command` is a deliberate choice materialization would overwrite, so it+ * keeps a record legacy; a harness with no recipe (`direct`) has nothing to check.+ */+const spawnsRecipeBinary = (record, harness) => !harness.recipe || harness.recipe.command === record.command;+export function presetDerivable(record) {if (!record || typeof record !== 'object' || isDerivedPreset(record)) return false;const harness = harnessForProvider(record);// A harness with no capability bindings (Kilo, OpenChamber) composes onto nothing.- if (!harness || harness.bindings.length === 0) return false;- if (harness.recipe && harness.recipe.command !== record.command) return false;+ if (!harness || harness.bindings.length === 0 || !spawnsRecipeBinary(record, harness)) return false;return providerConnectionProfile(record).reasons.length === 0;}+/** The instance's catalog as this plan lists it — empty until the service has been asked. */+export const listedModels = (instance, catalog) => (catalog?.state === 'known'+ ? applyServicePlanFilter(instance.definition, instance.plan, Array.isArray(catalog.models) ? catalog.models : [])+ : []);+/*** The models a derived preset offers: the instance's plan-filtered catalog,* narrowed to `catalogNarrowing` when the preset declares one (in the@@ -75,9 +83,7 @@ export function presetDerivable(record) {* must not lose the list it was running with.*/export function derivedPresetModels(record, instance, catalog) {- const listed = catalog?.state === 'known'- ? applyServicePlanFilter(instance.definition, instance.plan, Array.isArray(catalog.models) ? catalog.models : [])- : [];+ const listed = listedModels(instance, catalog);if (listed.length === 0) return Array.isArray(record.models) ? [...record.models] : [];if (!Array.isArray(record.catalogNarrowing)) return [...listed];const known = new Set(listed);@@ -110,12 +116,10 @@ function opencodeTransportShape(raw) {* base URLs the service would write: rewriting it would discard permissions* and agent settings the user typed into it.*/-function mergeDerivedEnv(record, materialized) {- const stored = record.envVars && typeof record.envVars === 'object' ? record.envVars : {};- const owned = providerConnectionProfile(record).owned.envVars;- const routeOwned = Object.fromEntries(Object.entries(stored).filter(([name]) => !Object.hasOwn(owned, name)));+function mergeDerivedEnv(record, owned, materialized) {+ const routeOwned = withoutConnectionOwnedFields(record, owned).envVars || {};const next = { ...routeOwned, ...materialized.envVars };- const keep = stored.OPENCODE_CONFIG_CONTENT;+ const keep = record.envVars?.OPENCODE_CONFIG_CONTENT;const written = materialized.envVars.OPENCODE_CONFIG_CONTENT;if (keep && written && isDeepStrictEqual(opencodeTransportShape(keep), opencodeTransportShape(written))) {next.OPENCODE_CONFIG_CONTENT = keep;@@ -164,7 +168,7 @@ const bootstrapShape = (bootstrap, harness) => (bootstrap?.command ? {export function matchBootstrapApp(inline, harness, apps = {}) {const wanted = bootstrapShape(inline, harness);if (!wanted) return null;- for (const [slug, app] of Object.entries(apps || {})) {+ for (const [slug, app] of Object.entries(apps)) {const shape = bootstrapShape({ ...app, harnessId: app.harnessNames?.[harness.id] }, harness);if (isDeepStrictEqual(shape, wanted)) return { slug, app };}@@ -207,8 +211,9 @@ export function materializeDerivedPreset({ record, harness, instance, catalog =});if (outcome.error) return { record: null, error: outcome.error, ownedEnvNames: null };const materialized = outcome.record;+ const { owned } = providerConnectionProfile(record);- const envVars = mergeDerivedEnv(record, materialized);+ const envVars = mergeDerivedEnv(record, owned, materialized);const stored = new Set(Array.isArray(record.secretEnvVars) ? record.secretEnvVars : []);const secretEnvVars = [...new Set([...materialized.secretEnvVars,@@ -217,11 +222,9 @@ export function materializeDerivedPreset({ record, harness, instance, catalog =const derived = {...record,- id: record.id,name: record.name ?? materialized.name,type: record.method,harnessId: harness.id,- method: record.method,serviceId: instance.slug,command: materialized.command ?? null,// A direct API preset spawns nothing; `args` is written only where a program reads it.@@ -233,8 +236,10 @@ export function materializeDerivedPreset({ record, harness, instance, catalog =models: derivedPresetModels(record, instance, catalog),timeout: record.timeout ?? materialized.timeout,};- for (const key of BACKEND_MARKER_KEYS) delete derived[key];- for (const key of BACKEND_MARKER_KEYS) if (Object.hasOwn(materialized, key)) derived[key] = materialized[key];+ for (const key of BACKEND_MARKER_KEYS) {+ if (Object.hasOwn(materialized, key)) derived[key] = materialized[key];+ else delete derived[key];+ }// `servicePlan` is a fact about the instance, read from it — never a stored snapshot.delete derived.servicePlan;if (record.method === 'cli' && !Array.isArray(record.headlessArgs)) derived.headlessArgs = materialized.headlessArgs ?? [];@@ -251,10 +256,7 @@ export function materializeDerivedPreset({ record, harness, instance, catalog =delete derived.credentialBootstrap;delete derived.credentialBootstrapId;}- const ownedEnvNames = new Set([- ...Object.keys(providerConnectionProfile(record).owned.envVars),- ...Object.keys(materialized.envVars),- ]);+ const ownedEnvNames = new Set([...Object.keys(owned.envVars), ...Object.keys(materialized.envVars)]);return { record: derived, error: null, ownedEnvNames };}@@ -300,13 +302,12 @@ export function refusedDerivedEdits(updates, derived, ownedEnvNames) {const refused = [];for (const key of DERIVED_PRESET_OWNED_KEYS) {if (!Object.hasOwn(updates, key)) continue;- const sent = key === 'apiKey' ? (updates[key] ?? '') : key === 'secretEnvVars' ? null : orNull(updates[key]);- const kept = key === 'apiKey' ? (derived[key] ?? '') : key === 'secretEnvVars' ? null : orNull(derived[key]);if (key === 'secretEnvVars') {if (!sameSet(Array.isArray(updates[key]) ? updates[key] : [], derived[key])) refused.push(key);continue;}- if (!isDeepStrictEqual(sent, kept)) refused.push(key);+ const normalize = key === 'apiKey' ? (value) => value ?? '' : orNull;+ if (!isDeepStrictEqual(normalize(updates[key]), normalize(derived[key]))) refused.push(key);}if (updates.envVars && typeof updates.envVars === 'object') {for (const name of ownedEnvNames) {@@ -328,11 +329,6 @@ export function derivedPresetPatch(record, derived) {return patch;}-/** The catalog listing a backfill compares a record's models against — the same rule as {@link derivedPresetModels}. */-const listedModels = (instance, catalog) => (catalog?.state === 'known'- ? applyServicePlanFilter(instance.definition, instance.plan, Array.isArray(catalog.models) ? catalog.models : [])- : []);-/*** The boot-time backfill (#7565): every LEGACY record the graph already routes* onto a named service instance, stamped with the structural keys that make it@@ -358,6 +354,12 @@ export function planPresetBackfill({ graph, providers, bootstraps = {}, env = prconst connections = new Map(graph.connections.map((connection) => [connection.id, connection]));const patches = {};const skipped = [];+ // Mode siblings share one row; resolve its instance once.+ const instances = new Map();+ const instanceFor = (connection) => {+ if (!instances.has(connection.id)) instances.set(connection.id, instanceForConnection(connection, env));+ return instances.get(connection.id);+ };for (const record of providers) {if (!record || typeof record !== 'object' || !record.id || isDerivedPreset(record)) continue;@@ -366,11 +368,11 @@ export function planPresetBackfill({ graph, providers, bootstraps = {}, env = prif (!route) { skip('unmapped'); continue; }const connection = connections.get(bindings.get(route.bindingId)?.connectionId);if (!connection?.slug) { skip('service-unnamed'); continue; }- const instance = instanceForConnection(connection, env);+ const instance = instanceFor(connection);if (!instance) { skip('service-undefined'); continue; }const harness = harnessForProvider(record);if (!harness) { skip('harness-unknown'); continue; }- if (harness.recipe && harness.recipe.command !== record.command) { skip('command-differs'); continue; }+ if (!spawnsRecipeBinary(record, harness)) { skip('command-differs'); continue; }const match = matchBootstrapApp(record.credentialBootstrap, harness, bootstraps);if (record.credentialBootstrap?.command && !match) { skip('bootstrap-unmatched'); continue; }diff --git a/server/lib/providerRouteRecipes.js b/server/lib/providerRouteRecipes.jsindex 63ee94fce6..387daedbce 100644--- a/server/lib/providerRouteRecipes.js+++ b/server/lib/providerRouteRecipes.js@@ -54,6 +54,18 @@ const LOCAL_RUNTIME_MARKERS = Object.freeze({sglang: 'sglangBacked',});+/**+ * Every record key a backend marker can sit under: the local-runtime booleans,+ * the generic gateway marker, and each gateway's legacy per-gateway boolean —+ * so a writer that has to CLEAR a stale marker (a preset re-derived from a+ * different service, #7565) names the same set this module writes.+ */+export const BACKEND_MARKER_KEYS = Object.freeze([+ ...Object.values(LOCAL_RUNTIME_MARKERS),+ 'gatewayBacked',+ ...PROVIDER_GATEWAYS.flatMap((gateway) => (gateway.legacyMarker ? [gateway.legacyMarker] : [])),+]);+/** Every `kind` `POST /api/providers/connections` accepts. */export const CREATABLE_CONNECTION_KINDS = Object.freeze([...Object.keys(LOCAL_RUNTIME_MARKERS),diff --git a/server/lib/validation.js b/server/lib/validation.jsindex cc084ab751..171bb1a45d 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -512,6 +512,9 @@ const providerHardwareRequirementsSchema = z.object({minCudaComputeCapability: z.number().positive().max(20).optional(),}).strict();+/** A service or bootstrap slug on a preset (#7565), clearable with `null`. */+const presetSlugField = z.string().trim().min(1).max(64).regex(SERVICE_SLUG_RE).nullable().optional();+export const providerSchema = z.object({name: z.string().min(1).max(100),type: z.enum(['cli', 'api', 'tui']),@@ -575,9 +578,9 @@ export const providerSchema = z.object({// optional catalog narrowing, and the bootstrap app it spawns through.harnessId: z.enum(PROVIDER_HARNESS_IDS).nullable().optional(),method: z.enum(ROUTE_MODES).nullable().optional(),- serviceId: z.string().trim().min(1).max(64).regex(SERVICE_SLUG_RE).nullable().optional(),+ serviceId: presetSlugField,catalogNarrowing: z.array(z.string().trim().min(1).max(512)).max(1000).nullable().optional(),- credentialBootstrapId: z.string().trim().min(1).max(64).regex(SERVICE_SLUG_RE).nullable().optional(),+ credentialBootstrapId: presetSlugField,});// POST /api/providers/:id/test-vision.diff --git a/server/routes/providers.composite.test.js b/server/routes/providers.composite.test.jsindex 5bb55d2fae..a77df7a3f4 100644--- a/server/routes/providers.composite.test.js+++ b/server/routes/providers.composite.test.js@@ -28,7 +28,7 @@ vi.mock('../services/credentialBootstrapApps.js', () => bootstrapService);const readinessService = vi.hoisted(() => ({ getProviderReadinessMap: vi.fn(), resetProviderReadinessCache: vi.fn() }));vi.mock('../services/providerReadiness.js', async (importOriginal) => ({ ...(await importOriginal()), ...readinessService }));const presetService = vi.hoisted(() => ({- createPresetFromComposite: vi.fn(), derivePreset: vi.fn(), materializeStoredPreset: vi.fn(), savesAsDerivedPreset: vi.fn(),+ createPresetFromComposite: vi.fn(), derivePreset: vi.fn(), materializeStoredPreset: vi.fn(), savesAsDerivedPreset: vi.fn(), storableProviderRecord: vi.fn(),}));vi.mock('../services/providerPresets.js', () => presetService);import { createPortOSProviderRoutes } from './providers.js';@@ -65,6 +65,9 @@ beforeEach(() => {providerService.createProvider.mockImplementation(async (body) => ({ ...body }));presetService.savesAsDerivedPreset.mockImplementation((candidate) => Boolean(candidate.harnessId && candidate.method && candidate.serviceId));presetService.materializeStoredPreset.mockImplementation(async (candidate) => ({ ...candidate, rederived: true }));+ // The real one-liner, over the doubles above, so the route's choice of path stays observable.+ presetService.storableProviderRecord.mockImplementation((candidate, updates) =>+ (presetService.savesAsDerivedPreset(candidate) ? presetService.materializeStoredPreset(candidate, { updates }) : Promise.resolve(updates)));});describe('PUT /api/providers/active', () => {diff --git a/server/routes/providers.js b/server/routes/providers.jsindex 7b478414b2..d688af42d3 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -1122,13 +1122,10 @@ export function createPortOSProviderRoutes(aiToolkit) {}}- // A DERIVED preset (#7565) stores what its service derives: the record is- // re-materialized from the instance it names, a connection-owned value the- // client moved is refused with a pointer at the service, and a `models`- // edit is read as a narrowing of the service catalog.- const { savesAsDerivedPreset, materializeStoredPreset } = await presetService();- const candidate = { ...existing, ...updates, id: req.params.id };- const stored = savesAsDerivedPreset(candidate) ? await materializeStoredPreset(candidate, { updates }) : updates;+ // A DERIVED preset (#7565) stores what its service derives — see+ // `storableProviderRecord` for what is refused and what is read as a narrowing.+ const { storableProviderRecord } = await presetService();+ const stored = await storableProviderRecord({ ...existing, ...updates, id: req.params.id }, updates);const provider = await providerService.updateProvider(req.params.id, stored);res.json(presentProvider(withResolvedModelAccess(provider, existing), await detectSystemCapabilities()));@@ -1216,13 +1213,9 @@ export function createPortOSProviderRoutes(aiToolkit) {res.status(201).json({ providers: created.map(provider => presentProvider(provider, capabilities)) });return;}- // A body naming a harness, method and service is a DERIVED preset (#7565)- // and is stored as the service derives it — see PUT /:id.- const { savesAsDerivedPreset, materializeStoredPreset } = await presetService();- const body = savesAsDerivedPreset(validation.data)- ? await materializeStoredPreset(validation.data, { updates: validation.data })- : validation.data;- const provider = await providerService.createProvider(body);+ // A body naming a harness, method and service is a DERIVED preset (#7565).+ const { storableProviderRecord } = await presetService();+ const provider = await providerService.createProvider(await storableProviderRecord(validation.data, validation.data));res.status(201).json(presentProvider(provider, await detectSystemCapabilities()));}));diff --git a/server/services/compositeProviders.js b/server/services/compositeProviders.jsindex 4e5aa7eb40..52d7d00ecd 100644--- a/server/services/compositeProviders.js+++ b/server/services/compositeProviders.js@@ -77,9 +77,33 @@ async function graphWithinTtl() {});}-// The instance shape behind a row lives with the other pure instance readers-// (#7565); re-exported so the composition surface keeps one import for it.-export { instanceForConnection };+/**+ * The parts a (harness, method, service, bootstrap) tuple names, or the reason+ * one of them does not resolve — shared by the composite resolver and the+ * preset save (#7565), so both refuse the same input with the same code.+ * Enablement is NOT checked here: a stored preset on a switched-off harness is+ * still editable, while a composite on one is not runnable.+ *+ * @returns {{harness: object, connection: object, instance: object, bootstrap: object|null, code: null, reason: null}+ * | {harness: null, connection: null, instance: null, bootstrap: null, code: string, reason: string}}+ */+export function resolveCompositeParts({ harnessId, method, serviceSlug, bootstrapSlug = null }, { graph, bootstraps, env = process.env }) {+ const refuse = (code, reason) => ({ harness: null, connection: null, instance: null, bootstrap: null, code, reason });+ const harness = harnessById(harnessId);+ if (!harness) return refuse('harness-unknown', `No harness "${harnessId}"`);+ if (!harness.modes.includes(method)) return refuse('method-unsupported', `${harness.label} has no ${method} mode`);+ const connection = findConnectionByRef(graph, serviceSlug);+ if (!connection || connection.slug !== serviceSlug) return refuse('service-unknown', `No service is addressed as "${serviceSlug}"`);+ const instance = instanceForConnection(connection, env);+ if (!instance) return refuse('service-undefined', `Service "${serviceSlug}" has no definition this build composes onto`);+ let bootstrap = null;+ if (bootstrapSlug) {+ const app = bootstraps?.[bootstrapSlug];+ if (!app) return refuse('bootstrap-unknown', `No credential bootstrap app is addressed as "${bootstrapSlug}"`);+ bootstrap = bootstrapInputFor(bootstrapSlug, app);+ }+ return { harness, connection, instance, bootstrap, code: null, reason: null };+}/*** Resolve, with the reason for a refusal. Pure over its inputs so the tests@@ -102,22 +126,12 @@ export function materializeComposite(id, { graph, settings, bootstraps, runtimesif (!enablement?.enabled) {return refuse('harness-disabled', `${harness.label} is ${enablement?.source === 'setting' ? 'switched off' : 'not detected on this machine'}`);}- if (!harness.modes.includes(ref.method)) return refuse('method-unsupported', `${harness.label} has no ${ref.method} mode`);-- const connection = findConnectionByRef(graph, ref.serviceSlug);- if (!connection || connection.slug !== ref.serviceSlug) return refuse('service-unknown', `No service is addressed as "${ref.serviceSlug}"`);+ const resolved = resolveCompositeParts(parts, { graph, bootstraps, env });+ if (resolved.code) return refuse(resolved.code, resolved.reason);+ const { connection, instance, bootstrap } = resolved;if (connection.enabled === false) return refuse('service-disabled', `Service "${ref.serviceSlug}" is switched off`);- const instance = instanceForConnection(connection, env);- if (!instance) return refuse('service-undefined', `Service "${ref.serviceSlug}" has no definition this build composes onto`);if (!isCompatible(harness, instance)) return refuse('incompatible', `${harness.label} cannot be pointed at ${instance.definition.label}`);- let bootstrap = null;- if (ref.bootstrapSlug) {- const app = bootstraps?.[ref.bootstrapSlug];- if (!app) return refuse('bootstrap-unknown', `No credential bootstrap app is addressed as "${ref.bootstrapSlug}"`);- bootstrap = bootstrapInputFor(ref.bootstrapSlug, app);- }-const models = applyServicePlanFilter(instance.definition, instance.plan, connection.catalog?.models || []);const { record, error } = materializeRouteOutcome({harness,diff --git a/server/services/compositeProviders.test.js b/server/services/compositeProviders.test.jsindex 464aee6656..83ea944675 100644--- a/server/services/compositeProviders.test.js+++ b/server/services/compositeProviders.test.js@@ -47,6 +47,7 @@ vi.mock('./providerRuntimeInstaller.js', async (importOriginal) => ({vi.mock('./providerServices.js', () => ({ listServices: vi.fn(async () => ({ services: [{ slug: 'nvidia-nim' }] })) }));const composite = await import('./compositeProviders.js');+const { instanceForConnection } = await import('../lib/providerServiceInstances.js');const { buildCliArgs } = await import('../lib/cliProviderArgs.js');const { buildTuiInvocation } = await import('../lib/tuiHandshake.js');const { buildTuiShellLaunch } = await import('../lib/tuiShellLaunch.js');@@ -238,7 +239,7 @@ describe('materializeComposite — refusals carry a reason and never substitute'// written with. That must drop the one service, not throw out of the whole// composition surface (the catalog resolves EVERY row in one pass).const stale = { ...GRAPH, connections: GRAPH.connections.map((row) => (row.slug === 'nvidia-nim' ? { ...row, plan: 'retired-tier' } : row)) };- expect(composite.instanceForConnection(stale.connections.find((row) => row.slug === 'nvidia-nim'))).toBeNull();+ expect(instanceForConnection(stale.connections.find((row) => row.slug === 'nvidia-nim'))).toBeNull();expect(resolve('pi.tui@nvidia-nim', { graph: stale })).toMatchObject({ record: null, code: 'service-undefined' });// A sibling row on a plan that still exists is unaffected.expect(resolve('pi.tui@openrouter', { graph: stale }).record).not.toBeNull();diff --git a/server/services/credentialBootstrapApps.js b/server/services/credentialBootstrapApps.jsindex 291187a6ce..6e6051bfc4 100644--- a/server/services/credentialBootstrapApps.js+++ b/server/services/credentialBootstrapApps.js@@ -1,4 +1,3 @@-import { bootstrapInputFor } from '../lib/providerPresets.js';import { credentialBootstrapsSettingsSchema } from '../lib/validation.js';import { isPlainObject } from '../lib/objects.js';import { getSettings, updateSettingsWith } from './settings.js';@@ -52,10 +51,6 @@ export function normalizeCredentialBootstraps(raw) {}));}-// The bootstrap input `materializeRoute` takes for an app is a pure shape the-// preset library also needs (#7565); it lives there and is re-exported here.-export { bootstrapInputFor };-/** The catalog's sanitized view of the table: never a command line, only what a picker names. */export const presentCredentialBootstraps = (apps) => Object.entries(apps).map(([slug, app]) => ({slug,diff --git a/server/services/providerGraph.js b/server/services/providerGraph.jsindex b78ada2efd..bd7f42202a 100644--- a/server/services/providerGraph.js+++ b/server/services/providerGraph.js@@ -8,6 +8,7 @@ import {} from '../lib/providerConnections.js';import {connectionOwnedSnapshot,+ isDerivedPreset,mergeConnectionCredentials,nextConnectionCatalog,planGraphReconciliation,@@ -32,7 +33,6 @@ import {materializeDerivedPreset,planPresetBackfill,} from '../lib/providerPresets.js';-import { isDerivedPreset } from '../lib/providerGraphRecords.js';import { effortLevelsForProvider } from '../lib/providerModels.js';import {bindingBlocker,@@ -209,7 +209,7 @@ async function reconcilePass(reason) {// are eligible now, a clone or split waits for the next pass.const named = new Map(backfill.map((row) => [row.id, row]));const removed = new Set(plan.removals);- const stamped = await backfillPresets({+ const presets = await backfillPresets({connections: [...graph.connections.map((connection) => ({ ...connection, ...(named.get(connection.id) || {}) })), ...plan.imports.connections],bindings: [...graph.bindings, ...plan.imports.bindings],routes: [...graph.routes.filter((route) => !removed.has(route.providerId)), ...plan.imports.routes],@@ -217,16 +217,16 @@ async function reconcilePass(reason) {const detached = plan.regroups.filter((regroup) => regroup.connectionAction === 'clone').length;const split = plan.regroups.filter((regroup) => !regroup.bindingId).length;- if (!noop || plan.conflicts.length > 0 || stamped > 0) {+ if (!noop || plan.conflicts.length > 0 || presets.stamped.length > 0) {console.log(`🔗 Provider graph reconciled (${reason}): ${plan.imports.routes.length} imported, `+ `${detached} detached, ${split} split, ${plan.removals.length} removed, `- + `${plan.acknowledgements.length} acknowledged, ${plan.conflicts.length} conflicted, ${stamped} presets derived`);+ + `${plan.acknowledgements.length} acknowledged, ${plan.conflicts.length} conflicted, ${presets.stamped.length} presets derived`);}for (const conflict of plan.conflicts) {console.error(`⚠️ Provider route ${conflict.providerId} changed outside the graph mid-projection; `+ 'leaving it untouched and blocking its binding until repaired');}- return { activeProvider, plan, noop };+ return { activeProvider, plan, noop, presets };}/**@@ -234,18 +234,19 @@ async function reconcilePass(reason) {* directly: the caller already holds the `reconciling` latch for the whole* pass, so the save hook this write fires returns immediately.*- * @returns {Promise<number>} how many records were stamped+ * @returns {Promise<{stamped: string[], skipped: {id: string, reason: string}[]}>}*/async function backfillPresets(graph, providers) {+ // The bootstrap table is read only when a legacy record is routed at all.+ const routed = new Set(graph.routes.map((route) => route.providerId));+ if (!providers.some((record) => routed.has(record?.id) && !isDerivedPreset(record))) return { stamped: [], skipped: [] };const { patches, skipped } = planPresetBackfill({ graph, providers, bootstraps: await bootstrapApps(), env: process.env });- const ids = Object.keys(patches);- if (ids.length === 0) return 0;- const written = await providerService().applyProviderPatches(patches);- if (written.length > 0) console.log(`🔗 Provider graph: derived ${written.length} preset(s) from their services (${written.join(', ')})`);+ const stamped = Object.keys(patches).length > 0 ? await providerService().applyProviderPatches(patches) : [];+ if (stamped.length > 0) console.log(`🔗 Provider graph: derived ${stamped.length} preset(s) from their services (${stamped.join(', ')})`);// Aggregate only: a reason names a record, never a value off it.const legacy = skipped.filter(({ reason }) => reason !== 'unmapped').length;if (legacy > 0) console.log(`🔗 Provider graph: ${legacy} routed record(s) stay legacy presets`);- return written.length;+ return { stamped, skipped };}/**@@ -259,15 +260,18 @@ async function backfillPresets(graph, providers) {* endpoint, its bootstrap app was deleted) is left exactly as it was.** @param {object} connection - the row as saved+ * @param {{providerIds?: string[]|null}} [options] - the derived presets to re-derive+ * ONTO this row (a binding that just moved here), instead of the ones already naming it* @returns {Promise<string[]>} the preset ids rewritten*/-export async function rematerializeDerivedPresets(connection) {+export async function rematerializeDerivedPresets(connection, { providerIds = null } = {}) {const instance = instanceForConnection(connection);if (!instance) return [];const [{ providers }, bootstraps] = await Promise.all([providerService().getAllProviders(), bootstrapApps()]);+ const onRow = (record) => (providerIds ? providerIds.includes(record.id) : record.serviceId === connection.slug);const patches = {};for (const record of providers) {- if (!isDerivedPreset(record) || record.serviceId !== connection.slug) continue;+ if (!isDerivedPreset(record) || !onRow(record)) continue;const harness = harnessById(record.harnessId);if (!harness) continue;const app = record.credentialBootstrapId ? bootstraps[record.credentialBootstrapId] : null;@@ -287,24 +291,11 @@ export async function rematerializeDerivedPresets(connection) {/*** A binding moved between instances (link, unlink): the derived presets on its- * routes now sit on `connection` and must say so. Their `serviceId` is- * re-addressed, then they are re-derived from the row they landed on.+ * routes now sit on `connection` and must say so. One re-derivation from the+ * row they landed on writes the new `serviceId` with everything else.*/-async function repointDerivedPresets(providerIds, connection) {- if (!connection?.slug) return [];- const { providers } = await providerService().getAllProviders();- const moved = providers.filter((record) => providerIds.includes(record.id) && isDerivedPreset(record) && record.serviceId !== connection.slug);- if (moved.length === 0) return [];- await writeProviderPatches(Object.fromEntries(moved.map((record) => [record.id, { serviceId: connection.slug }])));- return rematerializeDerivedPresets(connection);-}--/**- * Write provider patches from a caller that runs INSIDE a serialized pass- * (the preset service's convert-to-derived), holding the latch exactly as a- * projection does. Not for use outside the queue.- */-export const writeProviderPatchesInPass = (patches) => writeProviderPatches(patches);+const repointDerivedPresets = (providerIds, connection) =>+ (connection?.slug ? rematerializeDerivedPresets(connection, { providerIds }) : Promise.resolve([]));/*** Reconcile the graph against providers.json.diff --git a/server/services/providerGraph.test.js b/server/services/providerGraph.test.jsindex 4f9dddbe66..26a6bad665 100644--- a/server/services/providerGraph.test.js+++ b/server/services/providerGraph.test.js@@ -238,8 +238,8 @@ describe('linking', () => {ANTHROPIC_BASE_URL: 'http://127.0.0.1:12345',ANTHROPIC_AUTH_TOKEN: 'token-for-22222222-2222-4222-8222-222222222222',});- // The derived preset on the moved binding now names the instance it landed on (#7565).- expect(providers.applyProviderPatches.mock.calls[1][0]).toEqual({ 'claude-ollama': { serviceId: 'ollama-2' } });+ // The derived preset on the moved binding is re-derived from the instance it landed on (#7565).+ expect(providers.applyProviderPatches.mock.calls[1][0]['claude-ollama']).toMatchObject({ serviceId: 'ollama-2' });});it.each([@@ -290,10 +290,15 @@ describe('unlinking', () => {const [{ connection: clone }] = store.detachBindingToConnection.mock.calls[0];expect(clone.transports).toEqual({ anthropic: { baseUrl: 'http://127.0.0.1:11434' } });expect(clone.credentials).toEqual({ ANTHROPIC_AUTH_TOKEN: `token-for-${CONN_A}` });- // Nothing about execution changes: the one write re-addresses the derived- // preset to the clone's slug (#7565) and touches no executable value.+ // Nothing about execution changes: the one write re-derives the preset from+ // the clone (#7565), which re-addresses it and moves no executable value.expect(providers.applyProviderPatches).toHaveBeenCalledTimes(1);- expect(providers.applyProviderPatches).toHaveBeenCalledWith({ 'claude-ollama': { serviceId: clone.slug } });+ const [patches] = providers.applyProviderPatches.mock.calls[0];+ expect(patches['claude-ollama']).toMatchObject({ serviceId: clone.slug });+ // The env and program are the same on the clone; only empty normalizations ride along.+ for (const key of ['envVars', 'command', 'models']) expect(patches['claude-ollama']).not.toHaveProperty(key);+ expect(patches['claude-ollama'].apiKey ?? '').toBe('');+ expect(patches['claude-ollama'].endpoint ?? null).toBeNull();expect(clone.slug).toBe('ollama-3');});diff --git a/server/services/providerPresets.js b/server/services/providerPresets.jsindex bdd31aebb2..db85b8f7c0 100644--- a/server/services/providerPresets.js+++ b/server/services/providerPresets.js@@ -1,25 +1,12 @@import { ServerError } from '../lib/errorHandler.js';import { requireToolkit } from '../lib/aiToolkitState.js';import { isDerivedPreset } from '../lib/providerGraphRecords.js';-import { harnessById } from '../lib/providerHarnesses.js';import { effortLevelsForProvider } from '../lib/providerModels.js';-import {- bootstrapInputFor,- materializeDerivedPreset,- planPresetBackfill,- refusedDerivedEdits,-} from '../lib/providerPresets.js';-import { instanceForConnection } from '../lib/providerServiceInstances.js';+import { listedModels, materializeDerivedPreset, refusedDerivedEdits } from '../lib/providerPresets.js';+import { allocateServiceSlug } from '../lib/providerServiceInstances.js';import { listCredentialBootstraps } from './credentialBootstrapApps.js';-import { describeCompositeProvider } from './compositeProviders.js';-import {- findConnectionByRef,- providerGraphEnabled,- reconcileProviderGraph,- requireProviderGraph,- serializeProviderGraph,- writeProviderPatchesInPass,-} from './providerGraph.js';+import { describeCompositeProvider, resolveCompositeParts } from './compositeProviders.js';+import { providerGraphEnabled, reconcileProviderGraph, requireProviderGraph } from './providerGraph.js';import { readGraph } from './providerGraphStore.js';/**@@ -44,32 +31,20 @@ import { readGraph } from './providerGraphStore.js';const providerService = () => requireToolkit().services.providers;-/** The graph, the bootstrap apps, and the instance a derived record names — or the typed 400 for a name nothing answers to. */+/**+ * The harness, instance and bootstrap a derived record names — resolved by+ * the same lookup a composite id goes through, so a name nothing answers to+ * is the same 400 (`service-unknown`, `bootstrap-unknown`, …) either way.+ */async function presetInputs(record) {requireProviderGraph();const [graph, bootstraps] = await Promise.all([readGraph(), listCredentialBootstraps()]);- const harness = harnessById(record.harnessId);- if (!harness) throw new ServerError(`No harness "${record.harnessId}"`, { status: 400, code: 'PRESET_HARNESS_UNKNOWN' });- if (!harness.modes.includes(record.method)) {- throw new ServerError(`${harness.label} has no ${record.method} mode`, { status: 400, code: 'PRESET_METHOD_UNSUPPORTED' });- }- const connection = findConnectionByRef(graph, record.serviceId);- if (!connection || connection.slug !== record.serviceId) {- throw new ServerError(`No service is addressed as "${record.serviceId}"`, { status: 400, code: 'PRESET_SERVICE_UNKNOWN' });- }- const instance = instanceForConnection(connection);- if (!instance) {- throw new ServerError(`Service "${record.serviceId}" has no definition this build composes onto`, { status: 400, code: 'PRESET_SERVICE_UNDEFINED' });- }- let bootstrap = null;- if (record.credentialBootstrapId) {- const app = bootstraps[record.credentialBootstrapId];- if (!app) {- throw new ServerError(`No credential bootstrap app is addressed as "${record.credentialBootstrapId}"`, { status: 400, code: 'PRESET_BOOTSTRAP_UNKNOWN' });- }- bootstrap = bootstrapInputFor(record.credentialBootstrapId, app);- }- return { harness, connection, instance, bootstrap };+ const resolved = resolveCompositeParts(+ { harnessId: record.harnessId, method: record.method, serviceSlug: record.serviceId, bootstrapSlug: record.credentialBootstrapId ?? null },+ { graph, bootstraps },+ );+ if (resolved.code) throw new ServerError(resolved.reason, { status: 400, code: resolved.code });+ return resolved;}/**@@ -89,7 +64,7 @@ async function presetInputs(record) {export async function materializeStoredPreset(candidate, { updates = {} } = {}) {const record = { ...candidate, method: candidate.method ?? candidate.type };const { harness, connection, instance, bootstrap } = await presetInputs(record);- const listed = connection.catalog?.state === 'known' ? connection.catalog.models : [];+ const listed = listedModels(instance, connection.catalog);if (Array.isArray(updates.models) && listed.length > 0) {const known = new Set(listed);const narrowing = updates.models.filter((model) => known.has(model));@@ -110,14 +85,8 @@ export async function materializeStoredPreset(candidate, { updates = {} } = {})}/** A readable, free record id for a composite: `pi-tui-nvidia-nim-free`, `claude-cli-anthropic-corp-auth`, suffixed when taken. */-function mintPresetId(parts, taken) {- const stem = [parts.harnessId, parts.method, parts.serviceSlug, parts.bootstrapSlug].filter(Boolean).join('-');- for (let n = 1; n < 1000; n += 1) {- const candidate = n === 1 ? stem : `${stem}-${n}`;- if (!taken.has(candidate)) return candidate;- }- throw new ServerError(`Could not mint a free preset id for ${stem}`, { status: 409, code: 'PRESET_ID_EXHAUSTED' });-}+const mintPresetId = (parts, taken) =>+ allocateServiceSlug([parts.harnessId, parts.method, parts.serviceSlug, parts.bootstrapSlug].filter(Boolean).join('-'), taken);/*** "Save as preset": store the record a composite id resolves to.@@ -169,11 +138,12 @@ export async function createPresetFromComposite({ compositeId, id, name, model,/*** Convert ONE legacy preset into a derived one, on demand.*- * A reconcile pass runs first so a record the graph has never routed is- * imported (as its own fragment, named as a service instance) before the- * fixpoint check — the same rule the boot backfill applies, so the button and- * the boot pass cannot disagree about what is convertible. Refused with the- * reason when re-deriving the record would change how it runs.+ * The conversion IS a reconcile pass: it imports a record the graph has never+ * routed (as its own fragment, named as a service instance) and stamps every+ * routed legacy record whose re-derivation is a fixpoint — the same rule the+ * boot backfill applies, so the button and the boot pass cannot disagree about+ * what is convertible. Refused with the pass's own reason when re-deriving+ * this record would change how it runs.** @param {string} id* @returns {Promise<object>} the record as stored afterwards@@ -183,22 +153,24 @@ export async function derivePreset(id) {const before = await providerService().getProviderById(id);if (!before) throw new ServerError('Provider not found', { status: 404 });if (isDerivedPreset(before)) return before;- await reconcileProviderGraph('derive');- return serializeProviderGraph(async () => {- const [graph, { providers }, bootstraps] = await Promise.all([readGraph(), providerService().getAllProviders(), listCredentialBootstraps()]);- const record = providers.find((provider) => provider.id === id);- if (!record) throw new ServerError('Provider not found', { status: 404 });- const { patches, skipped } = planPresetBackfill({ graph, providers: [record], bootstraps, env: process.env });- if (!patches[id]) {- const reason = skipped.find((entry) => entry.id === id)?.reason ?? 'not-derivable';- throw new ServerError(`"${id}" cannot be derived from a service as it is configured (${reason})`,- { status: 409, code: 'PRESET_NOT_DERIVABLE', context: { reason } });- }- await writeProviderPatchesInPass(patches);- console.log(`🔗 Converted ${id} into a derived preset on service ${patches[id].serviceId}`);- return providerService().getProviderById(id);- });+ const pass = await reconcileProviderGraph('derive');+ const after = await providerService().getProviderById(id);+ if (after && isDerivedPreset(after)) {+ console.log(`🔗 Converted ${id} into a derived preset on service ${after.serviceId}`);+ return after;+ }+ const reason = pass?.presets?.skipped.find((entry) => entry.id === id)?.reason ?? 'not-derivable';+ throw new ServerError(`"${id}" cannot be derived from a service as it is configured (${reason})`,+ { status: 409, code: 'PRESET_NOT_DERIVABLE', context: { reason } });}/** Whether a save has to go through {@link materializeStoredPreset}: the record is derived and the graph can answer for its service. */export const savesAsDerivedPreset = (candidate) => isDerivedPreset(candidate) && providerGraphEnabled();++/**+ * What a create or update hands the toolkit: the service-derived record for a+ * derived preset, the caller's own body for a legacy one. `candidate` is the+ * record as it would be stored; `updates` the patch the client sent.+ */+export const storableProviderRecord = (candidate, updates) =>+ (savesAsDerivedPreset(candidate) ? materializeStoredPreset(candidate, { updates }) : Promise.resolve(updates));diff --git a/server/services/providerPresets.test.js b/server/services/providerPresets.test.jsindex f290a29268..350967b129 100644--- a/server/services/providerPresets.test.js+++ b/server/services/providerPresets.test.js@@ -117,7 +117,7 @@ describe('materializeStoredPreset', () => {await expect(presets.materializeStoredPreset({ ...stored, envVars: { ...stored.envVars, ANTHROPIC_BASE_URL: 'http://elsewhere.test' } }, { updates: { envVars: { ...stored.envVars, ANTHROPIC_BASE_URL: 'http://elsewhere.test' } } })).rejects.toMatchObject({ status: 400, code: 'PRESET_FIELD_DERIVED', context: { fields: ['envVars.ANTHROPIC_BASE_URL'], serviceId: 'ollama' } });- await expect(presets.materializeStoredPreset({ ...stored, serviceId: 'nowhere' })).rejects.toMatchObject({ status: 400, code: 'PRESET_SERVICE_UNKNOWN' });+ await expect(presets.materializeStoredPreset({ ...stored, serviceId: 'nowhere' })).rejects.toMatchObject({ status: 400, code: 'service-unknown' });});});@@ -126,10 +126,10 @@ describe('derivePreset', () => {const legacy = { id: 'claude-ollama', name: 'Claude on Ollama', type: 'cli', command: 'claude', args: ['--print'], ollamaBacked: true, enabled: true, models: ['example-llama'],envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:11434', ANTHROPIC_AUTH_TOKEN: 'ollama' }, secretEnvVars: ['ANTHROPIC_AUTH_TOKEN'] };await providerService().createProvider(legacy);- // The record is unmapped, so the derive pass imports it first — as its own- // fragment, a second instance of the daemon (import never auto-links), which- // is the service it is then derived from. The store double records the- // plan and the next read serves it back.+ // The record is unmapped, so the pass its save fires imports it — as its+ // own fragment, a second instance of the daemon (import never auto-links),+ // which is the service it is then derived from in that same pass. The store+ // double records the plan and the next read serves it back.store.applyReconciliation.mockImplementation(async (plan) => {const imported = plan.imports;graphState.current = {