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
address review (codex): fix IN_REVIEW drain stall + migrate old branchReconcile opt-ins
Adam Eivyabffd1b86138
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d1227a59cb..8ddf04c6d9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -117,4 +117,4 @@- **`getSettings()` now serves from an in-memory cache instead of re-reading settings.json on every call.** `getSettings()` is invoked 100+ times across the codebase (several per request), each previously doing a fresh filesystem read + JSON.parse of app-wide, rarely-changing data. It now memoizes the parsed settings, populated lazily on first read and refreshed off the `settings:updated` event that every `save()`/`updateSettings()`/`updateSettingsWith()` already emits — so app-driven writes keep the cache coherent while write paths still read fresh off disk inside their write queue for the read-merge-write, preserving write-ordering guarantees. Mirrors the existing `settings:updated`-invalidated cache in `sharing/annotationIdentity.js`. Alongside it, a few independent per-file read loops are now parallelized (`digital-twin-analysis.validateCompleteness`, editorial series-health's series+settings load) and hot page derivations memoized (`Review` grouping/sorting, `Tribe` care-queue), cutting redundant work on socket-driven re-renders.-- **Branch & PR reconciliation now runs on any managed app as a Chief-of-Staff scheduled task — not just PortOS.** The branch reconciler (finish this machine's unfinished local git work: delete fully-merged orphaned branches + their worktrees, open PRs for pushed-but-unopened work, resolve merge conflicts, drive the review loop, and auto-merge when a PR is green) used to be a PortOS-only feature with its own daily cron, `/api/branch-reconcile` route, `settings.branchReconcile` toggle, and a dedicated Settings tab — hardwired to the PortOS checkout. It is now a first-class per-app CoS task type, **`branch-reconcile`**, configured like every other improvement task (per-app enable, provider/model, cadence, cooldown, budget) under Chief of Staff → task scheduling. It runs `perpetual` (drain-until-done): each dispatch runs the deterministic, peer-safe cleanup + classification against the *app's* repo, dispatches the coordinator agent only while actionable in-flight branches remain, then parks on a daily recheck — so no agent is burned on a no-op run. A progress-signature convergence guard ensures the drain only re-dispatches when the actionable set actually *changed* since the last run (a branch advanced NEEDS_PR→IN_REVIEW→merged, or a new/removed branch): a cycle that leaves the same branches in the same states (a branch judged "not ready", a PR blocked on human review or red CI) parks instead of re-spawning an identical coordinator back-to-back. The peer-safety guarantee is unchanged (only local `refs/heads/` are ever touched; a federated peer's branch exists here only as a remote-tracking ref and is structurally invisible), and the per-behavior toggles (`cleanupMerged` / `openPr` / `resolveConflicts` / `autoMerge`) are now per-app task-metadata overrides. Off by default; enabling it on an app is the user's explicit consent to let it drive PRs on a schedule. The old dedicated scheduler, route, settings key, and Settings tab are removed. (`server/services/branchReconcile.js`, `server/services/cosTaskGenerator.js`, `server/services/taskSchedule.js`, `server/services/taskPromptDefaults/prompts.js`)+- **Branch & PR reconciliation now runs on any managed app as a Chief-of-Staff scheduled task — not just PortOS.** The branch reconciler (finish this machine's unfinished local git work: delete fully-merged orphaned branches + their worktrees, open PRs for pushed-but-unopened work, resolve merge conflicts, drive the review loop, and auto-merge when a PR is green) used to be a PortOS-only feature with its own daily cron, `/api/branch-reconcile` route, `settings.branchReconcile` toggle, and a dedicated Settings tab — hardwired to the PortOS checkout. It is now a first-class per-app CoS task type, **`branch-reconcile`**, configured like every other improvement task (per-app enable, provider/model, cadence, cooldown, budget) under Chief of Staff → task scheduling. It runs `perpetual` (drain-until-done): each dispatch runs the deterministic, peer-safe cleanup + classification against the *app's* repo, dispatches the coordinator agent only while actionable in-flight branches remain, then parks on a daily recheck — so no agent is burned on a no-op run. A progress-signature convergence guard ensures the drain only re-dispatches when the actionable set actually *changed* since the last run (a branch advanced NEEDS_PR→IN_REVIEW→merged, or a new/removed branch): a cycle that leaves the same branches in the same states (a branch judged "not ready", a PR blocked on human review or red CI) parks instead of re-spawning an identical coordinator back-to-back. The peer-safety guarantee is unchanged (only local `refs/heads/` are ever touched; a federated peer's branch exists here only as a remote-tracking ref and is structurally invisible), and the per-behavior toggles (`cleanupMerged` / `openPr` / `resolveConflicts` / `autoMerge`) are now per-app task-metadata overrides. Off by default; enabling it on an app is the user's explicit consent to let it drive PRs on a schedule. The old dedicated scheduler, route, settings key, and Settings tab are removed; a migration (`scripts/migrations/170-branch-reconcile-to-cos-task.js`) carries a previously-enabled `branchReconcile` opt-in into the new task (cron→recheckCron, actions→per-app metadata) scoped to the PortOS app, and drops the dead settings key — so an install that had it on keeps reconciling instead of silently stopping. (`server/services/branchReconcile.js`, `server/services/cosTaskGenerator.js`, `server/services/taskSchedule.js`, `server/services/taskPromptDefaults/prompts.js`)diff --git a/scripts/migrations/170-branch-reconcile-to-cos-task.js b/scripts/migrations/170-branch-reconcile-to-cos-task.jsnew file mode 100644index 0000000000..78044c5d4d--- /dev/null+++ b/scripts/migrations/170-branch-reconcile-to-cos-task.js@@ -0,0 +1,117 @@+/**+ * Migrate the retired PortOS-only Branch & PR Reconciler into the new per-app+ * `branch-reconcile` Chief-of-Staff scheduled task.+ *+ * The old feature was a bespoke daily cron gated by `settings.branchReconcile`+ * (enabled/cron/actions), hardwired to the PortOS checkout. Its scheduler,+ * `/api/branch-reconcile` route, and settings schema were removed when the+ * feature became the per-app `branch-reconcile` task type — which is disabled by+ * default. Without this migration, an install that had `branchReconcile.enabled:+ * true` would silently STOP reconciling after the upgrade.+ *+ * This migration:+ * 1. If the old reconciler was ENABLED, enables the new `branch-reconcile`+ * task in the schedule, carrying `cron` → `recheckCron` and `actions` →+ * per-app action `taskMetadata` (cleanupMerged/openPr/resolveConflicts/+ * autoMerge). It preserves the old PortOS-only scope by disabling the task+ * (via `taskTypeOverrides`) on every OTHER managed app — the global enable+ * would otherwise run it everywhere. The PortOS baseline app (which owns the+ * install repo the old reconciler ran on) inherits the enable.+ * 2. Removes the now-dead `settings.branchReconcile` key (its scheduler/route/+ * schema are gone; leaving it would just be re-imported and renamed aside on+ * each boot).+ *+ * Idempotent: once the key is removed a re-run finds nothing and no-ops. When the+ * old reconciler was disabled, only the dead key is removed (no task is enabled).+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';++const SETTINGS_REL = 'data/settings.json';+const SCHEDULE_REL = 'data/cos/task-schedule.json';+const APPS_REL = 'data/apps.json';+const PORTOS_APP_ID = 'portos-default';++async function readJson(path) {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return null;+ try {+ return JSON.parse(raw);+ } catch {+ return null;+ }+}++const isObject = (v) => v && typeof v === 'object' && !Array.isArray(v);+/** ON unless explicitly false — mirrors the runtime `actionOn` opt-out semantics. */+const on = (actions, key) => actions?.[key] !== false;++export default {+ async up({ rootDir }) {+ const settingsPath = join(rootDir, SETTINGS_REL);+ const settings = await readJson(settingsPath);+ if (!isObject(settings) || !('branchReconcile' in settings)) {+ return { updated: 0, reason: 'no-branchReconcile-settings' };+ }++ const old = isObject(settings.branchReconcile) ? settings.branchReconcile : {};+ const wasEnabled = old.enabled === true;++ if (wasEnabled) {+ // 1a. Enable + configure the new task from the old settings.+ const schedulePath = join(rootDir, SCHEDULE_REL);+ const schedule = await readJson(schedulePath);+ if (isObject(schedule) && isObject(schedule.tasks)) {+ const task = isObject(schedule.tasks['branch-reconcile']) ? schedule.tasks['branch-reconcile'] : {};+ task.enabled = true;+ if (typeof old.cron === 'string' && old.cron.trim().split(/\s+/).length === 5) {+ task.recheckCron = old.cron;+ }+ const actions = isObject(old.actions) ? old.actions : {};+ task.taskMetadata = {+ ...(isObject(task.taskMetadata) ? task.taskMetadata : {}),+ useWorktree: false,+ openPR: false,+ cleanupMerged: on(actions, 'cleanupMerged'),+ openPr: on(actions, 'openPr'),+ resolveConflicts: on(actions, 'resolveConflicts'),+ autoMerge: on(actions, 'autoMerge')+ };+ schedule.tasks['branch-reconcile'] = task;+ await writeFile(schedulePath, `${JSON.stringify(schedule, null, 2)}\n`);+ console.log('📝 branch-reconcile: carried the enabled PortOS reconciler into the new per-app CoS task');+ } else {+ console.log('⚠️ branch-reconcile: no task-schedule.json to enable — loadSchedule will backfill the disabled default; enable it under Chief of Staff');+ }++ // 1b. Preserve PortOS-only scope: disable the task on every non-PortOS app.+ const appsPath = join(rootDir, APPS_REL);+ const appsData = await readJson(appsPath);+ if (isObject(appsData) && isObject(appsData.apps)) {+ let scoped = 0;+ for (const [appId, app] of Object.entries(appsData.apps)) {+ if (appId === PORTOS_APP_ID || !isObject(app)) continue;+ const overrides = isObject(app.taskTypeOverrides) ? app.taskTypeOverrides : {};+ if (overrides['branch-reconcile']?.enabled === false) continue;+ overrides['branch-reconcile'] = { ...(isObject(overrides['branch-reconcile']) ? overrides['branch-reconcile'] : {}), enabled: false };+ app.taskTypeOverrides = overrides;+ scoped += 1;+ }+ if (scoped > 0) {+ await writeFile(appsPath, `${JSON.stringify(appsData, null, 2)}\n`);+ console.log(`📝 branch-reconcile: preserved PortOS-only scope — disabled on ${scoped} other managed app(s) (re-enable per app under Chief of Staff)`);+ }+ }+ }++ // 2. Drop the dead settings key.+ delete settings.branchReconcile;+ await writeFile(settingsPath, `${JSON.stringify(settings, null, 2)}\n`);+ console.log(`✅ branch-reconcile: removed dead settings.branchReconcile key (was ${wasEnabled ? 'enabled → migrated to CoS task' : 'disabled'})`);+ return { updated: 1, wasEnabled };+ }+};diff --git a/scripts/migrations/170-branch-reconcile-to-cos-task.test.js b/scripts/migrations/170-branch-reconcile-to-cos-task.test.jsnew file mode 100644index 0000000000..61a5a31e67--- /dev/null+++ b/scripts/migrations/170-branch-reconcile-to-cos-task.test.js@@ -0,0 +1,109 @@+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 from './170-branch-reconcile-to-cos-task.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 170 — branch reconciler → per-app CoS task', () => {+ let rootDir, settingsPath, schedulePath, appsPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-170-'));+ mkdirSync(join(rootDir, 'data', 'cos'), { recursive: true });+ settingsPath = join(rootDir, 'data', 'settings.json');+ schedulePath = join(rootDir, 'data', 'cos', 'task-schedule.json');+ appsPath = join(rootDir, 'data', 'apps.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('no-ops when there is no settings.json (fresh install)', async () => {+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(0);+ expect(result.reason).toBe('no-branchReconcile-settings');+ });++ it('no-ops when settings has no branchReconcile key', async () => {+ writeJson(settingsPath, { theme: 'dark' });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(0);+ expect(result.reason).toBe('no-branchReconcile-settings');+ expect(readJson(settingsPath)).toEqual({ theme: 'dark' });+ });++ it('removes the dead key without enabling anything when the old reconciler was disabled', async () => {+ writeJson(settingsPath, { branchReconcile: { enabled: false, cron: '0 3 * * *' }, theme: 'dark' });+ writeJson(schedulePath, { tasks: { 'branch-reconcile': { enabled: false } } });+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ updated: 1, wasEnabled: false });+ expect('branchReconcile' in readJson(settingsPath)).toBe(false);+ expect(readJson(settingsPath).theme).toBe('dark');+ // Task stays disabled — user never opted in.+ expect(readJson(schedulePath).tasks['branch-reconcile'].enabled).toBe(false);+ });++ it('carries an enabled reconciler into the new task: cron→recheckCron, actions→taskMetadata', async () => {+ writeJson(settingsPath, {+ branchReconcile: { enabled: true, cron: '30 4 * * *', actions: { cleanupMerged: true, openPr: false, resolveConflicts: true, autoMerge: false } }+ });+ writeJson(schedulePath, { tasks: { 'branch-reconcile': { type: 'perpetual', enabled: false, taskMetadata: { useWorktree: false, openPR: false, cleanupMerged: true, openPr: true, resolveConflicts: true, autoMerge: true } } } });+ const result = await migration.up({ rootDir });+ expect(result.wasEnabled).toBe(true);++ const task = readJson(schedulePath).tasks['branch-reconcile'];+ expect(task.enabled).toBe(true);+ expect(task.recheckCron).toBe('30 4 * * *');+ expect(task.taskMetadata.openPr).toBe(false); // carried from actions+ expect(task.taskMetadata.autoMerge).toBe(false); // carried from actions+ expect(task.taskMetadata.cleanupMerged).toBe(true);+ expect(task.taskMetadata.resolveConflicts).toBe(true);+ // Managed isolation flags preserved.+ expect(task.taskMetadata.useWorktree).toBe(false);+ expect(task.taskMetadata.openPR).toBe(false);+ // Dead key gone.+ expect('branchReconcile' in readJson(settingsPath)).toBe(false);+ });++ it('absent action keys default to ON (opt-out semantics)', async () => {+ writeJson(settingsPath, { branchReconcile: { enabled: true, actions: {} } });+ writeJson(schedulePath, { tasks: { 'branch-reconcile': {} } });+ await migration.up({ rootDir });+ const meta = readJson(schedulePath).tasks['branch-reconcile'].taskMetadata;+ expect(meta).toMatchObject({ cleanupMerged: true, openPr: true, resolveConflicts: true, autoMerge: true });+ });++ it('preserves PortOS-only scope by disabling the task on other managed apps', async () => {+ writeJson(settingsPath, { branchReconcile: { enabled: true } });+ writeJson(schedulePath, { tasks: { 'branch-reconcile': {} } });+ writeJson(appsPath, {+ apps: {+ 'portos-default': { name: 'PortOS' },+ 'other-app': { name: 'Other', taskTypeOverrides: { security: { enabled: true } } },+ 'third-app': { name: 'Third' }+ }+ });+ await migration.up({ rootDir });+ const apps = readJson(appsPath).apps;+ // PortOS inherits the enable — no override added.+ expect(apps['portos-default'].taskTypeOverrides?.['branch-reconcile']).toBeUndefined();+ // Others are explicitly disabled, preserving unrelated overrides.+ expect(apps['other-app'].taskTypeOverrides['branch-reconcile'].enabled).toBe(false);+ expect(apps['other-app'].taskTypeOverrides.security.enabled).toBe(true);+ expect(apps['third-app'].taskTypeOverrides['branch-reconcile'].enabled).toBe(false);+ });++ it('is idempotent — re-running after the key is gone no-ops', async () => {+ writeJson(settingsPath, { branchReconcile: { enabled: true } });+ writeJson(schedulePath, { tasks: { 'branch-reconcile': {} } });+ await migration.up({ rootDir });+ const second = await migration.up({ rootDir });+ expect(second.updated).toBe(0);+ expect(second.reason).toBe('no-branchReconcile-settings');+ });+});diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex c12e14668d..d7d6d600cc 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -318,7 +318,7 @@ export function desiredEndState(state, actions) {*/export function actionableSignature(actionable) {return actionable- .map((b) => `${b.branch}:${b.state}:${b.openPr?.number ?? 'none'}`)+ .map((b) => `${b.branch}:${b.state}:${b.openPr?.number ?? 'none'}:${b.openPr?.mergeable ?? 'none'}`).sort().join('|');}diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.jsindex 23c755501b..829f4629a6 100644--- a/server/services/branchReconcile.test.js+++ b/server/services/branchReconcile.test.js@@ -271,6 +271,12 @@ describe('actionableSignature', () => {expect(actionableSignature(two)).not.toBe(actionableSignature(one));});+ it('changes when an IN_REVIEW PR becomes mergeable (readiness advanced within the same state)', () => {+ const unknown = [{ branch: 'a', state: 'IN_REVIEW', openPr: { number: 3, mergeable: 'UNKNOWN' } }];+ const mergeable = [{ branch: 'a', state: 'IN_REVIEW', openPr: { number: 3, mergeable: 'MERGEABLE' } }];+ expect(actionableSignature(unknown)).not.toBe(actionableSignature(mergeable));+ });+it('empty set yields an empty signature', () => {expect(actionableSignature([])).toBe('');});diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 7ec163dd14..e4403d3359 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -1649,25 +1649,30 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, stemitLog('info', `🔀 branch-reconcile parked for ${app.name}: nothing in-flight (cleaned ${result.cleaned.length})`, { appId: app.id });return null;}- // Convergence guard: dispatch only when the actionable set CHANGED since the- // last dispatch. A productive coordinator run advances branches through states- // (NEEDS_PR → IN_REVIEW → merged/cleaned), changing the signature — so the- // back-to-back drain keeps driving real progress. But a run that leaves the- // SAME branches in the SAME states (a NEEDS_PR branch judged "not ready", an- // IN_REVIEW PR blocked on human review / red CI) produces an identical- // signature; re-dispatching an identical coordinator would loop forever- // (metadata.perpetual bypasses the post-completion cooldown). Park it instead- // until the recheck cadence — or until a human advances the branch, which- // changes the signature and resumes the drain.+ // Convergence guard — kills the back-to-back re-dispatch loop WITHOUT stalling+ // slow PRs. The signature (branch:state:pr#:mergeable) is stored at dispatch;+ // when the perpetual-drain refill fires right after the coordinator completes+ // (metadata.perpetual bypasses the post-completion cooldown), we compare:+ // - signature CHANGED → the run made progress (branch advanced+ // NEEDS_PR→IN_REVIEW→merged/cleaned, conflicts resolved, PR became+ // mergeable) → keep draining back-to-back.+ // - signature UNCHANGED → the run left the same branches in the same states+ // (a NEEDS_PR branch judged "not ready", an IN_REVIEW PR blocked on human+ // review / red CI). Park on the recheck cadence AND CLEAR the stored+ // signature — so the next DAILY recheck re-dispatches unconditionally+ // (re-driving the PR in case CI turned green / review cleared overnight),+ // rather than seeing the same signature and re-parking forever. The+ // signature only suppresses the immediate back-to-back refill; it never+ // suppresses a recheck.const signature = actionableSignature(actionable);const lastSignature = await taskSchedule.getPerpetualSignature(taskType, app.id);if (signature === lastSignature) {- await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-progress', actionableCount: actionable.length, signature });- emitLog('info', `🔀 branch-reconcile parked for ${app.name}: ${actionable.length} branch(es) unchanged since last run (no progress)`, { appId: app.id });+ await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-progress', actionableCount: actionable.length, signature: null });+ emitLog('info', `🔀 branch-reconcile parked for ${app.name}: ${actionable.length} branch(es) unchanged since last run (no progress — will re-drive on next recheck)`, { appId: app.id });return null;}// New or advanced actionable set — drive it. Resume the drain (clear any park)- // and record the signature so an unproductive re-run next cycle parks instead+ // and record the signature so an unproductive back-to-back refill parks instead// of looping. Skip the post-completion cooldown so productive progress drains// back-to-back.await taskSchedule.clearPerpetualPark(taskType, app.id);