Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(pi): keep diagnostics and orphan cleanup conservative

zqchris6d7e6aadad65
diff --git a/apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts b/apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts
index b2b02cb69a..241fd7428b 100644
--- a/apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts
@@ -644,6 +644,38 @@ describe('Pi package executable-code boundary', () => {
}
});
+ it('returns startup diagnostics while cache persistence waits for another instance', async () => {
+ const { root } = await createPackage({ oversizedManifest: true });
+ const store = await import('../pi-package-store.js');
+ let release!: () => void;
+ lockRuntime.tail = new Promise<void>((resolve) => { release = resolve; });
+ try {
+ const result = await store.resolveManagedPiPackageResources({ startupTraceId: '0123456789abcdef' });
+ expect(result.packageRoots).toEqual([]);
+ await vi.waitFor(() => expect(lockRuntime.calls).toHaveLength(1));
+ expect(lockRuntime.calls[0]).toMatchObject({ label: 'pi-package-mutation', waitMs: 0 });
+ // Native loading is independent of both advisory analysis and its write.
+ await expect(store.resolveManagedPiNativePackagePaths()).resolves.toEqual([root]);
+ } finally {
+ release();
+ await store.listPiPackages();
+ }
+ });
+
+ it.each(['busy', 'unavailable'] as const)('skips optional cache persistence when the mutation lock is %s', async (reason) => {
+ const { root } = await createPackage({ oversizedManifest: true });
+ const store = await import('../pi-package-store.js');
+ lockRuntime.nextStatus = { held: false, reason };
+ await expect(store.resolveManagedPiPackageResources({ startupTraceId: '0123456789abcdef' }))
+ .resolves.toEqual({ extensions: [], skills: [], promptTemplates: [], packageRoots: [] });
+ await store.listPiPackages();
+ expect(lockRuntime.calls).toHaveLength(1);
+ expect(lockRuntime.calls[0]?.waitMs).toBe(0);
+ await expect(fs.readFile(path.join(runtime.userData, 'pi-package-home', 'cindy-package-state.json')))
+ .rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(store.resolveManagedPiNativePackagePaths()).resolves.toEqual([root]);
+ });
+
it('coalesces startup diagnostics and honors the existing short inspection cache', async () => {
const { root } = await createSkillOnlyPackage('npm:concurrent-startup-metadata');
const store = await import('../pi-package-store.js');
@@ -2162,6 +2194,7 @@ describe('Pi package executable-code boundary', () => {
packageRoots: [],
});
+ await store.listPiPackages(); // Wait for the optional background cache write.
const statePath = path.join(
runtime.userData,
'pi-package-home',
diff --git a/apps/desktop/src/main/maker-host/pi-package-store.ts b/apps/desktop/src/main/maker-host/pi-package-store.ts
index 972299f7b7..8396c02690 100644
--- a/apps/desktop/src/main/maker-host/pi-package-store.ts
+++ b/apps/desktop/src/main/maker-host/pi-package-store.ts
@@ -692,12 +692,15 @@ function mutationLockPath(): string {
return path.join(app.getPath('userData'), 'pi-package-home.mutation.lock');
}
-async function withPiPackageMutationLock<T>(operation: () => Promise<T>): Promise<T> {
+async function withPiPackageMutationLock<T>(
+ operation: () => Promise<T>,
+ waitMs = PACKAGE_MUTATION_LOCK_WAIT_MS,
+): Promise<T> {
const lockPath = mutationLockPath();
await fs.mkdir(path.dirname(lockPath), { recursive: true, mode: 0o700 });
return withSecurityBoundaryLock(
lockPath,
- { label: 'pi-package-mutation', waitMs: PACKAGE_MUTATION_LOCK_WAIT_MS },
+ { label: 'pi-package-mutation', waitMs },
async (status) => {
if (!status.held) {
throw new Error('Pi extension store is busy or unavailable');
@@ -2409,8 +2412,18 @@ export async function resolveManagedPiPackageResources(
if (!snapshotRoot) {
// Native Pi owns loading. Cache only advisory inspection limits here;
// startup timing must not reintroduce per-session package copies.
- if (startupTiming && await persistSnapshotUnavailableProjection([], inspected)) {
- await publishPiPackagesChanged({ invalidateCache: false });
+ if (startupTiming && (snapshotUnavailablePackages.size > 0
+ || inspected.some((pkg) => pkg.snapshotUnavailable))) {
+ // Persist advisory cache data off the startup path. Keep the existing
+ // state-write boundary, but skip this optional write when another
+ // instance owns it instead of waiting for an install/update to finish.
+ void enqueueMutation(async () => {
+ if (await persistSnapshotUnavailableProjection([], inspected)) {
+ await publishPiPackagesChanged({ invalidateCache: false });
+ }
+ }, undefined, 0).catch(() => {
+ log.debug('Pi package inspection cache persistence skipped');
+ });
}
return resources;
}
@@ -2601,12 +2614,12 @@ export async function resolveManagedPiPackageResources(
recordPiPackageStartupDuration(startupTiming, 'package-snapshot', snapshotStartedAt);
}
};
- if (snapshotRoot || startupTiming) {
- // Only an explicitly requested snapshot needs fresh byte verification.
- // Startup diagnostics share the existing short cache and in-flight inspection.
- return await enqueueMutation(() => resolveResources(Boolean(snapshotRoot)));
+ if (snapshotRoot) {
+ return await enqueueMutation(() => resolveResources(true));
}
- await mutationTail;
+ // Native startup diagnostics are read-only and must not queue behind package
+ // mutations. Concurrent readers share the existing in-flight/short cache.
+ if (!startupTiming) await mutationTail;
return await resolveResources();
} catch (error) {
if (startupTiming) startupTiming.degraded = true;
@@ -2795,6 +2808,7 @@ async function findAffectedInspectedPackage(
function enqueueMutation<T>(
operation: () => Promise<T>,
onErrorUnderLock?: (error: unknown) => Promise<void>,
+ waitMs = PACKAGE_MUTATION_LOCK_WAIT_MS,
): Promise<T> {
// mutationTail prevents overlapping work inside one Main process. The
// strict file lock extends the same critical section across packaged, dev,
@@ -2808,7 +2822,7 @@ function enqueueMutation<T>(
throw error;
}
};
- const result = mutationTail.then(() => withPiPackageMutationLock(guardedOperation));
+ const result = mutationTail.then(() => withPiPackageMutationLock(guardedOperation, waitMs));
mutationTail = result.then(() => undefined, () => undefined);
return result;
}
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
index 2b0f31f33c..dcf83cd3b6 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
@@ -2679,7 +2679,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
}
});
- it('records process incarnation plus redacted session/runtime identity in the local owner marker', async () => {
+ it('records process ownership plus redacted session/runtime identity in the local owner marker', async () => {
const sessionId = 'owner-marker-session';
const handle = await new PiAgent(buildDeps()).startSession({
sessionId,
@@ -2698,7 +2698,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
runtimeId: path.basename(configHome),
sessionIdHash: createHash('sha256').update(sessionId).digest('hex'),
});
- expect(owner.ownerStartTimeSec).toEqual(expect.any(Number));
+ expect(owner.createdAt).toEqual(expect.any(Number));
expect(owner).not.toHaveProperty('sessionId');
} finally {
await handle.close();
@@ -2860,46 +2860,46 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
}
});
- it('shares one process-start probe memo across config homes owned by the same process', async () => {
- const ownerPid = process.ppid;
- const ownerStartTimeSec = 1;
- const ownerHomes = ['c'.repeat(32), 'd'.repeat(32)].map((runtimeId) => {
- const ownerHome = path.join(agentHome, 'run-tmp', runtimeId);
- mkdirSync(ownerHome, { recursive: true });
- writeFileSync(
- path.join(ownerHome, '.cindy-owner.json'),
- `${JSON.stringify({
- version: 2,
- ownerPid,
- ownerStartTimeSec,
- createdAt: 1,
- directoryName: runtimeId,
- runtimeId,
- sessionIdHash: 'e'.repeat(64),
- })}\n`,
- );
- return ownerHome;
+ it.each([-60_000, 60_000])('preserves live foreign owners after a wall-clock correction of %i ms', async (clockStep) => {
+ const runtimeId = 'c'.repeat(32);
+ const ownerHome = path.join(agentHome, 'run-tmp', runtimeId);
+ mkdirSync(ownerHome, { recursive: true });
+ writeFileSync(path.join(ownerHome, '.cindy-owner.json'), JSON.stringify({
+ version: 2,
+ ownerPid: process.ppid,
+ // Earlier builds estimated this timestamp. Even a mismatch cannot prove
+ // whether the PID was reused or the wall clock changed since publication.
+ ownerStartTimeSec: 1,
+ createdAt: Date.now(),
+ directoryName: runtimeId,
+ runtimeId,
+ sessionIdHash: 'e'.repeat(64),
+ }));
+ writeFileSync(path.join(ownerHome, 'models.json'), '{}\n');
+ const { promises: fs } = await import('node:fs');
+ const originalOpendir = fs.opendir.bind(fs);
+ let sweepFinished!: () => void;
+ const swept = new Promise<void>((resolve) => { sweepFinished = resolve; });
+ vi.spyOn(fs, 'opendir').mockImplementation(async (...args) => {
+ const directory = await originalOpendir(...args);
+ if (path.resolve(String(args[0])) !== path.resolve(agentHome, 'run-tmp')) return directory;
+ const iterate = directory[Symbol.asyncIterator].bind(directory);
+ directory[Symbol.asyncIterator] = async function* () {
+ try { yield* iterate(); } finally { sweepFinished(); }
+ return undefined;
+ };
+ return directory;
});
- const probeMemos: unknown[] = [];
- vi.spyOn(piSubagentRuns, 'isPiHostProcessInstanceAliveAsync')
- .mockImplementation(async (identity, memo) => {
- if (identity.pid === ownerPid) probeMemos.push(memo);
- return true;
- });
-
+ const now = Date.now();
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(now + clockStep);
const handle = await new PiAgent(buildDeps()).startSession({
- sessionId: 'shared-owner-probe-memo',
- workingDir: cwd,
- model: 'm',
+ sessionId: 'live-owner-after-clock-step', workingDir: cwd, model: 'm',
});
try {
- await vi.waitFor(() => expect(probeMemos).toHaveLength(ownerHomes.length));
- // pi-subagent-runs separately locks that one shared memo means one
- // PowerShell/ps start-time probe per owner pid and sweep.
- expect(probeMemos[0]).toBeInstanceOf(Map);
- expect(probeMemos[1]).toBe(probeMemos[0]);
- for (const ownerHome of ownerHomes) expect(existsSync(ownerHome)).toBe(true);
+ await swept;
+ expect(readFileSync(path.join(ownerHome, 'models.json'), 'utf8')).toBe('{}\n');
} finally {
+ clock.mockRestore();
await handle.close();
}
});
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts
index f4443eb6a6..e76441f0bd 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts
@@ -19,7 +19,6 @@ import {
piSubagentDeletedTombstonePath,
writePiSubagentDeletedTombstone,
clearPiSubagentDeletedTombstone,
- isPiHostProcessInstanceAliveAsync,
isPiSubagentRunStale,
piSubagentControlOwnership,
piSubagentLaunchFencePath,
@@ -994,44 +993,6 @@ describe('PI durable subagent run store', () => {
});
});
- it('keeps the event loop responsive while probing several host process incarnations', async () => {
- const pids = [410_001, 410_002, 410_003, 410_004, 410_005, 410_006];
- const startTimeSec = 123_456;
- const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')!;
- const realKill = process.kill.bind(process);
- Object.defineProperty(process, 'platform', { ...originalPlatform, value: 'win32' });
- const killSpy = vi.spyOn(process, 'kill').mockImplementation(
- ((pid: number, signal?: NodeJS.Signals | number) => {
- if (pids.includes(pid) && signal === 0) return true;
- return realKill(pid, signal);
- }) as typeof process.kill,
- );
- childProcess.probeDelayMs = 50;
- childProcess.spawnSync.mockReset();
- childProcess.spawnSync.mockImplementation(() => ({
- status: 0,
- stdout: String(startTimeSec),
- }));
- let settled = 0;
- try {
- const probes = pids.map((pid) => isPiHostProcessInstanceAliveAsync({
- pid,
- startTimeSec,
- }).finally(() => { settled += 1; }));
-
- await new Promise<void>((resolve) => setTimeout(resolve, 0));
- expect(settled).toBe(0);
- await expect(Promise.all(probes)).resolves.toEqual(pids.map(() => true));
- expect(childProcess.spawnSync).toHaveBeenCalledTimes(pids.length);
- } finally {
- childProcess.probeDelayMs = 0;
- childProcess.spawnSync.mockReset();
- childProcess.spawnSync.mockImplementation(() => ({ status: 0, stdout: '' }));
- killSpy.mockRestore();
- Object.defineProperty(process, 'platform', originalPlatform);
- }
- });
-
/**
* The account boundary escalates to killing the runner because a durable
* child holds unrevocable BYOM credentials. "Reclaimed" therefore has to mean
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 141159c10f..7a568bd558 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -109,8 +109,6 @@ import {
listPiSubagentRunDiagnostics,
listPiSubagentRunDirectoryIds,
listPiSubagentRuns,
- isPiHostProcessInstanceAliveAsync,
- piHostProcessStartTimeSec,
piSubagentRunRoot,
piSubagentApprovalScope,
piSubagentRuntimeOwnerId,
@@ -122,7 +120,6 @@ import {
syncPiSubagentPermissions,
type PiSubagentRunDiagnostic,
type PiSubagentRunStatus,
- type ProcessStartTimeMemo,
} from './pi-subagent-runs.js';
import {
annotatePermissionRequestForUnavailableReview,
@@ -538,7 +535,6 @@ interface LocalConfigHomeOwnerV1 {
interface LocalConfigHomeOwnerV2 {
version: typeof LOCAL_CONFIG_HOME_OWNER_VERSION;
ownerPid: number;
- ownerStartTimeSec: number;
createdAt: number;
directoryName: string;
runtimeId: string;
@@ -588,7 +584,6 @@ async function registerLocalConfigHome(
const owner: LocalConfigHomeOwnerV2 = {
version: LOCAL_CONFIG_HOME_OWNER_VERSION,
ownerPid: process.pid,
- ownerStartTimeSec: piHostProcessStartTimeSec(),
createdAt: Date.now(),
directoryName: path.basename(normalized),
runtimeId,
@@ -635,8 +630,6 @@ async function readLocalConfigHomeOwner(configHome: string): Promise<LocalConfig
}
if (
parsed.version !== LOCAL_CONFIG_HOME_OWNER_VERSION
- || !Number.isSafeInteger(parsed.ownerStartTimeSec)
- || (parsed.ownerStartTimeSec as number) <= 0
|| typeof parsed.runtimeId !== 'string'
|| parsed.runtimeId !== parsed.directoryName
|| !LOCAL_CONFIG_HOME_RUNTIME_ID_RE.test(parsed.runtimeId)
@@ -646,7 +639,6 @@ async function readLocalConfigHomeOwner(configHome: string): Promise<LocalConfig
return {
version: LOCAL_CONFIG_HOME_OWNER_VERSION,
ownerPid: parsed.ownerPid as number,
- ownerStartTimeSec: parsed.ownerStartTimeSec as number,
createdAt: parsed.createdAt as number,
directoryName: parsed.directoryName,
runtimeId: parsed.runtimeId,
@@ -666,22 +658,17 @@ function isLocalProcessAlive(pid: number): boolean {
}
}
-async function localConfigHomeOwnerIsActive(
+function localConfigHomeOwnerIsActive(
owner: LocalConfigHomeOwner,
configHome: string,
- startTimeMemo?: ProcessStartTimeMemo,
-): Promise<boolean> {
- if (owner.version === 1) {
- return owner.ownerPid === process.pid
- ? activeLocalConfigHomes.has(localConfigHomeKey(configHome))
- : isLocalProcessAlive(owner.ownerPid);
- }
- if (!await isPiHostProcessInstanceAliveAsync({
- pid: owner.ownerPid,
- startTimeSec: owner.ownerStartTimeSec,
- }, startTimeMemo)) return false;
- return owner.ownerPid !== process.pid
- || activeLocalConfigHomes.has(localConfigHomeKey(configHome));
+): boolean {
+ // A wall-clock start-time estimate cannot prove a foreign process exited:
+ // clock corrections make a live owner look like a different incarnation.
+ // Retain live/unknown foreign PIDs, including possible PID reuse, until exit.
+ // Our own active set also covers startup publication and unconfirmed shutdown.
+ return owner.ownerPid === process.pid
+ ? activeLocalConfigHomes.has(localConfigHomeKey(configHome))
+ : isLocalProcessAlive(owner.ownerPid);
}
function sameLocalConfigHomeOwner(
@@ -696,7 +683,6 @@ function sameLocalConfigHomeOwner(
) return false;
return left.version === 1 || (
right.version === LOCAL_CONFIG_HOME_OWNER_VERSION
- && left.ownerStartTimeSec === right.ownerStartTimeSec
&& left.runtimeId === right.runtimeId
&& left.sessionIdHash === right.sessionIdHash
);
@@ -735,7 +721,6 @@ async function sweepStaleLocalConfigHomes(
});
return;
}
- let ownerStartTimeMemo: ProcessStartTimeMemo = new Map();
let roundStartedAt = Date.now();
let inspected = 0;
// Stream the directory: the backlog itself must not become one unbounded allocation.
@@ -746,7 +731,6 @@ async function sweepStaleLocalConfigHomes(
const timer = setTimeout(resolve, 0);
timer.unref();
});
- ownerStartTimeMemo = new Map();
roundStartedAt = Date.now();
inspected = 0;
}
@@ -758,7 +742,7 @@ async function sweepStaleLocalConfigHomes(
// Markerless homes may belong to an older Cindy instance between directory
// creation and Pi spawn. No process snapshot can prove them reclaimable.
if (!owner) continue;
- if (await localConfigHomeOwnerIsActive(owner, candidate, ownerStartTimeMemo)) continue;
+ if (localConfigHomeOwnerIsActive(owner, candidate)) continue;
// Re-read immediately before deletion. A directory whose marker changed or
// whose owner became active is no longer the orphan we proved above.
@@ -767,7 +751,7 @@ async function sweepStaleLocalConfigHomes(
!currentOwner
|| !sameLocalConfigHomeOwner(currentOwner, owner)
) continue;
- if (await localConfigHomeOwnerIsActive(currentOwner, candidate, ownerStartTimeMemo)) continue;
+ if (localConfigHomeOwnerIsActive(currentOwner, candidate)) continue;
const outcome = await removeLocalConfigHomeWithRetry(candidate);
if (!outcome.removed) {
diff --git a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts
index 061c4b761a..5e3f88e94b 100644
--- a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts
+++ b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts
@@ -405,7 +405,7 @@ function parseLaunchFence(value: unknown): PiSubagentLaunchFence | null {
*/
function fenceMatchesOwnIncarnation(fence: PiSubagentLaunchFence): boolean {
if (fence.hostStartTimeSec === undefined) return true;
- return Math.abs(piHostProcessStartTimeSec() - fence.hostStartTimeSec) <= OWNER_START_TIME_TOLERANCE_SEC;
+ return Math.abs(ownProcessStartTimeSec() - fence.hostStartTimeSec) <= OWNER_START_TIME_TOLERANCE_SEC;
}
/**
@@ -516,7 +516,7 @@ export async function acquirePiSubagentLaunchFence(agentHome: string): Promise<(
await writeAtomicJson(file, {
version: 1,
hostPid: process.pid,
- hostStartTimeSec: piHostProcessStartTimeSec(),
+ hostStartTimeSec: ownProcessStartTimeSec(),
leaseId,
createdAt: Date.now(),
} satisfies PiSubagentLaunchFence);
@@ -677,7 +677,7 @@ export async function clearStalePiSubagentLaunchFence(agentHome: string): Promis
if (fence && isProcessAlive(fence.hostPid) !== false) {
if (fence.hostStartTimeSec === undefined) return;
const startTimeSec = fence.hostPid === process.pid
- ? piHostProcessStartTimeSec()
+ ? ownProcessStartTimeSec()
: probeProcessStartTimeSec(fence.hostPid, Date.now());
if (startTimeSec === null) return;
if (Math.abs(startTimeSec - fence.hostStartTimeSec) <= OWNER_START_TIME_TOLERANCE_SEC) return;
@@ -1018,12 +1018,12 @@ export function piSubagentRuntimeOwnerId(hostPid: number, scopeId: string): stri
// a live foreign owner reads as an orphan the moment the gap exceeds the
// tolerance. A legacy id has no start time, so liveness stays conservative.
return hostPid === process.pid
- ? `${hostPid}.${piHostProcessStartTimeSec()}:${scopeId}`
+ ? `${hostPid}.${ownProcessStartTimeSec()}:${scopeId}`
: `${hostPid}:${scopeId}`;
}
-/** Wall-clock start second shared by host-owned Pi runtime records. */
-export function piHostProcessStartTimeSec(): number {
+/** Wall-clock second this process started, in the form the owner id records. */
+function ownProcessStartTimeSec(): number {
return OWN_PROCESS_START_TIME_SEC;
}
@@ -1212,43 +1212,6 @@ function probeProcessStartTimeSec(pid: number, now: number): number | null {
}
}
-/**
- * Reclaim probes must never block Electron Main while Windows starts PowerShell.
- * An unreadable or timed-out probe remains conservative: the owner is treated
- * as alive and the directory is left for a later sweep.
- */
-const PROCESS_START_TIME_PROBE_TIMEOUT_MS = 1_000;
-
-async function probeProcessStartTimeSecAsync(pid: number, now: number): Promise<number | null> {
- try {
- if (process.platform === 'win32') {
- const { stdout } = await execFileAsync(
- 'powershell.exe',
- [
- '-NoProfile', '-NonInteractive', '-Command',
- `[int64]((Get-Process -Id ${pid}).StartTime.ToUniversalTime() - [datetime]'1970-01-01').TotalSeconds`,
- ],
- {
- encoding: 'utf8',
- timeout: PROCESS_START_TIME_PROBE_TIMEOUT_MS,
- windowsHide: true,
- },
- );
- const match = (typeof stdout === 'string' ? stdout : '').match(/-?\d+/);
- const seconds = match ? Number(match[0]) : NaN;
- return Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds) : null;
- }
- const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-o', 'etime='], {
- encoding: 'utf8',
- timeout: PROCESS_START_TIME_PROBE_TIMEOUT_MS,
- });
- const elapsed = parseElapsedSeconds(typeof stdout === 'string' ? stdout : '');
- return elapsed === null ? null : Math.round(now / 1_000 - elapsed);
- } catch {
- return null;
- }
-}
-
/**
* Per-sweep memo for the start-time probe, passed down rather than held.
*
@@ -1261,7 +1224,7 @@ async function probeProcessStartTimeSecAsync(pid: number, now: number): Promise<
* cannot detect reuse; only a fresh probe can, and a sweep-scoped memo is the
* largest window in which reuse is not observable anyway.
*/
-export type ProcessStartTimeMemo = Map<number, number | null>;
+type ProcessStartTimeMemo = Map<number, number | null>;
function readProcessStartTimeSec(pid: number, memo?: ProcessStartTimeMemo): number | null {
const cached = memo?.get(pid);
@@ -1271,16 +1234,6 @@ function readProcessStartTimeSec(pid: number, memo?: ProcessStartTimeMemo): numb
return startTimeSec;
}
-async function readProcessStartTimeSecAsync(
- pid: number,
- memo?: ProcessStartTimeMemo,
-): Promise<number | null> {
- if (memo?.has(pid)) return memo.get(pid) ?? null;
- const startTimeSec = await probeProcessStartTimeSecAsync(pid, Date.now());
- memo?.set(pid, startTimeSec);
- return startTimeSec;
-}
-
/** `ps` rounds to the second and samples after we read the clock. */
const OWNER_START_TIME_TOLERANCE_SEC = 5;
@@ -1305,26 +1258,12 @@ function isOwnerInstanceAlive(
if (isProcessAlive(identity.pid) === false) return false;
if (identity.startTimeSec === undefined) return true;
const startTimeSec = identity.pid === process.pid
- ? piHostProcessStartTimeSec()
+ ? ownProcessStartTimeSec()
: readProcessStartTimeSec(identity.pid, memo);
if (startTimeSec === null) return true;
return Math.abs(startTimeSec - identity.startTimeSec) <= OWNER_START_TIME_TOLERANCE_SEC;
}
-/** Non-blocking incarnation check for background config-home reclamation. */
-export async function isPiHostProcessInstanceAliveAsync(
- identity: PiSubagentOwnerIdentity,
- startTimeMemo?: ProcessStartTimeMemo,
-): Promise<boolean> {
- if (isProcessAlive(identity.pid) === false) return false;
- if (identity.startTimeSec === undefined) return true;
- const startTimeSec = identity.pid === process.pid
- ? piHostProcessStartTimeSec()
- : await readProcessStartTimeSecAsync(identity.pid, startTimeMemo);
- if (startTimeSec === null) return true;
- return Math.abs(startTimeSec - identity.startTimeSec) <= OWNER_START_TIME_TOLERANCE_SEC;
-}
-
function isProcessAlive(pid: number | undefined): boolean | null {
if (!Number.isSafeInteger(pid) || (pid ?? 0) <= 0) return null;
try {
@@ -2300,7 +2239,7 @@ async function acquirePiSubagentResumeClaim(
version: 1,
...(runtimeOwnerId ? { runtimeOwnerId } : {}),
hostPid,
- hostStartTimeSec: piHostProcessStartTimeSec(),
+ hostStartTimeSec: ownProcessStartTimeSec(),
claimedAt: Date.now(),
})}\n`;
const release = async (): Promise<void> => {