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

Retain bounded cleanup quarantine across broker restart

[._.]/ Adam Eivyd6f9c5812e9a
diff --git a/docs/features/managed-visitors.md b/docs/features/managed-visitors.md
index 64243a763b..d1c7e58d53 100644
--- a/docs/features/managed-visitors.md
+++ b/docs/features/managed-visitors.md
@@ -67,3 +67,5 @@ This foundation does not implement connectome execution, retained learning, trav
When an admission times out before returning a session ID, use `POST /admissions/cancel` with exactly `{individualId,individualSessionId,worldId}` and the app credential. It cancels matching pending attempts and removes matching published visits, without touching another recipient or runtime session. The response contains `version`, `appId`, those scope IDs, `confirmed`, `pending` and nullable `expiresAt`. Keep local embodiment ownership paused while `confirmed:false`; retry cancellation until confirmed. A pending acknowledgment is cleaned when it arrives and cannot publish authority after cancellation.
Host negotiation additionally requires `admissionDeadline:true`. Every host admission carries `X-Managed-Visitor-Deadline`, an absolute same-machine wall-clock upper bound chosen before the host call. The host must validate it after consuming the body and clamp its lease expiry to that bound. If the host call itself times out without a lease ID, PortOS keeps a revoked unresolved receipt until this trustworthy deadline. Invalid host expiry values cannot extend that bound. A stale or older host lacking this capability is unavailable; no TTL is guessed from receipt time.
+
+After a broker restart, host leases may remain while their private receipt mappings have been lost. Unknown cleanup therefore remains unconfirmed until broker boot time plus the maximum 300,000 ms host lease. Original-scope cancellation exposes this bound; unknown session leave refuses premature confirmation. Exact current-process cleanup receipts remain immediately idempotent, and a successfully acknowledged current-process admission establishes its original scope. These bounded proof caches hold at most 256 entries; eviction can conservatively delay confirmation. Backward clock movement fails closed. No restart cleanup grants access outside the credential's individual/world allowlists.
diff --git a/server/routes/managedVisitors.test.js b/server/routes/managedVisitors.test.js
index 9211ff15a2..820658d0a1 100644
--- a/server/routes/managedVisitors.test.js
+++ b/server/routes/managedVisitors.test.js
@@ -169,15 +169,19 @@ it('cancels an unknown pending admission by original scope, waits for its acknow
expect(await shared.broker.cancelAdmission(auth, original)).toMatchObject({ confirmed: true, pending: false });
});
-it('an unknown host admission outcome remains quarantined through the exact broker-supplied deadline', async () => {
+it('an unknown host admission outcome respects sent and possible pre-boot lease deadlines', async () => {
+ credentials = await shared.broker.provision(appId, { ...credentialInput, ttlMs: 600000 });
+ const bootBound = clock + 300000;
const auth = await shared.broker.authenticate(credentials.credential);
host.admit.mockRejectedValueOnce(new Error('timeout without acknowledgment'));
await expect(shared.broker.admit(auth, admission)).rejects.toThrow(/timeout/);
const original = { individualId, individualSessionId, worldId };
expect(host.admit.mock.calls[0][1]).toEqual({ deadlineMs: clock + admission.ttlMs });
- expect(await shared.broker.cancelAdmission(auth, original)).toMatchObject({ confirmed: false, pending: false, expiresAt: clock + admission.ttlMs });
+ expect(await shared.broker.cancelAdmission(auth, original)).toMatchObject({ confirmed: false, pending: false, expiresAt: bootBound });
await expect(shared.broker.admit(auth, admission)).rejects.toThrow(/already/);
clock += admission.ttlMs;
+ expect((await shared.broker.cancelAdmission(auth, original)).confirmed).toBe(false);
+ clock = bootBound;
expect(await shared.broker.cancelAdmission(auth, original)).toMatchObject({ confirmed: true, pending: false });
});
@@ -191,13 +195,35 @@ it('an unconfirmed leave revokes a pending action even while retaining its clean
await expect(shared.broker.leave(auth, visit.sessionId, scope(visit))).rejects.toThrow(/unconfirmed/);
release(); await expect(pending).rejects.toThrow(/revoked/);
});
-it('an invalid host expiry cannot extend quarantine beyond the broker admission deadline', async () => {
+it('an invalid host expiry cannot extend quarantine beyond trusted admission and boot bounds', async () => {
+ credentials = await shared.broker.provision(appId, { ...credentialInput, ttlMs: 600000 });
+ const bootBound = clock + 300000;
const auth = await shared.broker.authenticate(credentials.credential), normal = host.admit.getMockImplementation();
host.admit.mockImplementationOnce(async body => ({ ...await normal(body), expiresAt: clock + 999999 }));
host.leave.mockRejectedValue(new Error('offline'));
await expect(shared.broker.admit(auth, admission)).rejects.toThrow(/expired/);
const original = { individualId, individualSessionId, worldId };
- expect((await shared.broker.cancelAdmission(auth, original)).expiresAt).toBe(clock + admission.ttlMs);
- clock += admission.ttlMs;
+ expect((await shared.broker.cancelAdmission(auth, original)).expiresAt).toBe(bootBound);
+ clock = bootBound;
expect((await shared.broker.cancelAdmission(auth, original)).confirmed).toBe(true);
});
+
+// Restart deliberately reuses persisted credentials and the still-live host, not session maps.
+it('does not confirm unknown cleanup after restart before the maximum pre-boot lease expires', async () => {
+ credentials = await shared.broker.provision(appId, { ...credentialInput, ttlMs: 600000 });
+ const auth = await shared.broker.authenticate(credentials.credential);
+ const visit = await shared.broker.admit(auth, { ...admission, ttlMs: 300000 });
+ const rebooted = createManagedVisitorBroker({ path: join(directory, 'credentials.json'), getApp: async id => ({ id }), host, now: () => clock });
+ const original = { individualId, individualSessionId, worldId };
+ await expect(rebooted.leave(auth, visit.sessionId, scope(visit))).rejects.toThrow(/restart.*unconfirmed/);
+ expect(host.leave).not.toHaveBeenCalled();
+ expect(await rebooted.cancelAdmission(auth, original)).toMatchObject({ confirmed: false, pending: false, expiresAt: clock + 300000 });
+ await expect(rebooted.leave(auth, visit.sessionId, { ...scope(visit), individualId: 'outside' })).rejects.toThrow(/scope/);
+ clock += 299999;
+ expect((await rebooted.cancelAdmission(auth, original)).confirmed).toBe(false);
+ clock += 1;
+ expect((await rebooted.leave(auth, visit.sessionId, scope(visit))).status).toBe('left');
+ expect((await rebooted.cancelAdmission(auth, original)).confirmed).toBe(true);
+ clock -= 1;
+ await expect(rebooted.cancelAdmission(auth, original)).rejects.toThrow(/clock/);
+});
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 8907a78834..9d189a39e3 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -69,7 +69,7 @@ import { EventEmitter } from 'events';
import { createHash } from 'crypto';
import { hostname } from 'os';
import { PassThrough } from 'node:stream';
-import { spawn as spawnChild } from 'node:child_process';
+import { spawn as spawnChild, spawnSync } from 'node:child_process';
import { spawn } from '../lib/childProcess.js';
// Partial mock: only override spawn. Preserve execFile et al. because
// backup.js transitively imports fileUtils.js, which promisifies execFile.
@@ -1482,7 +1482,13 @@ describe('restoreSnapshot manifest verification', () => {
});
});
- it('restores differing bytes when size and mtime match through real rsync', async () => {
+ it('restores differing bytes when size and mtime match through real rsync', async context => {
+ // Windows CI does not provision MSYS rsync. Unix coverage remains mandatory;
+ // installed Windows rsync errors still fail this test rather than being hidden.
+ if (process.platform === 'win32' && spawnSync('rsync', ['--version']).error?.code === 'ENOENT') {
+ context.skip('Windows runner has no rsync executable; real rsync remains required on Linux/macOS.');
+ return;
+ }
const relativePath = 'brain/example.json';
const snapshotContent = '{"value":"old"}';
const liveContent = '{"value":"new"}';
diff --git a/server/services/managedVisitorBroker.js b/server/services/managedVisitorBroker.js
index 1a93599bb4..483baa82ed 100644
--- a/server/services/managedVisitorBroker.js
+++ b/server/services/managedVisitorBroker.js
@@ -27,6 +27,12 @@ export function createManagedVisitorBroker({ path, getApp, host, now = Date.now
const queue = createFileWriteQueue(), sessions = new Map(), pendingAdmissions = new Map();
const wallNow = now;
let lastTime = wallNow();
+ if (!Number.isSafeInteger(lastTime) || lastTime < 0 || !Number.isSafeInteger(lastTime + 300000)) throw fail('Broker boot clock is invalid.');
+ const bootQuarantineUntil = lastTime + 300000;
+ const confirmedSessions = new Map(), confirmedScopes = new Map();
+ const originalScopeKey = scope => JSON.stringify([scope.appId, scope.individualId, scope.individualSessionId, scope.worldId]);
+ function remember(map, key, value) { map.set(key, value); if (map.size > 256) map.delete(map.keys().next().value); }
+ function unknownCleanupBound(scope) { return confirmedScopes.has(originalScopeKey(scope)) || time() >= bootQuarantineUntil ? null : bootQuarantineUntil; }
function time() {
const current = wallNow();
if (!Number.isSafeInteger(current) || current < lastTime) {
@@ -68,7 +74,11 @@ export function createManagedVisitorBroker({ path, getApp, host, now = Date.now
sessions.set(session.id, session);
const acknowledged = wallNow() >= (session.admissionDeadline ?? session.hostExpiresAt) || session.hostId !== null && await host.leave(session.hostId, session.scope)
.then(result => result?.status === 'left' && result.sessionId === session.hostId && scopeKeys.every(key => result[key] === session.scope[key]), () => false);
- if (acknowledged) sessions.delete(session.id);
+ if (acknowledged) {
+ sessions.delete(session.id);
+ remember(confirmedSessions, session.id, { ...session.scope });
+ if (session.provenAdmission) remember(confirmedScopes, originalScopeKey(session.scope), true);
+ }
return acknowledged;
}
async function revokeSessions(appId) { await Promise.all([...sessions.values()].filter(s => s.scope.appId === appId).map(close)); }
@@ -130,9 +140,11 @@ export function createManagedVisitorBroker({ path, getApp, host, now = Date.now
session.expiresAt = Math.min(result.expiresAt, begin + ttlMs);
const valid = session.expiresAt > time() && result.expiresAt <= time() + ttlMs;
// Rotation while an admission is pending must not publish fresh authority from the old credential.
+ session.provenAdmission = valid;
const current = await credential(auth).then(() => true, () => false);
if (!valid || !current || attempt.canceled) throw fail('Admission expired or credential changed during negotiation.');
sessions.set(session.id, session);
+ remember(confirmedScopes, originalScopeKey(session.scope), true);
return { ...result, sessionId: session.id, expiresAt: session.expiresAt };
})().catch(async error => { if (candidate) await close(candidate); throw error; })
.finally(() => { if (pendingAdmissions.get(key) === attempt) pendingAdmissions.delete(key); });
@@ -169,9 +181,15 @@ export function createManagedVisitorBroker({ path, getApp, host, now = Date.now
}
async function leave(auth, id, input) {
- const request = visitorScopeSchema.parse(input); await credential(auth);
+ const request = visitorScopeSchema.parse(input), c = await credential(auth);
+ if (!c.individualIds.includes(request.individualId) || !c.worldIds.includes(request.worldId)) throw fail('Cleanup is outside the approved app scope.', 403);
const session = sessions.get(id);
- if (!session) return { version: 1, appId: auth.appId, ...request, sessionId: id, status: 'left' };
+ if (!session) {
+ const receipt = confirmedSessions.get(id);
+ if (receipt && scopeKeys.some(key => receipt[key] !== (key === 'appId' ? auth.appId : request[key]))) throw fail('Visitor cleanup scope mismatch.', 403);
+ if (!receipt && time() < bootQuarantineUntil) throw fail('Unknown cleanup after broker restart is unconfirmed until the maximum host lease deadline.');
+ return { version: 1, appId: auth.appId, ...request, sessionId: id, status: 'left' };
+ }
if (session.scope.appId !== auth.appId || scopeKeys.some(key => (key === 'appId' ? auth.appId : request[key]) !== session.scope[key])) throw fail('Visitor cleanup scope mismatch.', 403);
if (!await close(session)) throw fail('Host cleanup is unconfirmed; retain paused ownership until retry or expiry.');
return { version: 1, appId: auth.appId, ...request, sessionId: id, status: 'left' };
@@ -184,8 +202,9 @@ export function createManagedVisitorBroker({ path, getApp, host, now = Date.now
await Promise.all([...sessions.values()].filter(session => matches(session.scope)).map(close));
const pending = [...pendingAdmissions.values()].some(attempt => matches(attempt.scope));
const unresolved = [...sessions.values()].filter(session => matches(session.scope));
- return { version: 1, appId: auth.appId, ...request, confirmed: !pending && !unresolved.length, pending,
- expiresAt: pending ? null : unresolved.length ? Math.max(...unresolved.map(session => session.admissionDeadline ?? session.hostExpiresAt)) : null };
+ const bootBound = unknownCleanupBound({ appId: auth.appId, ...request });
+ return { version: 1, appId: auth.appId, ...request, confirmed: !pending && !unresolved.length && bootBound === null, pending,
+ expiresAt: pending ? null : unresolved.length || bootBound !== null ? Math.max(bootBound ?? 0, ...unresolved.map(session => session.admissionDeadline ?? session.hostExpiresAt)) : null };
}
return { authenticate, provision, revoke, capabilities, admit, leave, cancelAdmission,
listCredentials: async () => (await read()).credentials.map(publicCredential),