feat(FN-2089): merge fusion/fn-2089

This commit is contained in:
Fusion
2026-04-19 00:37:03 -07:00
committed by gsxdsm
parent f3de45b050
commit 7424c843f2
12 changed files with 312 additions and 113 deletions

View File

@@ -0,0 +1,26 @@
/**
* Vitest globalSetup hook. The returned function runs once after the entire
* test run completes, regardless of whether individual workers exited cleanly.
* Wipes the shared FUSION_TEST_WORKER_ROOT directory that holds per-worker
* temp dirs created by vitest-setup.ts.
*/
import { tmpdir } from "node:os";
import { join } from "node:path";
const WORKER_ROOT = join(tmpdir(), "fusion-test-workers");
export default function setup(): () => Promise<void> {
// Set the env var here too so vitest-setup.ts workers pick it up even if
// their own mkdir runs after globalSetup.
process.env.FUSION_TEST_WORKER_ROOT = WORKER_ROOT;
return async function teardown() {
// Intentionally no-op.
//
// Worker temp dirs are cleaned by vitest-setup.ts using process.on("exit")
// after first chdir-ing out of the worker dir. Deleting shared temp roots
// from global teardown is unsafe under some Vitest pool modes because it
// can run while other suites are still active, causing ENOENT uv_cwd.
};
}

View File

@@ -0,0 +1,26 @@
/**
* Vitest globalSetup hook. The returned function runs once after the entire
* test run completes, regardless of whether individual workers exited cleanly.
* Wipes the shared FUSION_TEST_WORKER_ROOT directory that holds per-worker
* temp dirs created by vitest-setup.ts.
*/
import { tmpdir } from "node:os";
import { join } from "node:path";
const WORKER_ROOT = join(tmpdir(), "fusion-test-workers");
export default function setup(): () => Promise<void> {
// Set the env var here too so vitest-setup.ts workers pick it up even if
// their own mkdir runs after globalSetup.
process.env.FUSION_TEST_WORKER_ROOT = WORKER_ROOT;
return async function teardown() {
// Intentionally no-op.
//
// Worker temp dirs are cleaned by vitest-setup.ts using process.on("exit")
// after first chdir-ing out of the worker dir. Deleting shared temp roots
// from global teardown is unsafe under some Vitest pool modes because it
// can run while other suites are still active, causing ENOENT uv_cwd.
};
}

View File

