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 (claude): converge branch-reconcile perpetual drain via progress signature
Adam Eivyf08ef6d2bf43
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b6bd455fbc..d1227a59cb 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. 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. (`server/services/branchReconcile.js`, `server/services/cosTaskGenerator.js`, `server/services/taskSchedule.js`, `server/services/taskPromptDefaults/prompts.js`)diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex dd1aa0a713..c12e14668d 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -304,6 +304,25 @@ export function desiredEndState(state, actions) {: ' Do NOT merge (auto-merge is disabled) — stop once the PR is green and ready for the user to merge.'}`;}+/**+ * Stable signature of an actionable set — used by the perpetual drain to detect+ * PROGRESS between dispatches. A productive coordinator run advances branches+ * through states (NEEDS_PR → IN_REVIEW → merged/cleaned) or removes them, all of+ * which change this signature; a run that leaves the SAME branches in the SAME+ * states (a `NEEDS_PR` branch the agent judged "not ready", an `IN_REVIEW` PR+ * blocked on human review / red CI) produces an identical signature, which the+ * generator treats as "no progress → park" instead of re-dispatching an+ * identical coordinator back-to-back. Order-independent (sorted).+ * @param {object[]} actionable - post-filterActionable branches+ * @returns {string}+ */+export function actionableSignature(actionable) {+ return actionable+ .map((b) => `${b.branch}:${b.state}:${b.openPr?.number ?? 'none'}`)+ .sort()+ .join('|');+}+/*** Render the actionable in-flight branch set into the coordinator prompt body* (injected as `{inFlightBranches}`).diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.jsindex 064388ec53..23c755501b 100644--- a/server/services/branchReconcile.test.js+++ b/server/services/branchReconcile.test.js@@ -37,7 +37,7 @@ vi.mock('../lib/fileUtils.js', () => ({import {classifyBranch, classifyBranches, cleanupMerged, reconcile, gatherBranchState, worktreeProtectionReason,- actionOn, filterActionable, desiredEndState, formatInFlightForPrompt+ actionOn, filterActionable, desiredEndState, formatInFlightForPrompt, actionableSignature} from './branchReconcile.js';import * as git from './git.js';import * as wt from './worktreeManager.js';@@ -247,6 +247,35 @@ describe('desiredEndState', () => {});});+describe('actionableSignature', () => {+ it('is order-independent', () => {+ const a = [{ branch: 'x', state: 'NEEDS_PR', openPr: null }, { branch: 'y', state: 'IN_REVIEW', openPr: { number: 5 } }];+ const b = [{ branch: 'y', state: 'IN_REVIEW', openPr: { number: 5 } }, { branch: 'x', state: 'NEEDS_PR', openPr: null }];+ expect(actionableSignature(a)).toBe(actionableSignature(b));+ });++ it('changes when a branch advances state (progress) — drives the drain forward', () => {+ const before = [{ branch: 'x', state: 'NEEDS_PR', openPr: null }];+ const after = [{ branch: 'x', state: 'IN_REVIEW', openPr: { number: 9 } }];+ expect(actionableSignature(before)).not.toBe(actionableSignature(after));+ });++ it('is identical for the same stuck set (no progress) — the park trigger', () => {+ const set = [{ branch: 'stuck', state: 'NEEDS_PR', openPr: null }];+ expect(actionableSignature(set)).toBe(actionableSignature([{ branch: 'stuck', state: 'NEEDS_PR', openPr: null }]));+ });++ it('changes when a branch leaves the set (merged/cleaned)', () => {+ const two = [{ branch: 'a', state: 'IN_REVIEW', openPr: { number: 1 } }, { branch: 'b', state: 'NEEDS_PR', openPr: null }];+ const one = [{ branch: 'b', state: 'NEEDS_PR', openPr: null }];+ expect(actionableSignature(two)).not.toBe(actionableSignature(one));+ });++ it('empty set yields an empty signature', () => {+ expect(actionableSignature([])).toBe('');+ });+});+describe('formatInFlightForPrompt', () => {it('renders the default branch, each branch with its PR + worktree + Do line', () => {const block = formatInFlightForPrompt([diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 8e4e86138e..7ec163dd14 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -1614,7 +1614,7 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st// work in the generator before dispatch.let inFlightBranchesBlock = '';if (taskType === 'branch-reconcile') {- const { reconcile, filterActionable, formatInFlightForPrompt } = await import('./branchReconcile.js');+ const { reconcile, filterActionable, formatInFlightForPrompt, actionableSignature } = await import('./branchReconcile.js');const { getActiveAgentIds } = await import('./agentState.js');// Action toggles were merged (global → per-app override) + value-constrained// by sanitizeTaskMetadata into `metadata`; each is ON unless explicitly false.@@ -1631,22 +1631,47 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, stemitLog('warn', `branch-reconcile pre-step failed for ${app.name}: ${err.message}`, { appId: app.id });return null;});- // A failed scan is transient (git/gh blip) — skip WITHOUT parking so the next- // tick retries instead of waiting out a full recheck cadence.+ // A failed scan is treated as transient (git/gh blip) — skip WITHOUT parking+ // so the next tick retries instead of waiting out a full recheck cadence.+ // Trade-off: a PERSISTENT failure (bad repoPath, broken gh auth, non-git dir)+ // re-probes git every tick. That's git/gh-only cost (no LLM), and parking on+ // the first failure would delay recovery from a genuine blip by a full+ // recheck cadence — so transient-skip is the intentional choice here.if (!result) return null;if (result.cleaned.length) {emitLog('info', `🔀 branch-reconcile ${app.name}: cleaned ${result.cleaned.length} merged branch(es)`, { appId: app.id, analysisType: taskType });}const actionable = filterActionable(result.inFlight, actions);if (actionable.length === 0) {- // Definitive idle: nothing in-flight to drive. Park on the recheck cadence.- await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-in-flight-branches', actionableCount: 0 });+ // Definitive idle: nothing in-flight to drive. Park on the recheck cadence+ // and clear the progress signature so a fresh set later dispatches.+ await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-in-flight-branches', actionableCount: 0, signature: null });emitLog('info', `🔀 branch-reconcile parked for ${app.name}: nothing in-flight (cleaned ${result.cleaned.length})`, { appId: app.id });return null;}- // Actionable work remains — resume the back-to-back drain and skip the- // post-completion cooldown so the next tick re-dispatches promptly.+ // 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.+ 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 });+ 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+ // of looping. Skip the post-completion cooldown so productive progress drains+ // back-to-back.await taskSchedule.clearPerpetualPark(taskType, app.id);+ await taskSchedule.setPerpetualSignature(taskType, app.id, signature);metadata.perpetual = true;inFlightBranchesBlock = formatInFlightForPrompt(actionable, { defaultBranch: result.defaultBranch, actions });emitLog('info', `🔀 branch-reconcile dispatching for ${app.name}: ${actionable.length} in-flight branch(es)`, { appId: app.id, analysisType: taskType });diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex ee503436ac..7995360449 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -742,7 +742,7 @@ function ensureExecutionRecord(schedule, taskType, appId) {* draining and wait until `parkedUntil` before re-probing. Stamps the park* fields on the (per-app or global) execution record.*/-export async function parkPerpetual(taskType, appId = null, { reason = null, actionableCount = 0 } = {}) {+export async function parkPerpetual(taskType, appId = null, { reason = null, actionableCount = 0, signature } = {}) {const schedule = await loadSchedule();const interval = schedule.tasks[taskType] || {};const parkedUntil = await computePerpetualRecheckAt(interval);@@ -751,12 +751,45 @@ export async function parkPerpetual(taskType, appId = null, { reason = null, actrecord.parkReason = reason;record.parkActionableCount = actionableCount;record.parkedAt = new Date().toISOString();+ // A drain that parks because a full cycle made NO progress (branch-reconcile's+ // 'no-progress' park) records the actionable signature it was stuck on, so the+ // next recheck can tell "same stuck set" (park again) from "the set changed"+ // (resume). `null` clears it (an idle park with nothing actionable); `undefined`+ // (the default) leaves any prior signature untouched.+ if (signature !== undefined) {+ if (signature === null) delete record.lastActionableSignature;+ else record.lastActionableSignature = signature;+ }await saveSchedule(schedule);emitLog('info', `Perpetual ${taskType} parked until ${parkedUntil} (${reason || 'idle'})`, { taskType, appId, parkedUntil }, '📅 TaskSchedule');cosEvents.emit('schedule:perpetual-parked', { taskType, appId, parkedUntil, reason });return record;}+/** Read the last actionable signature recorded for a perpetual drain (or null). */+export async function getPerpetualSignature(taskType, appId = null) {+ const schedule = await loadSchedule();+ const key = taskType.startsWith('task:') ? taskType : `task:${taskType}`;+ const top = schedule.executions[key];+ if (!top) return null;+ const record = appId ? top.perApp?.[appId] : top;+ return record?.lastActionableSignature ?? null;+}++/**+ * Record the actionable signature a perpetual drain is dispatching against, so a+ * later cycle that finds the same signature can recognize "no progress" and park+ * instead of re-dispatching an identical run. `null` clears it.+ */+export async function setPerpetualSignature(taskType, appId = null, signature) {+ const schedule = await loadSchedule();+ const record = ensureExecutionRecord(schedule, taskType, appId);+ if (signature == null) delete record.lastActionableSignature;+ else record.lastActionableSignature = signature;+ await saveSchedule(schedule);+ return record;+}+/*** Clear a perpetual task's park so the drain resumes (its work-detector found* actionable work). No-op (and no write) when there's nothing parked.diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsindex ee9ad99f6c..d1465763a8 100644--- a/server/services/taskSchedule.test.js+++ b/server/services/taskSchedule.test.js@@ -102,6 +102,8 @@ import {computePerpetualRecheckAt,parkPerpetual,clearPerpetualPark,+ getPerpetualSignature,+ setPerpetualSignature,PROMPT_VERSIONS,DEFAULT_TASK_INTERVALS,MANAGED_AGENT_OPTIONS,@@ -1293,6 +1295,47 @@ describe('taskSchedule', () => {})expect(await clearPerpetualPark('claim-issue', 'app-1')).toBe(false)})++ it('parkPerpetual stores an actionable signature and getPerpetualSignature reads it back', async () => {+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } } })+ await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-progress', actionableCount: 2, signature: 'a:NEEDS_PR:none|b:IN_REVIEW:5' })+ const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])+ expect(saved.executions['task:branch-reconcile'].perApp['app-1'].lastActionableSignature).toBe('a:NEEDS_PR:none|b:IN_REVIEW:5')+ })++ it('getPerpetualSignature returns the stored signature (and null when absent)', async () => {+ mockSchedule({+ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } },+ executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, lastActionableSignature: 'sig-1' } } } }+ })+ expect(await getPerpetualSignature('branch-reconcile', 'app-1')).toBe('sig-1')+ expect(await getPerpetualSignature('branch-reconcile', 'app-2')).toBeNull()+ })++ it('setPerpetualSignature writes it, and null clears it', async () => {+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } } })+ await setPerpetualSignature('branch-reconcile', 'app-1', 'sig-2')+ let saved = JSON.parse(writeFile.mock.calls.at(-1)[1])+ expect(saved.executions['task:branch-reconcile'].perApp['app-1'].lastActionableSignature).toBe('sig-2')++ mockSchedule({+ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } },+ executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, lastActionableSignature: 'sig-2' } } } }+ })+ await setPerpetualSignature('branch-reconcile', 'app-1', null)+ saved = JSON.parse(writeFile.mock.calls.at(-1)[1])+ expect(saved.executions['task:branch-reconcile'].perApp['app-1'].lastActionableSignature).toBeUndefined()+ })++ it('parkPerpetual with signature:null clears a prior signature (idle park)', async () => {+ mockSchedule({+ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } },+ executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, lastActionableSignature: 'old-sig' } } } }+ })+ await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-in-flight-branches', actionableCount: 0, signature: null })+ const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])+ expect(saved.executions['task:branch-reconcile'].perApp['app-1'].lastActionableSignature).toBeUndefined()+ })})describe('updateTaskInterval recompute-on-cadence-change', () => {