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: report machine-local reconciliation recovery truthfully
[._.]/ Adam Eivyda491589bd7f
diff --git a/server/services/branchReconcile.localCompletion.test.js b/server/services/branchReconcile.localCompletion.test.jsnew file mode 100644index 0000000000..5840494339--- /dev/null+++ b/server/services/branchReconcile.localCompletion.test.js@@ -0,0 +1,82 @@+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises';+import { realpathSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { execGit } from '../lib/execGit.js';+import { attachBareOrigin, materializeGitRepo, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/paths.js', async importOriginal => makePathsProxy(await importOriginal(), {+ dataRoot: () => lazyTempDataRoot('portos-local-reconcile-'),+}));+vi.mock('./cosClaimOwnership.js', () => ({ readClaimOwnershipAgents: async () => [] }));+vi.mock('./agentState.js', async importOriginal => ({ ...await importOriginal(), getActiveAgentIds: () => new Set() }));+vi.mock('./cosState.js', () => ({ readAgentsStateForSafetyCheck: async () => ({ trusted: true, agents: {} }) }));+vi.mock('./userTimezone.js', () => ({ getUserTimezone: async () => 'UTC' }));+vi.mock('./apps.js', () => ({ getAppById: async () => null }));+vi.mock('./supersededLedger.js', async importOriginal => ({ ...await importOriginal(), readVerdictLedger: async () => [] }));++import { PATHS } from '../lib/paths.js';+import { resolveBranchReconcileBlock } from './cosTaskPreStepBlocks.js';+import * as schedule from './taskSchedule.js';++describe.skipIf(SKIP_HEAVY_INTEGRATION)('machine-local reconciliation completion (two real clones)', () => {+ let scratch;+ let local;+ let peer;+ let app;+ const outcome = async () => JSON.parse(await readFile(join(PATHS.cos, 'task-schedule.json'), 'utf8'))+ .executions['task:branch-reconcile'].perApp[app.id].branchReconcileOutcome;+ const run = () => resolveBranchReconcileBlock(app, 'branch-reconcile', { cleanupMerged: false }, schedule);++ beforeAll(async () => {+ scratch = realpathSync(await mkdtemp(join(tmpdir(), 'portos-local-reconcile-git-')));+ local = join(scratch, 'local');+ await mkdir(local);+ await materializeGitRepo(local);+ const origin = await attachBareOrigin(scratch, local);+ peer = join(scratch, 'peer');+ await execGit(['clone', origin, peer], scratch);+ await execGit(['config', 'user.email', '[email protected]'], peer);+ await execGit(['config', 'user.name', 'Test'], peer);+ await execGit(['checkout', '-b', 'feature/peer-only'], peer);+ await writeFile(join(peer, 'peer.txt'), 'unpublished-on-local-machine\n');+ await execGit(['add', 'peer.txt'], peer);+ await execGit(['commit', '-m', 'peer work'], peer);+ await execGit(['push', '-u', 'origin', 'feature/peer-only'], peer);+ await execGit(['fetch', 'origin'], local);+ app = { id: 'local-example', name: 'Local example', repoPath: local };+ });+ afterAll(async () => {+ await rm(scratch, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+ await cleanupTempDataRoots();+ });++ it('persists a drained local outcome with visible peer-only inventory, but retains a real local checkout hold', async () => {+ const remoteBefore = (await execGit(['ls-remote', '--heads', 'origin'], local)).stdout;+ const peerBefore = (await execGit(['rev-parse', 'HEAD'], peer)).stdout;+ expect(await run()).toEqual({ skip: true });+ expect(await outcome()).toMatchObject({+ status: 'drained', remaining: [], nextAction: null,+ remoteInventory: { reported: [{ branch: 'feature/peer-only', reason: 'unmerged-remote-only' }], reaped: [] },+ });+ expect(await schedule.getBranchReconcileOutcome(app.id)).toMatchObject(await outcome());+ expect(await run()).toEqual({ skip: true });+ expect(await outcome()).toMatchObject({ status: 'drained', remaining: [],+ remoteInventory: { reported: [{ branch: 'feature/peer-only', reason: 'unmerged-remote-only' }] } });++ const held = join(scratch, 'held-local');+ await execGit(['worktree', 'add', '--detach', held, 'main'], local);+ await execGit(['worktree', 'lock', '--reason', 'explicit local owner handoff', held], local);+ expect(await run()).toEqual({ skip: true });+ expect(await outcome()).toMatchObject({+ status: 'incomplete',+ remaining: expect.arrayContaining([expect.objectContaining({ locked: true, reason: 'worktree-locked' })]),+ remoteInventory: { reported: [{ branch: 'feature/peer-only', reason: 'unmerged-remote-only' }] },+ });+ expect((await execGit(['ls-remote', '--heads', 'origin'], local)).stdout).toBe(remoteBefore);+ expect((await execGit(['rev-parse', 'HEAD'], peer)).stdout).toBe(peerBefore);+ expect((await execGit(['worktree', 'list', '--porcelain'], local)).stdout).toContain('explicit local owner handoff');+ });+});diff --git a/server/services/cosMergeHandoff.completedOwner.test.js b/server/services/cosMergeHandoff.completedOwner.test.jsindex 9e3a9aa9ec..d09281f5c6 100644--- a/server/services/cosMergeHandoff.completedOwner.test.js+++ b/server/services/cosMergeHandoff.completedOwner.test.js@@ -35,6 +35,19 @@ beforeEach(async () => {await rm(join(workspace, 'review-status'), { force: true });});describe('completed owner required review inspection', () => {+ it('keeps another instance owner separate even for the same repository branch and PR head', async () => {+ const foreign = structuredClone(f.agents[0]);+ foreign.id = 'other-instance-owner';+ foreign.metadata.sourceWorkspace = '/other-instance/repo';+ foreign.metadata.workspacePath = '/other-instance/worktree';+ f.agents.push(foreign);+ expect(await inspect()).toMatchObject({ disposition: 'review-required', agentId: 'owner' });+ f.agents = [foreign];+ expect(await inspect()).toMatchObject({ disposition: 'held', reason: 'review-owner-ambiguous' });+ expect(f.queue).toEqual([]);+ expect(f.pending).toEqual([]);+ });+it('establishes a missing nonoptional review without creating merge admission or changing backlog policy', async () => {const result = await inspect();expect(result).toMatchObject({ disposition: 'review-required', agentId: 'owner', originalTask: { id: 'task' },diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.jsindex 686637d266..5c91bef42d 100644--- a/server/services/cosTaskPreStepBlocks.js+++ b/server/services/cosTaskPreStepBlocks.js@@ -593,11 +593,14 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS// the repository contains only its default branch. Keep known holds visible.const dispatchedOutcome = await taskSchedule.recordBranchReconcileOutcome(app.id, {status: 'running', reason: 'batch-pending',+ // Shared-origin branches without a local ref/checkout may belong to another+ // install. Keep their report visible without making local completion wait+ // for that machine's work. Unknown remote state still fails closed below.+ remoteInventory: result.orphanRemotes ?? { reaped: [], reported: [] },remaining: [...idlePark.remaining,...allActionable.map(b => ({ ...(b.retirement?.release || { branch: b.branch }), reason: b.retirement ? 'retirement-review-pending' : 'actionable' })),...(result.orphanRemotes?.remoteUnavailable ? [{ reason: 'remote-state-unavailable' }] : []),- ...(result.orphanRemotes?.reported || []).map(b => ({ branch: typeof b === 'string' ? b : b.branch, reason: 'remote-branch-held' })),],nextAction: 'Continue the bounded sweep and rescan after the final batch.',});diff --git a/server/services/repoCleanupRecovery.js b/server/services/repoCleanupRecovery.jsindex dcf62f24fd..69a323e7f0 100644--- a/server/services/repoCleanupRecovery.js+++ b/server/services/repoCleanupRecovery.js@@ -57,10 +57,15 @@ export async function inspectOrQueueCompletedReview(input, deps = {}) {// successor can be identified, never reset its budget or blindly redispatch.return { disposition: 'held', reason: 'cleanup-publication-unverified' };}- const reason = task?.id ? (purpose === 'code-repair' ? 'code-repair-queued' : 'required-code-review-queued') : 'required-code-review-held';+ // An existing coordinator id is also returned on a refused resume. Keep its+ // ownership link without claiming it was queued or retrying its spent budget.+ const queued = Boolean(task?.id && !task.blocked && !task.deferred);+ const phase = queued ? 'dispatched' : task?.deferred ? 'deferred' : 'blocked';+ const reason = task?.blocked || (task?.deferred ? 'required-code-review-deferred'+ : queued ? (purpose === 'code-repair' ? 'code-repair-queued' : 'required-code-review-queued') : 'required-code-review-held');await lifecycle.recordRepoCleanupRecovery(inspected.agentId, target.branch, observation,- { phase: task?.id ? 'dispatched' : 'blocked', taskId: task?.id || null });+ { phase, taskId: task?.id || null, reason });await lifecycle.recordCleanupOutcome(inspected.agentId, { branch: target.branch, path: target.worktreePath,- status: task?.id ? 'pending' : 'blocked', reason, taskId: task?.id || null });- return { disposition: task?.id ? 'queued-review' : 'held', reason, taskId: task?.id || null };+ status: queued ? 'pending' : 'blocked', reason, taskId: task?.id || null });+ return { disposition: queued ? 'queued-review' : 'held', reason, taskId: task?.id || null };}diff --git a/server/services/repoCleanupRecovery.test.js b/server/services/repoCleanupRecovery.test.jsindex e16ab1de9c..fe80b52296 100644--- a/server/services/repoCleanupRecovery.test.js+++ b/server/services/repoCleanupRecovery.test.js@@ -22,6 +22,19 @@ function harness(inspection = required()) {}describe('completed cleanup review dispatch', () => {+ it.each([+ [{ id: 'review-1', blocked: 'Review coordinator retry budget exhausted or unreadable' }, 'blocked', 'Review coordinator retry budget exhausted or unreadable'],+ [{ id: 'review-1', deferred: true }, 'deferred', 'required-code-review-deferred'],+ ])('retains refused successors without claiming dispatch: %j', async (task, phase, reason) => {+ const deps = harness();+ deps.spawn.mockResolvedValue(task);+ expect(await inspectOrQueueCompletedReview(input, deps)).toEqual({ disposition: 'held', reason, taskId: 'review-1' });+ expect(deps.reservation()).toMatchObject({ phase, taskId: 'review-1', reason });+ expect(deps.lifecycle.recordCleanupOutcome).toHaveBeenCalledWith('owner', expect.objectContaining({ status: 'blocked', reason, taskId: 'review-1' }));+ for (let i = 0; i < 3; i++) await inspectOrQueueCompletedReview(input, deps);+ expect(deps.spawn).toHaveBeenCalledOnce();+ });+it('creates one exact configured review owner across 70 scans and joins existing successors without reserving', async () => {const deps = harness();expect(await inspectOrQueueCompletedReview(input, deps)).toMatchObject({ disposition: 'queued-review', taskId: 'review-1' });diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 4c24df4a7c..c7043d1bab 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -769,7 +769,7 @@ export async function isPerpetualParkActive(taskType, appId = null) {}/** Persist the latest deterministic sweep evidence independently of agent success. */-export async function recordBranchReconcileOutcome(appId, { status, reason, remaining, nextAction, retirementObligations: additionalObligations = [] }) {+export async function recordBranchReconcileOutcome(appId, { status, reason, remaining, nextAction, remoteInventory, retirementObligations: additionalObligations = [] }) {const outcome = await updateSchedule(async (schedule) => {const record = ensureExecutionRecord(schedule, 'branch-reconcile', appId);const now = new Date().toISOString();@@ -788,6 +788,7 @@ export async function recordBranchReconcileOutcome(appId, { status, reason, remaconst retained = retirementObligations.filter(obligation => !current?.some(row => sameRetirementCheckout(row, obligation)));record.branchReconcileOutcome = {...previous, status, reason, nextAction, updatedAt: now, retirementObligations,+ ...(remoteInventory !== undefined && { remoteInventory }),remaining: retained.length ? [...(current || []), ...retained] : current,observedAt: remaining === undefined ? record.branchReconcileOutcome?.observedAt ?? null : now,...(retirementObligations.some(row => row.reason === 'retirement-provenance-unverified') && missingPreservationStatus),