@@ -16,7 +16,30 @@ import { tmpdir } from "node:os";
import { dirname, join, resolve, sep } from "node:path";
import { isMainThread } from "node:worker_threads";
const realProjectRootRaw = process.cwd();
const originalCwd = process.cwd.bind(process);
function ensureValidCwd(): string {
try {
return originalCwd();
} catch {
const fallback = tmpdir();
try {
process.chdir(fallback);
} catch {
// Ignore — if this fails too, callers will still get fallback.
}
return fallback;
}
}
// Guard against uv_cwd crashes if a prior test removed the current directory.
process.cwd = (() => {
return function guardedCwd() {
return ensureValidCwd();
};
})() as typeof process.cwd;
const realProjectRootRaw = ensureValidCwd();
const realProjectRoot = (() => {
try {
return realpathSync(realProjectRootRaw);

View File

@@ -1,11 +1,12 @@
/**
* Vitest globalSetup hook. The returned function runs once after the entire
* test run completes, regardless of whether individual workers exited cleanly.
* Wipes the shared FUSION_TEST_WORKER_ROOT directory that holds per-worker
* temp dirs created by vitest-setup.ts.
* Vitest globalSetup hook.
*
* We only publish the shared worker-root env var here. Teardown is intentionally
* a no-op because deleting shared temp roots during teardown can race with
* still-running suites in some Vitest pool modes and trigger uv_cwd failures.
* Worker dirs are cleaned by vitest-setup.ts on process exit.
*/
import { readdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -17,27 +18,11 @@ export default function setup(): () => Promise<void> {
process.env.FUSION_TEST_WORKER_ROOT = WORKER_ROOT;
return async function teardown() {
// IMPORTANT: do not remove WORKER_ROOT recursively here.
// In some Vitest pool modes, global setup/teardown can run in multiple
// processes. If one process deletes the shared root while another process
// is still running with cwd inside it, the other process will fail with
// ENOENT uv_cwd.
// Intentionally no-op.
//
// Instead, clean up only this process's worker dirs. Other processes clean
// up their own dirs via their exit hooks.
const ownPrefix = `w-${process.pid}-`;
try {
const entries = readdirSync(WORKER_ROOT, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory() || !entry.name.startsWith(ownPrefix)) continue;
try {
rmSync(join(WORKER_ROOT, entry.name), { recursive: true, force: true });
} catch {
// Ignore per-dir cleanup errors.
}
}
} catch {
// Ignore — OS cleans /tmp eventually.
}
// Worker temp dirs are cleaned by vitest-setup.ts using process.on("exit")
// after first chdir-ing out of the worker dir. Deleting shared temp roots
// from global teardown is unsafe under some Vitest pool modes because it
// can run while other suites are still active, causing ENOENT uv_cwd.
};
}

View File

@@ -8,12 +8,12 @@ declare module "express" {
}
import multer from "multer";
import { createReadStream, createWriteStream } from "node:fs";
import { mkdtemp, access, stat, mkdir, readdir, rm, readFile as fsReadFile, appendFile } from "node:fs/promises";
import { mkdtemp, access, stat, mkdir, readdir, rm, readFile as fsReadFile } from "node:fs/promises";
import { Readable } from "node:stream";
import { pipeline as streamPipeline } from "node:stream/promises";
import { execFile } from "node:child_process";
import { resolve, sep, join } from "node:path";
import { tmpdir, homedir } from "node:os";
import { tmpdir } from "node:os";
import * as nodeFs from "node:fs";
import { promisify } from "node:util";
@@ -1880,16 +1880,6 @@ function checkSessionLock(
export function createApiRoutes(store: TaskStore, options?: ServerOptions): Router {
const router = Router();
// Dashboard load perf log — server and client timings get appended here so
// they can be inspected without browser devtools (e.g. on mobile).
const PERF_LOG_PATH = join(homedir(), ".fusion", "dashboard-perf.log");
const perfLog = (source: string, message: string): void => {
const line = `[${new Date().toISOString()}] ${source} ${message}\n`;
appendFile(PERF_LOG_PATH, line).catch(() => {
// best-effort only
});
};
function prioritizeProjectsForCurrentDirectory<T extends { path: string }>(projects: T[]): T[] {
const cwd = resolve(process.cwd());
@@ -14702,33 +14692,19 @@ export function createApiRoutes(store: TaskStore, options?: ServerOptions): Rout
* Returns: Array of projects with nodeId and _sourceNodeName for remote projects.
*/
router.get("/projects/across-nodes", async (_req, res) => {
const t0 = performance.now();
const timings: Record<string, number> = {};
const mark = (label: string, from: number) => {
timings[label] = Math.round(performance.now() - from);
};
try {
const tImport = performance.now();
const { CentralCore } = await import("@fusion/core");
const central = new CentralCore();
mark("import+construct", tImport);
const tInit = performance.now();
await central.init();
mark("central.init", tInit);
// Reconcile stale "initializing" projects before listing
const tReconcile = performance.now();
await central.reconcileProjectStatuses();
mark("reconcileProjectStatuses", tReconcile);
// Get local projects and registered nodes in parallel
const tListLocal = performance.now();
const [localProjects, allNodes] = await Promise.all([
central.listProjects(),
central.listNodes(),
]);
mark("listProjects+listNodes", tListLocal);
// Filter to online remote nodes with URLs
const remoteNodes = allNodes.filter(
@@ -14739,24 +14715,13 @@ export function createApiRoutes(store: TaskStore, options?: ServerOptions): Rout
// Skip the Promise.allSettled machinery entirely so local-only setups pay
// no cross-node aggregation overhead.
if (remoteNodes.length === 0) {
const tPrioritize = performance.now();
const prioritizedProjects = prioritizeProjectsForCurrentDirectory(localProjects);
mark("prioritize", tPrioritize);
const tClose = performance.now();
await central.close();
mark("central.close", tClose);
timings.total = Math.round(performance.now() - t0);
const msg = `local-only path (${localProjects.length} projects) timings=${JSON.stringify(timings)}`;
console.log(`[projects:across-nodes] ${msg}`);
perfLog("[projects:across-nodes]", msg);
res.json(prioritizedProjects);
return;
}
// Fetch projects from all remote nodes in parallel
const tRemote = performance.now();
const remoteProjectArrays = await Promise.allSettled(
remoteNodes.map(async (node) => {
const controller = new AbortController();
@@ -14797,7 +14762,6 @@ export function createApiRoutes(store: TaskStore, options?: ServerOptions): Rout
}
})
);
mark("remoteFetch", tRemote);
// Collect successful remote projects, log failures
type RemoteProject = {
@@ -14828,18 +14792,10 @@ export function createApiRoutes(store: TaskStore, options?: ServerOptions): Rout
const mergedProjects = [...localProjects, ...remoteProjects];
// Apply directory prioritization
const tPrioritize = performance.now();
const prioritizedProjects = prioritizeProjectsForCurrentDirectory(mergedProjects);
mark("prioritize", tPrioritize);
const tClose = performance.now();
await central.close();
mark("central.close", tClose);
timings.total = Math.round(performance.now() - t0);
const msg = `${remoteNodes.length} remote node(s), ${localProjects.length} local + ${remoteProjects.length} remote projects timings=${JSON.stringify(timings)}`;
console.log(`[projects:across-nodes] ${msg}`);
perfLog("[projects:across-nodes]", msg);
res.json(prioritizedProjects);
} catch (err: unknown) {
if (err instanceof ApiError) {
@@ -14849,23 +14805,6 @@ export function createApiRoutes(store: TaskStore, options?: ServerOptions): Rout
}
});
/**
* POST /api/_perf/dashboard-load
* Collect client-side dashboard-load timings. Appended to the same perf log
* the server uses so both sides can be inspected together without devtools.
* Body: { source: string, message: string } — message typically JSON-stringified timings.
*/
router.post("/_perf/dashboard-load", (req, res) => {
try {
const source = typeof req.body?.source === "string" ? req.body.source.slice(0, 64) : "[client]";
const message = typeof req.body?.message === "string" ? req.body.message.slice(0, 1024) : "";
perfLog(source, message);
res.json({ ok: true });
} catch {
res.status(200).json({ ok: false });
}
});
/**
* POST /api/projects
* Register a new project.

View File

@@ -1337,7 +1337,12 @@ export class HeartbeatMonitor {
try { this.untrackAgent(agentId); } catch (untrackErr) {
heartbeatLog.warn(`untrackAgent failed for ${agentId}: ${untrackErr instanceof Error ? untrackErr.message : String(untrackErr)}`);
}
try { session.dispose(); } catch { /* ignore */ }
try {
session.dispose();
} catch (disposeErr: unknown) {
const errorMessage = disposeErr instanceof Error ? disposeErr.message : String(disposeErr);
heartbeatLog.warn(`session.dispose() failed for ${agentId}: ${errorMessage}`);
}
}
return (await this.store.getRunDetail(agentId, run.id))!;

View File

@@ -36,6 +36,14 @@ vi.mock("./pi.js", () => {
return { createKbAgent, promptWithFallback };
});
vi.mock("./logger.js", () => ({
createLogger: vi.fn((_name: string) => ({
log: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
})),
}));
// Helper to reset mock session state
function resetMockSession() {
mockSessionHolder.session.state.messages = [];
@@ -43,7 +51,7 @@ function resetMockSession() {
}
// Import AFTER vi.mock so the mock is applied
import { MissionExecutionLoop } from "./mission-execution-loop.js";
import { MissionExecutionLoop, loopLog } from "./mission-execution-loop.js";
// ── Mock Factories ──────────────────────────────────────────────────────────
@@ -594,6 +602,31 @@ describe("MissionExecutionLoop", () => {
await expect(loop.recoverActiveMissions()).resolves.not.toThrow();
});
it("logs warn when mission hierarchy lookup throws during recovery", async () => {
const mission = createMockMission({ id: "M-LOOKUP", status: "active" });
missionStore._setMission(mission);
missionStore.getMissionWithHierarchy = vi.fn().mockImplementation(() => {
throw new Error("Database error");
});
vi.mocked(loopLog.warn).mockClear();
loop = new MissionExecutionLoop({
taskStore: taskStore as any,
missionStore: missionStore as any,
rootDir: "/tmp",
});
loop.start();
await loop.recoverActiveMissions();
expect(loopLog.warn).toHaveBeenCalledWith(
expect.stringContaining(
"getMissionWithHierarchy failed for mission M-LOOKUP: Database error",
),
);
});
it("should handle empty hierarchy gracefully", async () => {
const mission = createMockMission({ status: "active" });
missionStore._setMission(mission);

View File

@@ -139,7 +139,9 @@ export class MissionExecutionLoop extends EventEmitter {
let hierarchy;
try {
hierarchy = this.missionStore.getMissionWithHierarchy(mission.id);
} catch {
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err);
loopLog.warn(`getMissionWithHierarchy failed for mission ${mission.id}: ${errorMessage} — skipping`);
// Database error, skip this mission
continue;
}
@@ -424,7 +426,7 @@ export class MissionExecutionLoop extends EventEmitter {
try {
parsed = JSON.parse(jsonCandidate);
} catch {
// Try to repair common JSON issues
// Intentional fallback: initial parse can fail on malformed JSON; try repairJson() next.
const repaired = this.repairJson(jsonCandidate);
try {
parsed = JSON.parse(repaired);
@@ -493,7 +495,9 @@ export class MissionExecutionLoop extends EventEmitter {
}
return undefined;
} catch {
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err);
loopLog.warn(`AI response JSON extraction failed: ${errorMessage}`);
return undefined;
}
}

View File

@@ -5,6 +5,7 @@ import { AgentSemaphore } from "./concurrency.js";
import type { TaskStore, Task, TaskDetail } from "@fusion/core";
import { existsSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { schedulerLog } from "./logger.js";
// Mock fs modules
vi.mock("node:fs", async (importOriginal) => {
@@ -23,6 +24,14 @@ vi.mock("node:fs/promises", async (importOriginal) => {
};
});
vi.mock("./logger.js", () => ({
schedulerLog: {
log: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
}));
// Helper to create mock tasks
function createMockTask(overrides: Partial<Task> = {}): Task {
return {
@@ -834,6 +843,26 @@ describe("Scheduler", () => {
);
});
it("logs warn when PROMPT.md read throws during validation", async () => {
const store = createMockStore({
getTasksDir: vi.fn().mockReturnValue("/test/project/.fusion/tasks"),
});
const scheduler = new Scheduler(store);
vi.mocked(schedulerLog.warn).mockClear();
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFile).mockRejectedValue(new Error("EACCES"));
const validation = await (scheduler as any).validateTaskFilesystem("FN-READ");
expect(validation).toEqual({ valid: false, reason: "missing or empty PROMPT.md" });
expect(schedulerLog.warn).toHaveBeenCalledWith(
expect.stringContaining(
"PROMPT.md read failed for task dispatch validation (FN-READ): EACCES",
),
);
});
it("proceeds with scheduling when filesystem is valid", async () => {
const tasks = [
createMockTask({ id: "FN-004", column: "todo", dependencies: [] }),

View File

@@ -295,7 +295,9 @@ export class Scheduler {
if (!content || content.trim().length === 0) {
return { valid: false, reason: "missing or empty PROMPT.md" };
}
} catch {
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err);
schedulerLog.warn(`PROMPT.md read failed for task dispatch validation (${id}): ${errorMessage}`);
return { valid: false, reason: "missing or empty PROMPT.md" };
}
@@ -545,7 +547,11 @@ export class Scheduler {
}
}
}
} catch {
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err);
schedulerLog.warn(
`Mission/slice lookup failed during scheduling (task ${t.id}): ${errorMessage} — proceeding without blocked-slice check`,
);
// If lookup fails, don't block the task
}
}

View File

@@ -56,16 +56,40 @@ vi.mock("./worktree-pool.js", () => ({
scanOrphanedBranches: vi.fn().mockResolvedValue([]),
}));
vi.mock("./logger.js", () => ({
createLogger: vi.fn((_name: string) => ({
log: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
})),
}));
import { SelfHealingManager } from "./self-healing.js";
import type { TaskStore, Settings, Task } from "@fusion/core";
import { EventEmitter } from "node:events";
import { execSync } from "node:child_process";
import { existsSync } from "node:fs";
import { scanOrphanedBranches } from "./worktree-pool.js";
import { createLogger } from "./logger.js";
const mockedExecSync = vi.mocked(execSync);
const mockedExistsSync = vi.mocked(existsSync);
const mockedScanOrphanedBranches = vi.mocked(scanOrphanedBranches);
const mockedCreateLogger = vi.mocked(createLogger);
type MockLogger = {
log: ReturnType<typeof vi.fn>;
warn: ReturnType<typeof vi.fn>;
error: ReturnType<typeof vi.fn>;
};
function getSelfHealingLogger(): MockLogger {
const idx = mockedCreateLogger.mock.calls.findIndex(([name]) => name === "self-healing");
if (idx === -1) {
throw new Error("self-healing logger was not created");
}
return mockedCreateLogger.mock.results[idx]?.value as MockLogger;
}
// ── Mock helpers ────────────────────────────────────────────────────
@@ -485,6 +509,64 @@ describe("SelfHealingManager", () => {
});
});
describe("silent catch logging", () => {
it("logs warn when interrupted-merge worktree removal fails", async () => {
const warn = getSelfHealingLogger().warn;
warn.mockClear();
const task = {
id: "FN-123",
worktree: "/tmp/test-project/.worktrees/fn-123",
branch: "fusion/fn-123",
} as Task;
mockedExistsSync.mockReset();
mockedExistsSync.mockReturnValueOnce(true);
mockedExecSync.mockReset();
mockedExecSync.mockImplementationOnce(() => {
throw new Error("cannot remove worktree");
});
await (manager as any).cleanupInterruptedMergeArtifacts(task);
expect(warn).toHaveBeenCalledWith(
expect.stringContaining(
`Failed to remove interrupted-merge worktree ${task.worktree} for ${task.id}: cannot remove worktree`,
),
);
mockedExecSync.mockClear();
mockedExistsSync.mockReset();
});
it("logs warn when interrupted-merge branch deletion fails", async () => {
const warn = getSelfHealingLogger().warn;
warn.mockClear();
const task = {
id: "FN-124",
branch: "fusion/fn-124",
} as Task;
mockedExistsSync.mockReset();
mockedExecSync.mockReset();
mockedExecSync.mockImplementationOnce(() => {
throw new Error("cannot delete branch");
});
await (manager as any).cleanupInterruptedMergeArtifacts(task);
expect(warn).toHaveBeenCalledWith(
expect.stringContaining(
`Failed to delete interrupted-merge branch fusion/fn-124 for FN-124: cannot delete branch`,
),
);
mockedExecSync.mockClear();
mockedExistsSync.mockReset();
});
});
// ── cleanupOrphanedBranches ────────────────────────────────────────
describe("cleanupOrphanedBranches", () => {

View File

@@ -177,8 +177,10 @@ export class SelfHealingManager {
if (this.settingsListener) {
try {
this.store.removeListener("settings:updated", this.settingsListener);
} catch {
// Store may not support removeListener (e.g., test mocks)
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err);
// Store may not support removeListener (e.g., test mocks) — non-fatal.
log.warn(`Failed to remove settings:updated listener during stop(): ${errorMessage}`);
}
this.settingsListener = null;
}
@@ -372,8 +374,11 @@ export class SelfHealingManager {
`Reset ${completedSteps.length} step(s) to pending — branch had no commits (uncommitted work lost with worktree)`,
);
}
} catch {
// Branch may not exist or git commands may fail — non-fatal
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err);
log.warn(
`Failed to reset steps for ${task.id} after branch/worktree loss (${branchName}): ${errorMessage} — non-fatal`,
);
}
}
@@ -421,7 +426,11 @@ export class SelfHealingManager {
try {
const result = await readLog(task.baseCommitSha ? `${task.baseCommitSha}..HEAD` : "HEAD");
stdout = result.stdout;
} catch {
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err);
log.warn(
`Failed to read git log for landed commit lookup (${task.id}): ${errorMessage} — retrying with HEAD range`,
);
if (!task.baseCommitSha) return null;
const result = await readLog("HEAD");
stdout = result.stdout;
@@ -440,7 +449,11 @@ export class SelfHealingManager {
maxBuffer: 1024 * 1024,
});
Object.assign(commit, parseShortstat(stats.stdout));
} catch {
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err);
log.warn(
`Failed to read shortstat for landed commit ${sha} (${task.id}): ${errorMessage} — continuing without stats`,
);
// Stats are useful for the task detail view but not required for recovery.
}
@@ -454,8 +467,11 @@ export class SelfHealingManager {
cwd: this.options.rootDir,
timeout: 120_000,
});
} catch {
// Non-fatal; existing orphan/worktree cleanup can retry later.
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err);
log.warn(
`Failed to remove interrupted-merge worktree ${task.worktree} for ${task.id}: ${errorMessage} — non-fatal, cleanup can retry later`,
);
}
}
@@ -465,7 +481,11 @@ export class SelfHealingManager {
cwd: this.options.rootDir,
timeout: 120_000,
});
} catch {
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err);
log.warn(
`Failed to delete interrupted-merge branch ${branch} for ${task.id}: ${errorMessage} — non-fatal`,
);
// Non-fatal; branch may be gone or still checked out.
}
}
@@ -1181,7 +1201,11 @@ export class SelfHealingManager {
timeout: 30_000,
});
if (status.trim().length > 0) return true;
} catch {
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err);
log.warn(
`Failed to inspect worktree status for ${task.id} at ${task.worktree}: ${errorMessage} — preserving worktree`,
);
// If we cannot inspect an existing worktree, preserve it.
return true;
}
@@ -1194,6 +1218,7 @@ export class SelfHealingManager {
timeout: 30_000,
});
} catch {
// Intentional negative test: rev-parse exits non-zero when branch does not exist.
return false;
}
@@ -1203,7 +1228,11 @@ export class SelfHealingManager {
{ cwd: this.options.rootDir, timeout: 30_000 },
);
return Number.parseInt(uniqueCommits.trim(), 10) > 0;
} catch {
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err);
log.warn(
`Failed to compare branch ${branchName} against HEAD for ${task.id}: ${errorMessage} — preserving branch`,
);
// If the branch exists but cannot be compared, preserve it.
return true;
}
@@ -1354,7 +1383,9 @@ export class SelfHealingManager {
timeout: 30_000,
});
cleaned++;
} catch {
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err);
log.warn(`Failed to remove orphaned worktree ${worktreePath}: ${errorMessage} — non-fatal`);
// Individual failure is non-fatal
}
}
@@ -1397,7 +1428,11 @@ export class SelfHealingManager {
});
log.log(`Deleted branch: ${branch}`);
cleaned++;
} catch {
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err);
log.warn(
`Safe delete failed for orphaned branch ${branch}: ${errorMessage} — attempting force delete`,
);
// Safe delete failed (not merged) — force delete
try {
await execAsync(`git branch -D "${branch}"`, {
@@ -1406,7 +1441,9 @@ export class SelfHealingManager {
});
log.log(`Force-deleted branch: ${branch}`);
cleaned++;
} catch {
} catch (forceErr: unknown) {
const forceErrorMessage = forceErr instanceof Error ? forceErr.message : String(forceErr);
log.warn(`Failed to force-delete orphaned branch ${branch}: ${forceErrorMessage} — non-fatal`);
// Individual failure is non-fatal
}
}
@@ -1457,7 +1494,9 @@ export class SelfHealingManager {
const withMtime = idle.map((p) => {
try {
return { path: p, mtime: statSync(p).mtimeMs };
} catch {
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err);
log.warn(`Failed to read mtime for worktree ${p}: ${errorMessage} — defaulting mtime to 0`);
return { path: p, mtime: 0 };
}
});
@@ -1474,7 +1513,9 @@ export class SelfHealingManager {
timeout: 30_000,
});
removed++;
} catch {
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err);
log.warn(`Failed to remove idle worktree ${worktreePath} during cap enforcement: ${errorMessage} — non-fatal`);
// Individual failure is non-fatal
}
}