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
fix: stop the data.reference seed from wiping CoS settings on the #6182 update
[._.]/ Adam Eivy85c0cea546c4
diff --git a/AGENTS.md b/AGENTS.mdindex 13b63f1909..7a6ffaa8c0 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -66,6 +66,7 @@ Because both are off by default, **never treat "the password is set" as an avail- **Never delete or skip migration / compatibility code on the grounds that "there's only one install."** There isn't — other people and other machines run this code and update it independently.- On-disk format changes need a migration in `scripts/migrations/` (applied-list tracked per install in `data/migrations.applied.json`). Seed files must ship in `data.reference/`.+- **A migration that DERIVES `data/<x>` from an install's existing records ships NO `data.reference/<x>` seed, and gates on the presence of its INPUT — never the absence of its output.** `setup-data.js` runs before `run-migrations.js` and copies every `data.reference/` file the install lacks, so a seed lands first; a migration that skips because its output already exists then silently leaves shipped defaults where the user's data was, and the next write destroys the original. Declare such a path in `scripts/lib/migrationOwnedPaths.js` (its test fails if a seed reappears). The applied-list already provides re-run safety, so gating on the input costs nothing. This is not hypothetical: it replaced CoS settings with shipped defaults on any install whose update crossed #6182 — see `scripts/migrations/340-cos-config-seed-repair.js`.- Prompt-default changes need a `PROMPT_VERSIONS` bump AND the prior default preserved in `PREVIOUS_DEFAULT_PROMPTS`, so other installs recognize their stored prompt and auto-upgrade it (`server/services/taskSchedule.js`).- Cross-machine sync payloads stay version-gated (`server/lib/schemaVersions.js`) so a newer peer can't corrupt an older one.- The self-update path stays fork-aware — other users run forks, not just upstream. **Never add `--force` to the server-side `gh repo sync`** (it would discard a user's fork commits; the 409 `FORK_DIVERGED` message points them at running it themselves). Don't re-hardcode the upstream slug outside `server/lib/gitRemote.js`, and new UI claiming "you are running PortOS" must read `remoteInfo.isUpstream`, not just `currentVersion`, or it lies to fork users. Mechanism: [docs/SELF_UPDATE.md](docs/SELF_UPDATE.md).diff --git a/data.reference/cos/config.json b/data.reference/cos/config.jsondeleted file mode 100644index 8eebdbb4d6..0000000000--- a/data.reference/cos/config.json+++ /dev/null@@ -1,42 +0,0 @@-{- "userTasksFile": "data/TASKS.md",- "cosTasksFile": "data/COS-TASKS.md",- "healthCheckIntervalMs": 900000,- "maxConcurrentAgents": 3,- "maxConcurrentAgentsPerProject": 2,- "maxProcessMemoryMb": 2048,- "maxTotalProcesses": 50,- "mcpServers": [- {- "name": "filesystem",- "command": "npx",- "args": [- "-y",- "@anthropic/mcp-server-filesystem"- ]- },- {- "name": "puppeteer",- "command": "npx",- "args": [- "-y",- "@anthropic/mcp-puppeteer",- "--isolated"- ]- }- ],- "autoStart": false,- "alwaysOn": false,- "selfImprovementEnabled": true,- "dynamicAvatar": true,- "persistentMindCapabilities": {- "schemaVersion": 5,- "createTasks": false,- "manageMind": false,- "manageEidoverse": false,- "callUser": false,- "readPortos": false,- "writePortos": false,- "taskModelAllowlist": []- }-}diff --git a/scripts/lib/migrationOwnedPaths.js b/scripts/lib/migrationOwnedPaths.jsnew file mode 100644index 0000000000..1954089eea--- /dev/null+++ b/scripts/lib/migrationOwnedPaths.js@@ -0,0 +1,17 @@+/**+ * `data/` paths that a MIGRATION derives from an install's existing records,+ * and that must therefore ship no `data.reference/` seed.+ *+ * The enforcement is the seed's ABSENCE, asserted by the sibling test. The+ * filter this list drives in `scripts/setup-data.js` (its one consumer) is+ * defense in depth for a seed someone re-adds. Full rationale — and the+ * silent data loss a seed causes here — is in+ * `scripts/migrations/340-cos-config-seed-repair.js`.+ */++/** Paths relative to `data/` (and to `data.reference/`), always posix-spelled. */+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',+]);diff --git a/scripts/lib/migrationOwnedPaths.test.js b/scripts/lib/migrationOwnedPaths.test.jsnew file mode 100644index 0000000000..109173ad93--- /dev/null+++ b/scripts/lib/migrationOwnedPaths.test.js@@ -0,0 +1,27 @@+/**+ * Guards the invariant `MIGRATION_OWNED_PATHS` exists to state: none of these+ * paths may ship a `data.reference/` seed.+ *+ * The regression it uniquely catches is #6182's — a seed added beside a+ * migration that derives the same file from the install's existing records+ * silently replaces the user's settings with shipped defaults, because+ * setup-data runs before run-migrations. See+ * `scripts/migrations/340-cos-config-seed-repair.js`.+ */+import { describe, it, expect } from 'vitest';+import { existsSync } from 'fs';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';++import { MIGRATION_OWNED_PATHS } from './migrationOwnedPaths.js';++const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');++describe('migration-owned data paths', () => {+ it('ships no data.reference seed for any migration-owned path', () => {+ const seeded = [...MIGRATION_OWNED_PATHS].filter((relPath) =>+ existsSync(join(repoRoot, 'data.reference', ...relPath.split('/'))),+ );+ expect(seeded).toEqual([]);+ });+});diff --git a/scripts/migrations/340-cos-config-seed-repair.js b/scripts/migrations/340-cos-config-seed-repair.jsnew file mode 100644index 0000000000..9ba170fc4d--- /dev/null+++ b/scripts/migrations/340-cos-config-seed-repair.js@@ -0,0 +1,170 @@+/**+ * Repair installs whose CoS settings were replaced by the shipped seed during+ * the #6182 config split.+ *+ * `update.sh` runs `scripts/setup-data.js` BEFORE `scripts/run-migrations.js`,+ * and setup-data copies every `data.reference/` file the install is missing.+ * The commit that introduced migration 339 (lift `config` out of+ * `data/cos/state.json` into `data/cos/config.json`) also added a+ * `data.reference/cos/config.json` seed — so on the one update that crossed+ * that commit, setup-data wrote the seed first, migration 339 saw config.json+ * "already exists" and no-opped, `loadConfig()` preferred the seed over its+ * legacy `state.json` read, and the next `saveState()` stripped the real config+ * slice off disk for good. An install that updated before or after that commit+ * never sees it.+ *+ * The seed set `alwaysOn: false` / `autoStart: false` while `DEFAULT_CONFIG`+ * shipped `alwaysOn: true`, so the visible symptom was CoS refusing to come+ * back after an update until the user started it by hand, on top of concurrency+ * caps and Persistent Mind grants reverting to defaults. (`alwaysOn` now+ * defaults to `false` too — see `server/services/cosState.js`.)+ *+ * Two rules keep this from recurring, both recorded in the root `AGENTS.md`:+ * a derive-from-existing-data migration ships no seed (declared in+ * `scripts/lib/migrationOwnedPaths.js`, which setup-data also honors), and such+ * a migration gates on the presence of its INPUT rather than the absence of its+ * output — 339 did the latter, which is what let a pre-existing output file+ * silence it.+ *+ * This migration cleans up the installs that already took the hit:+ *+ * - config.json is the retired seed AND state.json still carries a `config`+ * slice → redo migration 339's lift, recovering the real settings.+ * - state.json was stripped but a quarantined `state.json.corrupted.*` copy+ * still carries one → lift from the newest of those. On an install that+ * took this hit, those backups are frequently the LAST copy of the real+ * settings anywhere on disk.+ * - nothing left to lift → delete config.json, so `loadConfig()` falls back+ * to `DEFAULT_CONFIG`, one source of truth for the defaults.+ *+ * Every repair branch requires config.json to EQUAL the retired seed (deep+ * equality; key order is not the contract). That is the proof it was+ * machine-written: `saveConfig()` always persists the full merged+ * `DEFAULT_CONFIG` key set (34 keys), so a file deep-equal to the 13-key seed+ * cannot have come from a user saving settings. Anything else is left strictly+ * alone — but if a quarantined copy holds settings that config.json does not,+ * we still say so, because the user who reacted to the symptom by re-entering+ * their settings by hand lands exactly there.+ */++import { readdir, readFile, rm } from 'fs/promises';+import { isDeepStrictEqual } from 'util';+import { basename, dirname, join } from 'path';++import { writeJsonAtomic } from './_lib.js';++const STATE_PATH = join('data', 'cos', 'state.json');+const CONFIG_PATH = join('data', 'cos', 'config.json');++/**+ * `data.reference/cos/config.json` as it shipped between the #6182 split and+ * this repair — frozen here because the file no longer exists in the tree and+ * this migration's whole guard is equality with it. Exported for the test.+ */+export const RETIRED_SEED = {+ userTasksFile: 'data/TASKS.md',+ cosTasksFile: 'data/COS-TASKS.md',+ healthCheckIntervalMs: 900000,+ maxConcurrentAgents: 3,+ maxConcurrentAgentsPerProject: 2,+ maxProcessMemoryMb: 2048,+ maxTotalProcesses: 50,+ mcpServers: [+ { name: 'filesystem', command: 'npx', args: ['-y', '@anthropic/mcp-server-filesystem'] },+ { name: 'puppeteer', command: 'npx', args: ['-y', '@anthropic/mcp-puppeteer', '--isolated'] },+ ],+ autoStart: false,+ alwaysOn: false,+ selfImprovementEnabled: true,+ dynamicAvatar: true,+ persistentMindCapabilities: {+ schemaVersion: 5,+ createTasks: false,+ manageMind: false,+ manageEidoverse: false,+ callUser: false,+ readPortos: false,+ writePortos: false,+ taskModelAllowlist: [],+ },+};++const isPlainObject = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);++async function readJson(path) {+ const raw = await readFile(path, 'utf-8').catch(() => null);+ if (raw == null) return null;+ try {+ return JSON.parse(raw);+ } catch {+ return null;+ }+}++/**+ * The config slice from the newest quarantined `state.json.corrupted.*`, or+ * `null`. `cosState.js` writes those copies when state.json fails to parse, and+ * their suffix is `Date.now()`. Read newest-first and stop at the first hit —+ * the newest is nearly always the answer, so reading the rest is wasted I/O.+ */+async function readQuarantinedConfig(stateDir) {+ const prefix = `${basename(STATE_PATH)}.corrupted.`;+ const names = await readdir(stateDir).catch(() => []);+ const backups = names+ .filter((name) => name.startsWith(prefix))+ .sort()+ .reverse();+ for (const name of backups) {+ const config = (await readJson(join(stateDir, name)))?.config;+ if (isPlainObject(config)) return { config, source: name };+ }+ return null;+}++export default {+ async up({ rootDir }) {+ const configPath = join(rootDir, CONFIG_PATH);+ const statePath = join(rootDir, STATE_PATH);+ const config = await readJson(configPath);+ // Absent (the normal case on a healthy or fresh install) or unreadable — an+ // unreadable config.json belongs to the state loader's quarantine path, not+ // to a migration that would delete it.+ if (config === null) return { repaired: false, reason: 'no readable config.json' };++ if (!isDeepStrictEqual(config, RETIRED_SEED)) {+ // Not ours to touch. But an install that re-entered its settings by hand+ // after the reset lands here with its ONLY pre-split copy sitting in a+ // quarantined backup, so point at it rather than saying nothing.+ const stranded = await readQuarantinedConfig(dirname(statePath));+ if (stranded) {+ console.log(`💡 ${CONFIG_PATH} carries real settings, so it was left alone — an older copy of ${Object.keys(stranded.config).length} CoS settings is still readable in ${join(dirname(STATE_PATH), stranded.source)} if anything looks missing`);+ }+ return { repaired: false, reason: 'config.json carries real settings' };+ }++ const state = await readJson(statePath);+ const legacyConfig = state?.config;+ if (isPlainObject(legacyConfig)) {+ // Config file first, same ordering as migration 339: a crash between the+ // two writes leaves the settings in both places, never in neither.+ await writeJsonAtomic(configPath, legacyConfig);+ delete state.config;+ await writeJsonAtomic(statePath, state);+ console.log(`📦 ${CONFIG_PATH}: replaced the shipped seed with the ${Object.keys(legacyConfig).length} settings still in ${STATE_PATH}`);+ return { repaired: 'lifted', keys: Object.keys(legacyConfig).length };+ }++ // state.json no longer carries the slice — the post-seed `saveState()`+ // already stripped it. A quarantined copy may still hold it.+ const quarantined = await readQuarantinedConfig(dirname(statePath));+ if (quarantined) {+ await writeJsonAtomic(configPath, quarantined.config);+ console.log(`📦 ${CONFIG_PATH}: recovered ${Object.keys(quarantined.config).length} settings from the quarantined ${quarantined.source}`);+ return { repaired: 'recovered', keys: Object.keys(quarantined.config).length, source: quarantined.source };+ }++ await rm(configPath);+ console.log(`🧹 Removed ${CONFIG_PATH} — it was the shipped seed, so CoS reads its in-code defaults again`);+ return { repaired: 'removed' };+ },+};diff --git a/scripts/migrations/340-cos-config-seed-repair.test.js b/scripts/migrations/340-cos-config-seed-repair.test.jsnew file mode 100644index 0000000000..dd848779e9--- /dev/null+++ b/scripts/migrations/340-cos-config-seed-repair.test.js@@ -0,0 +1,94 @@+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 migration, { RETIRED_SEED } from './340-cos-config-seed-repair.js';++const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 340 — repair a CoS config.json overwritten by the shipped seed', () => {+ let rootDir;+ let statePath;+ let configPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-340-'));+ mkdirSync(join(rootDir, 'data', 'cos'), { recursive: true });+ statePath = join(rootDir, 'data', 'cos', 'state.json');+ configPath = join(rootDir, 'data', 'cos', 'config.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('lifts the settings still in state.json over the seed', async () => {+ writeJson(configPath, RETIRED_SEED);+ writeJson(statePath, {+ running: true,+ config: { maxConcurrentAgents: 12, alwaysOn: true },+ agents: { 'agent-1': { status: 'running' } },+ });++ const result = await migration.up({ rootDir });++ expect(result).toEqual({ repaired: 'lifted', keys: 2 });+ expect(readJson(configPath)).toEqual({ maxConcurrentAgents: 12, alwaysOn: true });+ expect(readJson(statePath)).toEqual({ running: true, agents: { 'agent-1': { status: 'running' } } });+ });++ it('recovers from the newest quarantined state.json.corrupted.* holding a slice', async () => {+ writeJson(configPath, RETIRED_SEED);+ writeJson(statePath, { running: false, agents: {} });+ writeJson(`${statePath}.corrupted.1788000000000`, { config: { maxConcurrentAgents: 4 } });+ writeJson(`${statePath}.corrupted.1788472679099`, { config: { maxConcurrentAgents: 20, alwaysOn: true } });+ // Newer still, but carries no slice — must be skipped, not treated as empty.+ writeJson(`${statePath}.corrupted.1788999999999`, { running: false, agents: {} });++ const result = await migration.up({ rootDir });++ expect(result).toEqual({ repaired: 'recovered', keys: 2, source: 'state.json.corrupted.1788472679099' });+ expect(readJson(configPath)).toEqual({ maxConcurrentAgents: 20, alwaysOn: true });+ });++ it('deletes the seed when nothing anywhere has settings left to lift, so CoS reads DEFAULT_CONFIG', async () => {+ writeJson(configPath, RETIRED_SEED);+ writeJson(statePath, { running: false, agents: {} });++ const result = await migration.up({ rootDir });++ expect(result).toEqual({ repaired: 'removed' });+ expect(existsSync(configPath)).toBe(false);+ // The runtime file is not this migration's to touch on the delete branch.+ expect(readJson(statePath)).toEqual({ running: false, agents: {} });+ });++ it('leaves a user-written config.json — and its legacy slice — alone', async () => {+ const userConfig = { ...RETIRED_SEED, maxConcurrentAgents: 12 };+ writeJson(configPath, userConfig);+ writeJson(statePath, { running: false, config: { maxConcurrentAgents: 3 }, agents: {} });++ const result = await migration.up({ rootDir });++ expect(result).toEqual({ repaired: false, reason: 'config.json carries real settings' });+ expect(readJson(configPath)).toEqual(userConfig);+ // Deleting the slice here would destroy the only remaining pre-split copy.+ expect(readJson(statePath).config).toEqual({ maxConcurrentAgents: 3 });+ });++ it('is a no-op when config.json is absent (healthy or fresh install)', async () => {+ writeJson(statePath, { running: false, agents: {} });++ expect(await migration.up({ rootDir })).toEqual({ repaired: false, reason: 'no readable config.json' });+ expect(existsSync(configPath)).toBe(false);+ });++ it('leaves an unreadable config.json to the state loader’s quarantine path', async () => {+ writeFileSync(configPath, '{ truncated');++ expect(await migration.up({ rootDir })).toEqual({ repaired: false, reason: 'no readable config.json' });+ expect(existsSync(configPath)).toBe(true);+ });+});diff --git a/scripts/setup-data.js b/scripts/setup-data.jsindex 811245b2d7..16fc5fd808 100644--- a/scripts/setup-data.js+++ b/scripts/setup-data.js@@ -4,12 +4,23 @@ import { dirname, join } from 'path';import { fileURLToPath } from 'url';import { md5, buildPromptDriftTables } from './migrations/_lib.js';+import { MIGRATION_OWNED_PATHS } from './lib/migrationOwnedPaths.js';const __dirname = dirname(fileURLToPath(import.meta.url));const rootDir = join(__dirname, '..');const dataDir = join(rootDir, 'data');const referenceDir = join(rootDir, 'data.reference');+// Absolute data.reference paths this script must never copy: a migration builds+// each of them from the install's own records, and setup-data runs BEFORE+// run-migrations — so seeding one makes the migration see its output as already+// present, no-op, and leave shipped defaults where the user's settings were.+// See scripts/migrations/340-cos-config-seed-repair.js for the case that+// prompted it.+const migrationOwnedSeeds = new Set(+ [...MIGRATION_OWNED_PATHS].map((relPath) => join(referenceDir, ...relPath.split('/'))),+);+console.log('📁 Setting up data directory...');// One-shot cleanup for installs that predate the migrations-out-of-data move:@@ -33,7 +44,7 @@ if (existsSync(legacyMigrationsDir) && readdirSync(legacyMigrationsDir).length =if (!existsSync(dataDir)) {console.log('📁 Creating data directory from data.reference...');mkdirSync(dataDir, { recursive: true });- cpSync(referenceDir, dataDir, { recursive: true });+ cpSync(referenceDir, dataDir, { recursive: true, filter: (src) => !migrationOwnedSeeds.has(src) });// Replace __PORTOS_ROOT__ placeholder with actual install path in apps.jsonconst appsFile = join(dataDir, 'apps.json');@@ -52,6 +63,7 @@ if (!existsSync(dataDir)) {const items = readdirSync(srcDir);for (const item of items) {const srcPath = join(srcDir, item);+ if (migrationOwnedSeeds.has(srcPath)) continue;const destPath = join(destDir, item);const stat = statSync(srcPath);diff --git a/server/services/cosState.js b/server/services/cosState.jsindex 4aa30b7bbf..1441dcbb46 100644--- a/server/services/cosState.js+++ b/server/services/cosState.js@@ -69,7 +69,14 @@ export const DEFAULT_CONFIG = {improvementEnabled: true,avatarStyle: 'svg',dynamicAvatar: true,- alwaysOn: true,+ // Start CoS with the server. FALSE is the shipped posture: an install that+ // has never been configured must not begin autonomous, LLM-backed work on its+ // own (AGENTS.md, "No cold-bootstrap LLM calls"), and every other work-+ // generation flag below defaults on. This used to read `true` and was masked+ // by a `data.reference/cos/config.json` seed seeding `false` over it; the+ // seed is gone (see scripts/migrations/340-cos-config-seed-repair.js), so the+ // default is now the only thing a fresh install reads.+ alwaysOn: false,appReviewCooldownMs: 1800000,idleReviewEnabled: true,idleReviewPriority: 'MEDIUM',