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): preserve markerless legacy config homes

lizzjin40e62cba61f6
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index 497f3d7229..252b037076 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -64,10 +64,6 @@ import {
matchesManagedOllamaFingerprint,
} from '../../shared/localModelRuntime.js';
import { ensureManagedOllamaReadyForSession } from '../local-model-runtime/preflight.js';
-import {
- hasLiveCindyManagedPiProcess,
- scanOsProcessesFresh,
-} from '../process-monitor/agent-scan.js';
import {
applyQwen38NativeOverlay,
shouldApplyQwen38Overlay,
@@ -1652,10 +1648,6 @@ export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {
if (remoteHostId) return '$HOME/.xdt-server/v1/pi-agent-home';
return path.join(app.getPath('userData'), 'pi-agent-home');
},
- canReclaimLegacyPiConfigHomes: async () => {
- const snapshot = await scanOsProcessesFresh();
- return !hasLiveCindyManagedPiProcess(snapshot, binaryPath);
- },
resolvePiManagedPackageResources: resolveManagedPiPackageResources,
mutatePiManagedPackage: mutateAuthorizedPiManagedPackage,
getPiExtensionUiStrings: () => ({
diff --git a/apps/desktop/src/main/process-monitor/__tests__/agent-scan.test.ts b/apps/desktop/src/main/process-monitor/__tests__/agent-scan.test.ts
index 44cb818967..0921bb3187 100644
--- a/apps/desktop/src/main/process-monitor/__tests__/agent-scan.test.ts
+++ b/apps/desktop/src/main/process-monitor/__tests__/agent-scan.test.ts
@@ -10,7 +10,6 @@ import {
classifyMonitoredAgentCommandLine,
collectDescendantPids,
createWindowsProcessScanner,
- hasLiveCindyManagedPiProcess,
parsePosixProcessTable,
parseWindowsProcessTable,
registerPiUserDataMarkers,
@@ -137,35 +136,6 @@ describe('classifyMonitoredAgentCommandLine', () => {
});
});
-describe('hasLiveCindyManagedPiProcess', () => {
- const snapshot = (rows: Array<{ state: string | null; cmdLineLower: string }>) => ({
- rows: rows.map((row, index) => ({
- pid: index + 1,
- ppid: 0,
- memoryKb: 0,
- cpuPercent: null,
- cpuTimeMs: null,
- startIdentity: null,
- ...row,
- })),
- childrenByParent: new Map<number, number[]>(),
- });
-
- it('recognizes an exact custom binary path across separator styles', () => {
- expect(hasLiveCindyManagedPiProcess(
- snapshot([{ state: null, cmdLineLower: '"d:/custom pi/bin/pi.exe" --mode rpc' }]),
- 'D:\\custom pi\\bin\\pi.exe',
- )).toBe(true);
- });
-
- it('ignores zombies and unrelated external pi commands', () => {
- expect(hasLiveCindyManagedPiProcess(snapshot([
- { state: 'Z+', cmdLineLower: '/repo/apps/pi-bin/linux-x64/pi --mode rpc' },
- { state: 'S', cmdLineLower: '/usr/local/bin/pi serve' },
- ]), '/different/custom/pi')).toBe(false);
- });
-});
-
describe('buildChildrenByParent / collectDescendantPids', () => {
it('展开整棵子树且防环', () => {
const rows = [
diff --git a/apps/desktop/src/main/process-monitor/agent-scan.ts b/apps/desktop/src/main/process-monitor/agent-scan.ts
index 89f538f230..a9aa07af33 100644
--- a/apps/desktop/src/main/process-monitor/agent-scan.ts
+++ b/apps/desktop/src/main/process-monitor/agent-scan.ts
@@ -110,27 +110,6 @@ export function classifyMonitoredAgentCommandLine(
return null;
}
-/**
- * Does a fresh snapshot contain any live Pi process owned by this Cindy
- * installation? Exact binary-path matching covers custom/dev layouts; the
- * normal classifier covers other concurrent Cindy editions sharing userData.
- */
-export function hasLiveCindyManagedPiProcess(
- snapshot: OsProcessSnapshot,
- binaryPath: string,
-): boolean {
- const binaryLower = binaryPath.toLowerCase();
- const binarySlash = binaryLower.replace(/\\/g, '/');
- const binaryBackslash = binaryLower.replace(/\//g, '\\');
- return snapshot.rows.some((row) => {
- if (row.state?.toUpperCase().includes('Z')) return false;
- return row.cmdLineLower.includes(binaryLower)
- || row.cmdLineLower.includes(binarySlash)
- || row.cmdLineLower.includes(binaryBackslash)
- || classifyMonitoredAgentCommandLine(row.cmdLineLower) === 'pi';
- });
-}
-
// ps 行:pid ppid stat %cpu rss lstart command(command 可含空格,贪婪吃尾)。
// LC_ALL=C 把 lstart 固定为 "Mon Aug 6 12:34:56 2026" 一类格式。
const POSIX_PS_ROW_RE =
@@ -275,27 +254,6 @@ export function createWindowsProcessScanner(
const scanWindows = createWindowsProcessScanner({ runWorker: runWindowsProcessScanWorker });
-/**
- * Uncached process snapshot for ownership decisions. Unlike the UI sampler's
- * backoff-aware scanner, this never turns a recent Windows scan failure into
- * an empty snapshot: callers either receive fresh evidence or an exception.
- */
-export async function scanOsProcessesFresh(): Promise<OsProcessSnapshot> {
- const snapshot = process.platform !== 'win32'
- ? await scanPosix()
- : await (async (): Promise<OsProcessSnapshot> => {
- const stdout = await runWindowsProcessScanWorker();
- const rows = parseWindowsProcessTable(stdout);
- return { rows, childrenByParent: buildChildrenByParent(rows) };
- })();
- // A whole-OS scan always includes at least this Cindy/worker process. Empty
- // therefore means format drift or incomplete evidence, never "no live Pi".
- if (snapshot.rows.length === 0) {
- throw new Error('Fresh OS process ownership scan returned no parseable rows');
- }
- return snapshot;
-}
-
/** 生产扫描入口(sampler / terminate 校验共用)。 */
export function scanOsProcesses(): Promise<OsProcessSnapshot> {
return process.platform === 'win32' ? scanWindows() : scanPosix();
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 13ea0fa866..5607c7f60b 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -544,14 +544,6 @@ export interface AgentDeps {
*/
resolvePiAgentHome?: (remoteHostId?: string | null) => string | undefined;
- /**
- * Pi-only: return true only after a fresh host-process scan proves that no
- * Cindy-managed Pi process is alive. Local startup uses this narrow proof to
- * reclaim markerless config homes left by builds that predate owner markers.
- * Missing, false, or throwing resolvers fail closed and preserve the homes.
- */
- canReclaimLegacyPiConfigHomes?: () => Promise<boolean>;
-
/**
* Pi-only: Cindy-owned packages explicitly enabled for a new runtime on this device.
* The host owns package installation, compatibility inspection, persistence,
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 a7d8afa561..bd0765a699 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
@@ -2370,32 +2370,26 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
}
});
- it('reclaims markerless legacy homes only after the host proves no managed Pi process is live', async () => {
+ it('preserves markerless legacy homes even when the host process scan finds no live Pi', async () => {
const legacyHome = path.join(agentHome, 'run-tmp', '0123456789abcdef');
mkdirSync(legacyHome, { recursive: true });
writeFileSync(path.join(legacyHome, 'models.json'), '{}\n');
- const preservingHandle = await new PiAgent(buildDeps({
- canReclaimLegacyPiConfigHomes: async () => false,
- })).startSession({
- sessionId: 'legacy-preserve',
- workingDir: cwd,
- model: 'm',
- });
- await preservingHandle.close();
- expect(existsSync(legacyHome)).toBe(true);
-
- const reclaimingHandle = await new PiAgent(buildDeps({
+ // Simulate the removed host hint so a future sweep cannot accidentally
+ // reinstate markerless deletion based only on post-spawn process evidence.
+ const deps = {
+ ...buildDeps(),
canReclaimLegacyPiConfigHomes: async () => true,
- })).startSession({
- sessionId: 'legacy-reclaim',
+ };
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: 'legacy-preserve-pre-spawn',
workingDir: cwd,
model: 'm',
});
try {
- expect(existsSync(legacyHome)).toBe(false);
+ expect(existsSync(legacyHome)).toBe(true);
} finally {
- await reclaimingHandle.close();
+ await handle.close();
}
});
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 725d371e2f..6c6751b86d 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -454,7 +454,6 @@ async function stageManagedRipgrep(configHome: string, sourcePath: string | unde
const LOCAL_CONFIG_HOME_OWNER_FILE = '.cindy-owner.json';
const LOCAL_CONFIG_HOME_OWNER_VERSION = 2;
const LOCAL_CONFIG_HOME_REMOVE_RETRY_DELAYS_MS = [0, 25, 100] as const;
-const LEGACY_LOCAL_CONFIG_HOME_NAME_RE = /^[a-f0-9]{16}$/;
const LOCAL_CONFIG_HOME_RUNTIME_ID_RE = /^[a-f0-9]{32}$/;
const SHA256_HEX_RE = /^[a-f0-9]{64}$/;
const activeLocalConfigHomes = new Set<string>();
@@ -645,7 +644,6 @@ async function removeLocalConfigHomeWithRetry(
async function sweepStaleLocalConfigHomes(
agentHome: string,
logger: ConfigHomeCleanupLogger,
- canReclaimLegacyHomes: (() => Promise<boolean>) | undefined,
): Promise<void> {
const runTmp = path.resolve(agentHome, 'run-tmp');
let entries;
@@ -658,38 +656,14 @@ async function sweepStaleLocalConfigHomes(
});
return;
}
- let legacyReclaimDecision: Promise<boolean> | undefined;
- const canReclaimLegacy = (): Promise<boolean> => {
- legacyReclaimDecision ??= canReclaimLegacyHomes
- ? canReclaimLegacyHomes().catch((error) => {
- logger.debug('pi legacy configHome ownership scan failed (preserved)', {
- message: error instanceof Error ? error.message : String(error),
- });
- return false;
- })
- : Promise.resolve(false);
- return legacyReclaimDecision;
- };
-
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const candidate = path.resolve(runTmp, entry.name);
if (path.dirname(candidate) !== runTmp) continue;
const owner = await readLocalConfigHomeOwner(candidate);
- if (!owner) {
- if (!LEGACY_LOCAL_CONFIG_HOME_NAME_RE.test(entry.name) || !await canReclaimLegacy()) continue;
- // A marker may have appeared while the host process scan was in flight.
- // Markerless legacy homes are deleted only while they remain markerless.
- if (await readLocalConfigHomeOwner(candidate)) continue;
- const outcome = await removeLocalConfigHomeWithRetry(candidate);
- if (!outcome.removed) {
- logger.debug('pi legacy configHome cleanup failed (retried next startSession)', {
- configHomeId: entry.name,
- message: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),
- });
- }
- continue;
- }
+ // 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 (localConfigHomeOwnerIsActive(owner, candidate)) continue;
// Re-read immediately before deletion. A directory whose marker changed or
@@ -2306,7 +2280,6 @@ export class PiAgent extends BaseAgent {
await sweepStaleLocalConfigHomes(
agentHome,
this.deps.logger,
- this.deps.canReclaimLegacyPiConfigHomes,
);
}
const allowPiPackageManagement = !reviewMode && !remote && Boolean(this.deps.mutatePiManagedPackage);