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
feat: persist AI provider connections while providers.json stays executable (#6367)
[._.]/ Adam Eivy726739457b41
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 3f026d91d5..e9f8acef8c 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -42,6 +42,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- `games` — Game studio workspaces (#3177): one row per managed-app asset plan, with the full reusable sprite/music binding set, current compiled-manifest pointer, compile history, and user-requested AI feedback history in `data` JSONB; `app_id`/`name`/`updated_at` are mirrored for list and relationship queries. The record is **machine-local** because managed-app registration, sprite atlases, and music-library bytes are machine-local; there is no peer-sync cursor or tombstone, and deletes are hard deletes. Compiled manifests are immutable, SHA-256-addressed artifacts under `data/games/{id}/manifests/`; their pointers and hashes live in the DB record. Adapter: `server/services/games/db.js`, selected pg-vs-collectionStore by `server/services/games/store.js` (collectionStore is test/unsupported file escape hatch only).- `fableloom_stories` — FableLoom branching narratives: one row per loom (a branching-narrative story), with episodes, scene-node graphs, and intent transitions in `data` JSONB; `name`/`universe_id`/`series_id`/`updated_at` are mirrored for list and relationship queries (both refs are soft — no FK). `db-primary` because looms relate to universes and series and the index queries by recency. Federates through the opt-in per-record `fableLoom` category: whole-record LWW merges carry soft-delete tombstones, conflict-journal recovery, and hashed manifests for scene images/videos; there is no snapshot cursor or `sync_sequence`. Adapter: `server/services/fableLoom/db.js`, selected pg-vs-collectionStore by `server/services/fableLoom/store.js` (collectionStore is the test/unsupported file escape hatch only). Feature doc: [FableLoom](./features/fableloom.md).- `threejs_models` — generated procedural 3D-model workspaces: one row per model with gallery-image lineage, provider/model attribution, generation/refinement status, and the validated declarative scene spec in `data` JSONB. The referenced image bytes remain under `data/images/`; deterministic Three.js source is derived from the stored spec rather than persisted as a second mutable artifact. The table is local-only in this first slice, with soft-delete columns retained so federation can be added without a record-shape migration.+- `ai_connections` / `ai_harness_bindings` / `ai_route_bindings` — the AI provider connection graph (#6367, design record [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md)): the backend a harness talks to, each harness configuration bound to it, and the executable route each one projects. `db-primary` because it is a real graph — a connection has many bindings, a binding has one route per mode, and the uniqueness rules (`UNIQUE(binding_id, mode)`, `UNIQUE(connection_id, harness_id, variant_key)` plus a partial index for null-harness API bindings) are integrity constraints a set of JSON files cannot hold. `data/providers.json` REMAINS the execution contract and stays fully materialized: every connection-owned value is projected back into it, so a downgraded release runs unchanged with these tables simply idle. **Intentionally machine-local — never federated**: rows carry endpoints, credential material and this host's execution environment (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)). No `sync_sequence`, no tombstones, no `PORTOS_SCHEMA_VERSIONS` entry, no `dataSync` category; deletes are hard deletes and are refused while a binding still references the row. `ai_route_bindings.projected` / `.pending` are the projection snapshots that make an interrupted file write recoverable — as private as the credentials, and covered by the Postgres dump like every other db-primary table. Adapters: `server/services/providerGraphStore.js` (rows) and `server/services/providerGraph.js` (import, reconciliation, link/unlink), over the pure `server/lib/providerGraphRecords.js`.- `privacy_subjects` / `privacy_vault_records` / `privacy_consents` / `privacy_orgs` / `privacy_org_holdings` / `privacy_change_events` / `privacy_brokers` / `privacy_broker_cases` — the Privacy Center (epic #2138): the household subjects the suite works on behalf of (`self` plus consenting partners/children/parents — every other table carries a `subject_id` FK defaulted to the seeded `self` row, #3658), the encrypted PII vault, the trusted-organization registry with per-field holdings, the change-of-address inventory, and the data-broker opt-out ledger. Relational by nature (org ↔ holdings ↔ vault records ↔ change events ↔ broker cases), which is why they are `db-primary`. Vault *values* are AES-256-GCM ciphertext (`v1:<iv>:<tag>:<ct>`, key from `PRIVACY_VAULT_KEY`) — the DB holds bytes of ciphertext, never plaintext PII, and plaintext never appears in logs (`server/lib/vaultCrypto.js`). **Intentionally machine-local — never federated**, and this is a product *guarantee*, not a deferred feature (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), #2148). NO `sync_sequence`, NO peer-sync record kind, NO `dataSync` category, NO `PORTOS_SCHEMA_VERSIONS` entry, and no `deleted`/`deleted_at` tombstones — deletes are hard deletes, mirroring `tribe`. The reasoning is the same class as the Tribe graph but stronger: the peer-sync **pull** path (`GET /api/peer-sync/record`) carries no peer identity, `masked_value` is plaintext by design so even ciphertext-only sync would leak a PII fingerprint, and a shared `PRIVACY_VAULT_KEY` would widen the at-rest blast radius to every peer's `.env`. A second machine gets the vault by restoring a backup and copying the key by hand — a deliberate act, not continuous replication. Enforced by `server/services/sharing/privacyNeverFederates.test.js`. Adapters: `server/services/privacySubjects.js`, `privacyVault.js`, `privacyOrgs.js`, `privacyChanges.js`, `privacyBrokers.js`, `privacyOptOut.js`.**Postgres-First target.** Pipeline series/issues, Story Builder sessions, and searchable media metadata are still `db-primary` targets — they currently live in `data/` JSON but carry relationships and status that belong in the DB. The schema for the Create domains is designed in [`docs/plans/2026-06-07-create-relational-schema-design.md`](./plans/2026-06-07-create-relational-schema-design.md) (#999), with implementation tracked as #1014–#1018. (Creative Director project/scene/run state moved to Postgres in Phase 3 / #997; catalog user-defined types moved in Phase 4 lead-in / #1001; **universes moved in Phase 3 Create slice 1 / #1014** — see the `universes` entry above. Pipeline series/issues #1015, Story Builder #1016, Writers Room #1017, and the catalog ref resolver #1018 are the remaining slices.)diff --git a/scripts/lib/migrationOwnedPaths.js b/scripts/lib/migrationOwnedPaths.jsindex b511062ab8..57e6768917 100644--- a/scripts/lib/migrationOwnedPaths.js+++ b/scripts/lib/migrationOwnedPaths.js@@ -16,4 +16,9 @@ export const MIGRATION_OWNED_PATHS = new Set([// Migration 339 lifts the durable CoS config out of data/cos/state.json.// Absent, `loadConfig()` in server/services/cosState.js returns DEFAULT_CONFIG.'cos/config.json',+ // Migration 358 parks an untouched pre-graph copy of the install's own+ // data/providers.json before the provider connection graph (#6367) can write+ // to it. Derived from the user's records; a shipped seed would masquerade as+ // their pre-graph configuration and destroy the recovery path.+ 'private/providers.pre-graph.json',]);diff --git a/scripts/migrations/358-provider-connection-graph.js b/scripts/migrations/358-provider-connection-graph.jsnew file mode 100644index 0000000000..eeda6d9e9d--- /dev/null+++ b/scripts/migrations/358-provider-connection-graph.js@@ -0,0 +1,47 @@+import { join } from 'node:path';+import { atomicWrite, readJSONFileStrict, tryReadFile } from '../../server/lib/fileUtils.js';++/**+ * Register the provider connection graph and park a recovery copy of its INPUT+ * (issue #6367, design record+ * `docs/plans/2026-09-06-provider-connections-and-harnesses.md`).+ *+ * The import itself cannot run here. `ai_connections` / `ai_harness_bindings` /+ * `ai_route_bindings` are created by `ensureSchema()` at boot, and this file+ * runner executes BEFORE the database phase — the same ordering that makes+ * migrations 048-052 and 108 stub registrations. The import instead runs in the+ * database phase (`reconcileProviderGraph` in `bootstrapSequence.js` →+ * `initProviderGraph`), where the tables exist and the toolkit is warm.+ *+ * What this migration DOES own is the part that must happen before anything can+ * write to `data/providers.json` under a graph-aware server: a private,+ * untouched copy of the provider file as it stood before the graph existed. The+ * import is designed to be lossless and is proven so by round-trip tests, but a+ * recovery copy costs one small file and turns "the import mangled my custom+ * route" from unrecoverable into a diff.+ *+ * GATED ON THE INPUT, never on the absence of the output (root `AGENTS.md`): it+ * runs when `data/providers.json` exists, and skips when it does not. The+ * output is DERIVED, so it ships no `data.reference/` seed and its path is+ * declared in `scripts/lib/migrationOwnedPaths.js`. Re-run safety comes from+ * the applied-list plus the explicit "already parked" check below — a second+ * run must never overwrite the pre-graph copy with a post-graph file.+ */+export default {+ async up({ rootDir }) {+ const input = join(rootDir, 'data/providers.json');+ const { ok, value } = await readJSONFileStrict(input, null);+ if (!ok) throw new Error('Cannot migrate an unreadable data/providers.json');+ if (!value) return { success: true, skipped: 'no providers.json' };++ const recovery = join(rootDir, 'data/private/providers.pre-graph.json');+ if (await tryReadFile(recovery) !== null) {+ return { success: true, skipped: 'recovery copy already parked' };+ }++ await atomicWrite(recovery, value);+ const count = Object.keys(value.providers || {}).length;+ console.log(`🔗 Parked a pre-graph copy of ${count} provider records; the graph import runs at boot`);+ return { success: true };+ },+};diff --git a/scripts/migrations/358-provider-connection-graph.test.js b/scripts/migrations/358-provider-connection-graph.test.jsnew file mode 100644index 0000000000..d080f0f5f6--- /dev/null+++ b/scripts/migrations/358-provider-connection-graph.test.js@@ -0,0 +1,76 @@+/**+ * Migration 358 parks a pre-graph recovery copy of `data/providers.json`+ * (#6367).+ *+ * The gate direction is the regression worth a test: gating on the OUTPUT's+ * absence is the shape that silently left shipped defaults where a user's data+ * was (see `scripts/migrations/340-cos-config-seed-repair.js`). This one gates+ * on the INPUT, and a re-run must never overwrite the parked copy with a+ * post-graph file.+ */++import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import migration from './358-provider-connection-graph.js';+import { MIGRATION_OWNED_PATHS } from '../lib/migrationOwnedPaths.js';++let rootDir;+const recoveryPath = () => join(rootDir, 'data/private/providers.pre-graph.json');++const PROVIDERS = {+ activeProvider: 'example-cli',+ providers: {+ 'example-cli': {+ id: 'example-cli', name: 'Example', type: 'cli', command: 'claude', enabled: true,+ envVars: { ANTHROPIC_AUTH_TOKEN: 'example-token' },+ },+ 'example-disabled': { id: 'example-disabled', name: 'Off', type: 'tui', command: 'claude', enabled: false },+ },+};++beforeEach(async () => {+ rootDir = await mkdtemp(join(tmpdir(), 'portos-migration-358-'));+ await mkdir(join(rootDir, 'data'), { recursive: true });+ vi.spyOn(console, 'log').mockImplementation(() => {});+});++afterEach(async () => {+ vi.restoreAllMocks();+ if (rootDir) await rm(rootDir, { recursive: true, force: true });+});++describe('358-provider-connection-graph', () => {+ it('parks an exact copy of the provider file, disabled records included', async () => {+ await writeFile(join(rootDir, 'data/providers.json'), JSON.stringify(PROVIDERS));++ expect(await migration.up({ rootDir })).toEqual({ success: true });+ expect(JSON.parse(await readFile(recoveryPath(), 'utf-8'))).toEqual(PROVIDERS);+ });++ it('skips when the INPUT is absent rather than seeding anything', async () => {+ expect(await migration.up({ rootDir })).toEqual({ success: true, skipped: 'no providers.json' });+ await expect(readFile(recoveryPath(), 'utf-8')).rejects.toThrow();+ });++ it('never overwrites an existing recovery copy with a post-graph file', async () => {+ // A re-run after the graph has already rewritten providers.json must leave+ // the pre-graph copy alone — that copy is the whole point.+ await writeFile(join(rootDir, 'data/providers.json'), JSON.stringify(PROVIDERS));+ await migration.up({ rootDir });+ await writeFile(join(rootDir, 'data/providers.json'), JSON.stringify({ activeProvider: null, providers: {} }));++ expect(await migration.up({ rootDir })).toEqual({ success: true, skipped: 'recovery copy already parked' });+ expect(JSON.parse(await readFile(recoveryPath(), 'utf-8'))).toEqual(PROVIDERS);+ });++ it('fails loudly on an unreadable provider file rather than parking nothing', async () => {+ await writeFile(join(rootDir, 'data/providers.json'), '{ not json');+ await expect(migration.up({ rootDir })).rejects.toThrow(/unreadable/i);+ });++ it('declares its derived output so no data.reference seed can shadow it', () => {+ expect(MIGRATION_OWNED_PATHS.has('private/providers.pre-graph.json')).toBe(true);+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 17e9edd3dc..8921ff97b7 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -192,6 +192,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `providerHarnesses.js` | Provider HARNESS identity for the connection graph (#6366) — `PROVIDER_HARNESSES` (one row per agent program PortOS drives: claude/opencode/codex/antigravity/cursor/grok/kimi/pi, each with its supported `modes`, wire `protocol` and the existing `is*Provider` predicate as its matcher), `PROVIDER_HARNESS_IDS`, `harnessById`, `harnessForProvider` (null for an `api` record AND for an unknown harness — use `providerRouteMode` to tell them apart), `harnessSupportsMode`, `ROUTE_MODES`, plus the model-name adapters `toExecutableModelName` / `toCanonicalModelName` (the verified inverse of `prefixOpencodeModel`: a stored alias is canonicalized only when it maps back to the exact stored string, so import never rewrites a saved model by heuristically stripping a prefix). Distinct from `providerVendors.js` (argv-shaped), `providerFamilies.js` (subscription quota) and `providerGateways.js` (hosted backend). || `providerConnections.js` | Provider CONNECTION identity for the connection graph (#6366) — `providerConnectionProfile(provider)` reads one record as the backend it describes (`kind`, `protocol`, `transports`, RAW server-only `credentials`, the `owned` field/env split, and `reasons` from `CONNECTION_ISOLATION_REASONS` when the config is dynamic, external, unparsable or endpoint-less). `sameConnectionIdentity` compares real credential values and refuses once any is the `REDACTED_CREDENTIAL` sentinel, so a sanitized record can never merge two connections; `compareBackendEndpoints` is the looser same-daemon test that only ever produces a link SUGGESTION, applying the recognized OpenAI-compatible `/v1` conversion (never DNS resolution, loopback/remote equivalence or arbitrary path trimming). `withoutConnectionOwnedFields` / `withConnectionOwnedFields` are the lossless split/materialize pair that keeps a downgraded install runnable from `data/providers.json` alone. Pure: no I/O. || `providerGraphPreview.js` | READ-ONLY import preview for the provider connection graph (#6366) — `buildProviderGraphPreview({providers, activeProvider})` projects the records an install already runs into proposed connections, harness bindings and executable routes, grouping ONLY the proven same-harness CLI/TUI siblings from `providerModeGroups` and surfacing a cross-harness daemon match as a `suggestedLinks` entry requiring an explicit link. `toManagementPreviewDto` sanitizes and validates the version-1 DTOs (`managementPreviewSchema`, `PROVIDER_GRAPH_SCHEMA_VERSION`) that `GET /api/providers/management/preview` returns; `projectPreviewToProviders` re-materializes every original record (pins, secrets, consent flags and unknown custom fields included) as the import-fidelity and downgrade proof; `providerGraphUniquenessViolations` checks the UNIQUE constraints #6367 will enforce; `routeModeEligibility` is the pure declarative half of mode eligibility (harness support + enabled + caller-allowed mode + text-transport consent), with the prerequisite/fallback policy left to #6368. Persists nothing and makes no generation call or runtime launch. |+| `providerGraphRecords.js` | The DURABLE half of the provider connection graph (#6367) — the pure record layer over `ai_connections` / `ai_harness_bindings` / `ai_route_bindings`. `graphFromPreview` / `importGraphFromProviders` mint UUID-keyed rows from a #6366 preview while every executable `providerId` stays untouched; `toManagementGraphDto` (`managementGraphSchema`) sanitizes them for `GET /api/providers/management` (credential PRESENCE only, no projection snapshots); `connectionOwnedSnapshot` / `applyProjections` materialize connection-owned values back into providers.json so a downgraded install still runs; and `planGraphReconciliation` / `reconciliationIsNoop` are the reconciliation contract shared by boot, legacy provider writes and downgrade-edit-reupgrade — acknowledging a landed projection, retrying an interrupted one, REFUSING a third externally changed value, dropping deleted records without resurrecting them, and detaching or splitting a binding whose backend moved. Pure: no DB handle, no file I/O, no provider call. || `providerTranscriptUsage.js` | Parsers for the session files the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `parseGrokTurns`/`parseGrokChatHistory`/`decodeGrokSessionDir` (`~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/`), `parseAgyTranscript`/`parseAgyHistory` (`~/.gemini/antigravity-cli/`), `claudeProjectSlug`, `totalTranscriptTokens`. Each de-duplicates a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, Codex's `total_token_usage` is cumulative and repeated, grok's `turn_completed.usage` has shipped in both per-prompt and cumulative shapes (detected and delta'd, never summed raw) while its `_meta.totalTokens` is context occupancy and never billed. Antigravity writes no token fields at all, so its parser returns chars for the caller to estimate from. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. || `opencodeCatalogCache.js` | Primes the on-disk catalog `opencode models` prints from — `primeOpencodeCatalogCache()` fetches OpenCode's `api.json` with Node's fetch and atomically writes `$XDG_CACHE_HOME/opencode/models.json` (`~/.cache` when unset). OpenCode refreshes that file from a forked task whose failures it swallows (`opencode models --refresh` still prints `Models cache refreshed`) and its HTTP client has no Happy Eyeballs, so a host advertising an unreachable IPv6 default route freezes the catalog indefinitely while other machines on the same account list newer models. Refuses to fetch or write when `OPENCODE_MODELS_PATH` / a custom `OPENCODE_MODELS_URL` / `OPENCODE_DISABLE_MODELS_FETCH` means PortOS cannot be sure which file OpenCode reads, when the file is under five minutes old, or when the body did not parse as a catalog — a stale list beats an empty picker. Never throws; the caller probes either way. || `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring model ids under the namespace the provider's marker selects: a local runtime (`ollama` / `mtplx` / `llama` / `vllm` / `sglang`, bare ids) or a hosted gateway from `providerGateways.js` (`vendor/model` ids kept whole). Fixes --model rejection. Also attaches the key for a key-bearing namespace, and pins `small_model` to the run model for a gateway so OpenCode's own side calls (titles, summarization) can't land on its built-in default — a billed model the operator never chose. Under a `no-tool` public-review profile it also applies `hardenOpencodeConfigForNoTool` — root `permission: deny`, an emptied tool map on every agent, `tool_call: false` on every declared model, and no MCP/plugins/share/autoupdate — which IS OpenCode's enforced tool-free recipe, since it ships no read-only argv flag (`providerVendors.js` pairs it with `run --agent` + `OPENCODE_PUBLIC_REVIEW_AGENT`). The harden step also copies `agent.build`'s generation settings onto that agent, so the stage's configured thinking effort reaches the model that actually runs. |diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.mdindex d733b32a92..32b3521b6d 100644--- a/server/lib/aiToolkit/AGENTS.md+++ b/server/lib/aiToolkit/AGENTS.md@@ -11,6 +11,8 @@ The AI provider/runner/prompt toolkit is vendored in-tree here. (It was previous- `updateProvider()` uses spread so existing providers preserve custom fields, but `createProvider()` has an explicit field list- **Refreshing more than one provider goes through `refreshProviderModelsBatch(ids)`, never a loop over `refreshProviderModels(id)`.** Every single-provider refresh ends in `saveProviders`, which invalidates the read cache and rewrites all of `providers.json`; an N-provider fan-out that way is N full-file writes, each superseded by the next. The batch form groups by `ollamaRefreshGroupKey` (one probe per daemon + probe shape), probes each group's lead without persisting, then applies every result and saves **exactly once**. It never throws for a per-provider failure — each group carries its own `status` (`updated` / `failed` / `missing`) so the host logs one line per group rather than one per member. PortOS's post-install fan-out (`refreshOllamaBackedProviders` in `server/services/localLlm.js`) is the worked example.+**Provider-service extension point.** `createProviderService` / `createAIToolkit` accept `onProvidersSaved(data)`, invoked after every SUCCESSFUL `providers.json` write with the data that landed. PortOS injects it in `server/services/bootstrap.js` to keep its machine-local provider connection graph (`server/services/providerGraph.js`, #6367) reconciled with a file that a legacy `PATCH /api/providers/:id`, a model refresh, a migration or a downgraded release may also write. The hook is deliberately non-fatal: the write already landed and the cache already reflects it, and callers include boot warmups and schedulers with no `next(err)` to bubble to, so a throwing hook is logged and swallowed. Pair it with `applyProviderPatches(patches)`, which applies partial updates to SEVERAL named records in ONE write and — unlike `updateProvider` — performs no sibling fan-out, because a projection must touch exactly the routes it named and no conventional neighbour.+**Runner extension points.** The runner exposes a small declared override surface (in `runner.js`) so the host (PortOS) supplies its own runners without reaching into private internals:- `setCliRunner(fn)` / `setTuiRunner(fn)` — register host CLI/TUI runners (pass `null` to revert). PortOS calls both in `server/index.js`: its CLI variant is stdin-based and knows the per-CLI argv conventions (Codex `exec -`, Antigravity `agy --print`, Claude Code `-p -`); the TUI runner has no toolkit built-in, and `setTuiRunner` attaches/detaches `executeTuiRun` so the runs router's `typeof runnerService.executeTuiRun === 'function'` gate stays honest.diff --git a/server/lib/aiToolkit/index.js b/server/lib/aiToolkit/index.jsindex 071eb6a16e..29332d62f1 100644--- a/server/lib/aiToolkit/index.js+++ b/server/lib/aiToolkit/index.js@@ -59,13 +59,18 @@ export function createAIToolkit(config = {}) {defaultFallbackPriority = ['claude-code', 'codex', 'nvidia-kimi', 'lmstudio', 'ollama', 'antigravity-cli', 'gemini-cli'],// Host gate for "can this provider run at all?" — see providerStatus.js.// Unset standalone, so the toolkit routes on enabled + availability alone.- prerequisitesMet = null+ prerequisitesMet = null,+ // Host persistence hook fired after every providers.json write — see+ // createProviderService(). PortOS keeps its provider connection graph+ // reconciled through it; unset standalone.+ onProvidersSaved = null} = config;const providerService = createProviderService({dataDir,providersFile,- sampleFile: sampleProvidersFile+ sampleFile: sampleProvidersFile,+ onProvidersSaved});let providerStatusService = null;diff --git a/server/lib/aiToolkit/providers.hostPersistence.test.js b/server/lib/aiToolkit/providers.hostPersistence.test.jsnew file mode 100644index 0000000000..79b7615521--- /dev/null+++ b/server/lib/aiToolkit/providers.hostPersistence.test.js@@ -0,0 +1,115 @@+/**+ * The host-persistence extension point on the provider service (#6367).+ *+ * PortOS keeps a machine-local connection graph beside `providers.json` and has+ * to know when that file changes — including when an OLD client, a migration or+ * a model refresh is what changed it. The toolkit stays self-contained+ * (`AGENTS.md` in this directory), so the host injects a callback rather than+ * the toolkit importing anything.+ *+ * Two properties matter enough to pin: the hook fires after EVERY successful+ * write (not just the one path someone remembered), and a failing hook cannot+ * turn a write that already landed into a failed call.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createProviderService } from './providers.js';++let dataDir;+let saved;+let service;++const seed = () => writeFile(join(dataDir, 'providers.json'), JSON.stringify({+ activeProvider: 'example-cli',+ providers: {+ 'example-cli': { id: 'example-cli', name: 'Example', type: 'cli', command: 'claude', enabled: true, models: ['m'] },+ 'example-api': { id: 'example-api', name: 'Example API', type: 'api', endpoint: 'https://api.example.com', enabled: false, models: [] },+ },+}));++const readFileJson = async () => JSON.parse(await readFile(join(dataDir, 'providers.json'), 'utf-8'));++beforeEach(async () => {+ dataDir = await mkdtemp(join(tmpdir(), 'portos-provider-graph-'));+ await seed();+ saved = vi.fn();+ service = createProviderService({ dataDir, providersFile: 'providers.json', onProvidersSaved: saved });+});++afterEach(async () => {+ vi.restoreAllMocks();+ if (dataDir) await rm(dataDir, { recursive: true, force: true });+});++describe('onProvidersSaved', () => {+ it.each([+ ['updateProvider', () => service.updateProvider('example-cli', { timeout: 1000 })],+ ['createProvider', () => service.createProvider({ id: 'new-cli', name: 'New', type: 'cli', command: 'claude' })],+ ['deleteProvider', () => service.deleteProvider('example-api')],+ ['setActiveProvider', () => service.setActiveProvider('example-api')],+ ['applyProviderPatches', () => service.applyProviderPatches({ 'example-cli': { timeout: 2000 } })],+ ])('fires after %s', async (_label, mutate) => {+ await mutate();+ expect(saved).toHaveBeenCalledTimes(1);+ // The hook sees what landed, not a pre-write draft.+ expect(saved.mock.calls[0][0].providers).toEqual((await readFileJson()).providers);+ });++ it('does not fire when the read path finds nothing to change', async () => {+ await service.getAllProviders();+ expect(saved).not.toHaveBeenCalled();+ });++ it('cannot fail a write that already landed', async () => {+ // The hook runs for boot warmups and schedulers too, where there is no+ // request lifecycle to bubble a rejection into.+ vi.spyOn(console, 'error').mockImplementation(() => {});+ saved.mockRejectedValue(new Error('graph unavailable'));++ await expect(service.updateProvider('example-cli', { timeout: 3000 })).resolves.toMatchObject({ timeout: 3000 });+ expect((await readFileJson()).providers['example-cli'].timeout).toBe(3000);+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('providers save hook failed'));+ });+});++describe('applyProviderPatches', () => {+ it('applies several records in ONE write and names exactly the ids it changed', async () => {+ const applied = await service.applyProviderPatches({+ 'example-cli': { endpoint: 'http://127.0.0.1:11434' },+ 'example-api': { endpoint: 'http://127.0.0.1:11434' },+ 'not-a-provider': { endpoint: 'http://127.0.0.1:11434' },+ });++ expect(applied.sort()).toEqual(['example-api', 'example-cli']);+ expect(saved).toHaveBeenCalledTimes(1);+ const { providers } = await readFileJson();+ expect(providers['example-cli'].endpoint).toBe('http://127.0.0.1:11434');+ expect(providers['example-api'].endpoint).toBe('http://127.0.0.1:11434');+ expect(providers['not-a-provider']).toBeUndefined();+ });++ it('does NOT fan out to a conventional sibling the way updateProvider does', async () => {+ // A projection materializes a shared connection into exactly the routes+ // bound to it. Sibling fan-out would rewrite a route the graph never named.+ await writeFile(join(dataDir, 'providers.json'), JSON.stringify({+ activeProvider: null,+ providers: {+ example: { id: 'example', name: 'Example', type: 'cli', command: 'claude', enabled: true, models: ['m'] },+ 'example-tui': { id: 'example-tui', name: 'Example TUI', type: 'tui', command: 'claude', enabled: true, models: ['m'] },+ },+ }));++ await service.applyProviderPatches({ example: { endpoint: 'http://127.0.0.1:11434' } });+ const { providers } = await readFileJson();+ expect(providers.example.endpoint).toBe('http://127.0.0.1:11434');+ expect(providers['example-tui'].endpoint).toBeUndefined();+ });++ it('writes nothing when no named id exists', async () => {+ expect(await service.applyProviderPatches({ ghost: { timeout: 1 } })).toEqual([]);+ expect(saved).not.toHaveBeenCalled();+ });+});diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex 7a7d795254..9720ec26d2 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -459,7 +459,14 @@ export function createProviderService(config = {}) {// that storm to a single read without making config edits feel stale// (provider config changes are human-paced; saveProviders refreshes// the cache inline so a write is reflected immediately).- providersCacheTtlMs = 1000+ providersCacheTtlMs = 1000,+ // Host persistence hook, called after every SUCCESSFUL providers.json write+ // with the data that landed. Injected rather than imported because this+ // directory stays self-contained (see AGENTS.md): PortOS uses it to keep+ // its machine-local provider connection graph (#6367) reconciled with a+ // file any old client, migration or downgraded release may also write.+ // Unset standalone, so the toolkit behaves exactly as before.+ onProvidersSaved = null} = config;const PROVIDERS_PATH = join(dataDir, providersFile);@@ -582,6 +589,19 @@ export function createProviderService(config = {}) {return providersLoadInFlight;}+ // The write already landed and the cache already reflects it, so a host+ // hook must never be able to turn a successful save into a failed one — and+ // callers include schedulers and boot warmups with no Express `next(err)` to+ // bubble to. Log and continue (AGENTS.md's stated try/catch exception).+ async function notifyProvidersSaved(data) {+ if (typeof onProvidersSaved !== 'function') return;+ try {+ await onProvidersSaved(data);+ } catch (err) {+ console.error(`❌ providers save hook failed: ${err.message}`);+ }+ }+async function saveProviders(data) {// Drop the cache BEFORE the write: mutators read → mutate the cached// object in place → save, so the warm cache already holds the unsaved@@ -592,6 +612,7 @@ export function createProviderService(config = {}) {invalidateProvidersCache();await atomicWrite(PROVIDERS_PATH, data);refreshProvidersCache(data);+ await notifyProvidersSaved(data);}return {@@ -747,6 +768,29 @@ export function createProviderService(config = {}) {return provider;},+ /**+ * Apply partial updates to SEVERAL providers in ONE providers.json write.+ *+ * Unlike {@link updateProvider} this performs no sibling fan-out: the+ * caller names every route it means to change, which is the contract a+ * projection needs — materializing a shared connection's values must touch+ * exactly the routes bound to it and no conventional neighbour.+ *+ * @param {Record<string, object>} patches - provider id → partial update+ * @returns {Promise<string[]>} the ids that existed and were updated+ */+ async applyProviderPatches(patches) {+ const data = await loadProviders();+ const applied = [];+ for (const [id, updates] of Object.entries(patches || {})) {+ if (!data.providers[id]) continue;+ data.providers[id] = { ...data.providers[id], ...updates, id };+ applied.push(id);+ }+ if (applied.length > 0) await saveProviders(data);+ return applied;+ },+async deleteProvider(id) {const data = await loadProviders();diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 004585c24d..da38f1157a 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -13880,6 +13880,30 @@"server/routes/providers.js"]},+ {+ "method": "POST",+ "path": "/api/providers/bindings/:id/link",+ "mountPath": "/api/providers",+ "sources": [+ "server/routes/providers.js"+ ]+ },+ {+ "method": "POST",+ "path": "/api/providers/bindings/:id/link/preview",+ "mountPath": "/api/providers",+ "sources": [+ "server/routes/providers.js"+ ]+ },+ {+ "method": "POST",+ "path": "/api/providers/bindings/:id/unlink",+ "mountPath": "/api/providers",+ "sources": [+ "server/routes/providers.js"+ ]+ },{"method": "GET","path": "/api/providers/codex/account",@@ -13952,6 +13976,14 @@"server/routes/modelComparison.js"]},+ {+ "method": "DELETE",+ "path": "/api/providers/connections/:id",+ "mountPath": "/api/providers",+ "sources": [+ "server/routes/providers.js"+ ]+ },{"method": "GET","path": "/api/providers/fleet-host",@@ -13992,6 +14024,14 @@"server/routes/providers.js"]},+ {+ "method": "GET",+ "path": "/api/providers/management",+ "mountPath": "/api/providers",+ "sources": [+ "server/routes/providers.js"+ ]+ },{"method": "GET","path": "/api/providers/management/preview",@@ -17828,8 +17868,8 @@],"stats": {"mounts": 150,- "operations": 2208,- "declarations": 2216,+ "operations": 2213,+ "declarations": 2221,"sourceFiles": 233}}diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.mdindex 2fd277ca2c..883b9b3e19 100644--- a/server/lib/db/schema/README.md+++ b/server/lib/db/schema/README.md@@ -24,6 +24,7 @@ Parity with `server/scripts/init-db.sql` (the fresh-install path) is locked by| `post.js` | `postDdl` | MeatSpace POST normalized runs and attempts (machine-local) || `commissions.js` | `commissionsDdl` | Creative Commissions + feedback (machine-local) || `userActions.js` | `userActionsDdl` | Operator-action ledger — what the human did in the UI (machine-local) |+| `aiGraph.js` | `aiGraphDdl` | AI provider connection graph — connections, harness bindings, executable route bindings (machine-local) || `catalog.js` | `catalogDdl`, `catalogUserTypesDdl` | Catalog scraps/ingredients/tags/media + user-defined types || `media.js` | `mediaDdl` | Creative-director / music-video projects, mood boards, media assets || `universes.js` | `universesDdl` | Universes, machine-local character voice profiles/renders, + universe run history |@@ -38,7 +39,7 @@ Parity with `server/scripts/init-db.sql` (the fresh-install path) is locked by### Composer (`index.js`)-- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `post` → `commissions` → `userActions`).+- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `post` → `commissions` → `userActions` → `aiGraph`).- `buildCatalogDdl()` → phase-2 list (`catalog` → `media` → `catalogUserTypes` →`universes` → `library` → `pipeline` → `writersRoom` → `lora` → `privacy` → `stackerNews` → `x` →`audit` DDL → audit triggers).diff --git a/server/lib/db/schema/aiGraph.js b/server/lib/db/schema/aiGraph.jsnew file mode 100644index 0000000000..c22b7351c3--- /dev/null+++ b/server/lib/db/schema/aiGraph.js@@ -0,0 +1,89 @@+// AI provider connection graph DDL — `ai_connections`, `ai_harness_bindings`+// and `ai_route_bindings` (#6367, design record+// docs/plans/2026-09-06-provider-connections-and-harnesses.md).+//+// The MANAGEMENT half of provider configuration: which backend a harness talks+// to, which harness configurations exist on it, and which executable route each+// one projects into `data/providers.json`. The provider file stays the+// EXECUTION contract — every connection-owned value is materialized back into+// it — so a downgraded install runs unchanged with these tables simply idle.+//+// Machine-local by construction and never federated: rows carry endpoints,+// credential material and this host's execution environment, which the privacy+// ADR (docs/decisions/2026-08-08-privacy-records-machine-local.md) keeps off the+// federation layer entirely. No `sync_sequence`, no tombstones, no+// PORTOS_SCHEMA_VERSIONS entry. Hard deletes, refused by the service while a+// row is still referenced.+//+// Ordering inside this array is load-bearing: `ai_harness_bindings` references+// `ai_connections`, and `ai_route_bindings` references `ai_harness_bindings`.++export const aiGraphDdl = [+ // The backend a harness talks to. `credentials` is raw server-side secret+ // material under the same private boundary as provider secrets — it is never+ // published, logged, or federated; DTOs carry a `hasCredentials` boolean.+ `CREATE TABLE IF NOT EXISTS ai_connections (+ id UUID PRIMARY KEY,+ revision INTEGER NOT NULL DEFAULT 1,+ kind TEXT NOT NULL,+ label TEXT NOT NULL DEFAULT '',+ transports JSONB NOT NULL DEFAULT '{}'::jsonb,+ credentials JSONB NOT NULL DEFAULT '{}'::jsonb,+ catalog JSONB NOT NULL DEFAULT '{"state":"unknown","models":[]}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+ )`,++ // One harness configuration on one connection. `harness_id` is NULL only for+ // a direct API binding, which is why the uniqueness below needs two partial+ // indexes rather than one constraint: in Postgres a NULL never equals another+ // NULL, so a plain UNIQUE(connection_id, harness_id, variant_key) would let+ // unlimited duplicate `default` API bindings onto one connection.+ `CREATE TABLE IF NOT EXISTS ai_harness_bindings (+ id UUID PRIMARY KEY,+ revision INTEGER NOT NULL DEFAULT 1,+ connection_id UUID NOT NULL REFERENCES ai_connections (id),+ harness_id TEXT,+ variant_key TEXT NOT NULL DEFAULT 'default',+ label TEXT NOT NULL DEFAULT '',+ enabled BOOLEAN NOT NULL DEFAULT false,+ selected_models JSONB NOT NULL DEFAULT '[]'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+ )`,+ `CREATE UNIQUE INDEX IF NOT EXISTS uq_ai_harness_bindings_variant+ ON ai_harness_bindings (connection_id, harness_id, variant_key)+ WHERE harness_id IS NOT NULL`,+ `CREATE UNIQUE INDEX IF NOT EXISTS uq_ai_harness_bindings_api_variant+ ON ai_harness_bindings (connection_id, variant_key)+ WHERE harness_id IS NULL`,+ `CREATE INDEX IF NOT EXISTS idx_ai_harness_bindings_connection+ ON ai_harness_bindings (connection_id)`,++ // The executable route. `provider_id` is the PRIMARY KEY because it IS the+ // saved-selection contract every scheduled task, CoS pin, orchestration role+ // and fallback reference already stores — route ids are never reused.+ //+ // `projected` is the connection-owned snapshot last acknowledged as present+ // in providers.json; `pending` is one committed to the DB but not yet+ // acknowledged. A crash between the two is recoverable precisely because both+ // are kept: reconciliation compares the file's ACTUAL values against both+ // before deciding to retry, acknowledge, or refuse to overwrite a third,+ // externally changed value. Both snapshots can carry secrets, so they are as+ // private as `ai_connections.credentials`.+ `CREATE TABLE IF NOT EXISTS ai_route_bindings (+ provider_id TEXT PRIMARY KEY,+ binding_id UUID NOT NULL REFERENCES ai_harness_bindings (id),+ mode TEXT NOT NULL CHECK (mode IN ('cli', 'tui', 'api')),+ model_map JSONB NOT NULL DEFAULT '{}'::jsonb,+ projected JSONB NOT NULL DEFAULT '{}'::jsonb,+ pending JSONB,+ pending_revision INTEGER,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+ )`,+ `CREATE UNIQUE INDEX IF NOT EXISTS uq_ai_route_bindings_binding_mode+ ON ai_route_bindings (binding_id, mode)`,+ `CREATE INDEX IF NOT EXISTS idx_ai_route_bindings_binding+ ON ai_route_bindings (binding_id)`,+];diff --git a/server/lib/db/schema/index.js b/server/lib/db/schema/index.jsindex 04419ead62..ef0cfb4980 100644--- a/server/lib/db/schema/index.js+++ b/server/lib/db/schema/index.js@@ -19,6 +19,7 @@ import { humanActivityDdl } from './humanActivity.js';import { postDdl } from './post.js';import { commissionsDdl } from './commissions.js';import { userActionsDdl } from './userActions.js';+import { aiGraphDdl } from './aiGraph.js';import { catalogDdl, catalogUserTypesDdl } from './catalog.js';import { mediaDdl } from './media.js';import { universesDdl } from './universes.js';@@ -38,6 +39,7 @@ export {postDdl,commissionsDdl,userActionsDdl,+ aiGraphDdl,catalogDdl,catalogUserTypesDdl,mediaDdl,@@ -55,8 +57,8 @@ export {};// Phase 1 — the `upgrades` list: memory-sync columns + migration tracker, then-// the machine-local Tribe / human-activity / POST / commission / user-action-// tables. Run first, before the catalog block.+// the machine-local Tribe / human-activity / POST / commission / user-action /+// AI-connection-graph tables. Run first, before the catalog block.export function buildUpgradeDdl() {return [...coreDdl,@@ -65,6 +67,7 @@ export function buildUpgradeDdl() {...postDdl,...commissionsDdl,...userActionsDdl,+ ...aiGraphDdl,];}diff --git a/server/lib/db/schema/schema.test.js b/server/lib/db/schema/schema.test.jsindex 3cd0f72984..6c353ffc81 100644--- a/server/lib/db/schema/schema.test.js+++ b/server/lib/db/schema/schema.test.js@@ -25,7 +25,7 @@ import {} from './index.js';const DOMAIN_ARRAYS = [- 'coreDdl', 'tribeDdl', 'humanActivityDdl', 'postDdl', 'commissionsDdl', 'userActionsDdl',+ 'coreDdl', 'tribeDdl', 'humanActivityDdl', 'postDdl', 'commissionsDdl', 'userActionsDdl', 'aiGraphDdl','catalogDdl', 'catalogUserTypesDdl', 'mediaDdl', 'universesDdl','libraryDdl', 'pipelineDdl', 'writersRoomDdl', 'loraDdl', 'privacyDdl', 'stackerNewsDdl', 'xDdl','auditDdl',@@ -47,6 +47,7 @@ describe('db/schema barrel + composer (#2832)', () => {...schema.postDdl,...schema.commissionsDdl,...schema.userActionsDdl,+ ...schema.aiGraphDdl,];expect(buildUpgradeDdl()).toEqual(expected);});diff --git a/server/lib/index.js b/server/lib/index.jsindex 825ec83cb9..a40d295d22 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -412,6 +412,7 @@ export * from './providerGateways.js';export * from './providerHarnesses.js';export * from './providerConnections.js';export * from './providerGraphPreview.js';+export * from './providerGraphRecords.js';export * from './personaTraitBlend.js';export * from './pipelineIssueOrder.js';export * from './postAdaptive.js';diff --git a/server/lib/providerGraphRecords.js b/server/lib/providerGraphRecords.jsnew file mode 100644index 0000000000..0744ee913e--- /dev/null+++ b/server/lib/providerGraphRecords.js@@ -0,0 +1,369 @@+import { randomUUID } from 'node:crypto';+import { isDeepStrictEqual } from 'node:util';+import { z } from 'zod';+import { providerConnectionProfile } from './providerConnections.js';+import {+ PROVIDER_GRAPH_SCHEMA_VERSION,+ buildProviderGraphPreview,+} from './providerGraphPreview.js';+import { PROVIDER_HARNESS_IDS, ROUTE_MODES, providerRouteMode } from './providerHarnesses.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+// directory publishing one identifier is exactly what the barrel's collision+// detector refuses. Import it from `providerGraphPreview.js`.++/**+ * The DURABLE half of the provider connection graph (#6367, design record+ * `docs/plans/2026-09-06-provider-connections-and-harnesses.md`).+ *+ * `providerGraphPreview.js` (#6366) answers "what WOULD an import create?" from+ * provider records alone. This module owns the records that survive a restart:+ * how a preview becomes durable rows, how those rows are sanitized for a+ * client, how they are materialized back into `data/providers.json`, and — the+ * load-bearing part — how a persisted graph is RECONCILED against a provider+ * file that may have moved underneath it.+ *+ * Everything here is pure. No database handle, no file I/O, no clock beyond the+ * injected id minter, so the reconciliation contract (which is where the data+ * loss lives) is testable without a Postgres or a temp directory.+ *+ * The three states a route's connection-owned values can be in:+ *+ * - `projected` — last snapshot ACKNOWLEDGED as present in providers.json.+ * - `pending` — committed to the DB, not yet acknowledged as written.+ * - the file's ACTUAL values, read fresh at reconcile time.+ *+ * Keeping both snapshots is what makes a crash between the DB commit and the+ * file write recoverable, and what stops a retry from clobbering a third value+ * some other writer put there — see {@link planGraphReconciliation}.+ */++// --- durable row DTOs --------------------------------------------------------+// `.strict()` for the same reason the preview DTOs are strict: a field added to+// a row must never ride out to a client because a mapper forgot to drop it.++const catalogSchema = z.object({+ state: z.enum(['unknown', 'known', 'failed']),+ models: z.array(z.string()),+}).strict();++const connectionDtoSchema = z.object({+ id: z.string().min(1),+ revision: z.number().int().positive(),+ kind: z.string().min(1),+ label: z.string(),+ transports: z.record(z.string(), z.object({ baseUrl: z.string().min(1) }).strict()),+ hasCredentials: z.boolean(),+ catalog: catalogSchema,+}).strict();++const bindingDtoSchema = z.object({+ id: z.string().min(1),+ revision: z.number().int().positive(),+ connectionId: z.string().min(1),+ harnessId: z.enum(PROVIDER_HARNESS_IDS).nullable(),+ variantKey: z.string().min(1),+ label: z.string(),+ enabled: z.boolean(),+ selectedModels: z.array(z.string()),+ // Derived, never stored: a binding whose route projection is unresolved+ // refuses further graph mutations until reconciliation repairs it.+ blocked: z.boolean(),+}).strict();++const routeDtoSchema = z.object({+ providerId: z.string().min(1),+ bindingId: z.string().min(1),+ mode: z.enum(ROUTE_MODES),+ modelMap: z.record(z.string(), z.string()),+ // Presence only — the snapshots themselves can carry secrets.+ projectionPending: z.boolean(),+}).strict();++/** The full `GET /api/providers/management` body. */+export const managementGraphSchema = z.object({+ schemaVersion: z.literal(PROVIDER_GRAPH_SCHEMA_VERSION),+ activeProvider: z.string().nullable(),+ connections: z.array(connectionDtoSchema),+ bindings: z.array(bindingDtoSchema),+ routes: z.array(routeDtoSchema),+}).strict();++/**+ * The sanitized, validated body a client receives.+ *+ * Credentials, projection snapshots and raw provider records never appear: the+ * browser is told only WHETHER a connection has credentials and whether a+ * route's projection is settled. Every identity decision was already made+ * server-side on real values.+ */+export function toManagementGraphDto({ connections, bindings, routes, activeProvider = null }) {+ const blocked = new Set(routes.filter((route) => route.pending).map((route) => route.bindingId));+ return managementGraphSchema.parse({+ schemaVersion: PROVIDER_GRAPH_SCHEMA_VERSION,+ activeProvider: typeof activeProvider === 'string' ? activeProvider : null,+ connections: connections.map(({ id, revision, kind, label, transports, credentials, catalog }) => ({+ id,+ revision,+ kind,+ label,+ transports,+ hasCredentials: Object.keys(credentials || {}).length > 0,+ catalog,+ })),+ bindings: bindings.map(({ id, revision, connectionId, harnessId, variantKey, label, enabled, selectedModels }) => ({+ id, revision, connectionId, harnessId, variantKey, label, enabled, selectedModels, blocked: blocked.has(id),+ })),+ routes: routes.map(({ providerId, bindingId, mode, modelMap, pending }) => ({+ providerId, bindingId, mode, modelMap, projectionPending: Boolean(pending),+ })),+ });+}++// --- import ------------------------------------------------------------------++/** The connection-owned half of one provider record, as stored in a snapshot. */+export const connectionOwnedSnapshot = (provider) => providerConnectionProfile(provider).owned;++/** The identity a connection row asserts, secrets included. Server-side only. */+const identityKey = ({ kind, transports, credentials }) => JSON.stringify([+ kind,+ Object.entries(transports || {}).sort(([a], [b]) => a.localeCompare(b)),+ Object.entries(credentials || {}).sort(([a], [b]) => a.localeCompare(b)),+]);++/**+ * Mint durable rows from a read-only preview.+ *+ * Preview ids (`conn:…`, `binding:…`) are display scaffolding derived from a+ * provider id, so they would change the moment a record is renamed. Durable+ * rows get UUIDs, which is what lets a link survive a rename. Routes keep their+ * EXECUTABLE provider ids untouched — those are the saved-selection contract.+ *+ * A preview route with no binding (an isolated legacy record) gets no row at+ * all: it stays a valid legacy route the graph simply does not manage.+ *+ * @param {object} preview - from `buildProviderGraphPreview`+ * @param {() => string} [mintId] - injected for deterministic tests+ */+export function graphFromPreview(preview, mintId = randomUUID) {+ const connectionIds = new Map();+ const connections = preview.connections.map((connection) => {+ const id = mintId();+ connectionIds.set(connection.id, id);+ return {+ id,+ revision: 1,+ kind: connection.kind,+ label: connection.label,+ transports: connection.transports,+ credentials: connection.profile.credentials,+ catalog: connection.catalog,+ };+ });++ const bindingIds = new Map();+ const bindings = preview.bindings.map((binding) => {+ const id = mintId();+ bindingIds.set(binding.id, id);+ return {+ id,+ revision: 1,+ connectionId: connectionIds.get(binding.connectionId),+ harnessId: binding.harnessId,+ variantKey: binding.variantKey,+ label: binding.label,+ enabled: binding.enabled,+ selectedModels: binding.selectedModels,+ };+ });++ const routes = preview.routes.filter((route) => route.bindingId).map((route) => ({+ providerId: route.providerId,+ bindingId: bindingIds.get(route.bindingId),+ mode: route.mode,+ modelMap: route.modelMap,+ projected: route.owned,+ pending: null,+ pendingRevision: null,+ }));++ return { connections, bindings, routes };+}++/** Build the durable graph an install's current provider records imply. */+export const importGraphFromProviders = (data, mintId = randomUUID) =>+ graphFromPreview(buildProviderGraphPreview(data), mintId);++// --- reconciliation ----------------------------------------------------------++/**+ * Reconcile a persisted graph against the provider file as it ACTUALLY is.+ *+ * One function serves three callers, because they are the same problem:+ *+ * - **boot** — the file may have been edited by a downgraded release, or a+ * crash may have landed a DB commit without its file write;+ * - **after a legacy write** — an old client's `PATCH /api/providers/:id`+ * changed a connection-owned field with no idea a graph exists;+ * - **after a restore** — half a backup can arrive without the other half.+ *+ * The rules, in the order they are applied per route:+ *+ * 1. The record is GONE → drop its row. A deleted provider is never+ * resurrected; any saved selection naming it stays a visibly unresolved+ * pin, and an emptied binding/connection is kept for explicit cleanup+ * rather than deleted or auto-refilled.+ * 2. A `pending` snapshot exists and the file matches it → the write landed;+ * acknowledge it.+ * 3. A `pending` snapshot exists and the file still matches `projected` → the+ * write did not land; retry it.+ * 4. A `pending` snapshot exists and the file matches NEITHER → a third+ * writer changed it. Refuse: never overwrite, keep the row's last valid+ * executable values readable, and report the binding as blocked.+ * 5. Otherwise the file's values are authoritative. Routes are regrouped by+ * the connection they actually describe: an unchanged group keeps its+ * UUIDs; a changed group whose connection is SHARED with another binding+ * clones it (detach) rather than editing a value another harness relies+ * on; a changed group on an exclusive connection updates it in place; and+ * a binding whose routes now disagree with each other splits.+ * 6. A provider record the graph has no row for is imported independently,+ * as its own fragment — never auto-linked into an existing connection.+ *+ * @param {{connections:object[], bindings:object[], routes:object[]}} graph+ * @param {object[]} providers - current executable records+ * @param {{mintId?: () => string}} [options]+ */+export function planGraphReconciliation(graph, providers, { mintId = randomUUID } = {}) {+ const records = new Map(+ (Array.isArray(providers) ? providers : [])+ .filter((provider) => provider && typeof provider === 'object' && provider.id)+ .map((provider) => [provider.id, provider]),+ );+ const bindingsById = new Map(graph.bindings.map((binding) => [binding.id, binding]));+ const connectionsById = new Map(graph.connections.map((connection) => [connection.id, connection]));+ const bindingsPerConnection = new Map();+ for (const binding of graph.bindings) {+ bindingsPerConnection.set(binding.connectionId, (bindingsPerConnection.get(binding.connectionId) || 0) + 1);+ }++ const plan = {+ acknowledgements: [], // { providerId } — pending landed; promote it to projected+ retries: [], // { providerId, owned } — rewrite these values into providers.json+ conflicts: [], // { providerId, bindingId, reason } — refuse; the binding stays blocked+ removals: [], // providerId[] — drop the row, never resurrect+ regroups: [], // see below — detach / split / in-place update+ snapshots: [], // { providerId, owned } — record the file's values as projected+ imports: { connections: [], bindings: [], routes: [] }, // rows for records with no mapping yet+ };++ const routesByBinding = new Map();+ for (const route of graph.routes) {+ if (!records.has(route.providerId)) {+ plan.removals.push(route.providerId);+ continue;+ }+ const provider = records.get(route.providerId);+ const owned = connectionOwnedSnapshot(provider);++ if (route.pending) {+ if (isDeepStrictEqual(owned, route.pending)) {+ plan.acknowledgements.push({ providerId: route.providerId });+ } else if (isDeepStrictEqual(owned, route.projected)) {+ plan.retries.push({ providerId: route.providerId, owned: route.pending });+ } else {+ plan.conflicts.push({ providerId: route.providerId, bindingId: route.bindingId, reason: 'external-change' });+ }+ // A route with an unsettled projection is deliberately excluded from the+ // regrouping below: its own values are exactly what is in dispute, and+ // regrouping on them would bake the disputed state into the graph.+ continue;+ }++ const list = routesByBinding.get(route.bindingId) || [];+ list.push({ route, provider, owned, profile: providerConnectionProfile(provider) });+ routesByBinding.set(route.bindingId, list);+ }++ for (const [bindingId, entries] of routesByBinding) {+ const binding = bindingsById.get(bindingId);+ if (!binding) continue;+ const stored = connectionsById.get(binding.connectionId) || null;+ const storedKey = stored ? identityKey(stored) : null;+ const shared = (bindingsPerConnection.get(binding.connectionId) || 0) > 1;++ // Group this binding's routes by the connection each one now describes.+ const groups = new Map();+ for (const entry of entries) {+ const key = identityKey(entry.profile);+ groups.set(key, [...(groups.get(key) || []), entry]);+ }++ // The group that KEEPS this binding is the one still matching the stored+ // connection; failing that, the largest, so the fewest routes are moved.+ const ordered = [...groups.values()].sort((a, b) => b.length - a.length);+ const keeperIndex = Math.max(0, ordered.findIndex((group) => identityKey(group[0].profile) === storedKey));+ const [keeper] = ordered.splice(keeperIndex, 1);++ for (const [index, group] of [keeper, ...ordered].entries()) {+ const isKeeper = index === 0;+ const lead = group[0];+ const unchanged = isKeeper && storedKey === identityKey(lead.profile);+ // A clone is required whenever the values changed AND the connection row+ // is shared: editing it in place would silently repoint another harness.+ const action = unchanged ? 'unchanged' : (isKeeper && !shared ? 'update' : 'clone');+ const models = [...new Set(group.flatMap((entry) => Object.keys(entry.route.modelMap)))];++ plan.regroups.push({+ routeIds: group.map((entry) => entry.route.providerId),+ // `null` means "mint this binding" — a split.+ bindingId: isKeeper ? bindingId : null,+ binding: isKeeper ? null : {+ id: mintId(),+ revision: 1,+ harnessId: binding.harnessId,+ // A split binding is a NEW configuration of the same harness on a+ // different backend, so it gets its own labeled variant rather than+ // colliding with the original's `default`.+ variantKey: `variant:${lead.route.providerId}`,+ label: String(lead.provider.name || lead.provider.id),+ // OR across the group, exactly as import does. Consent flags stay+ // per-route and never participate.+ enabled: group.some((entry) => entry.provider.enabled === true),+ selectedModels: models,+ },+ connectionAction: action,+ connection: {+ id: action === 'clone' ? mintId() : binding.connectionId,+ kind: lead.profile.kind,+ label: stored && isKeeper ? stored.label : String(lead.provider.name || lead.provider.id),+ transports: lead.profile.transports,+ credentials: lead.profile.credentials,+ catalog: unchanged ? stored.catalog : { state: models.length > 0 ? 'known' : 'unknown', models },+ },+ });++ for (const entry of group) {+ if (!isDeepStrictEqual(entry.owned, entry.route.projected)) {+ plan.snapshots.push({ providerId: entry.route.providerId, owned: entry.owned });+ }+ }+ }+ }++ const mapped = new Set(graph.routes.map((route) => route.providerId));+ const unmapped = [...records.values()].filter((provider) => !mapped.has(provider.id));+ if (unmapped.length > 0) plan.imports = importGraphFromProviders({ providers: unmapped }, mintId);++ return plan;+}++/** Whether a plan asks for any write at all. Lets boot skip a no-op pass. */+export const reconciliationIsNoop = (plan) =>+ plan.acknowledgements.length === 0+ && plan.retries.length === 0+ && plan.removals.length === 0+ && plan.snapshots.length === 0+ && plan.imports.routes.length === 0+ && plan.regroups.every((regroup) => regroup.connectionAction === 'unchanged' && regroup.bindingId);diff --git a/server/lib/providerGraphRecords.test.js b/server/lib/providerGraphRecords.test.jsnew file mode 100644index 0000000000..5b7234f89b--- /dev/null+++ b/server/lib/providerGraphRecords.test.js@@ -0,0 +1,339 @@+/**+ * The durable provider-graph record contract (#6367).+ *+ * These are the assertions that stand between a provider-configuration import+ * and silent data loss, so they live at the pure layer where every branch is+ * reachable without a Postgres or a temp directory:+ *+ * - an import round-trips every executable record byte-for-byte, custom+ * fields and secrets included, because that round-trip IS the downgrade+ * contract;+ * - the client DTO carries credential PRESENCE and nothing else;+ * - a crash between the DB commit and the file write is recoverable, and a+ * third writer's value is never overwritten to recover it;+ * - an edit made by a downgraded release or an old client detaches, updates+ * or splits the right rows and resurrects nothing.+ *+ * Every fixture is synthetic. Nothing here is read out of a running install.+ */++import { describe, expect, it } from 'vitest';+import { buildProviderGraphPreview } from './providerGraphPreview.js';+import { withConnectionOwnedFields } from './providerConnections.js';+import {+ connectionOwnedSnapshot,+ graphFromPreview,+ importGraphFromProviders,+ planGraphReconciliation,+ reconciliationIsNoop,+ toManagementGraphDto,+} from './providerGraphRecords.js';++// A deterministic id minter so a plan can be asserted without matching UUIDs.+const minter = (prefix = 'id') => {+ let n = 0;+ return () => `${prefix}-${(n += 1)}`;+};++const CLAUDE_CLI = Object.freeze({+ id: 'claude-ollama',+ name: 'Claude on the example daemon',+ type: 'cli',+ command: 'claude',+ ollamaBacked: true,+ enabled: true,+ models: ['example-model:8b'],+ defaultModel: 'example-model:8b',+ envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:11434', ANTHROPIC_AUTH_TOKEN: 'example-token' },+ secretEnvVars: ['ANTHROPIC_AUTH_TOKEN'],+ // A field no module in this tree has ever heard of. It must survive import.+ someFutureField: { nested: [1, 2, 3] },+});+const CLAUDE_TUI = Object.freeze({+ ...CLAUDE_CLI,+ id: 'claude-ollama-tui',+ type: 'tui',+ enabled: false,+ textTransport: 'tui',+ textTransportEnabled: true,+});+const REMOTE_API = Object.freeze({+ id: 'remote-ollama',+ name: 'Remote Ollama',+ type: 'api',+ endpoint: 'https://ollama.example.com/v1',+ apiKey: 'example-remote-key',+ enabled: true,+ models: [],+});++// Deep clones: the CLI and TUI literals deliberately SHARE one `envVars`+// object (that is what makes them siblings), so a shallow copy would let one+// test's edit reach the other record and the next test's fixture.+const providersFixture = () => [CLAUDE_CLI, CLAUDE_TUI, REMOTE_API].map((record) => structuredClone(record));++/** The graph an install with these records would import, plus the records. */+const imported = (providers = providersFixture(), mintId = minter()) => ({+ providers,+ graph: importGraphFromProviders({ providers }, mintId),+});++describe('importing an install into durable rows', () => {+ it('round-trips every executable record, including unknown custom fields', () => {+ // The import-fidelity proof and the downgrade contract are the same+ // assertion: a downgraded release runs providers.json with no graph, so a+ // record missing a connection-owned value would stop executing.+ const providers = providersFixture();+ const { graph } = imported(providers);+ const snapshots = new Map(graph.routes.map((route) => [route.providerId, route.projected]));+ const rematerialized = providers.map((provider) =>+ withConnectionOwnedFields(provider, snapshots.get(provider.id)));+ expect(rematerialized).toEqual(providers);+ });++ it('keeps the executable provider ids and mints UUID-shaped ids for the graph', () => {+ const { graph } = imported();+ // Saved selections everywhere in PortOS name these strings.+ expect(graph.routes.map((route) => route.providerId).sort())+ .toEqual(['claude-ollama', 'claude-ollama-tui', 'remote-ollama']);+ // Graph identity is durable and independent of any provider id, so a+ // rename cannot break a link.+ for (const connection of graph.connections) expect(connection.id).not.toContain('claude');+ });++ it('OR-enables a proven CLI/TUI sibling pair without touching either route', () => {+ const { providers, graph } = imported();+ const binding = graph.bindings.find((candidate) => candidate.harnessId === 'claude');+ expect(binding.enabled).toBe(true); // CLI enabled, TUI disabled+ // The per-route records keep their own enabled flags and their consent.+ expect(providers.find((p) => p.id === 'claude-ollama-tui').enabled).toBe(false);+ expect(providers.find((p) => p.id === 'claude-ollama-tui').textTransportEnabled).toBe(true);+ });++ it('imports a disabled or custom route rather than dropping it', () => {+ const custom = { id: 'custom-cli', name: 'Custom', type: 'cli', command: 'claude', enabled: false, models: [] };+ const { graph } = imported([...providersFixture(), custom]);+ expect(graph.routes.map((route) => route.providerId)).toContain('custom-cli');+ });++ it('leaves an unmappable record as a legacy route with no row at all', () => {+ // An unknown harness stays executable and unmanaged, never guessed into a+ // connection it might not reach.+ const unknown = { id: 'mystery', name: 'Mystery', type: 'cli', command: 'mystery-bin', enabled: true, models: [] };+ const { graph } = imported([...providersFixture(), unknown]);+ expect(graph.routes.map((route) => route.providerId)).not.toContain('mystery');+ });+});++describe('the client DTO', () => {+ const dto = () => toManagementGraphDto({ ...imported().graph, activeProvider: 'claude-ollama' });++ it('publishes credential presence and never a credential or a snapshot', () => {+ const serialized = JSON.stringify(dto());+ expect(serialized).not.toContain('example-token');+ expect(serialized).not.toContain('example-remote-key');+ expect(serialized).not.toContain('projected');+ expect(dto().connections.every((connection) => connection.hasCredentials)).toBe(true);+ });++ it('publishes the same executable activeProvider string as the flat API', () => {+ expect(dto().activeProvider).toBe('claude-ollama');+ });++ it('marks a binding blocked while one of its routes has an unsettled projection', () => {+ const graph = imported().graph;+ graph.routes[0].pending = { fields: {}, envVars: {}, hasEnvVars: true };+ const blocked = toManagementGraphDto(graph).bindings.filter((binding) => binding.blocked);+ expect(blocked.map((binding) => binding.id)).toEqual([graph.routes[0].bindingId]);+ });+});++describe('recovering an interrupted projection', () => {+ /** A graph whose first Claude route is mid-projection to `pendingUrl`. */+ const midProjection = (pendingUrl) => {+ const providers = providersFixture();+ const { graph } = imported(providers);+ const route = graph.routes.find((candidate) => candidate.providerId === 'claude-ollama');+ route.pending = {+ ...route.projected,+ envVars: { ...route.projected.envVars, ANTHROPIC_BASE_URL: pendingUrl },+ };+ return { providers, graph, route };+ };++ it('acknowledges a projection whose file write landed', () => {+ const { providers, graph } = midProjection('http://127.0.0.1:9999');+ // The crash happened AFTER the file write, so the file already holds it.+ providers.find((p) => p.id === 'claude-ollama').envVars.ANTHROPIC_BASE_URL = 'http://127.0.0.1:9999';++ const plan = planGraphReconciliation(graph, providers, { mintId: minter('new') });+ expect(plan.acknowledgements).toEqual([{ providerId: 'claude-ollama' }]);+ expect(plan.retries).toEqual([]);+ expect(plan.conflicts).toEqual([]);+ });++ it('retries a projection whose file write did not land', () => {+ const { providers, graph, route } = midProjection('http://127.0.0.1:9999');+ // The file still holds the pre-projection value.+ const plan = planGraphReconciliation(graph, providers, { mintId: minter('new') });+ expect(plan.retries).toEqual([{ providerId: 'claude-ollama', owned: route.pending }]);+ expect(plan.acknowledgements).toEqual([]);+ });++ it('REFUSES to overwrite a third value a different writer put there', () => {+ // This is the assertion the whole two-snapshot design exists for: matching+ // neither snapshot means someone else edited the file, and a retry would+ // destroy their change.+ const { providers, graph } = midProjection('http://127.0.0.1:9999');+ providers.find((p) => p.id === 'claude-ollama').envVars.ANTHROPIC_BASE_URL = 'http://127.0.0.1:7777';++ const plan = planGraphReconciliation(graph, providers, { mintId: minter('new') });+ expect(plan.conflicts).toEqual([+ { providerId: 'claude-ollama', bindingId: expect.any(String), reason: 'external-change' },+ ]);+ expect(plan.retries).toEqual([]);+ expect(plan.acknowledgements).toEqual([]);+ // Nothing about the disputed route is regrouped or re-snapshotted either.+ expect(plan.snapshots.map((snapshot) => snapshot.providerId)).not.toContain('claude-ollama');+ });+});++describe('reconciling after a downgrade edited providers.json', () => {+ it('is a no-op when nothing moved, and keeps every UUID', () => {+ const { providers, graph } = imported();+ const plan = planGraphReconciliation(graph, providers, { mintId: minter('new') });+ expect(reconciliationIsNoop(plan)).toBe(true);+ expect(plan.regroups.every((regroup) => regroup.connectionAction === 'unchanged')).toBe(true);+ const original = new Set(graph.connections.map((connection) => connection.id));+ for (const regroup of plan.regroups) expect(original.has(regroup.connection.id)).toBe(true);+ });++ it('updates an EXCLUSIVE connection in place when its backend moved', () => {+ const providers = providersFixture();+ const { graph } = imported(providers);+ for (const id of ['claude-ollama', 'claude-ollama-tui']) {+ providers.find((p) => p.id === id).envVars.ANTHROPIC_BASE_URL = 'http://127.0.0.1:12345';+ }++ const plan = planGraphReconciliation(graph, providers, { mintId: minter('new') });+ const claude = plan.regroups.find((regroup) => regroup.routeIds.includes('claude-ollama'));+ expect(claude.connectionAction).toBe('update');+ // Only one binding uses it, so nothing else can be repointed by the edit —+ // the row keeps its id and the routes keep their binding.+ expect(claude.connection.id).toBe(graph.bindings.find((b) => b.harnessId === 'claude').connectionId);+ expect(claude.bindingId).toBeTruthy();+ expect(plan.snapshots.map((snapshot) => snapshot.providerId).sort())+ .toEqual(['claude-ollama', 'claude-ollama-tui']);+ });++ it('CLONES a shared connection rather than repointing another harness', () => {+ // Two harnesses on one connection is the whole point of the graph; an edit+ // to one of them must not silently move the other's backend.+ const providers = providersFixture();+ const { graph } = imported(providers);+ const claudeBinding = graph.bindings.find((binding) => binding.harnessId === 'claude');+ const apiBinding = graph.bindings.find((binding) => binding.harnessId === null);+ apiBinding.connectionId = claudeBinding.connectionId;++ for (const id of ['claude-ollama', 'claude-ollama-tui']) {+ providers.find((p) => p.id === id).envVars.ANTHROPIC_BASE_URL = 'http://127.0.0.1:12345';+ }++ const plan = planGraphReconciliation(graph, providers, { mintId: minter('new') });+ const claude = plan.regroups.find((regroup) => regroup.routeIds.includes('claude-ollama'));+ expect(claude.connectionAction).toBe('clone');+ expect(claude.connection.id).not.toBe(claudeBinding.connectionId);+ expect(claude.bindingId).toBe(claudeBinding.id); // route ids and binding retained+ });++ it('SPLITS a binding whose siblings now disagree with each other', () => {+ const providers = providersFixture();+ const { graph } = imported(providers);+ // Only the TUI half was repointed — the two are no longer one connection.+ providers.find((p) => p.id === 'claude-ollama-tui').envVars.ANTHROPIC_BASE_URL = 'http://127.0.0.1:12345';++ const plan = planGraphReconciliation(graph, providers, { mintId: minter('new') });+ const split = plan.regroups.find((regroup) => regroup.routeIds.includes('claude-ollama-tui'));+ expect(split.bindingId).toBeNull();+ expect(split.binding.harnessId).toBe('claude');+ // A distinct labeled variant, never a merge that would discard a route id.+ expect(split.binding.variantKey).toBe('variant:claude-ollama-tui');+ expect(split.connectionAction).toBe('clone');+ // The CLI half keeps the original binding and connection.+ const kept = plan.regroups.find((regroup) => regroup.routeIds.includes('claude-ollama'));+ expect(kept.connectionAction).toBe('unchanged');+ });++ it('drops a deleted record without resurrecting it', () => {+ const providers = providersFixture().filter((provider) => provider.id !== 'remote-ollama');+ const { graph } = imported(providersFixture());++ const plan = planGraphReconciliation(graph, providers, { mintId: minter('new') });+ expect(plan.removals).toEqual(['remote-ollama']);+ expect(plan.imports.routes).toEqual([]);+ // The emptied binding/connection are left for explicit cleanup, not deleted+ // and not refilled with a route the user removed.+ expect(plan.regroups.some((regroup) => regroup.routeIds.includes('remote-ollama'))).toBe(false);+ });++ it('imports a record added while the graph was not running', () => {+ const added = { id: 'codex-cli', name: 'Codex', type: 'cli', command: 'codex', enabled: true, models: [] };+ const { graph } = imported(providersFixture());++ const plan = planGraphReconciliation(graph, [...providersFixture(), added], { mintId: minter('new') });+ expect(plan.imports.routes.map((route) => route.providerId)).toEqual(['codex-cli']);+ // Imported as its own fragment — never auto-linked into an existing+ // connection on a name or vendor match.+ expect(plan.imports.connections).toHaveLength(1);+ });++ it('rebuilds isolated mappings when a restore brought the file but not the graph', () => {+ // Half a backup: providers.json is present, the DB tables are empty. Every+ // record is simply unmapped, so the same import path rebuilds them — with+ // the cross-harness link metadata legitimately lost.+ const providers = providersFixture();+ const plan = planGraphReconciliation({ connections: [], bindings: [], routes: [] }, providers,+ { mintId: minter('new') });+ expect(plan.imports.routes.map((route) => route.providerId).sort())+ .toEqual(['claude-ollama', 'claude-ollama-tui', 'remote-ollama']);+ expect(plan.removals).toEqual([]);+ });++ it('drops rows whose records a restore did not bring back', () => {+ // The other half: the DB has the graph, the provider file is a bare seed.+ const { graph } = imported(providersFixture());+ const plan = planGraphReconciliation(graph, [], { mintId: minter('new') });+ expect(plan.removals.sort()).toEqual(['claude-ollama', 'claude-ollama-tui', 'remote-ollama']);+ });+});++describe('a mode-only legacy edit stays route-scoped', () => {+ it('changes no connection-owned value and plans no graph change', () => {+ const providers = providersFixture();+ const { graph } = imported(providers);+ // Exactly the shape of an old client's PATCH on the mode editor.+ Object.assign(providers.find((p) => p.id === 'claude-ollama'), {+ timeout: 120000,+ args: ['--verbose'],+ defaultModel: 'example-model:70b',+ });++ expect(connectionOwnedSnapshot(providers.find((p) => p.id === 'claude-ollama')))+ .toEqual(graph.routes.find((route) => route.providerId === 'claude-ollama').projected);+ expect(reconciliationIsNoop(planGraphReconciliation(graph, providers, { mintId: minter('new') }))).toBe(true);+ });+});++describe('graphFromPreview', () => {+ it('proposes a graph the database uniqueness rules would accept', () => {+ // The preview already refuses to emit a violating graph; this pins that the+ // ROW mapping preserves it, since the DB indexes are the real enforcement.+ const preview = buildProviderGraphPreview({ providers: providersFixture() });+ const graph = graphFromPreview(preview, minter());+ const bindingModes = graph.routes.map((route) => `${route.bindingId}|${route.mode}`);+ expect(new Set(bindingModes).size).toBe(bindingModes.length);+ const variants = graph.bindings.map((binding) =>+ `${binding.connectionId}|${binding.harnessId ?? ''}|${binding.variantKey}`);+ expect(new Set(variants).size).toBe(variants.length);+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 2608afb164..f0a05f0717 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -556,6 +556,31 @@ export const codexLoginStartSchema = z.object({deviceCode: z.boolean().optional().default(false),});+// POST /api/providers/bindings/:id/link (and /link/preview).+//+// Every revision the caller reviewed is named explicitly. Omitting one is+// allowed for a PREVIEW (there is nothing to be stale against yet), but the+// service refuses to APPLY a link whose named revisions have moved -- a link is+// a decision about a specific difference, so a changed row invalidates it.+export const providerBindingLinkSchema = z.object({+ targetConnectionId: z.string().uuid(),+ expectedRevisions: z.object({+ binding: z.number().int().positive().optional(),+ sourceConnection: z.number().int().positive().optional(),+ targetConnection: z.number().int().positive().optional(),+ }).strict().optional().default({}),+}).strict();++// POST /api/providers/bindings/:id/unlink. No target: unlink clones the+// connection this binding already uses, so only the binding and its source+// participate.+export const providerBindingUnlinkSchema = z.object({+ expectedRevisions: z.object({+ binding: z.number().int().positive().optional(),+ sourceConnection: z.number().int().positive().optional(),+ }).strict().optional().default({}),+}).strict();+// POST /api/providers/:id/vision-suite.export const providerVisionSuiteSchema = z.object({model: z.preprocess(emptyToUndefined, z.string().trim().min(1).max(256).optional()),diff --git a/server/routes/providers.graph.test.js b/server/routes/providers.graph.test.jsnew file mode 100644index 0000000000..c480b6b412--- /dev/null+++ b/server/routes/providers.graph.test.js@@ -0,0 +1,173 @@+/**+ * HTTP boundary for the durable provider connection graph (#6367).+ *+ * The graph service is doubled here on purpose: what this file owns is the+ * boundary contract a client depends on — that the durable endpoint answers in+ * the same version-1 shape as the #6366 preview, that an install without a+ * database gets an EXPLICIT unsupported answer rather than an empty graph, that+ * link/unlink bodies are Zod-validated before any row is touched, and that the+ * flat provider API a downgraded or older client uses is unchanged.+ *+ * Fixtures are synthetic. Nothing here is read out of a running install.+ */++import { afterEach, describe, expect, it, vi } from 'vitest';+import express, { Router } from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware, ServerError } from '../lib/errorHandler.js';++const graph = {+ getManagementGraph: vi.fn(),+ previewBindingLink: vi.fn(),+ linkBinding: vi.fn(),+ unlinkBinding: vi.fn(),+ removeConnection: vi.fn(),+};+vi.mock('../services/providerGraph.js', () => graph);++const { createPortOSProviderRoutes } = await import('./providers.js');++const BINDING = '11111111-1111-4111-8111-111111111111';+const TARGET = '22222222-2222-4222-8222-222222222222';++const PROVIDERS = {+ activeProvider: 'claude-ollama',+ providers: [+ { id: 'claude-ollama', name: 'Claude', type: 'cli', command: 'claude', enabled: true, models: [] },+ ],+};++function app(providerService = { getAllProviders: vi.fn().mockResolvedValue(PROVIDERS) }) {+ const toolkit = { services: { providers: providerService }, routes: { providers: Router() } };+ const server = express();+ server.use(express.json());+ server.use('/api/providers', createPortOSProviderRoutes(toolkit));+ server.use(errorMiddleware);+ return server;+}++afterEach(() => vi.clearAllMocks());++describe('GET /api/providers/management', () => {+ it('serves the durable graph and never caches it', async () => {+ graph.getManagementGraph.mockResolvedValue({+ schemaVersion: 1, activeProvider: 'claude-ollama', connections: [], bindings: [], routes: [],+ });++ const res = await request(app()).get('/api/providers/management');+ expect(res.status).toBe(200);+ expect(res.body.schemaVersion).toBe(1);+ // A configuration graph read from a cache is a graph that lies after a save.+ expect(res.headers['cache-control']).toBe('no-store');+ });++ it('answers an install without a database EXPLICITLY, not with an empty graph', async () => {+ // An empty graph and an unavailable one must never look the same to a+ // client: one means "nothing configured", the other means "fall back to the+ // flat list".+ graph.getManagementGraph.mockRejectedValue(+ new ServerError('unavailable', { status: 503, code: 'PROVIDER_GRAPH_UNAVAILABLE' }));++ const res = await request(app()).get('/api/providers/management');+ expect(res.status).toBe(503);+ expect(res.body.code).toBe('PROVIDER_GRAPH_UNAVAILABLE');+ });++ it('leaves the flat provider API unchanged for an older client', async () => {+ const res = await request(app()).get('/api/providers');+ expect(res.status).toBe(200);+ expect(res.body.activeProvider).toBe('claude-ollama');+ expect(res.body.providers.map((provider) => provider.id)).toEqual(['claude-ollama']);+ expect(graph.getManagementGraph).not.toHaveBeenCalled();+ });+});++describe('POST /api/providers/bindings/:id/link', () => {+ it('previews without applying', async () => {+ graph.previewBindingLink.mockResolvedValue({ bindingId: BINDING, affectedRouteIds: ['claude-ollama'] });++ const res = await request(app())+ .post(`/api/providers/bindings/${BINDING}/link/preview`)+ .send({ targetConnectionId: TARGET });++ expect(res.status).toBe(200);+ expect(graph.previewBindingLink).toHaveBeenCalledWith({+ bindingId: BINDING, targetConnectionId: TARGET, expectedRevisions: {},+ });+ expect(graph.linkBinding).not.toHaveBeenCalled();+ });++ it('passes the reviewed revisions through to the service', async () => {+ graph.linkBinding.mockResolvedValue({ bindingId: BINDING, connectionId: TARGET, affectedRouteIds: [] });+ const expectedRevisions = { binding: 2, sourceConnection: 3, targetConnection: 4 };++ const res = await request(app())+ .post(`/api/providers/bindings/${BINDING}/link`)+ .send({ targetConnectionId: TARGET, expectedRevisions });++ expect(res.status).toBe(200);+ expect(graph.linkBinding).toHaveBeenCalledWith({ bindingId: BINDING, targetConnectionId: TARGET, expectedRevisions });+ });++ it('surfaces a stale-revision refusal as a 409 rather than applying it', async () => {+ graph.linkBinding.mockRejectedValue(+ new ServerError('stale', { status: 409, code: 'PROVIDER_GRAPH_STALE_REVISION' }));++ const res = await request(app())+ .post(`/api/providers/bindings/${BINDING}/link`)+ .send({ targetConnectionId: TARGET, expectedRevisions: { binding: 1 } });++ expect(res.status).toBe(409);+ expect(res.body.code).toBe('PROVIDER_GRAPH_STALE_REVISION');+ });++ it.each([+ ['a missing target', {}],+ ['a non-uuid target', { targetConnectionId: 'not-a-uuid' }],+ ['an unknown field', { targetConnectionId: TARGET, mergeCredentials: true }],+ ])('rejects %s before the service is reached', async (_label, body) => {+ const res = await request(app()).post(`/api/providers/bindings/${BINDING}/link`).send(body);+ expect(res.status).toBe(400);+ expect(graph.linkBinding).not.toHaveBeenCalled();+ });+});++describe('POST /api/providers/bindings/:id/unlink', () => {+ it('takes no target connection and forwards the binding', async () => {+ graph.unlinkBinding.mockResolvedValue({ bindingId: BINDING, connectionId: TARGET });++ const res = await request(app())+ .post(`/api/providers/bindings/${BINDING}/unlink`)+ .send({ expectedRevisions: { binding: 1, sourceConnection: 1 } });++ expect(res.status).toBe(200);+ expect(graph.unlinkBinding).toHaveBeenCalledWith({+ bindingId: BINDING, expectedRevisions: { binding: 1, sourceConnection: 1 },+ });+ });++ it('rejects a body that names a target — unlink never repoints', async () => {+ const res = await request(app())+ .post(`/api/providers/bindings/${BINDING}/unlink`)+ .send({ targetConnectionId: TARGET });+ expect(res.status).toBe(400);+ expect(graph.unlinkBinding).not.toHaveBeenCalled();+ });+});++describe('DELETE /api/providers/connections/:id', () => {+ it('forwards the id and returns the service verdict', async () => {+ graph.removeConnection.mockResolvedValue({ deleted: true });+ const res = await request(app()).delete(`/api/providers/connections/${TARGET}`);+ expect(res.status).toBe(200);+ expect(graph.removeConnection).toHaveBeenCalledWith(TARGET);+ });++ it('surfaces an in-use refusal as a 409', async () => {+ graph.removeConnection.mockRejectedValue(+ new ServerError('in use', { status: 409, code: 'PROVIDER_GRAPH_CONNECTION_IN_USE' }));+ const res = await request(app()).delete(`/api/providers/connections/${TARGET}`);+ expect(res.status).toBe(409);+ expect(res.body.code).toBe('PROVIDER_GRAPH_CONNECTION_IN_USE');+ });+});diff --git a/server/routes/providers.js b/server/routes/providers.jsindex 37ce54d4ac..3f9b42653f 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -1,5 +1,12 @@import { providerModeGroups } from '../lib/aiToolkit/internal/providerModes.js';import { buildProviderGraphPreview, toManagementPreviewDto } from '../lib/providerGraphPreview.js';+import {+ getManagementGraph,+ linkBinding,+ previewBindingLink,+ removeConnection,+ unlinkBinding,+} from '../services/providerGraph.js';import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { testVision, runVisionTestSuite, checkVisionHealth } from '../services/visionTest.js';@@ -14,6 +21,8 @@ import {codexLoginStartSchema,providerVisionTestSchema,providerVisionSuiteSchema,+ providerBindingLinkSchema,+ providerBindingUnlinkSchema,} from '../lib/validation.js';import {getProviderRuntimeStatus,@@ -290,6 +299,52 @@ export function createPortOSProviderRoutes(aiToolkit) {res.set('Cache-Control', 'no-store').json(toManagementPreviewDto(buildProviderGraphPreview(data)));}));+ /**+ * The DURABLE provider connection graph (#6367) — the same shape as the+ * preview above, but read from ai_connections / ai_harness_bindings /+ * ai_route_bindings rather than derived on every request.+ *+ * Sanitized identically: credential PRESENCE only, no projection snapshots,+ * no raw provider records. An install whose database is unavailable gets an+ * explicit 503 `PROVIDER_GRAPH_UNAVAILABLE` rather than a silent empty graph,+ * so a client can fall back to the flat list on a known answer instead of+ * guessing from a failed request.+ */+ router.get('/management', asyncHandler(async (_req, res) => {+ res.set('Cache-Control', 'no-store').json(await getManagementGraph());+ }));++ /**+ * What linking this binding into another connection WOULD change: which+ * executable route ids move, how the two backends differ, and which variant+ * key the binding would occupy. Read-only — POST because the body carries the+ * revisions being reviewed, not because anything is written.+ */+ router.post('/bindings/:id/link/preview', asyncHandler(async (req, res) => {+ const input = validateRequest(providerBindingLinkSchema, req.body ?? {});+ res.json(await previewBindingLink({ bindingId: req.params.id, ...input }));+ }));++ // Apply a reviewed link. Every named revision is re-checked inside the graph+ // transaction; a stale one is a 409 that requires a fresh preview.+ router.post('/bindings/:id/link', asyncHandler(async (req, res) => {+ const input = validateRequest(providerBindingLinkSchema, req.body ?? {});+ res.json(await linkBinding({ bindingId: req.params.id, ...input }));+ }));++ // Give this binding its own copy of the connection it shares. Route ids,+ // activeProvider, task pins and fallback references are all retained.+ router.post('/bindings/:id/unlink', asyncHandler(async (req, res) => {+ const input = validateRequest(providerBindingUnlinkSchema, req.body ?? {});+ res.json(await unlinkBinding({ bindingId: req.params.id, ...input }));+ }));++ // Remove a connection no binding uses. Refused with a 409 while one still+ // does — the graph never silently orphans a binding to tidy a row away.+ router.delete('/connections/:id', asyncHandler(async (req, res) => {+ res.json(await removeConnection(req.params.id));+ }));+router.get('/samples', asyncHandler(async (req, res) => {const providers = await providerService.getSampleProviders();const capabilities = await detectSystemCapabilities();diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 397ad031a6..d0614b8031 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -90,6 +90,7 @@ import { startSignalScheduler } from './signalScheduler.js';import { startSpotifyScheduler } from './spotifyScheduler.js';import { startYoutubeScheduler } from './youtubeScheduler.js';import { reconcileStackerNewsSchedulers } from './stackerNewsScheduler.js';+import { onProvidersSaved as onProvidersSavedForGraph } from './providerGraph.js';import { startBrainScheduler } from './brainScheduler.js';import { startActivityDigestScheduler } from './activityDigestScheduler.js';import { startTwinEnrichmentScheduler } from './twinEnrichmentScheduler.js';@@ -253,6 +254,11 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD// canonical `{ error, code, timestamp, context? }` envelope (issue #1084).ServerError,hooks: aiToolkitHooks,+ // Keep the provider connection graph reconciled with any write to+ // providers.json — an old client's PATCH, a model refresh, a delete.+ // Injected rather than imported by the toolkit, which stays+ // self-contained. A no-op until the database phase enables the graph.+ onProvidersSaved: () => onProvidersSavedForGraph(),// Keep the fallback chain off providers whose CLI is not installed on// this host (#4611), so a run falls through to the next candidate instead// of dying at spawn time. Sync by contract: it reads the runtime probe's@@ -680,6 +686,11 @@ const runDatabaseBootPhase = () => runDatabasePhase({pruneLegacyFiles: async () => (await import('../scripts/pruneImportedLegacyFiles.js')).pruneImportedLegacyFiles()}),+ // Provider connection graph (#6367): first run imports every provider record+ // into ai_connections / ai_harness_bindings / ai_route_bindings; later runs+ // reconcile against providers.json. Reads and writes local state only.+ reconcileProviderGraph: async () => (await import('./providerGraph.js')).initProviderGraph(),+reconcileStackerNews: reconcileStackerNewsSchedulers});diff --git a/server/services/bootstrapSequence.js b/server/services/bootstrapSequence.jsindex 61fac38fb3..d72bf79570 100644--- a/server/services/bootstrapSequence.js+++ b/server/services/bootstrapSequence.js@@ -254,17 +254,24 @@ export const warmMandatoryStores = async ({};/**- * Database phase: gate, then migrate, then (only on a real DB) warm the stores- * and arm the Stacker News schedulers. The warm/arm pair is skipped on the+ * Database phase: gate, then migrate, then (only on a real DB) warm the stores,+ * reconcile the provider connection graph, and arm the Stacker News schedulers. The warm/arm pair is skipped on the* escape hatch for the same reason the migrations are — there is no DB to read.** Returns the gate result so a caller can branch on `dbReady`.*/-export const runDatabasePhase = async ({ gate, migrate, warmStores, reconcileStackerNews }) => {+export const runDatabasePhase = async ({ gate, migrate, warmStores, reconcileProviderGraph, reconcileStackerNews }) => {const gateResult = await gate();await migrate(gateResult);if (gateResult.dbReady) {await warmStores();+ // Provider connection graph (#6367): import on first run, then reconcile+ // the DB graph against providers.json — recovering an interrupted+ // projection and absorbing edits a downgraded release or an old client made+ // to the file. AFTER the schema migrations (its tables must exist) and+ // BEFORE listen(), so no request can read a half-reconciled graph. Local+ // I/O only: it reads two stores and writes rows, never a provider.+ await reconcileProviderGraph();// OFF by default — arms timers for opted-in accounts only, after their// tables exist. No initial sync, no local-LLM call.await reconcileStackerNews();diff --git a/server/services/bootstrapSequence.test.js b/server/services/bootstrapSequence.test.jsindex d81664dd57..af394a06dd 100644--- a/server/services/bootstrapSequence.test.js+++ b/server/services/bootstrapSequence.test.js@@ -464,6 +464,7 @@ describe('runDatabasePhase', () => {gate: step('gate', () => Promise.resolve(gateResult)),migrate: step('migrate', () => Promise.resolve()),warmStores: step('warmStores', () => Promise.resolve()),+ reconcileProviderGraph: step('reconcileProviderGraph', () => Promise.resolve()),reconcileStackerNews: step('reconcileStackerNews', () => Promise.resolve())};};@@ -471,7 +472,7 @@ describe('runDatabasePhase', () => {it('gates, migrates, warms, then arms the opt-in schedulers', async () => {const recorder = createRecorder();await runDatabasePhase(buildDeps(recorder));- expect(recorder.calls).toEqual(['gate', 'migrate', 'warmStores', 'reconcileStackerNews']);+ expect(recorder.calls).toEqual(['gate', 'migrate', 'warmStores', 'reconcileProviderGraph', 'reconcileStackerNews']);});it('passes the gate result (dbReady + ensureSchema) straight to the migrations', async () => {diff --git a/server/services/providerGraph.js b/server/services/providerGraph.jsnew file mode 100644index 0000000000..4c20ace0f1--- /dev/null+++ b/server/services/providerGraph.js@@ -0,0 +1,375 @@+import { randomUUID } from 'node:crypto';+import { ServerError } from '../lib/errorHandler.js';+import { compareBackendEndpoints, withConnectionOwnedFields } from '../lib/providerConnections.js';+import {+ connectionOwnedSnapshot,+ planGraphReconciliation,+ reconciliationIsNoop,+ toManagementGraphDto,+} from '../lib/providerGraphRecords.js';+import { requireToolkit } from '../lib/aiToolkitState.js';+import {+ acknowledgeProjection,+ applyReconciliation,+ commitPendingProjection,+ deleteConnection,+ detachBindingToConnection,+ readGraph,+ relinkBinding,+} from './providerGraphStore.js';++/**+ * The provider connection graph's orchestration layer (#6367).+ *+ * Two stores have to agree here and neither can be locked against the other:+ * the DB graph (`providerGraphStore.js`) and the executable+ * `data/providers.json` the toolkit owns. `providers.json` stays fully+ * materialized and authoritative for EXECUTION -- a downgraded release runs it+ * with no graph at all -- so every rule below is written from that direction:+ * the file is what a run reads, and the graph follows it.+ *+ * **Serialization.** Every pass runs on one promise queue, so a legacy provider+ * write, a boot reconcile and a link can never interleave their reads and+ * writes. This is re-entrancy control, not multi-actor locking (AGENTS.md+ * Security Model): there is one server process and one human.+ *+ * **Projection ordering.** A graph mutation commits its rows AND the pending+ * projection snapshot in one DB transaction, writes providers.json through the+ * toolkit, then acknowledges. A crash at any point leaves a `pending` snapshot+ * the next reconcile pass can resolve against the file's actual values --+ * retrying only when the file still holds the old value, and refusing outright+ * when it holds a third one.+ *+ * **No AI provider is ever contacted here.** Import, reconcile, link, unlink+ * and projection are local I/O only (AGENTS.md "No cold-bootstrap LLM calls").+ */++/** Off until the database phase says the graph tables exist. */+let graphEnabled = false;+/** Re-entrancy latch: a projection's own file write must not re-trigger a pass. */+let reconciling = false;+let queue = Promise.resolve();++/** One-at-a-time execution. A rejected pass must not poison the next one. */+const serialize = (fn) => {+ queue = queue.then(() => undefined, () => undefined).then(fn);+ return queue;+};++export const providerGraphEnabled = () => graphEnabled;++/** Test seam: reset module state between suites. */+export function resetProviderGraphState() {+ graphEnabled = false;+ reconciling = false;+ queue = Promise.resolve();+}++const providerService = () => requireToolkit().services.providers;++/**+ * The patch that materializes a connection-owned snapshot into an executable+ * record. Built from the live record so unknown custom fields and route-owned+ * env vars survive untouched.+ */+function projectionPatch(provider, owned) {+ const merged = withConnectionOwnedFields(provider, owned);+ const patch = { ...owned.fields };+ if (owned.hasEnvVars) patch.envVars = merged.envVars;+ return patch;+}++/**+ * One reconciliation pass: read both stores, plan, apply.+ *+ * Retries are written to the file BEFORE the plan is applied so their rows can+ * be acknowledged in the same transaction -- a retry that could not be written+ * stays pending and is retried on the next pass rather than being marked done.+ */+async function reconcilePass(reason) {+ const graph = await readGraph();+ const { providers, activeProvider } = await providerService().getAllProviders();+ const plan = planGraphReconciliation(graph, providers, { mintId: randomUUID });++ if (plan.retries.length > 0) {+ const byId = new Map(providers.map((provider) => [provider.id, provider]));+ const patches = Object.fromEntries(plan.retries+ .filter(({ providerId }) => byId.has(providerId))+ .map(({ providerId, owned }) => [providerId, projectionPatch(byId.get(providerId), owned)]));+ const written = await providerService().applyProviderPatches(patches);+ plan.acknowledgements.push(...written.map((providerId) => ({ providerId })));+ }++ const noop = reconciliationIsNoop(plan);+ if (!noop) await applyReconciliation(plan);++ 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) {+ 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`);+ }+ 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 };+}++/**+ * Reconcile the graph against providers.json.+ *+ * `reconciling` is set for the WHOLE pass, not just its write: the retry path+ * saves through the toolkit, which fires the same hook that calls this -- the+ * latch is what keeps that from recursing.+ */+export function reconcileProviderGraph(reason = 'manual') {+ if (!graphEnabled || reconciling) return Promise.resolve(null);+ return serialize(() => {+ reconciling = true;+ return reconcilePass(reason).finally(() => { reconciling = false; });+ });+}++/**+ * Boot entry, called from the database phase once the schema is up.+ *+ * The first pass on an install with no graph rows imports every provider record+ * -- including disabled and custom ones -- because each is simply "unmapped" to+ * the planner. That keeps ONE code path responsible for import, crash recovery+ * and downgrade reconciliation, so they cannot drift apart.+ */+export async function initProviderGraph() {+ graphEnabled = true;+ return reconcileProviderGraph('boot');+}++/**+ * The toolkit's post-save hook (wired in `bootstrap.js`).+ *+ * An old client's `PATCH /api/providers/:id` knows nothing about the graph, so+ * a connection-owned edit arrives here as a plain file change. Reconciliation+ * detaches the affected binding rather than letting the edit silently repoint+ * another harness's backend; a mode-only edit changes no connection-owned value+ * and is therefore route-scoped and a no-op here; and a deleted record drops+ * its row without being resurrected.+ */+export const onProvidersSaved = () => reconcileProviderGraph('legacy-write');++/** The sanitized `GET /api/providers/management` body. */+export async function getManagementGraph() {+ requireGraph();+ const [graph, data] = await Promise.all([readGraph(), providerService().getAllProviders()]);+ return toManagementGraphDto({ ...graph, activeProvider: data.activeProvider });+}++// --- link / unlink -----------------------------------------------------------++const requireGraph = () => {+ if (!graphEnabled) {+ throw new ServerError('Provider connection graph is unavailable on this install', { status: 503, code: 'PROVIDER_GRAPH_UNAVAILABLE' });+ }+};++const stale = (what) => new ServerError(+ `${what} changed since the preview was taken; take a new preview`,+ { status: 409, code: 'PROVIDER_GRAPH_STALE_REVISION' });++/**+ * Resolve and revision-check every row a link touches.+ *+ * All three revisions are checked -- binding, source connection and target+ * connection -- because a link is a decision about a difference the human just+ * reviewed. Any of the three moving invalidates that review, so a stale one is+ * a 409 requiring a fresh preview rather than a last-writer merge.+ */+async function resolveLink({ bindingId, targetConnectionId = null, expectedRevisions = {} }) {+ requireGraph();+ const graph = await readGraph();+ const binding = graph.bindings.find((candidate) => candidate.id === bindingId);+ if (!binding) throw new ServerError('Binding not found', { status: 404, code: 'BINDING_NOT_FOUND' });+ const source = graph.connections.find((candidate) => candidate.id === binding.connectionId) || null;+ const target = targetConnectionId+ ? graph.connections.find((candidate) => candidate.id === targetConnectionId) || null+ : null;+ if (targetConnectionId && !target) throw new ServerError('Connection not found', { status: 404, code: 'CONNECTION_NOT_FOUND' });+ if (target && target.id === binding.connectionId) {+ throw new ServerError('That binding already uses this connection', { status: 409, code: 'PROVIDER_GRAPH_ALREADY_LINKED' });+ }++ // A route mid-projection is precisely the state where the graph and the file+ // disagree, so a link decided against it would be decided against unknown+ // values. Refuse until reconciliation settles it.+ if (graph.routes.some((route) => route.bindingId === bindingId && route.pending)) {+ throw new ServerError('This binding has an unresolved projection and cannot be changed yet',+ { status: 409, code: 'PROVIDER_GRAPH_BINDING_BLOCKED' });+ }++ if (expectedRevisions.binding !== undefined && expectedRevisions.binding !== binding.revision) throw stale('The binding');+ if (expectedRevisions.sourceConnection !== undefined && expectedRevisions.sourceConnection !== source?.revision) {+ throw stale('The source connection');+ }+ if (target && expectedRevisions.targetConnection !== undefined && expectedRevisions.targetConnection !== target.revision) {+ throw stale('The target connection');+ }+ return { graph, binding, source, target };+}++/** A connection row in the shape the endpoint comparator expects. */+const asProfile = (connection) => ({+ kind: connection.kind,+ protocol: Object.keys(connection.transports)[0] || null,+ transports: connection.transports,+ credentials: connection.credentials,+});++/**+ * What linking this binding into `targetConnectionId` would change.+ *+ * Read-only and secret-free: the caller learns WHICH routes move, how the two+ * backends differ (protocol / credentials / catalog), and which variant key the+ * binding would land on -- never a credential, and never a comparison the+ * browser could make itself.+ */+export async function previewBindingLink(input) {+ const { graph, binding, source, target } = await resolveLink(input);+ const routes = graph.routes.filter((route) => route.bindingId === binding.id);+ const { differences } = compareBackendEndpoints(asProfile(source), asProfile(target));+ const catalogDiffers = source.catalog.models.join(' ') !== target.catalog.models.join(' ');++ return {+ bindingId: binding.id,+ revisions: { binding: binding.revision, sourceConnection: source.revision, targetConnection: target.revision },+ affectedRouteIds: routes.map((route) => route.providerId),+ variantKey: allocateVariantKey(graph, target.id, binding),+ differences: catalogDiffers ? [...differences, 'catalog'] : differences,+ // Union by canonical identity -- linking never drops a model either side saw.+ unionModels: [...new Set([...source.catalog.models, ...target.catalog.models])],+ // Applying is an explicit second call; a preview changes nothing.+ requiresConfirmation: true,+ };+}++/**+ * The variant key `binding` may occupy on `connectionId`.+ *+ * `default` when free; otherwise a distinct labeled variant. Never a merge:+ * two harness configurations sharing one connection are both legitimate, and+ * collapsing them would discard one side's executable route ids.+ */+function allocateVariantKey(graph, connectionId, binding) {+ const taken = new Set(graph.bindings+ .filter((candidate) => candidate.connectionId === connectionId+ && candidate.harnessId === binding.harnessId+ && candidate.id !== binding.id)+ .map((candidate) => candidate.variantKey));+ return taken.has('default') ? `variant:${binding.id}` : 'default';+}++/**+ * Repoint one binding at an existing connection, then project the target's+ * connection-owned values into that binding's executable routes.+ *+ * Route ids, `activeProvider`, task pins and fallback references are untouched+ * -- only the backend those routes reach changes, which is the whole point of a+ * link. The projection runs through the pending-snapshot protocol so an+ * interrupted file write is recoverable.+ */+export function linkBinding(input) {+ return serialize(async () => {+ const { graph, binding, target } = await resolveLink(input);+ const routes = graph.routes.filter((route) => route.bindingId === binding.id);+ await relinkBinding({ bindingId: binding.id, connectionId: target.id });+ const applied = await projectRoutes(routes.map((route) => route.providerId), target);+ console.log(`🔗 Linked binding ${binding.id} to connection ${target.id} (${applied.length} routes projected)`);+ return { bindingId: binding.id, connectionId: target.id, affectedRouteIds: applied };+ });+}++/**+ * Give this binding its own copy of the connection it currently shares.+ *+ * The clone keeps the transports, credentials and catalog, so nothing about+ * execution changes and no route needs rewriting; only the graph edge moves.+ * Route ids and every mode setting are retained by construction.+ */+export function unlinkBinding(input) {+ return serialize(async () => {+ const { binding, source } = await resolveLink({ ...input, targetConnectionId: null });+ const connection = { ...source, id: randomUUID(), revision: 1 };+ await detachBindingToConnection({ bindingId: binding.id, connection });+ console.log(`🔗 Unlinked binding ${binding.id} onto its own connection ${connection.id}`);+ return { bindingId: binding.id, connectionId: connection.id };+ });+}++/**+ * Delete a connection nothing binds any more.+ *+ * Reconciliation deliberately KEEPS an emptied connection rather than+ * garbage-collecting it — a backend the user configured is not something to+ * remove because a route was temporarily deleted. This is the explicit cleanup+ * that keeps them from accumulating forever, and it is refused while a binding+ * still names the row: unlink first, so no binding is ever silently orphaned.+ */+export async function removeConnection(connectionId) {+ requireGraph();+ return serialize(async () => {+ const result = await deleteConnection(connectionId);+ if (!result.deleted) {+ throw new ServerError('Unlink the bindings that use this connection first',+ { status: 409, code: 'PROVIDER_GRAPH_CONNECTION_IN_USE' });+ }+ console.log(`🔗 Deleted unused provider connection ${connectionId}`);+ return result;+ });+}++/**+ * Stage, write, acknowledge -- the three-step projection the crash-recovery+ * contract depends on. Never call the steps separately.+ */+async function projectRoutes(providerIds, connection) {+ const { providers } = await providerService().getAllProviders();+ const byId = new Map(providers.map((provider) => [provider.id, provider]));+ const projections = providerIds+ .filter((providerId) => byId.has(providerId))+ .map((providerId) => ({ providerId, owned: ownedFromConnection(byId.get(providerId), connection) }));+ if (projections.length === 0) return [];++ await commitPendingProjection(projections);+ reconciling = true;+ const written = await providerService().applyProviderPatches(Object.fromEntries(+ projections.map(({ providerId, owned }) => [providerId, projectionPatch(byId.get(providerId), owned)]),+ )).finally(() => { reconciling = false; });+ await acknowledgeProjection(written);+ return written;+}++/**+ * The connection-owned snapshot a route should carry once bound to+ * `connection`: the record's own owned KEY SET (so the split stays lossless for+ * this record's shape) filled with the connection's values.+ */+function ownedFromConnection(provider, connection) {+ const owned = connectionOwnedSnapshot(provider);+ const baseUrl = Object.values(connection.transports)[0]?.baseUrl ?? null;+ const fields = { ...owned.fields };+ if (Object.hasOwn(fields, 'endpoint') && baseUrl !== null) fields.endpoint = baseUrl;+ if (Object.hasOwn(fields, 'apiKey')) fields.apiKey = connection.credentials.apiKey ?? fields.apiKey;+ const envVars = { ...owned.envVars };+ for (const name of Object.keys(envVars)) {+ if (Object.hasOwn(connection.credentials, name)) {+ envVars[name] = connection.credentials[name];+ continue;+ }+ // `ANTHROPIC_BASE_URL` names the anthropic transport, not merely "a URL":+ // a connection that speaks several protocols has a different base URL for+ // each, and picking the first would point the harness at the wrong port.+ const protocol = /_BASE_URL$/.test(name) ? name.replace(/_BASE_URL$/, '').toLowerCase() : null;+ const url = protocol ? connection.transports[protocol]?.baseUrl ?? baseUrl : null;+ if (url) envVars[name] = url;+ }+ return { fields, envVars, hasEnvVars: owned.hasEnvVars };+}diff --git a/server/services/providerGraph.test.js b/server/services/providerGraph.test.jsnew file mode 100644index 0000000000..e25bd01262--- /dev/null+++ b/server/services/providerGraph.test.js@@ -0,0 +1,280 @@+/**+ * The provider-graph orchestration contract (#6367): projection ordering,+ * re-entrancy, and the revision gate on link/unlink.+ *+ * The reconciliation POLICY is pinned purely in+ * `server/lib/providerGraphRecords.test.js` and the row constraints in+ * `providerGraphStore.db.test.js`. What is only observable HERE is sequencing:+ * that a projection stages before it writes and acknowledges only after, that a+ * projection's own provider-file write cannot recurse back into a reconcile+ * pass, and that a link refuses stale or blocked state before it touches a row.+ *+ * Fixtures are synthetic. Nothing here is read out of a running install.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const store = {+ readGraph: vi.fn(),+ applyReconciliation: vi.fn().mockResolvedValue(undefined),+ commitPendingProjection: vi.fn().mockResolvedValue(undefined),+ acknowledgeProjection: vi.fn().mockResolvedValue(undefined),+ relinkBinding: vi.fn().mockResolvedValue(undefined),+ deleteConnection: vi.fn(),+ detachBindingToConnection: vi.fn().mockResolvedValue(undefined),+};+vi.mock('./providerGraphStore.js', () => store);++const providers = {+ getAllProviders: vi.fn(),+ applyProviderPatches: vi.fn(),+};+vi.mock('../lib/aiToolkitState.js', () => ({+ requireToolkit: () => ({ services: { providers } }),+}));++const graph = await import('./providerGraph.js');++const CONN_A = '11111111-1111-4111-8111-111111111111';+const CONN_B = '22222222-2222-4222-8222-222222222222';+const BINDING = '33333333-3333-4333-8333-333333333333';++const connection = (id, baseUrl) => ({+ id,+ revision: 1,+ kind: 'ollama',+ label: 'Example daemon',+ transports: { anthropic: { baseUrl } },+ credentials: { ANTHROPIC_AUTH_TOKEN: `token-for-${id}` },+ catalog: { state: 'known', models: ['example-model'] },+});++const CLAUDE = {+ id: 'claude-ollama',+ name: 'Claude',+ type: 'cli',+ command: 'claude',+ // Makes the record's connection kind 'ollama', matching the fixture rows.+ ollamaBacked: true,+ enabled: true,+ models: ['example-model'],+ // Matches connection CONN_A exactly, so the baseline is a settled graph.+ envVars: { ANTHROPIC_BASE_URL: `http://127.0.0.1:11434`, ANTHROPIC_AUTH_TOKEN: `token-for-${CONN_A}` },+ secretEnvVars: ['ANTHROPIC_AUTH_TOKEN'],+};++const graphFixture = () => ({+ connections: [connection(CONN_A, 'http://127.0.0.1:11434'), connection(CONN_B, 'http://127.0.0.1:12345')],+ bindings: [{+ id: BINDING, revision: 1, connectionId: CONN_A, harnessId: 'claude',+ variantKey: 'default', label: 'Claude', enabled: true, selectedModels: ['example-model'],+ }],+ routes: [{+ providerId: 'claude-ollama', bindingId: BINDING, mode: 'cli',+ modelMap: { 'example-model': 'example-model' },+ projected: { fields: {}, envVars: { ...CLAUDE.envVars }, hasEnvVars: true },+ pending: null, pendingRevision: null,+ }],+});++beforeEach(async () => {+ vi.clearAllMocks();+ graph.resetProviderGraphState();+ store.readGraph.mockResolvedValue(graphFixture());+ providers.getAllProviders.mockResolvedValue({+ activeProvider: 'claude-ollama',+ providers: [structuredClone(CLAUDE)],+ });+ providers.applyProviderPatches.mockImplementation(async (patches) => Object.keys(patches));+ vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(console, 'error').mockImplementation(() => {});+});++afterEach(() => vi.restoreAllMocks());++describe('before the database phase enables the graph', () => {+ it('a legacy provider save does nothing at all', async () => {+ expect(await graph.onProvidersSaved()).toBeNull();+ expect(store.readGraph).not.toHaveBeenCalled();+ });++ it('the management read answers unavailable rather than an empty graph', async () => {+ await expect(graph.getManagementGraph()).rejects.toMatchObject({ code: 'PROVIDER_GRAPH_UNAVAILABLE' });+ });++ it('a link is refused rather than silently queued', async () => {+ await expect(graph.linkBinding({ bindingId: BINDING, targetConnectionId: CONN_B }))+ .rejects.toMatchObject({ code: 'PROVIDER_GRAPH_UNAVAILABLE' });+ expect(store.relinkBinding).not.toHaveBeenCalled();+ });+});++describe('reconciliation', () => {+ it('is a no-op pass when the file and the graph already agree', async () => {+ await graph.initProviderGraph();+ expect(store.applyReconciliation).not.toHaveBeenCalled();+ expect(providers.applyProviderPatches).not.toHaveBeenCalled();+ });++ it('retries an interrupted projection, then acknowledges it in the same plan', async () => {+ const fixture = graphFixture();+ fixture.routes[0].pending = {+ fields: {},+ envVars: { ...CLAUDE.envVars, ANTHROPIC_BASE_URL: 'http://127.0.0.1:12345' },+ hasEnvVars: true,+ };+ store.readGraph.mockResolvedValue(fixture);++ await graph.initProviderGraph();++ expect(providers.applyProviderPatches).toHaveBeenCalledWith({+ 'claude-ollama': { envVars: { ...CLAUDE.envVars, ANTHROPIC_BASE_URL: 'http://127.0.0.1:12345' } },+ });+ // Acknowledged only because the retry write succeeded.+ expect(store.applyReconciliation.mock.calls[0][0].acknowledgements)+ .toEqual([{ providerId: 'claude-ollama' }]);+ });++ it('does not recurse when its own retry write fires the legacy save hook', async () => {+ // The retry goes through the toolkit, which calls onProvidersSaved — the+ // latch is the only thing between that and an infinite reconcile loop.+ const fixture = graphFixture();+ fixture.routes[0].pending = { fields: {}, envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:12345' }, hasEnvVars: true };+ store.readGraph.mockResolvedValue(fixture);+ providers.applyProviderPatches.mockImplementation(async (patches) => {+ await graph.onProvidersSaved();+ return Object.keys(patches);+ });++ await graph.initProviderGraph();+ expect(store.readGraph).toHaveBeenCalledTimes(1);+ });++ it('leaves an externally changed route untouched and logs it', async () => {+ const fixture = graphFixture();+ fixture.routes[0].pending = { fields: {}, envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:12345' }, hasEnvVars: true };+ store.readGraph.mockResolvedValue(fixture);+ providers.getAllProviders.mockResolvedValue({+ activeProvider: 'claude-ollama',+ // A third value: neither the projected snapshot nor the pending one.+ providers: [{ ...structuredClone(CLAUDE), envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:7777' } }],+ });++ await graph.initProviderGraph();+ expect(providers.applyProviderPatches).not.toHaveBeenCalled();+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('changed outside the graph'));+ });++ it('a legacy save runs one pass once the graph is enabled', async () => {+ await graph.initProviderGraph();+ store.readGraph.mockClear();+ await graph.onProvidersSaved();+ expect(store.readGraph).toHaveBeenCalledTimes(1);+ });+});++describe('linking', () => {+ beforeEach(() => graph.initProviderGraph());++ it('previews the difference without writing anything', async () => {+ const preview = await graph.previewBindingLink({ bindingId: BINDING, targetConnectionId: CONN_B });++ expect(preview.affectedRouteIds).toEqual(['claude-ollama']);+ expect(preview.revisions).toEqual({ binding: 1, sourceConnection: 1, targetConnection: 1 });+ expect(preview.requiresConfirmation).toBe(true);+ // Secrets never reach a preview; the browser learns only THAT they differ.+ expect(JSON.stringify(preview)).not.toContain('token-for-');+ expect(store.relinkBinding).not.toHaveBeenCalled();+ });++ it('stages the projection, writes the file, and acknowledges only then', async () => {+ const order = [];+ store.commitPendingProjection.mockImplementation(async () => { order.push('stage'); });+ providers.applyProviderPatches.mockImplementation(async (patches) => { order.push('write'); return Object.keys(patches); });+ store.acknowledgeProjection.mockImplementation(async () => { order.push('acknowledge'); });++ const result = await graph.linkBinding({+ bindingId: BINDING, targetConnectionId: CONN_B,+ expectedRevisions: { binding: 1, sourceConnection: 1, targetConnection: 1 },+ });++ expect(order).toEqual(['stage', 'write', 'acknowledge']);+ expect(result).toEqual({ bindingId: BINDING, connectionId: CONN_B, affectedRouteIds: ['claude-ollama'] });+ // The route keeps its executable id; only the backend it reaches moves.+ expect(providers.applyProviderPatches.mock.calls[0][0]['claude-ollama'].envVars).toEqual({+ ANTHROPIC_BASE_URL: 'http://127.0.0.1:12345',+ ANTHROPIC_AUTH_TOKEN: 'token-for-22222222-2222-4222-8222-222222222222',+ });+ });++ it.each([+ ['binding', { binding: 9, sourceConnection: 1, targetConnection: 1 }],+ ['source connection', { binding: 1, sourceConnection: 9, targetConnection: 1 }],+ ['target connection', { binding: 1, sourceConnection: 1, targetConnection: 9 }],+ ])('refuses a stale %s revision before any row is touched', async (_label, expectedRevisions) => {+ await expect(graph.linkBinding({ bindingId: BINDING, targetConnectionId: CONN_B, expectedRevisions }))+ .rejects.toMatchObject({ status: 409, code: 'PROVIDER_GRAPH_STALE_REVISION' });+ expect(store.relinkBinding).not.toHaveBeenCalled();+ });++ it('refuses a binding whose projection is still unsettled', async () => {+ const fixture = graphFixture();+ fixture.routes[0].pending = { fields: {}, envVars: {}, hasEnvVars: true };+ store.readGraph.mockResolvedValue(fixture);++ await expect(graph.linkBinding({ bindingId: BINDING, targetConnectionId: CONN_B }))+ .rejects.toMatchObject({ code: 'PROVIDER_GRAPH_BINDING_BLOCKED' });+ });++ it('allocates a distinct variant when the target already has this harness on default', async () => {+ const fixture = graphFixture();+ fixture.bindings.push({+ id: '44444444-4444-4444-8444-444444444444', revision: 1, connectionId: CONN_B,+ harnessId: 'claude', variantKey: 'default', label: 'Other Claude', enabled: true, selectedModels: [],+ });+ store.readGraph.mockResolvedValue(fixture);++ const preview = await graph.previewBindingLink({ bindingId: BINDING, targetConnectionId: CONN_B });+ expect(preview.variantKey).toBe(`variant:${BINDING}`);+ });++ it('refuses a link a binding already has', async () => {+ await expect(graph.linkBinding({ bindingId: BINDING, targetConnectionId: CONN_A }))+ .rejects.toMatchObject({ code: 'PROVIDER_GRAPH_ALREADY_LINKED' });+ });+});++describe('unlinking', () => {+ beforeEach(() => graph.initProviderGraph());++ it('clones the shared connection under a new id and rewrites no route', async () => {+ const result = await graph.unlinkBinding({ bindingId: BINDING, expectedRevisions: { binding: 1 } });++ expect(result.bindingId).toBe(BINDING);+ expect(result.connectionId).not.toBe(CONN_A);+ 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, so the provider file is not touched.+ expect(providers.applyProviderPatches).not.toHaveBeenCalled();+ });++ it('refuses an unknown binding', async () => {+ await expect(graph.unlinkBinding({ bindingId: CONN_B })).rejects.toMatchObject({ code: 'BINDING_NOT_FOUND' });+ });+});++describe('deleting an emptied connection', () => {+ beforeEach(() => graph.initProviderGraph());++ it('removes a connection nothing binds', async () => {+ store.deleteConnection.mockResolvedValue({ deleted: true });+ expect(await graph.removeConnection(CONN_B)).toEqual({ deleted: true });+ });++ it('refuses while a binding still names it, rather than orphaning the binding', async () => {+ store.deleteConnection.mockResolvedValue({ deleted: false, reason: 'referenced-by-binding' });+ await expect(graph.removeConnection(CONN_A))+ .rejects.toMatchObject({ status: 409, code: 'PROVIDER_GRAPH_CONNECTION_IN_USE' });+ });+});diff --git a/server/services/providerGraphStore.db.test.js b/server/services/providerGraphStore.db.test.jsnew file mode 100644index 0000000000..44399b28c0--- /dev/null+++ b/server/services/providerGraphStore.db.test.js@@ -0,0 +1,238 @@+/**+ * Postgres round-trip for the provider connection graph (#6367).+ *+ * The reconciliation POLICY is pinned without a database in+ * `server/lib/providerGraphRecords.test.js`; what needs a real Postgres is the+ * part only Postgres enforces — the two partial unique indexes that keep+ * duplicate bindings out (a plain UNIQUE over a nullable `harness_id` would not,+ * because NULL never equals NULL), the `(binding_id, mode)` uniqueness, the+ * foreign keys that refuse an orphan, and the JSONB round-trip of a projection+ * snapshot.+ *+ * Runs via `npm run test:db` (→ `portos_test`) ONLY; the guards in+ * `server/lib/db.js` refuse row writes to a non-test database. Skips cleanly+ * when no database is reachable.+ */++import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';+import { randomUUID } from 'node:crypto';+import { checkHealth, close, ensureSchema, query } from '../lib/db.js';+import { requireDbOrSkip } from '../lib/dbTestGate.js';++let dbReady = false;+let skipReason = '';+{+ const health = await checkHealth().catch((err) => ({ connected: false, error: err?.message }));+ if (!health.connected) {+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;+ } else {+ await ensureSchema().catch(() => {});+ const probe = await query(+ "SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'ai_route_bindings') AS ok",+ ).catch(() => ({ rows: [{ ok: false }] }));+ if (probe.rows?.[0]?.ok) dbReady = true;+ else skipReason = 'ai_route_bindings table not present';+ }+}++const runDb = requireDbOrSkip('services/providerGraphStore.db.test', dbReady, skipReason);++const connection = (overrides = {}) => ({+ id: randomUUID(),+ revision: 1,+ kind: 'ollama',+ label: 'Example local daemon',+ transports: { anthropic: { baseUrl: 'http://127.0.0.1:11434' } },+ credentials: { ANTHROPIC_AUTH_TOKEN: 'example-token' },+ catalog: { state: 'known', models: ['example-model'] },+ ...overrides,+});++const binding = (connectionId, overrides = {}) => ({+ id: randomUUID(),+ revision: 1,+ connectionId,+ harnessId: 'claude',+ variantKey: 'default',+ label: 'Claude',+ enabled: true,+ selectedModels: ['example-model'],+ ...overrides,+});++const route = (bindingId, providerId, overrides = {}) => ({+ providerId,+ bindingId,+ mode: 'cli',+ modelMap: { 'example-model': 'example-model' },+ projected: { fields: {}, envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:11434' }, hasEnvVars: true },+ pending: null,+ pendingRevision: null,+ ...overrides,+});++describe.skipIf(!runDb)('ai_* connection graph store', () => {+ let store;++ beforeAll(async () => {+ store = await import('./providerGraphStore.js');+ });++ beforeEach(async () => {+ await query('DELETE FROM ai_route_bindings');+ await query('DELETE FROM ai_harness_bindings');+ await query('DELETE FROM ai_connections');+ });++ afterAll(async () => {+ await query('DELETE FROM ai_route_bindings').catch(() => {});+ await query('DELETE FROM ai_harness_bindings').catch(() => {});+ await query('DELETE FROM ai_connections').catch(() => {});+ await close();+ });++ it('round-trips a whole graph, JSONB snapshots included', async () => {+ const conn = connection();+ const bind = binding(conn.id);+ await store.writeGraph({ connections: [conn], bindings: [bind], routes: [route(bind.id, 'claude-ollama')] });++ const read = await store.readGraph();+ expect(read.connections[0]).toMatchObject({+ id: conn.id, kind: 'ollama', transports: conn.transports, credentials: conn.credentials, catalog: conn.catalog,+ });+ expect(read.bindings[0]).toMatchObject({ id: bind.id, connectionId: conn.id, harnessId: 'claude', enabled: true });+ expect(read.routes[0]).toMatchObject({+ providerId: 'claude-ollama', bindingId: bind.id, mode: 'cli', pending: null,+ });+ // The projection snapshot must survive verbatim — it is the value a crash+ // recovery compares the provider file against.+ expect(read.routes[0].projected).toEqual(route(bind.id, 'x').projected);+ });++ it('refuses two routes on one binding in the same mode', async () => {+ const conn = connection();+ const bind = binding(conn.id);+ await store.writeGraph({ connections: [conn], bindings: [bind], routes: [route(bind.id, 'claude-ollama')] });++ await expect(store.writeGraph({+ connections: [], bindings: [], routes: [route(bind.id, 'claude-ollama-duplicate')],+ })).rejects.toThrow(/uq_ai_route_bindings_binding_mode|duplicate key/i);+ });++ it('refuses a duplicate default binding for one harness on one connection', async () => {+ const conn = connection();+ await store.writeGraph({ connections: [conn], bindings: [binding(conn.id)], routes: [] });+ await query('INSERT INTO ai_harness_bindings (id, connection_id, harness_id, variant_key) VALUES ($1, $2, $3, $4)',+ [randomUUID(), conn.id, 'claude', 'variant:other']); // a distinct variant is fine++ await expect(query(+ 'INSERT INTO ai_harness_bindings (id, connection_id, harness_id, variant_key) VALUES ($1, $2, $3, $4)',+ [randomUUID(), conn.id, 'claude', 'default'],+ )).rejects.toThrow(/uq_ai_harness_bindings_variant|duplicate key/i);+ });++ it('refuses a duplicate default API binding, which a nullable UNIQUE would allow', async () => {+ // NULL != NULL in a plain UNIQUE constraint, so without the partial index+ // an install could accumulate unlimited duplicate direct-API bindings.+ const conn = connection();+ await store.writeGraph({ connections: [conn], bindings: [], routes: [] });+ await query('INSERT INTO ai_harness_bindings (id, connection_id, harness_id, variant_key) VALUES ($1, $2, NULL, $3)',+ [randomUUID(), conn.id, 'default']);++ await expect(query(+ 'INSERT INTO ai_harness_bindings (id, connection_id, harness_id, variant_key) VALUES ($1, $2, NULL, $3)',+ [randomUUID(), conn.id, 'default'],+ )).rejects.toThrow(/uq_ai_harness_bindings_api_variant|duplicate key/i);+ });++ it('refuses to delete a connection a binding still names, and allows the orphan', async () => {+ const conn = connection();+ const bind = binding(conn.id);+ await store.writeGraph({ connections: [conn], bindings: [bind], routes: [] });++ expect(await store.deleteConnection(conn.id)).toEqual({ deleted: false, reason: 'referenced-by-binding' });+ await query('DELETE FROM ai_harness_bindings WHERE id = $1', [bind.id]);+ expect(await store.deleteConnection(conn.id)).toEqual({ deleted: true });+ });++ it('stages, then acknowledges, a projection', async () => {+ const conn = connection();+ const bind = binding(conn.id);+ await store.writeGraph({ connections: [conn], bindings: [bind], routes: [route(bind.id, 'claude-ollama')] });+ const owned = { fields: {}, envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:12345' }, hasEnvVars: true };++ await store.commitPendingProjection([{ providerId: 'claude-ollama', owned }]);+ let read = await store.readGraph();+ expect(read.routes[0].pending).toEqual(owned);+ // Staging bumps the binding revision so a concurrent link sees a stale one.+ expect(read.bindings[0].revision).toBe(2);+ expect(read.routes[0].pendingRevision).toBe(2);++ await store.acknowledgeProjection(['claude-ollama']);+ read = await store.readGraph();+ expect(read.routes[0].pending).toBeNull();+ expect(read.routes[0].projected).toEqual(owned);+ });++ it('applies a reconciliation plan atomically: remove, clone, re-snapshot, import', async () => {+ const conn = connection();+ const bind = binding(conn.id);+ await store.writeGraph({+ connections: [conn],+ bindings: [bind],+ routes: [route(bind.id, 'claude-ollama'), route(bind.id, 'claude-ollama-tui', { mode: 'tui' })],+ });++ const cloned = connection({ transports: { anthropic: { baseUrl: 'http://127.0.0.1:12345' } } });+ const importedConnection = connection({ kind: 'api', credentials: {} });+ const importedBinding = binding(importedConnection.id, { harnessId: null, label: 'Remote' });+ const moved = { fields: {}, envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:12345' }, hasEnvVars: true };++ await store.applyReconciliation({+ removals: ['claude-ollama-tui'],+ regroups: [{+ routeIds: ['claude-ollama'], bindingId: bind.id, binding: null,+ connectionAction: 'clone', connection: cloned,+ }],+ snapshots: [{ providerId: 'claude-ollama', owned: moved }],+ acknowledgements: [],+ conflicts: [],+ imports: {+ connections: [importedConnection],+ bindings: [importedBinding],+ routes: [route(importedBinding.id, 'remote-ollama', { mode: 'api' })],+ },+ });++ const read = await store.readGraph();+ expect(read.routes.map((row) => row.providerId).sort()).toEqual(['claude-ollama', 'remote-ollama']);+ expect(read.bindings.find((row) => row.id === bind.id).connectionId).toBe(cloned.id);+ expect(read.routes.find((row) => row.providerId === 'claude-ollama').projected).toEqual(moved);+ // The original connection row is kept for explicit cleanup, not deleted.+ expect(read.connections.map((row) => row.id)).toContain(conn.id);+ });++ it('rolls the whole plan back when one statement fails', async () => {+ const conn = connection();+ const bind = binding(conn.id);+ await store.writeGraph({ connections: [conn], bindings: [bind], routes: [route(bind.id, 'claude-ollama')] });++ await expect(store.applyReconciliation({+ removals: [],+ regroups: [],+ snapshots: [],+ acknowledgements: [],+ conflicts: [],+ // A binding pointing at a connection that does not exist: the FK rejects+ // it, and the route insert before it must not survive.+ imports: {+ connections: [],+ bindings: [binding(randomUUID(), { id: randomUUID() })],+ routes: [],+ },+ })).rejects.toThrow();++ const read = await store.readGraph();+ expect(read.bindings).toHaveLength(1);+ });+});diff --git a/server/services/providerGraphStore.js b/server/services/providerGraphStore.jsnew file mode 100644index 0000000000..2376217588--- /dev/null+++ b/server/services/providerGraphStore.js@@ -0,0 +1,249 @@+import { query, withTransaction } from '../lib/db.js';++/**+ * Postgres adapter for the provider connection graph — `ai_connections`,+ * `ai_harness_bindings`, `ai_route_bindings` (#6367).+ *+ * db-primary per `docs/STORAGE.md`: app-native relational identities with real+ * foreign keys, not an externally edited file. **Machine-local — never+ * federated**: every row names this host's endpoints, credentials and execution+ * environment (ADR `docs/decisions/2026-08-08-privacy-records-machine-local.md`).+ * No `sync_sequence`, no tombstones, no `PORTOS_SCHEMA_VERSIONS` entry. Covered+ * by the normal Postgres dump in backup, like every other db-primary table.+ *+ * This module is only row I/O and revision checks. The projection engine, the+ * reconciliation policy and the serialization against legacy provider writes+ * all live in `providerGraph.js`; the pure planning lives in+ * `server/lib/providerGraphRecords.js`. Keeping the split means the interesting+ * decisions are testable without a database.+ *+ * Every write here runs inside one transaction, so a graph revision and its+ * pending projection snapshot commit together or not at all — that atomicity is+ * what makes an interrupted file write recoverable rather than ambiguous.+ */++const connectionRow = (row) => ({+ id: row.id,+ revision: row.revision,+ kind: row.kind,+ label: row.label,+ transports: row.transports || {},+ credentials: row.credentials || {},+ catalog: row.catalog || { state: 'unknown', models: [] },+});++const bindingRow = (row) => ({+ id: row.id,+ revision: row.revision,+ connectionId: row.connection_id,+ harnessId: row.harness_id,+ variantKey: row.variant_key,+ label: row.label,+ enabled: row.enabled,+ selectedModels: row.selected_models || [],+});++const routeRow = (row) => ({+ providerId: row.provider_id,+ bindingId: row.binding_id,+ mode: row.mode,+ modelMap: row.model_map || {},+ projected: row.projected || {},+ pending: row.pending ?? null,+ pendingRevision: row.pending_revision ?? null,+});++/** The whole graph. Small by nature — one row per configured route. */+export async function readGraph() {+ const [connections, bindings, routes] = await Promise.all([+ query('SELECT * FROM ai_connections ORDER BY created_at, id'),+ query('SELECT * FROM ai_harness_bindings ORDER BY created_at, id'),+ query('SELECT * FROM ai_route_bindings ORDER BY provider_id'),+ ]);+ return {+ connections: connections.rows.map(connectionRow),+ bindings: bindings.rows.map(bindingRow),+ routes: routes.rows.map(routeRow),+ };+}++const upsertConnection = (client, connection) => client.query(+ `INSERT INTO ai_connections (id, revision, kind, label, transports, credentials, catalog, updated_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, NOW())+ ON CONFLICT (id) DO UPDATE SET+ revision = ai_connections.revision + 1,+ kind = EXCLUDED.kind, label = EXCLUDED.label,+ transports = EXCLUDED.transports, credentials = EXCLUDED.credentials,+ catalog = EXCLUDED.catalog, updated_at = NOW()`,+ [connection.id, connection.revision ?? 1, connection.kind, connection.label ?? '',+ JSON.stringify(connection.transports || {}), JSON.stringify(connection.credentials || {}),+ JSON.stringify(connection.catalog || { state: 'unknown', models: [] })],+);++const upsertBinding = (client, binding) => client.query(+ `INSERT INTO ai_harness_bindings+ (id, revision, connection_id, harness_id, variant_key, label, enabled, selected_models, updated_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW())+ ON CONFLICT (id) DO UPDATE SET+ revision = ai_harness_bindings.revision + 1,+ connection_id = EXCLUDED.connection_id, harness_id = EXCLUDED.harness_id,+ variant_key = EXCLUDED.variant_key, label = EXCLUDED.label,+ enabled = EXCLUDED.enabled, selected_models = EXCLUDED.selected_models, updated_at = NOW()`,+ [binding.id, binding.revision ?? 1, binding.connectionId, binding.harnessId ?? null,+ binding.variantKey, binding.label ?? '', binding.enabled === true,+ JSON.stringify(binding.selectedModels || [])],+);++const upsertRoute = (client, route) => client.query(+ `INSERT INTO ai_route_bindings+ (provider_id, binding_id, mode, model_map, projected, pending, pending_revision, updated_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, NOW())+ ON CONFLICT (provider_id) DO UPDATE SET+ binding_id = EXCLUDED.binding_id, mode = EXCLUDED.mode, model_map = EXCLUDED.model_map,+ projected = EXCLUDED.projected, pending = EXCLUDED.pending,+ pending_revision = EXCLUDED.pending_revision, updated_at = NOW()`,+ [route.providerId, route.bindingId, route.mode, JSON.stringify(route.modelMap || {}),+ JSON.stringify(route.projected || {}),+ route.pending == null ? null : JSON.stringify(route.pending),+ route.pendingRevision ?? null],+);++/**+ * Insert a freshly built graph in one transaction.+ *+ * Writes exactly what it is handed — a fragment with no routes is legitimate+ * (an emptied binding kept for explicit cleanup), so this must not short-circuit+ * on an empty route list.+ */+export async function writeGraph({ connections, bindings, routes }) {+ await withTransaction(async (client) => {+ for (const connection of connections) await upsertConnection(client, connection);+ for (const binding of bindings) await upsertBinding(client, binding);+ for (const route of routes) await upsertRoute(client, route);+ });+ return { connections: connections.length, bindings: bindings.length, routes: routes.length };+}++/**+ * Apply one reconciliation plan atomically.+ *+ * Ordering inside the transaction is load-bearing: connections before the+ * bindings that reference them, bindings before their routes, and route+ * REMOVALS before anything else so a deleted provider's row can never collide+ * with a re-import of the same id.+ *+ * Conflicts are deliberately not applied — a route whose file value matches+ * neither snapshot keeps its `pending` row untouched, which is exactly what+ * marks its binding blocked on the next read.+ */+export async function applyReconciliation(plan) {+ await withTransaction(async (client) => {+ if (plan.removals.length > 0) {+ await client.query('DELETE FROM ai_route_bindings WHERE provider_id = ANY($1::text[])', [plan.removals]);+ }++ for (const regroup of plan.regroups) {+ if (regroup.connectionAction !== 'unchanged') await upsertConnection(client, regroup.connection);+ const bindingId = regroup.binding?.id ?? regroup.bindingId;+ if (regroup.binding) {+ await upsertBinding(client, { ...regroup.binding, connectionId: regroup.connection.id });+ await client.query(+ 'UPDATE ai_route_bindings SET binding_id = $1, updated_at = NOW() WHERE provider_id = ANY($2::text[])',+ [bindingId, regroup.routeIds],+ );+ } else if (regroup.connectionAction === 'clone') {+ await client.query(+ 'UPDATE ai_harness_bindings SET connection_id = $1, revision = revision + 1, updated_at = NOW() WHERE id = $2',+ [regroup.connection.id, bindingId],+ );+ }+ }++ for (const { providerId, owned } of plan.snapshots) {+ await client.query(+ 'UPDATE ai_route_bindings SET projected = $1, updated_at = NOW() WHERE provider_id = $2',+ [JSON.stringify(owned), providerId],+ );+ }++ for (const { providerId } of plan.acknowledgements) {+ await client.query(+ `UPDATE ai_route_bindings+ SET projected = pending, pending = NULL, pending_revision = NULL, updated_at = NOW()+ WHERE provider_id = $1`,+ [providerId],+ );+ }++ for (const connection of plan.imports.connections) await upsertConnection(client, connection);+ for (const binding of plan.imports.bindings) await upsertBinding(client, binding);+ for (const route of plan.imports.routes) await upsertRoute(client, route);+ });+}++/**+ * Stage a projection: bump the named rows' revisions and record the snapshot+ * each route is ABOUT to receive, in one transaction. The file write happens+ * after this returns; {@link acknowledgeProjection} closes the loop.+ */+export async function commitPendingProjection(projections) {+ if (projections.length === 0) return;+ await withTransaction(async (client) => {+ for (const { providerId, owned } of projections) {+ const { rows } = await client.query(+ `UPDATE ai_route_bindings SET pending = $1, updated_at = NOW() WHERE provider_id = $2+ RETURNING binding_id`,+ [JSON.stringify(owned), providerId],+ );+ if (rows.length === 0) continue;+ const { rows: bumped } = await client.query(+ 'UPDATE ai_harness_bindings SET revision = revision + 1, updated_at = NOW() WHERE id = $1 RETURNING revision',+ [rows[0].binding_id],+ );+ await client.query('UPDATE ai_route_bindings SET pending_revision = $1 WHERE provider_id = $2',+ [bumped[0]?.revision ?? null, providerId]);+ }+ });+}++/** Promote every named route's pending snapshot to `projected`. */+export async function acknowledgeProjection(providerIds) {+ if (providerIds.length === 0) return;+ await query(+ `UPDATE ai_route_bindings+ SET projected = COALESCE(pending, projected), pending = NULL, pending_revision = NULL, updated_at = NOW()+ WHERE provider_id = ANY($1::text[])`,+ [providerIds],+ );+}++/** Repoint one binding at another connection. Revision-checked by the caller. */+export async function relinkBinding({ bindingId, connectionId }) {+ await withTransaction(async (client) => {+ await client.query(+ 'UPDATE ai_harness_bindings SET connection_id = $1, revision = revision + 1, updated_at = NOW() WHERE id = $2',+ [connectionId, bindingId],+ );+ await client.query('UPDATE ai_connections SET revision = revision + 1, updated_at = NOW() WHERE id = $1',+ [connectionId]);+ });+}++/** Attach a binding to a freshly cloned connection (the unlink half). */+export async function detachBindingToConnection({ bindingId, connection }) {+ await withTransaction(async (client) => {+ await upsertConnection(client, connection);+ await client.query(+ 'UPDATE ai_harness_bindings SET connection_id = $1, revision = revision + 1, updated_at = NOW() WHERE id = $2',+ [connection.id, bindingId],+ );+ });+}++/** Hard-delete an orphan connection. Refused while a binding still names it. */+export async function deleteConnection(connectionId) {+ const { rows } = await query('SELECT 1 FROM ai_harness_bindings WHERE connection_id = $1 LIMIT 1', [connectionId]);+ if (rows.length > 0) return { deleted: false, reason: 'referenced-by-binding' };+ await query('DELETE FROM ai_connections WHERE id = $1', [connectionId]);+ return { deleted: true };+}diff --git a/server/services/sharing/providerGraphNeverFederates.test.js b/server/services/sharing/providerGraphNeverFederates.test.jsnew file mode 100644index 0000000000..b825e5526c--- /dev/null+++ b/server/services/sharing/providerGraphNeverFederates.test.js@@ -0,0 +1,54 @@+/**+ * Guard: the AI provider connection graph must NEVER federate (#6367).+ *+ * `ai_connections` / `ai_harness_bindings` / `ai_route_bindings` hold this+ * machine's endpoints, credential material, execution environment and the+ * projection snapshots that carry both — exactly the class of record the+ * machine-local ADR (`docs/decisions/2026-08-08-privacy-records-machine-local.md`)+ * keeps off the federation layer. A sender's local connection UUID also cannot+ * identify a receiver's backend, so even the identifiers are meaningless+ * across installs while being dangerous to publish.+ *+ * Blunt on purpose, the same way `privacyNeverFederates.test.js` is: it matches+ * the strings BROADLY, so a future `aiConnection`, `providerGraph` or+ * `harnessBinding` entry trips it whatever it ends up being called. If you are+ * here because this failed, the answer is almost certainly "don't add it" — the+ * design record's "Peer/client boundary" section says a new peer-visible+ * eligibility field is a separately negotiated `schemaVersions.js` change, not+ * a graph kind on the wire.+ */++import { describe, expect, it } from 'vitest';+import { PEER_SUBSCRIBABLE_KINDS } from './peerSyncShared.js';+import { NON_RECORD_SCHEMA_CATEGORIES, PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';+import { aiGraphDdl } from '../../lib/db/schema/aiGraph.js';++const GRAPH_TERMS = /ai_?connection|harness_?binding|route_?binding|provider_?graph/i;+const mentionsGraph = (value) => GRAPH_TERMS.test(String(value));++// Columns that exist only to support cross-instance sync. A graph table that+// grows one is either federating already or being prepared to.+const FEDERATION_COLUMNS = ['sync_sequence', 'deleted_at', 'origin_instance_id'];++const createTableStatements = aiGraphDdl.filter((stmt) => /CREATE TABLE IF NOT EXISTS ai_/i.test(stmt));++describe('the provider connection graph never federates', () => {+ it('exposes no graph kind to peer-sync subscriptions', () => {+ expect(PEER_SUBSCRIBABLE_KINDS.filter(mentionsGraph)).toEqual([]);+ });++ it('declares no graph wire-schema category', () => {+ expect(Object.keys(PORTOS_SCHEMA_VERSIONS).filter(mentionsGraph)).toEqual([]);+ expect([...NON_RECORD_SCHEMA_CATEGORIES].filter(mentionsGraph)).toEqual([]);+ });++ it('gives no graph table a sync cursor, tombstone or origin column', () => {+ // Sanity: a filter that matched nothing would make the loop below vacuous.+ expect(createTableStatements).toHaveLength(3);+ for (const statement of createTableStatements) {+ for (const column of FEDERATION_COLUMNS) {+ expect(statement, `${column} appears in a graph table`).not.toContain(column);+ }+ }+ });+});diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex 1a0cba25ad..9b61ebd27c 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -29,6 +29,7 @@ export const DB_TEST_INCLUDE = ['services/privacyChanges.db.test.js','services/privacyBrokers.db.test.js','services/privacyOptOut.db.test.js',+ 'services/providerGraphStore.db.test.js','services/catalogCanonProjection.test.js','services/catalogRefResolver.test.js','services/creativeDirector/projectsDB.test.js',