Skip to content

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

refactor([issue-3617]): collapse the six provider-seed migrations onto a shared makeProviderSeedMigration factory

[._.]/ Adam Eivy5a645f71cf50
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0fbb461039..d8a12e0010 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -31,3 +31,6 @@
- **The labels on LoRA training dataset images are readable again.** The source chip ("upload", "generated", "sheet crop", "gallery") and the view label ("front three-quarter") were tinted overlays — 20%-opacity color on top of whatever the training image happened to be — so over a bright photo, or under a light theme, the text all but disappeared. They were also pinned to opposite corners of the thumbnail, so a long view label collided with the source chip in a narrow column and the two printed on top of each other. Both chips now carry their own near-opaque plate with light text, and they share one wrapping row so a long label drops to a second line instead of overlapping.
- **The Antigravity code reviewer no longer looks like it isn't installed.** Antigravity's command is `agy`, but every agent prompt named the reviewer by its internal slug, `antigravity` — a command that exists on no machine. A review-loop agent went looking for it, found nothing, concluded there was no reviewer available, reviewed its own work instead, and merged the PR. Prompts now name the actual command, and a reviewer whose command genuinely isn't installed blocks the merge with a note on the PR instead of quietly being replaced by a self-review.
- **Pull requests opened by a CoS agent under a "merge when CI is green" policy now actually get merged.** The check that watches those PRs only ran when an app's optional "PR Watcher" scheduled task fired — and that task ships disabled, since its default prompt is a review-and-comment agent most setups don't want. So PortOS was queueing green PRs into a list nothing ever read: they sat open indefinitely, and because the retry counter never advanced, the safety net that gives up and notifies you after a few hours never fired either. The watch now runs on the normal CoS cadence, independent of that task.
+
+## Internal
+- **The six provider-seed migrations share one shell instead of six copies of it.** Every migration that ships a new AI provider to already-installed setups (OpenCode Ollama, its TUI sibling, Grok, Cerebras, Kimi, Cursor) repeated the same byte-identical read → validate → add-missing-ids → write body, so any hardening of it was a six-file sweep nobody did — and none of the six had picked up the reserved-key guard (`__proto__` / `constructor` / `prototype`) the split-migration family already applies. They now call a shared `makeProviderSeedMigration` factory that carries that guard, and each migration keeps only its own frozen provider payload, since a migration is the historical record of what it installed. Their duplicated shell tests collapse into one suite against the factory; every payload assertion each migration already made still runs unchanged.
diff --git a/scripts/migrations/149-opencode-ollama-providers.js b/scripts/migrations/149-opencode-ollama-providers.js
index c09624d3df..868910e3c9 100644
--- a/scripts/migrations/149-opencode-ollama-providers.js
+++ b/scripts/migrations/149-opencode-ollama-providers.js
@@ -27,10 +27,7 @@
* own migrations rather than mutating this one.
*/
-import { readFile, writeFile } from 'fs/promises';
-import { join } from 'path';
-
-const PROVIDERS_REL_PATH = 'data/providers.json';
+import { makeProviderSeedMigration } from './_lib.js';
// Inline OpenCode config: declare the local Ollama daemon as an
// openai-compatible provider and auto-approve tools (the OpenCode equivalent of
@@ -55,46 +52,7 @@ const OPENCODE_OLLAMA_CLI = {
headlessArgs: [],
};
-export default {
- async up({ rootDir }) {
- const providersPath = join(rootDir, PROVIDERS_REL_PATH);
- const raw = await readFile(providersPath, 'utf-8').catch((err) => {
- if (err.code === 'ENOENT') return null;
- throw err;
- });
- if (raw == null) {
- console.log(`📄 ${PROVIDERS_REL_PATH} not present — skipping (fresh install seeds OpenCode Ollama from data.reference)`);
- return;
- }
-
- let config;
- try {
- config = JSON.parse(raw);
- } catch (err) {
- console.log(`⚠️ ${PROVIDERS_REL_PATH}: invalid JSON, skipping (${err.message})`);
- return;
- }
-
- if (!config || typeof config !== 'object' || !config.providers || typeof config.providers !== 'object') {
- console.log(`⚠️ ${PROVIDERS_REL_PATH}: unexpected shape, skipping`);
- return;
- }
-
- const providers = config.providers;
- let changed = false;
-
- for (const def of [OPENCODE_OLLAMA_CLI]) {
- if (!providers[def.id]) {
- providers[def.id] = { ...def, envVars: { ...def.envVars } };
- changed = true;
- console.log(`📝 ${PROVIDERS_REL_PATH}: added ${def.id} provider`);
- }
- }
-
- if (changed) {
- await writeFile(providersPath, `${JSON.stringify(config, null, 2)}\n`);
- } else {
- console.log(`✅ ${PROVIDERS_REL_PATH}: OpenCode Ollama providers already present — no change`);
- }
- },
-};
+export default makeProviderSeedMigration({
+ label: 'OpenCode Ollama',
+ defs: [OPENCODE_OLLAMA_CLI],
+});
diff --git a/scripts/migrations/149-opencode-ollama-providers.test.js b/scripts/migrations/149-opencode-ollama-providers.test.js
index 963f33d2b3..b3f1b0260e 100644
--- a/scripts/migrations/149-opencode-ollama-providers.test.js
+++ b/scripts/migrations/149-opencode-ollama-providers.test.js
@@ -2,9 +2,14 @@
* Test for migration 149 — add the OpenCode Ollama CLI provider to existing
* installs. Picked up by server/vitest.config.js's
* `../scripts/**\/*.test.js` glob.
+ *
+ * The shell shared by all six provider-seed migrations (read → guard → add
+ * missing ids → conditional write) is asserted once against
+ * `makeProviderSeedMigration` in _lib.test.js; what stays here is this
+ * migration's own frozen payload.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
-import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -60,47 +65,4 @@ describe('migration 149 — OpenCode Ollama providers', () => {
expect(cfg.provider.ollama.npm).toBe('@ai-sdk/openai-compatible');
expect(cfg.provider.ollama.options.baseURL).toBe('http://localhost:11434/v1');
});
-
- it('does not overwrite a user-customized opencode-ollama entry', async () => {
- writeJson(providersPath, {
- providers: {
- 'opencode-ollama': {
- id: 'opencode-ollama', type: 'cli', command: 'opencode',
- enabled: true, models: ['qwen2.5-coder:32b'], defaultModel: 'qwen2.5-coder:32b',
- },
- },
- });
-
- await migration.up({ rootDir });
-
- const out = readJson(providersPath);
- // existing CLI entry preserved untouched
- expect(out.providers['opencode-ollama'].enabled).toBe(true);
- expect(out.providers['opencode-ollama'].models).toEqual(['qwen2.5-coder:32b']);
- });
-
- it('is idempotent — a second run makes no changes', async () => {
- writeJson(providersPath, {
- providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },
- });
-
- await migration.up({ rootDir });
- const afterFirst = readFileSync(providersPath, 'utf-8');
- await migration.up({ rootDir });
- expect(readFileSync(providersPath, 'utf-8')).toBe(afterFirst);
- });
-
- it('is a no-op when data/providers.json does not exist (fresh install)', async () => {
- await migration.up({ rootDir });
- expect(existsSync(providersPath)).toBe(false);
- });
-
- it('does not modify the file on invalid JSON', async () => {
- writeFileSync(providersPath, '{ not valid json');
- const before = readFileSync(providersPath, 'utf-8');
-
- await migration.up({ rootDir });
-
- expect(readFileSync(providersPath, 'utf-8')).toBe(before);
- });
});
diff --git a/scripts/migrations/152-opencode-ollama-tui-provider.js b/scripts/migrations/152-opencode-ollama-tui-provider.js
index 1548c818e0..80b6956744 100644
--- a/scripts/migrations/152-opencode-ollama-tui-provider.js
+++ b/scripts/migrations/152-opencode-ollama-tui-provider.js
@@ -22,10 +22,7 @@
* migrations rather than mutating this one.
*/
-import { readFile, writeFile } from 'fs/promises';
-import { join } from 'path';
-
-const PROVIDERS_REL_PATH = 'data/providers.json';
+import { makeProviderSeedMigration } from './_lib.js';
// Inline OpenCode config: declare the local Ollama daemon as an openai-compatible
// provider and auto-approve tools (the OpenCode equivalent of claude's
@@ -54,46 +51,7 @@ const OPENCODE_OLLAMA_TUI = {
tuiIdleTimeoutMs: 180000,
};
-export default {
- async up({ rootDir }) {
- const providersPath = join(rootDir, PROVIDERS_REL_PATH);
- const raw = await readFile(providersPath, 'utf-8').catch((err) => {
- if (err.code === 'ENOENT') return null;
- throw err;
- });
- if (raw == null) {
- console.log(`📄 ${PROVIDERS_REL_PATH} not present — skipping (fresh install seeds OpenCode Ollama TUI from data.reference)`);
- return;
- }
-
- let config;
- try {
- config = JSON.parse(raw);
- } catch (err) {
- console.log(`⚠️ ${PROVIDERS_REL_PATH}: invalid JSON, skipping (${err.message})`);
- return;
- }
-
- if (!config || typeof config !== 'object' || !config.providers || typeof config.providers !== 'object') {
- console.log(`⚠️ ${PROVIDERS_REL_PATH}: unexpected shape, skipping`);
- return;
- }
-
- const providers = config.providers;
- let changed = false;
-
- for (const def of [OPENCODE_OLLAMA_TUI]) {
- if (!providers[def.id]) {
- providers[def.id] = { ...def, envVars: { ...def.envVars } };
- changed = true;
- console.log(`📝 ${PROVIDERS_REL_PATH}: added ${def.id} provider`);
- }
- }
-
- if (changed) {
- await writeFile(providersPath, `${JSON.stringify(config, null, 2)}\n`);
- } else {
- console.log(`✅ ${PROVIDERS_REL_PATH}: OpenCode Ollama TUI provider already present — no change`);
- }
- },
-};
+export default makeProviderSeedMigration({
+ label: 'OpenCode Ollama TUI',
+ defs: [OPENCODE_OLLAMA_TUI],
+});
diff --git a/scripts/migrations/152-opencode-ollama-tui-provider.test.js b/scripts/migrations/152-opencode-ollama-tui-provider.test.js
index b79b28fc9b..86d7a2699c 100644
--- a/scripts/migrations/152-opencode-ollama-tui-provider.test.js
+++ b/scripts/migrations/152-opencode-ollama-tui-provider.test.js
@@ -2,9 +2,14 @@
* Test for migration 152 — add the OpenCode Ollama TUI provider to existing
* installs. Picked up by server/vitest.config.js's `../scripts/**\/*.test.js`
* glob.
+ *
+ * The shell shared by all six provider-seed migrations (read → guard → add
+ * missing ids → conditional write) is asserted once against
+ * `makeProviderSeedMigration` in _lib.test.js; what stays here is this
+ * migration's own frozen payload.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
-import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -64,47 +69,4 @@ describe('migration 152 — OpenCode Ollama TUI provider', () => {
expect(cfg.provider.ollama.npm).toBe('@ai-sdk/openai-compatible');
expect(cfg.provider.ollama.options.baseURL).toBe('http://localhost:11434/v1');
});
-
- it('does not overwrite a user-customized opencode-ollama-tui entry', async () => {
- writeJson(providersPath, {
- providers: {
- 'opencode-ollama-tui': {
- id: 'opencode-ollama-tui', type: 'tui', command: 'opencode',
- enabled: true, models: ['qwen2.5-coder:32b'], defaultModel: 'qwen2.5-coder:32b',
- },
- },
- });
-
- await migration.up({ rootDir });
-
- const out = readJson(providersPath);
- // existing TUI entry preserved untouched
- expect(out.providers['opencode-ollama-tui'].enabled).toBe(true);
- expect(out.providers['opencode-ollama-tui'].models).toEqual(['qwen2.5-coder:32b']);
- });
-
- it('is idempotent — a second run makes no changes', async () => {
- writeJson(providersPath, {
- providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },
- });
-
- await migration.up({ rootDir });
- const afterFirst = readFileSync(providersPath, 'utf-8');
- await migration.up({ rootDir });
- expect(readFileSync(providersPath, 'utf-8')).toBe(afterFirst);
- });
-
- it('is a no-op when data/providers.json does not exist (fresh install)', async () => {
- await migration.up({ rootDir });
- expect(existsSync(providersPath)).toBe(false);
- });
-
- it('does not modify the file on invalid JSON', async () => {
- writeFileSync(providersPath, '{ not valid json');
- const before = readFileSync(providersPath, 'utf-8');
-
- await migration.up({ rootDir });
-
- expect(readFileSync(providersPath, 'utf-8')).toBe(before);
- });
});
diff --git a/scripts/migrations/185-grok-providers.js b/scripts/migrations/185-grok-providers.js
index af1478e152..b60021adb2 100644
--- a/scripts/migrations/185-grok-providers.js
+++ b/scripts/migrations/185-grok-providers.js
@@ -19,10 +19,7 @@
* own migrations rather than mutating this one.
*/
-import { readFile, writeFile } from 'fs/promises';
-import { join } from 'path';
-
-const PROVIDERS_REL_PATH = 'data/providers.json';
+import { makeProviderSeedMigration } from './_lib.js';
const GROK_API = {
id: 'grok',
@@ -80,48 +77,7 @@ const GROK_TUI = {
tuiIdleTimeoutMs: 180000,
};
-export default {
- async up({ rootDir }) {
- const providersPath = join(rootDir, PROVIDERS_REL_PATH);
- const raw = await readFile(providersPath, 'utf-8').catch((err) => {
- if (err.code === 'ENOENT') return null;
- throw err;
- });
- if (raw == null) {
- console.log(`📄 ${PROVIDERS_REL_PATH} not present — skipping (fresh install seeds Grok from data.reference)`);
- return;
- }
-
- let config;
- try {
- config = JSON.parse(raw);
- } catch (err) {
- console.log(`⚠️ ${PROVIDERS_REL_PATH}: invalid JSON, skipping (${err.message})`);
- return;
- }
-
- if (!config || typeof config !== 'object' || !config.providers || typeof config.providers !== 'object') {
- console.log(`⚠️ ${PROVIDERS_REL_PATH}: unexpected shape, skipping`);
- return;
- }
-
- const providers = config.providers;
- let changed = false;
-
- for (const def of [GROK_API, GROK_CLI, GROK_TUI]) {
- if (!providers[def.id]) {
- // structuredClone fully detaches the frozen shipped def (nested arrays/
- // objects included) so a later mutation of the install can't corrupt it.
- providers[def.id] = structuredClone(def);
- changed = true;
- console.log(`📝 ${PROVIDERS_REL_PATH}: added ${def.id} provider`);
- }
- }
-
- if (changed) {
- await writeFile(providersPath, `${JSON.stringify(config, null, 2)}\n`);
- } else {
- console.log(`✅ ${PROVIDERS_REL_PATH}: Grok providers already present — no change`);
- }
- },
-};
+export default makeProviderSeedMigration({
+ label: 'Grok',
+ defs: [GROK_API, GROK_CLI, GROK_TUI],
+});
diff --git a/scripts/migrations/185-grok-providers.test.js b/scripts/migrations/185-grok-providers.test.js
index a8f8efe250..fe6349445f 100644
--- a/scripts/migrations/185-grok-providers.test.js
+++ b/scripts/migrations/185-grok-providers.test.js
@@ -2,9 +2,14 @@
* Test for migration 185 — add the xAI Grok provider trio (API + Grok Build
* CLI + TUI) to existing installs. Picked up by server/vitest.config.js's
* `../scripts/**\/*.test.js` glob.
+ *
+ * The shell shared by all six provider-seed migrations (read → guard → add
+ * missing ids → conditional write) is asserted once against
+ * `makeProviderSeedMigration` in _lib.test.js; what stays here is this
+ * migration's own frozen payload.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
-import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -57,64 +62,4 @@ describe('migration 185 — Grok providers', () => {
expect(out.providers['claude-code']).toBeDefined();
expect(out.activeProvider).toBe('claude-code');
});
-
- it('does not overwrite a user-customized grok entry', async () => {
- writeJson(providersPath, {
- providers: {
- grok: { id: 'grok', type: 'api', endpoint: 'https://api.x.ai/v1', enabled: true, apiKey: 'sk-secret', defaultModel: 'grok-3' },
- },
- });
-
- await migration.up({ rootDir });
-
- const out = readJson(providersPath);
- // existing entry preserved untouched
- expect(out.providers.grok.enabled).toBe(true);
- expect(out.providers.grok.apiKey).toBe('sk-secret');
- expect(out.providers.grok.defaultModel).toBe('grok-3');
- // the still-missing CLI/TUI siblings are added alongside it
- expect(out.providers['grok-cli']).toBeDefined();
- expect(out.providers['grok-tui']).toBeDefined();
- });
-
- it('deep-copies shipped arrays/objects so mutating the install cannot corrupt the frozen defaults', async () => {
- writeJson(providersPath, { providers: {} });
- await migration.up({ rootDir });
- const first = readJson(providersPath);
- first.providers.grok.models.push('mutated');
-
- // A second install run must still ship the pristine model list.
- const rootDir2 = mkdtempSync(join(tmpdir(), 'migration-185-b-'));
- mkdirSync(join(rootDir2, 'data'), { recursive: true });
- const providersPath2 = join(rootDir2, 'data/providers.json');
- writeJson(providersPath2, { providers: {} });
- await migration.up({ rootDir: rootDir2 });
- expect(readJson(providersPath2).providers.grok.models).not.toContain('mutated');
- rmSync(rootDir2, { recursive: true, force: true });
- });
-
- it('is idempotent — a second run makes no changes', async () => {
- writeJson(providersPath, {
- providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },
- });
-
- await migration.up({ rootDir });
- const afterFirst = readFileSync(providersPath, 'utf-8');
- await migration.up({ rootDir });
- expect(readFileSync(providersPath, 'utf-8')).toBe(afterFirst);
- });
-
- it('is a no-op when data/providers.json does not exist (fresh install)', async () => {
- await migration.up({ rootDir });
- expect(existsSync(providersPath)).toBe(false);
- });
-
- it('does not modify the file on invalid JSON', async () => {
- writeFileSync(providersPath, '{ not valid json');
- const before = readFileSync(providersPath, 'utf-8');
-
- await migration.up({ rootDir });
-
- expect(readFileSync(providersPath, 'utf-8')).toBe(before);
- });
});
diff --git a/scripts/migrations/195-cerebras-provider.js b/scripts/migrations/195-cerebras-provider.js
index 384b147d90..9d15f8c59f 100644
--- a/scripts/migrations/195-cerebras-provider.js
+++ b/scripts/migrations/195-cerebras-provider.js
@@ -29,11 +29,7 @@
* own migrations rather than mutating this one.
*/
-import { readFile } from 'fs/promises';
-import { atomicWrite } from '../../server/lib/fileUtils.js';
-import { join } from 'path';
-
-const PROVIDERS_REL_PATH = 'data/providers.json';
+import { makeProviderSeedMigration } from './_lib.js';
const CEREBRAS_API = {
id: 'cerebras',
@@ -53,40 +49,7 @@ const CEREBRAS_API = {
secretEnvVars: [],
};
-export default {
- async up({ rootDir }) {
- const providersPath = join(rootDir, PROVIDERS_REL_PATH);
- const raw = await readFile(providersPath, 'utf-8').catch((err) => {
- if (err.code === 'ENOENT') return null;
- throw err;
- });
- if (raw == null) {
- console.log(`📄 ${PROVIDERS_REL_PATH} not present — skipping (fresh install seeds Cerebras from data.reference)`);
- return;
- }
-
- let config;
- try {
- config = JSON.parse(raw);
- } catch (err) {
- console.log(`⚠️ ${PROVIDERS_REL_PATH}: invalid JSON, skipping (${err.message})`);
- return;
- }
-
- if (!config || typeof config !== 'object' || !config.providers || typeof config.providers !== 'object') {
- console.log(`⚠️ ${PROVIDERS_REL_PATH}: unexpected shape, skipping`);
- return;
- }
-
- if (config.providers[CEREBRAS_API.id]) {
- console.log(`✅ ${PROVIDERS_REL_PATH}: Cerebras provider already present — no change`);
- return;
- }
-
- // structuredClone fully detaches the frozen shipped def (nested arrays/
- // objects included) so a later mutation of the install can't corrupt it.
- config.providers[CEREBRAS_API.id] = structuredClone(CEREBRAS_API);
- console.log(`📝 ${PROVIDERS_REL_PATH}: added ${CEREBRAS_API.id} provider`);
- await atomicWrite(providersPath, `${JSON.stringify(config, null, 2)}\n`);
- },
-};
+export default makeProviderSeedMigration({
+ label: 'Cerebras',
+ defs: [CEREBRAS_API],
+});
diff --git a/scripts/migrations/195-cerebras-provider.test.js b/scripts/migrations/195-cerebras-provider.test.js
index a532eff902..33454a1aed 100644
--- a/scripts/migrations/195-cerebras-provider.test.js
+++ b/scripts/migrations/195-cerebras-provider.test.js
@@ -1,9 +1,14 @@
/**
* Test for migration 195 — add the Cerebras API provider to existing installs.
* Picked up by server/vitest.config.js's `../scripts/**\/*.test.js` glob.
+ *
+ * The shell shared by all six provider-seed migrations (read → guard → add
+ * missing ids → conditional write) is asserted once against
+ * `makeProviderSeedMigration` in _lib.test.js; what stays here is this
+ * migration's own frozen payload.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
-import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -49,79 +54,4 @@ describe('migration 195 — Cerebras provider', () => {
expect(out.providers['claude-code']).toBeDefined();
expect(out.activeProvider).toBe('claude-code');
});
-
- it('does not overwrite a user-customized cerebras entry', async () => {
- writeJson(providersPath, {
- providers: {
- cerebras: {
- id: 'cerebras',
- type: 'api',
- endpoint: 'https://api.cerebras.ai/v1',
- enabled: true,
- apiKey: 'csk-secret',
- defaultModel: 'zai-glm-4.7',
- models: ['zai-glm-4.7', 'gpt-oss-120b'],
- },
- },
- });
-
- await migration.up({ rootDir });
-
- const out = readJson(providersPath);
- // stored key, enablement, and a refreshed model list all survive
- expect(out.providers.cerebras.enabled).toBe(true);
- expect(out.providers.cerebras.apiKey).toBe('csk-secret');
- expect(out.providers.cerebras.defaultModel).toBe('zai-glm-4.7');
- expect(out.providers.cerebras.models).toEqual(['zai-glm-4.7', 'gpt-oss-120b']);
- });
-
- it('deep-copies shipped arrays/objects so mutating the install cannot corrupt the frozen defaults', async () => {
- writeJson(providersPath, { providers: {} });
- await migration.up({ rootDir });
- const first = readJson(providersPath);
- first.providers.cerebras.models.push('mutated');
-
- // A second install run must still ship the pristine model list.
- const rootDir2 = mkdtempSync(join(tmpdir(), 'migration-195-b-'));
- mkdirSync(join(rootDir2, 'data'), { recursive: true });
- const providersPath2 = join(rootDir2, 'data/providers.json');
- writeJson(providersPath2, { providers: {} });
- await migration.up({ rootDir: rootDir2 });
- expect(readJson(providersPath2).providers.cerebras.models).not.toContain('mutated');
- rmSync(rootDir2, { recursive: true, force: true });
- });
-
- it('is idempotent — a second run makes no changes', async () => {
- writeJson(providersPath, {
- providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },
- });
-
- await migration.up({ rootDir });
- const afterFirst = readFileSync(providersPath, 'utf-8');
- await migration.up({ rootDir });
- expect(readFileSync(providersPath, 'utf-8')).toBe(afterFirst);
- });
-
- it('is a no-op when data/providers.json does not exist (fresh install)', async () => {
- await migration.up({ rootDir });
- expect(existsSync(providersPath)).toBe(false);
- });
-
- it('does not modify the file on invalid JSON', async () => {
- writeFileSync(providersPath, '{ not valid json');
- const before = readFileSync(providersPath, 'utf-8');
-
- await migration.up({ rootDir });
-
- expect(readFileSync(providersPath, 'utf-8')).toBe(before);
- });
-
- it('does not modify the file when the providers map is missing', async () => {
- writeJson(providersPath, { activeProvider: 'claude-code' });
- const before = readFileSync(providersPath, 'utf-8');
-
- await migration.up({ rootDir });
-
- expect(readFileSync(providersPath, 'utf-8')).toBe(before);
- });
});
diff --git a/scripts/migrations/201-kimi-providers.js b/scripts/migrations/201-kimi-providers.js
index 711d4155f5..37e63d4d49 100644
--- a/scripts/migrations/201-kimi-providers.js
+++ b/scripts/migrations/201-kimi-providers.js
@@ -21,10 +21,7 @@
* migrations rather than mutating this one.
*/
-import { readFile, writeFile } from 'fs/promises';
-import { join } from 'path';
-
-const PROVIDERS_REL_PATH = 'data/providers.json';
+import { makeProviderSeedMigration } from './_lib.js';
const KIMI_CLI = {
id: 'kimi-cli',
@@ -64,48 +61,7 @@ const KIMI_TUI = {
tuiIdleTimeoutMs: 180000,
};
-export default {
- async up({ rootDir }) {
- const providersPath = join(rootDir, PROVIDERS_REL_PATH);
- const raw = await readFile(providersPath, 'utf-8').catch((err) => {
- if (err.code === 'ENOENT') return null;
- throw err;
- });
- if (raw == null) {
- console.log(`📄 ${PROVIDERS_REL_PATH} not present — skipping (fresh install seeds Kimi from data.reference)`);
- return;
- }
-
- let config;
- try {
- config = JSON.parse(raw);
- } catch (err) {
- console.log(`⚠️ ${PROVIDERS_REL_PATH}: invalid JSON, skipping (${err.message})`);
- return;
- }
-
- if (!config || typeof config !== 'object' || !config.providers || typeof config.providers !== 'object') {
- console.log(`⚠️ ${PROVIDERS_REL_PATH}: unexpected shape, skipping`);
- return;
- }
-
- const providers = config.providers;
- let changed = false;
-
- for (const def of [KIMI_CLI, KIMI_TUI]) {
- if (!providers[def.id]) {
- // structuredClone fully detaches the frozen shipped def (nested arrays/
- // objects included) so a later mutation of the install can't corrupt it.
- providers[def.id] = structuredClone(def);
- changed = true;
- console.log(`📝 ${PROVIDERS_REL_PATH}: added ${def.id} provider`);
- }
- }
-
- if (changed) {
- await writeFile(providersPath, `${JSON.stringify(config, null, 2)}\n`);
- } else {
- console.log(`✅ ${PROVIDERS_REL_PATH}: Kimi providers already present — no change`);
- }
- },
-};
+export default makeProviderSeedMigration({
+ label: 'Kimi',
+ defs: [KIMI_CLI, KIMI_TUI],
+});
diff --git a/scripts/migrations/201-kimi-providers.test.js b/scripts/migrations/201-kimi-providers.test.js
index 6b55d86cdd..0cf72cecd2 100644
--- a/scripts/migrations/201-kimi-providers.test.js
+++ b/scripts/migrations/201-kimi-providers.test.js
@@ -2,9 +2,14 @@
* Test for migration 201 — add the Moonshot AI Kimi Code process-provider pair
* (CLI + TUI) to existing installs. Picked up by server/vitest.config.js's
* `../scripts/**\/*.test.js` glob.
+ *
+ * The shell shared by all six provider-seed migrations (read → guard → add
+ * missing ids → conditional write) is asserted once against
+ * `makeProviderSeedMigration` in _lib.test.js; what stays here is this
+ * migration's own frozen payload.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
-import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -56,62 +61,4 @@ describe('migration 201 — Kimi providers', () => {
expect(out.providers['claude-code']).toBeDefined();
expect(out.activeProvider).toBe('claude-code');
});
-
- it('does not overwrite a user-customized kimi entry', async () => {
- writeJson(providersPath, {
- providers: {
- 'kimi-cli': { id: 'kimi-cli', type: 'cli', command: 'kimi', enabled: true, defaultModel: 'kimi-k2' },
- },
- });
-
- await migration.up({ rootDir });
-
- const out = readJson(providersPath);
- // existing entry preserved untouched
- expect(out.providers['kimi-cli'].enabled).toBe(true);
- expect(out.providers['kimi-cli'].defaultModel).toBe('kimi-k2');
- // the still-missing TUI sibling is added alongside it
- expect(out.providers['kimi-tui']).toBeDefined();
- });
-
- it('deep-copies shipped arrays/objects so mutating the install cannot corrupt the frozen defaults', async () => {
- writeJson(providersPath, { providers: {} });
- await migration.up({ rootDir });
- const first = readJson(providersPath);
- first.providers['kimi-cli'].models.push('mutated');
-
- // A second install run must still ship the pristine model list.
- const rootDir2 = mkdtempSync(join(tmpdir(), 'migration-201-b-'));
- mkdirSync(join(rootDir2, 'data'), { recursive: true });
- const providersPath2 = join(rootDir2, 'data/providers.json');
- writeJson(providersPath2, { providers: {} });
- await migration.up({ rootDir: rootDir2 });
- expect(readJson(providersPath2).providers['kimi-cli'].models).not.toContain('mutated');
- rmSync(rootDir2, { recursive: true, force: true });
- });
-
- it('is idempotent — a second run makes no changes', async () => {
- writeJson(providersPath, {
- providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },
- });
-
- await migration.up({ rootDir });
- const afterFirst = readFileSync(providersPath, 'utf-8');
- await migration.up({ rootDir });
- expect(readFileSync(providersPath, 'utf-8')).toBe(afterFirst);
- });
-
- it('is a no-op when data/providers.json does not exist (fresh install)', async () => {
- await migration.up({ rootDir });
- expect(existsSync(providersPath)).toBe(false);
- });
-
- it('does not modify the file on invalid JSON', async () => {
- writeFileSync(providersPath, '{ not valid json');
- const before = readFileSync(providersPath, 'utf-8');
-
- await migration.up({ rootDir });
-
- expect(readFileSync(providersPath, 'utf-8')).toBe(before);
- });
});
diff --git a/scripts/migrations/231-cursor-providers.js b/scripts/migrations/231-cursor-providers.js
index 542df80602..4b22b0e46b 100644
--- a/scripts/migrations/231-cursor-providers.js
+++ b/scripts/migrations/231-cursor-providers.js
@@ -24,10 +24,7 @@
* migrations rather than mutating this one.
*/
-import { readFile, writeFile } from 'fs/promises';
-import { join } from 'path';
-
-const PROVIDERS_REL_PATH = 'data/providers.json';
+import { makeProviderSeedMigration } from './_lib.js';
// Curated from `cursor-agent models` (177 ids as of 2026-08-07). The full account
// catalog enumerates every reasoning tier AND a `-fast` priority-compute twin of
@@ -101,49 +98,7 @@ const CURSOR_TUI = {
tuiIdleTimeoutMs: 180000,
};
-export default {
- async up({ rootDir }) {
- const providersPath = join(rootDir, PROVIDERS_REL_PATH);
- const raw = await readFile(providersPath, 'utf-8').catch((err) => {
- if (err.code === 'ENOENT') return null;
- throw err;
- });
- if (raw == null) {
- console.log(`📄 ${PROVIDERS_REL_PATH} not present — skipping (fresh install seeds Cursor from data.reference)`);
- return;
- }
-
- let config;
- try {
- config = JSON.parse(raw);
- } catch (err) {
- console.log(`⚠️ ${PROVIDERS_REL_PATH}: invalid JSON, skipping (${err.message})`);
- return;
- }
-
- if (!config || typeof config !== 'object' || !config.providers || typeof config.providers !== 'object') {
- console.log(`⚠️ ${PROVIDERS_REL_PATH}: unexpected shape, skipping`);
- return;
- }
-
- const providers = config.providers;
- let changed = false;
-
- for (const def of [CURSOR_CLI, CURSOR_TUI]) {
- if (!providers[def.id]) {
- // structuredClone fully detaches the shipped def (nested arrays/objects
- // included — CURSOR_MODELS is shared by both entries) so a later mutation
- // of the install can't corrupt it or leak across the two providers.
- providers[def.id] = structuredClone(def);
- changed = true;
- console.log(`📝 ${PROVIDERS_REL_PATH}: added ${def.id} provider`);
- }
- }
-
- if (changed) {
- await writeFile(providersPath, `${JSON.stringify(config, null, 2)}\n`);
- } else {
- console.log(`✅ ${PROVIDERS_REL_PATH}: Cursor providers already present — no change`);
- }
- },
-};
+export default makeProviderSeedMigration({
+ label: 'Cursor',
+ defs: [CURSOR_CLI, CURSOR_TUI],
+});
diff --git a/scripts/migrations/231-cursor-providers.test.js b/scripts/migrations/231-cursor-providers.test.js
index 37599ae9d2..0ec1423515 100644
--- a/scripts/migrations/231-cursor-providers.test.js
+++ b/scripts/migrations/231-cursor-providers.test.js
@@ -2,9 +2,14 @@
* Test for migration 231 — add the Cursor Agent process-provider pair (CLI + TUI)
* to existing installs. Picked up by server/vitest.config.js's
* `../scripts/**\/*.test.js` glob.
+ *
+ * The shell shared by all six provider-seed migrations (read → guard → add
+ * missing ids → conditional write) is asserted once against
+ * `makeProviderSeedMigration` in _lib.test.js; what stays here is this
+ * migration's own frozen payload.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
-import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -59,23 +64,6 @@ describe('migration 231 — Cursor providers', () => {
expect(out.activeProvider).toBe('claude-code');
});
- it('does not overwrite a user-customized cursor entry', async () => {
- writeJson(providersPath, {
- providers: {
- 'cursor-cli': { id: 'cursor-cli', type: 'cli', command: 'cursor-agent', enabled: true, defaultModel: 'composer-2.5' },
- },
- });
-
- await migration.up({ rootDir });
-
- const out = readJson(providersPath);
- // existing entry preserved untouched
- expect(out.providers['cursor-cli'].enabled).toBe(true);
- expect(out.providers['cursor-cli'].defaultModel).toBe('composer-2.5');
- // the still-missing TUI sibling is added alongside it
- expect(out.providers['cursor-tui']).toBeDefined();
- });
-
// Replaces a pair of "deep-copy isolation" tests that could not fail: they
// mutated a value re-parsed from disk, which has no reference relationship to
// the module-level CURSOR_MODELS, so `structuredClone` could be deleted
@@ -103,29 +91,4 @@ describe('migration 231 — Cursor providers', () => {
expect(out.providers['cursor-cli'].models).toEqual(out.providers['cursor-tui'].models);
});
});
-
- it('is idempotent — a second run makes no changes', async () => {
- writeJson(providersPath, {
- providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },
- });
-
- await migration.up({ rootDir });
- const afterFirst = readFileSync(providersPath, 'utf-8');
- await migration.up({ rootDir });
- expect(readFileSync(providersPath, 'utf-8')).toBe(afterFirst);
- });
-
- it('is a no-op when data/providers.json does not exist (fresh install)', async () => {
- await migration.up({ rootDir });
- expect(existsSync(providersPath)).toBe(false);
- });
-
- it('does not modify the file on invalid JSON', async () => {
- writeFileSync(providersPath, '{ not valid json');
- const before = readFileSync(providersPath, 'utf-8');
-
- await migration.up({ rootDir });
-
- expect(readFileSync(providersPath, 'utf-8')).toBe(before);
- });
});
diff --git a/scripts/migrations/_lib.js b/scripts/migrations/_lib.js
index 97ed81473b..ac79446fb5 100644
--- a/scripts/migrations/_lib.js
+++ b/scripts/migrations/_lib.js
@@ -1,5 +1,5 @@
/**
- * Shared scaffolding for migrations. Two families live here:
+ * Shared scaffolding for migrations. Several families live here:
*
* 1. Hash-driven prompt-replace migrations — every one from 003 onward uses
* `makePromptReplaceMigration` to collapse onto ~50 lines (hash table +
@@ -8,6 +8,11 @@
* `writeLayoutsDoc` collapse the read → JSON.parse → `Array.isArray`
* guard → write shell shared by every migration that mutates built-in
* layouts in `data/dashboard-layouts.json` (029, 030, 033, …).
+ * 3. Monolithic → per-record split migrations — `makeSplitMigration`.
+ * 4. Brain seed-record migrations — `makeBrainSeedMigration`.
+ * 5. Provider-seed migrations — `makeProviderSeedMigration` collapses the
+ * read → guard → add-missing-ids → write shell every migration that ships
+ * a new `data/providers.json` entry repeats (149, 152, 185, 195, 201, 231).
*
* The runner (`scripts/run-migrations.js`) explicitly skips `_`-prefixed
* files so this module is never imported as a migration.
@@ -90,7 +95,7 @@ const splitReadJsonTolerant = async (path) => {
// authoritative legacy value, then stamp + rename the legacy store — and the
// truncated record would forever load as null. rename() is atomic within one
// filesystem, and tmp sits in the same dir as its target, so the swap is safe.
-const splitWriteJson = async (path, value) => {
+const writeJsonAtomic = async (path, value) => {
const tmp = `${path}.tmp-${process.pid}`;
await writeFile(tmp, JSON.stringify(value, null, 2) + '\n');
await rename(tmp, path);
@@ -178,7 +183,7 @@ export function makeSplitMigration({
// boot-time verifyCollectionVersions doesn't flag it missing.
if (!legacyExists && !backupExists) {
await mkdir(typeDir, { recursive: true });
- await splitWriteJson(typeIndexPath, {
+ await writeJsonAtomic(typeIndexPath, {
schemaVersion: typeSchemaVersion,
type: typeLabel,
updatedAt: new Date().toISOString(),
@@ -265,14 +270,14 @@ export function makeSplitMigration({
}
const recordDir = join(typeDir, id);
await mkdir(recordDir, { recursive: true });
- await splitWriteJson(join(recordDir, 'index.json'), record);
+ await writeJsonAtomic(join(recordDir, 'index.json'), record);
if (dedupe) existingIds.add(id); // first-wins: later duplicates skip above
written += 1;
}
// Stamp the type index AFTER all records land so a crash mid-split leaves
// it missing — the next boot's gate 1 won't trip and gate 2/recovery re-runs.
- await splitWriteJson(typeIndexPath, {
+ await writeJsonAtomic(typeIndexPath, {
schemaVersion: typeSchemaVersion,
type: typeLabel,
updatedAt: new Date().toISOString(),
@@ -649,6 +654,107 @@ export function makeBrainSeedMigration({ logTag, entityType, seedIds, seedLabel,
return { up };
}
+// ---- provider-seed migration family ----
+//
+// `scripts/setup-data.js` merges *missing* `data/providers.json` entries from
+// data.reference, but only when an install actually re-runs setup. Every
+// migration that ships a new provider therefore delivers it on a plain server
+// restart too, and each one repeats the identical shell: read
+// `data/providers.json` → ENOENT skip (a fresh install seeds from
+// data.reference) → JSON.parse guard → shape guard → add each missing id →
+// write only when something changed. 149 / 152 / 185 / 195 / 201 / 231 are the
+// current members; `makeProviderSeedMigration` is that shell.
+//
+// What each migration still owns is its `defs` — a FROZEN literal in its own
+// file, never read from `data.reference/providers.json` at migration time. A
+// migration is the historical record of what it installed; later default
+// changes ride their own migrations (precedent: 058/153/206 bumping the Claude
+// defaults). Reading the live reference would hand an upgrading install a
+// different payload than the migration's own tests assert, and a different one
+// than earlier users received.
+
+const PROVIDERS_REL_PATH = 'data/providers.json';
+
+/**
+ * Build a provider-seed migration's `up()`. Returns `{ up }`, so a migration is
+ * `export default makeProviderSeedMigration({ label, defs })`.
+ *
+ * - `label` — human name of the provider family for the log lines
+ * ("Grok", "Cerebras", "OpenCode Ollama TUI").
+ * - `defs` — the frozen provider objects this migration installs, each with
+ * an `id`. Added only when the id is missing, so an existing entry (user
+ * edits, a stored apiKey, a refreshed model list) is never clobbered and a
+ * second run is a no-op.
+ *
+ * Each def is installed via `structuredClone`, which fully detaches nested
+ * arrays/objects — necessary because sibling defs commonly share one constant
+ * (231's two entries both reference `CURSOR_MODELS`), so a shallow spread would
+ * leak a later in-memory mutation across both entries and back into the frozen
+ * module-level default.
+ *
+ * Resolves to `{ ok, reason: 'no-file' | 'unreadable' | 'bad-shape' |
+ * 'already-present' | 'seeded', added }`.
+ */
+export function makeProviderSeedMigration({ label, defs }) {
+ const noun = defs.length === 1 ? 'provider' : 'providers';
+
+ async function up({ rootDir }) {
+ const providersPath = join(rootDir, PROVIDERS_REL_PATH);
+ const raw = await readFile(providersPath, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) {
+ console.log(`📄 ${PROVIDERS_REL_PATH} not present — skipping (fresh install seeds ${label} from data.reference)`);
+ return { ok: false, reason: 'no-file', added: 0 };
+ }
+
+ let config;
+ try {
+ config = JSON.parse(raw);
+ } catch (err) {
+ console.log(`⚠️ ${PROVIDERS_REL_PATH}: invalid JSON, skipping (${err.message})`);
+ return { ok: false, reason: 'unreadable', added: 0 };
+ }
+
+ if (!config || typeof config !== 'object' || !config.providers || typeof config.providers !== 'object') {
+ console.log(`⚠️ ${PROVIDERS_REL_PATH}: unexpected shape, skipping`);
+ return { ok: false, reason: 'bad-shape', added: 0 };
+ }
+
+ const providers = config.providers;
+ let added = 0;
+
+ for (const def of defs) {
+ // Same guard the split family applies to legacy map keys: `__proto__` /
+ // `constructor` / `prototype` are inherited on any plain object, so the
+ // `providers[def.id]` presence probe below reads TRUTHY for them even on
+ // an empty map — the id would be silently skipped forever — and writing
+ // one would mutate the prototype rather than add a provider. A provider
+ // id is never one of these; refuse loudly if a def ever carries one.
+ if (RESERVED_MAP_KEYS.has(def.id)) {
+ console.log(`⚠️ ${PROVIDERS_REL_PATH}: refusing reserved provider id ${def.id}`);
+ continue;
+ }
+ if (!providers[def.id]) {
+ providers[def.id] = structuredClone(def);
+ added++;
+ console.log(`📝 ${PROVIDERS_REL_PATH}: added ${def.id} provider`);
+ }
+ }
+
+ if (added === 0) {
+ console.log(`✅ ${PROVIDERS_REL_PATH}: ${label} ${noun} already present — no change`);
+ return { ok: true, reason: 'already-present', added: 0 };
+ }
+
+ await writeJsonAtomic(providersPath, config);
+ return { ok: true, reason: 'seeded', added };
+ }
+
+ return { up };
+}
+
/**
* Build the per-subdir prompt-drift tables that `scripts/setup-data.js` uses
* for its "pending migration" warning by sweeping every numbered migration's
diff --git a/scripts/migrations/_lib.test.js b/scripts/migrations/_lib.test.js
index 448b63b88d..779a9117f1 100644
--- a/scripts/migrations/_lib.test.js
+++ b/scripts/migrations/_lib.test.js
@@ -7,13 +7,18 @@
*
* Per-migration tests still rely on the underlying loop logic; these
* exercise the branches the helper guards behind opt-in flags.
+ *
+ * Also home to the shell suites for the other migration factories —
+ * `makeSplitMigration`'s flags and `makeProviderSeedMigration`'s whole
+ * read → guard → add-missing-ids → write shell, which the six provider-seed
+ * migrations (149/152/185/195/201/231) used to re-assert one file at a time.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
-import { applyPromptReplaceMigration, md5, readLayoutsDoc, writeLayoutsDoc, makeSplitMigration } from './_lib.js';
+import { applyPromptReplaceMigration, md5, readLayoutsDoc, writeLayoutsDoc, makeSplitMigration, makeProviderSeedMigration } from './_lib.js';
const FILENAME = 'pipeline-fake.md';
const BODY_OLD = '# OLD\n';
@@ -308,3 +313,115 @@ describe('makeSplitMigration flags', () => {
expect(existsSync(join(dataDir, 'widgets', 'index.json'))).toBe(false);
});
});
+
+// The shell shared by every provider-seed migration (149/152/185/195/201/231).
+// These cases used to be re-asserted once per migration against byte-identical
+// code; they live here once now, so each migration's own suite only pins what
+// is genuinely specific to its payload.
+describe('makeProviderSeedMigration', () => {
+ let rootDir;
+ let providersPath;
+
+ // One shared array across both defs — the 231/CURSOR_MODELS shape.
+ const SHARED_MODELS = ['m1', 'm2'];
+ const DEF_A = { id: 'seed-a', name: 'Seed A', type: 'cli', models: SHARED_MODELS, envVars: { K: 'v' } };
+ const DEF_B = { id: 'seed-b', name: 'Seed B', type: 'tui', models: SHARED_MODELS, envVars: { K: 'v' } };
+ const mig = () => makeProviderSeedMigration({ label: 'Seed', defs: [DEF_A, DEF_B] });
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'provider-seed-'));
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ providersPath = join(rootDir, 'data/providers.json');
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ const write = (value) => writeFileSync(providersPath, JSON.stringify(value, null, 2) + '\n');
+ const read = () => JSON.parse(readFileSync(providersPath, 'utf-8'));
+
+ it('adds every missing def and leaves unrelated providers + top-level keys untouched', async () => {
+ write({ activeProvider: 'claude-code', providers: { 'claude-code': { id: 'claude-code', type: 'cli' } } });
+
+ expect(await mig().up({ rootDir })).toEqual({ ok: true, reason: 'seeded', added: 2 });
+
+ const out = read();
+ expect(out.providers['seed-a']).toEqual(DEF_A);
+ expect(out.providers['seed-b']).toEqual(DEF_B);
+ expect(out.providers['claude-code']).toEqual({ id: 'claude-code', type: 'cli' });
+ expect(out.activeProvider).toBe('claude-code');
+ });
+
+ it('never overwrites an existing entry, but still adds its missing siblings', async () => {
+ write({ providers: { 'seed-a': { id: 'seed-a', enabled: true, apiKey: 'user-key' } } });
+
+ expect(await mig().up({ rootDir })).toMatchObject({ reason: 'seeded', added: 1 });
+
+ const out = read();
+ expect(out.providers['seed-a']).toEqual({ id: 'seed-a', enabled: true, apiKey: 'user-key' });
+ expect(out.providers['seed-b']).toBeDefined();
+ });
+
+ it('deep-copies each def so sibling entries and the frozen module default stay detached', async () => {
+ // DEF_A and DEF_B share one `models` array by reference (231's CURSOR_MODELS
+ // shape). A shallow spread would give both installed entries — and the
+ // module-level constant — the same array object.
+ expect(DEF_A.models).toBe(DEF_B.models);
+ write({ providers: {} });
+
+ await mig().up({ rootDir });
+
+ const out = read();
+ out.providers['seed-a'].models.push('mutated');
+ out.providers['seed-a'].envVars.K = 'mutated';
+ expect(out.providers['seed-b'].models).toEqual(['m1', 'm2']);
+ expect(DEF_A.models).toEqual(['m1', 'm2']);
+ expect(DEF_A.envVars.K).toBe('v');
+ });
+
+ it('is idempotent — a second run rewrites nothing', async () => {
+ write({ providers: { 'claude-code': { id: 'claude-code', type: 'cli' } } });
+
+ await mig().up({ rootDir });
+ const afterFirst = readFileSync(providersPath, 'utf-8');
+
+ expect(await mig().up({ rootDir })).toEqual({ ok: true, reason: 'already-present', added: 0 });
+ expect(readFileSync(providersPath, 'utf-8')).toBe(afterFirst);
+ });
+
+ it('is a no-op when data/providers.json does not exist (fresh install seeds from data.reference)', async () => {
+ expect(await mig().up({ rootDir })).toEqual({ ok: false, reason: 'no-file', added: 0 });
+ expect(existsSync(providersPath)).toBe(false);
+ });
+
+ it('leaves an unparseable file byte-identical rather than clobbering user data', async () => {
+ writeFileSync(providersPath, '{ not valid json');
+
+ expect(await mig().up({ rootDir })).toEqual({ ok: false, reason: 'unreadable', added: 0 });
+ expect(readFileSync(providersPath, 'utf-8')).toBe('{ not valid json');
+ });
+
+ it('leaves the file untouched when the providers map is missing or not an object', async () => {
+ for (const doc of [{}, { providers: null }, { providers: 'nope' }]) {
+ write(doc);
+ const before = readFileSync(providersPath, 'utf-8');
+ expect(await mig().up({ rootDir })).toEqual({ ok: false, reason: 'bad-shape', added: 0 });
+ expect(readFileSync(providersPath, 'utf-8')).toBe(before);
+ }
+ });
+
+ it('refuses a reserved prototype key as a provider id instead of skipping it forever', async () => {
+ // `providers['constructor']` is truthy on ANY plain object, so the
+ // presence probe would read the inherited Object.prototype.constructor and
+ // silently treat the provider as already installed on every run.
+ write({ providers: {} });
+ const polluting = makeProviderSeedMigration({ label: 'Bad', defs: [{ id: 'constructor', name: 'Bad' }, DEF_A] });
+
+ expect(await polluting.up({ rootDir })).toMatchObject({ reason: 'seeded', added: 1 });
+
+ const out = read();
+ expect(Object.hasOwn(out.providers, 'constructor')).toBe(false);
+ expect(out.providers['seed-a']).toBeDefined();
+ // The prototype itself is untouched — nothing leaked onto Object.prototype.
+ expect({}.name).toBeUndefined();
+ });
+});