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

fix: preserve checkout identity across native Git path spellings

[._.]/ Adam Eivyaaa18a031db7
diff --git a/server/services/agentCompletionRetirement.integration.test.js b/server/services/agentCompletionRetirement.integration.test.js
index d98e5c7784..764fbcef26 100644
--- a/server/services/agentCompletionRetirement.integration.test.js
+++ b/server/services/agentCompletionRetirement.integration.test.js
@@ -1,13 +1,20 @@
/** No-inventory completion must retain one exact obligation through execution release and real preservation. */
import { afterEach, afterAll, describe, expect, it, vi } from 'vitest';
import { mkdtemp, mkdir, readFile, writeFile, rm, realpath } from 'node:fs/promises';
-import { join } from 'node:path';
+import { join, sep, resolve } from 'node:path';
import { tmpdir } from 'node:os';
import { materializeGitRepo } from '../lib/gitTestRepo.js';
import { execGit } from '../lib/execGit.js';
import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
-const fixture = vi.hoisted(() => ({ root: null, app: null, forge: null, task: null, agents: {}, schedule: null, raceTaskEdit: false }));
+const fixture = vi.hoisted(() => ({ root: null, app: null, forge: null, task: null, agents: {}, schedule: null, raceTaskEdit: false, inventoryAlias: false }));
vi.mock('../lib/paths.js', async original => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('portos-completion-retirement-state-') }));
+// Keep real Git and teardown; vary only the lexical spelling returned by its
+// inventory adapter, like Git-forward versus native Windows separators.
+vi.mock('./worktreeManager.js', async original => {
+ const actual = await original();
+ return { ...actual, listWorktrees: async (...args) => (await actual.listWorktrees(...args)).map(tree =>
+ fixture.inventoryAlias && tree.branch === 'refs/heads/claim/issue-42' ? { ...tree, path: `${tree.path}${sep}.` } : tree) };
+});
vi.mock('./cos.js', () => ({}));
vi.mock('./domainUsage.js', () => ({ recordDomainUsage: async () => {} }));
vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn(), cosEvents: { emit: vi.fn() } }));
@@ -54,7 +61,7 @@ const { PATHS } = await import('../lib/paths.js');
const { cosEvents } = await import('./cosEvents.js');
afterAll(cleanupTempDataRoots);
let scratch;
-afterEach(async () => { activeAgents.clear(); if (scratch) await rm(scratch, { recursive: true, force: true, maxRetries: 3 }); });
+afterEach(async () => { fixture.inventoryAlias = false; activeAgents.clear(); if (scratch) await rm(scratch, { recursive: true, force: true, maxRetries: 3 }); });
describe('completion to archive retirement (real Git and persisted service state)', () => {
it('drains context-less legacy handoffs instead of sweeping nonretryable failures forever', async () => {
scratch = await mkdtemp(join(tmpdir(), 'portos-completion-sweep-'));
@@ -81,9 +88,10 @@ describe('completion to archive retirement (real Git and persisted service state
expect(fixture.task.status).toBe('completed');
});
- it.each(['unchanged', 'changed-dispatch', 'concurrent-task-edit', 'claim-reacquired'])('recovers the missing task handoff after restart with exact task CAS (%s)', async scenario => {
- const changed = scenario !== 'unchanged';
+ it.each(['unchanged', 'lexical-workspace', 'changed-dispatch', 'concurrent-task-edit', 'claim-reacquired'])('recovers the missing task handoff after restart with exact task CAS (%s)', async scenario => {
+ const changed = !['unchanged', 'lexical-workspace'].includes(scenario);
fixture.raceTaskEdit = false;
+ fixture.inventoryAlias = scenario === 'lexical-workspace';
cosEvents.emit.mockClear();
scratch = await mkdtemp(join(tmpdir(), 'portos-completion-retirement-'));
fixture.root = PATHS.data; await mkdir(fixture.root, { recursive: true });
@@ -162,7 +170,8 @@ describe('completion to archive retirement (real Git and persisted service state
const restored = join(scratch, 'restored.git'); await execGit(['init', '--bare', restored], scratch);
await execGit(['bundle', 'unbundle', join(receipt.archiveDir, 'commits.bundle')], restored);
expect((await execGit(['show', `${head}:feature.txt`], restored)).stdout).toBe('delivered original\n');
- expect((await execGit(['worktree', 'list', '--porcelain'], repo)).stdout).not.toContain(path);
+ const { listWorktrees } = await import('./worktreeManager.js');
+ expect((await listWorktrees(repo)).some(tree => resolve(tree.path) === resolve(path))).toBe(false);
expect((await execGit(['rev-parse', '--verify', `refs/heads/${branch}`], repo, { ignoreExitCode: true })).exitCode).not.toBe(0);
expect(JSON.parse(await readFile(join(fixture.root, 'task.json'), 'utf8')).status).toBe('completed');
await verify(); expect((await getBranchReconcileOutcome(fixture.app.id)).retired).toHaveLength(1);
diff --git a/server/services/agentFinalization.retireDeadAgent.test.js b/server/services/agentFinalization.retireDeadAgent.test.js
index 65742ee202..353204393a 100644
--- a/server/services/agentFinalization.retireDeadAgent.test.js
+++ b/server/services/agentFinalization.retireDeadAgent.test.js
@@ -14,7 +14,11 @@
* the ORCHESTRATION — order, the private-security override, and which
* per-caller facts land where.
*/
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
+vi.mock('../lib/paths.js', async original => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('portos-retire-dead-agent-') }));
+afterAll(cleanupTempDataRoots);
vi.mock('./cosAgentLifecycle.js', () => ({
getAgent: vi.fn(async () => null),
diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.js
index d4cd92914e..4b2155b41f 100644
--- a/server/services/agentRepoStateVerification.js
+++ b/server/services/agentRepoStateVerification.js
@@ -564,8 +564,12 @@ async function resolveCheckoutIncarnation({ metadata, sourceWorkspace, branchNam
const inventory = await listWorktrees(sourceWorkspace).catch(() => null);
if (!inventory) return { reason: 'checkout-inventory-unavailable' };
const holders = inventory.filter(tree => tree.branch?.replace(/^refs\/heads\//, '') === branchName);
- const pathHolder = inventory.find(tree => tree.path === worktreePath);
- if (holders.some(tree => tree.path !== worktreePath)
+ // Git porcelain uses forward slashes on Windows; registration spelling is
+ // not an incarnation change. Resolve only native lexical path syntax here;
+ // the persisted pointer/private-administration identity is still checked below.
+ const samePath = tree => resolve(tree.path) === resolve(worktreePath);
+ const pathHolder = inventory.find(samePath);
+ if (holders.some(tree => !samePath(tree))
|| (pathHolder && pathHolder.branch?.replace(/^refs\/heads\//, '') !== branchName)) {
return { reason: 'checkout-incarnation-changed' };
}
@@ -718,13 +722,13 @@ async function prepareRecoveryRetirement({ agentId, app, sourceWorkspace, branch
if (!app?.id || !app.repoPath || resolve(app.repoPath) !== resolve(sourceWorkspace)) return { reason: 'retirement-app-unavailable' };
const trees = await listWorktrees(sourceWorkspace);
const matches = trees.filter(tree => tree.branch?.replace(/^refs\/heads\//, '') === branchName
- && (!worktreePath || tree.path === worktreePath));
+ && (!worktreePath || resolve(tree.path) === resolve(worktreePath)));
if (matches.length !== 1 || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(matches[0].head || '')) {
return { reason: 'retirement-exact-inventory-unavailable' };
}
const tree = matches[0];
const checkoutIdentity = await readRetirementCheckoutIdentity(tree.path);
- const release = { branch: branchName, path: tree.path, head: tree.head,
+ const release = { branch: branchName, path: worktreePath || tree.path, head: tree.head,
...(checkoutIdentity && { checkoutIdentity, observedAt: new Date().toISOString() }),
locked: tree.locked === true, lockReason: tree.lockReason ?? null };
const { recordBranchReconcileOutcome } = await import('./taskSchedule.js');
diff --git a/server/services/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.js
index 2496291d71..1dc39c86b7 100644
--- a/server/services/heldCheckoutRecovery.js
+++ b/server/services/heldCheckoutRecovery.js
@@ -834,9 +834,15 @@ async function matchesObservedCheckoutIncarnation(repoPath, release, worktrees =
async function matchRelease(repoPath, release) {
const trees = await listWorktrees(repoPath).catch(() => null);
if (!trees?.length) return { reason: 'worktree-ownership-unreadable' };
- const index = trees.findIndex(tree => tree.path === release.path);
+ const index = trees.findIndex(tree => resolve(tree.path) === resolve(release.path));
if (index === -1) return { reason: 'checkout-not-found' };
const tree = trees[index];
+ // Lexical equality alone can collapse '..' across a symlink. Different
+ // spellings must also resolve to the same existing filesystem checkout.
+ if (tree.path !== release.path) {
+ try { if (realpathSync.native(tree.path) !== realpathSync.native(release.path)) return { reason: 'checkout-identity-changed' }; }
+ catch { return { reason: 'checkout-identity-changed' }; }
+ }
if (index === 0 || tree.bare) return { reason: 'checkout-primary' };
if (tree.prunable) return { reason: 'worktree-prunable' };
if (tree.head !== release.head) return { reason: 'checkout-head-changed' };
@@ -845,7 +851,10 @@ async function matchRelease(repoPath, release) {
return { reason: 'checkout-lock-changed' };
}
if (!await matchesObservedCheckoutIncarnation(repoPath, release, trees)) return { reason: 'checkout-identity-changed' };
- return { tree };
+ // Carry the persisted release spelling through archive/receipt publication.
+ // Native lexical resolution above proves it names this registration; fresh
+ // head, lock and incarnation checks still bind the filesystem generation.
+ return { tree: { ...tree, path: release.path } };
}
/** Shared live policy/owner check for the explicit whole-checkout transaction.
diff --git a/server/services/heldCheckoutRecovery.test.js b/server/services/heldCheckoutRecovery.test.js
index e5c21100aa..5ac30214cd 100644
--- a/server/services/heldCheckoutRecovery.test.js
+++ b/server/services/heldCheckoutRecovery.test.js
@@ -855,6 +855,25 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
expect(await archives()).toEqual([]);
});
+ it('refuses a lexically equal release when the filesystem resolver identifies a different checkout', async () => {
+ const c = await heldCheckout('physical-alias-mismatch', { branch: 'feature/physical-alias-mismatch' });
+ const release = { ...c.release, path: `${c.path}/.` };
+ const originalRealpath = realpathSync.native;
+ // Inject at the filesystem boundary: lexical '..' across a symlink can
+ // name a different physical directory. Windows and POSIX resolve that
+ // syntax differently, so pin the disagreement rather than OS parsing.
+ const resolver = vi.spyOn(realpathSync, 'native').mockImplementation((path, ...args) =>
+ originalRealpath(path === release.path ? external : path, ...args));
+ try {
+ expect(await retire(release)).toMatchObject({ ok: false, reason: 'checkout-identity-changed' });
+ } finally { resolver.mockRestore(); }
+ expect(await registered(c.path)).toBe(true);
+ expect(await readFile(join(c.path, 'ignored.txt'), 'utf8')).toBe('ignored work\n');
+ expect(await lockText(c.path)).toBe(c.release.lockReason);
+ expect((await execGit(['rev-parse', `refs/heads/${c.release.branch}`], repo)).stdout.trim()).toBe(c.release.head);
+ expect(await archives()).toEqual([]);
+ });
+
it('keeps the checkout, its content and its original lock when an owner appears after the archive', async () => {
const { path, release } = await heldCheckout('owner-arrives', { lockReason: 'handoff pending' });
let reads = 0;