Skip to content

Commit 60d8001

Browse files
fix(gateway): pass the session liveness predicate on every worktree gc path
The worktrees.gc RPC handler and the CLI gc command called service.gc() with no isOwnerActive callback, while the scheduled maintenance sweep passes one. Session-owned worktrees take no git worktree lock (registry activity substitutes), so the callback is their only protection: the RPC and CLI paths force-removed an idle-expired worktree while its owning session was still live, destroying uncommitted work. The predicate now lives in one canonical module used by all three callers, with regressions for active/inactive session owners and the handler wiring. Fixes #104108
1 parent 10820e9 commit 60d8001

6 files changed

Lines changed: 89 additions & 25 deletions

File tree

‎src/cli/worktrees-cli.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { Command } from "commander";
22
import { getTerminalTableWidth, renderTable } from "../../packages/terminal-core/src/table.js";
33
import { managedWorktrees } from "../agents/worktrees/service.js";
44
import type { ManagedWorktreeRecord } from "../agents/worktrees/types.js";
5+
import { isManagedWorktreeOwnerActive } from "../gateway/worktree-owner-activity.js";
56
import { defaultRuntime } from "../runtime.js";
67
import { applyParentDefaultHelpAction } from "./program/parent-default-help.js";
78

@@ -115,7 +116,7 @@ export function registerWorktreesCli(program: Command): void {
115116
.description("Run managed worktree cleanup now")
116117
.option("--json", "Output JSON", false)
117118
.action(async (opts: JsonOption) => {
118-
const result = await managedWorktrees.gc();
119+
const result = await managedWorktrees.gc({ isOwnerActive: isManagedWorktreeOwnerActive });
119120
if (opts.json) {
120121
printJson(result);
121122
} else {

‎src/gateway/server-maintenance.ts‎

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,7 @@
11
// Gateway maintenance timers.
22
// Starts periodic health, dedupe, abort, and media cleanup loops.
33
import { isFutureDateTimestampMs } from "@openclaw/normalization-core/number-coercion";
4-
import {
5-
IDLE_GC_MS,
6-
managedWorktrees,
7-
WORKTREE_GC_INTERVAL_MS,
8-
} from "../agents/worktrees/service.js";
9-
import type { ManagedWorktreeOwnerKind } from "../agents/worktrees/types.js";
4+
import { managedWorktrees, WORKTREE_GC_INTERVAL_MS } from "../agents/worktrees/service.js";
105
import type { HealthSummary } from "../commands/health.js";
116
import { sweepStaleRunContexts } from "../infra/agent-events.js";
127
import { cleanOldMedia } from "../media/store.js";
@@ -31,23 +26,7 @@ import {
3126
import { PENDING_CHAT_SEND_DEDUPE_PREFIX, type DedupeEntry } from "./server-shared.js";
3227
import { formatError } from "./server-utils.js";
3328
import { setBroadcastHealthUpdate } from "./server/health-state.js";
34-
import { loadSessionEntry } from "./session-utils.js";
35-
36-
function isManagedWorktreeOwnerActive(
37-
ownerKind: ManagedWorktreeOwnerKind,
38-
ownerId: string,
39-
): boolean {
40-
if (ownerKind !== "session") {
41-
return false;
42-
}
43-
try {
44-
const entry = loadSessionEntry(ownerId, { clone: false }).entry;
45-
const activityAt = Math.max(entry?.lastInteractionAt ?? 0, entry?.updatedAt ?? 0);
46-
return activityAt > 0 && Date.now() - activityAt <= IDLE_GC_MS;
47-
} catch {
48-
return false;
49-
}
50-
}
29+
import { isManagedWorktreeOwnerActive } from "./worktree-owner-activity.js";
5130

5231
export function startGatewayMaintenanceTimers(params: {
5332
broadcast: (

‎src/gateway/server-methods/worktrees.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { describe, expect, it, vi } from "vitest";
22
import { WorktreeSnapshotError } from "../../agents/worktrees/service.js";
33
import type { ManagedWorktreeRecord } from "../../agents/worktrees/types.js";
4+
import { isManagedWorktreeOwnerActive } from "../worktree-owner-activity.js";
45
import { createWorktreesHandlers } from "./worktrees.js";
56

67
const record: ManagedWorktreeRecord = {
@@ -65,6 +66,10 @@ describe("worktrees gateway methods", () => {
6566
{ removed: [record.id], orphansDeleted: 1, snapshotsPruned: 2 },
6667
undefined,
6768
]);
69+
// The RPC path must pass the same session-owner liveness predicate the
70+
// scheduled maintenance sweep passes; omitting it removes a live session's
71+
// worktree (#104108).
72+
expect(service.gc).toHaveBeenCalledWith({ isOwnerActive: isManagedWorktreeOwnerActive });
6873

6974
expect(service.create).toHaveBeenCalledWith({
7075
repoRoot: "/repo",

‎src/gateway/server-methods/worktrees.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { listAgentIds, resolveAgentWorkspaceDir } from "../../agents/agent-scope
1414
import { managedWorktrees, WorktreeSnapshotError } from "../../agents/worktrees/service.js";
1515
import type { ManagedWorktreeService } from "../../agents/worktrees/service.js";
1616
import { ADMIN_SCOPE } from "../operator-scopes.js";
17+
import { isManagedWorktreeOwnerActive } from "../worktree-owner-activity.js";
1718
import type { GatewayRequestHandlers } from "./types.js";
1819

1920
type WorktreeService = Pick<
@@ -143,7 +144,7 @@ export function createWorktreesHandlers(service: WorktreeService): GatewayReques
143144
return;
144145
}
145146
try {
146-
respond(true, await service.gc(), undefined);
147+
respond(true, await service.gc({ isOwnerActive: isManagedWorktreeOwnerActive }), undefined);
147148
} catch (error) {
148149
respond(false, undefined, errorShape(ErrorCodes.UNAVAILABLE, String(error)));
149150
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Covers the canonical worktree-GC owner liveness predicate (#104108).
2+
import fs from "node:fs";
3+
import path from "node:path";
4+
import { afterEach, describe, expect, test } from "vitest";
5+
import { IDLE_GC_MS } from "../agents/worktrees/service.js";
6+
import { resetConfigRuntimeState, setRuntimeConfigSnapshot } from "../config/config.js";
7+
import type { OpenClawConfig } from "../config/config.js";
8+
import { withStateDirEnv } from "../test-helpers/state-dir-env.js";
9+
import { isManagedWorktreeOwnerActive } from "./worktree-owner-activity.js";
10+
11+
afterEach(() => {
12+
resetConfigRuntimeState();
13+
});
14+
15+
describe("isManagedWorktreeOwnerActive", () => {
16+
test("keeps live session owners active and idle-expired ones inactive", async () => {
17+
await withStateDirEnv("worktree-owner-activity-", async ({ stateDir }) => {
18+
const sessionsDir = path.join(stateDir, "agents", "main", "sessions");
19+
fs.mkdirSync(sessionsDir, { recursive: true });
20+
const now = Date.now();
21+
fs.writeFileSync(
22+
path.join(sessionsDir, "sessions.json"),
23+
JSON.stringify({
24+
"agent:main:live": { sessionId: "sess-live", lastInteractionAt: now, updatedAt: now },
25+
"agent:main:stale": {
26+
sessionId: "sess-stale",
27+
lastInteractionAt: now - IDLE_GC_MS - 60_000,
28+
updatedAt: now - IDLE_GC_MS - 60_000,
29+
},
30+
}),
31+
"utf8",
32+
);
33+
const cfg = {
34+
session: {
35+
mainKey: "main",
36+
store: path.join(stateDir, "agents", "{agentId}", "sessions", "sessions.json"),
37+
},
38+
agents: { list: [{ id: "main", default: true }] },
39+
} as OpenClawConfig;
40+
setRuntimeConfigSnapshot(cfg, cfg);
41+
42+
expect(isManagedWorktreeOwnerActive("session", "agent:main:live")).toBe(true);
43+
expect(isManagedWorktreeOwnerActive("session", "agent:main:stale")).toBe(false);
44+
// Non-session owners rely on the git-lock fallback inside gc(), never
45+
// on session activity.
46+
expect(isManagedWorktreeOwnerActive("manual", "agent:main:live")).toBe(false);
47+
// Unknown sessions are not treated as live.
48+
expect(isManagedWorktreeOwnerActive("session", "agent:main:missing")).toBe(false);
49+
});
50+
});
51+
});
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Canonical GC liveness predicate for managed worktrees.
2+
import { IDLE_GC_MS } from "../agents/worktrees/service.js";
3+
import type { ManagedWorktreeOwnerKind } from "../agents/worktrees/types.js";
4+
import { loadSessionEntry } from "./session-utils.js";
5+
6+
/**
7+
* Session-owned worktrees take no git worktree lock (chat runs avoid registry
8+
* acquire writes), so recent owning-session activity is their only protection
9+
* against idle-expiry removal. Every gc() caller — scheduled maintenance, the
10+
* worktrees.gc RPC, and the CLI command — must pass this same predicate;
11+
* omitting it lets gc remove a live session's worktree (#104108).
12+
*/
13+
export function isManagedWorktreeOwnerActive(
14+
ownerKind: ManagedWorktreeOwnerKind,
15+
ownerId: string,
16+
): boolean {
17+
if (ownerKind !== "session") {
18+
return false;
19+
}
20+
try {
21+
const entry = loadSessionEntry(ownerId, { clone: false }).entry;
22+
const activityAt = Math.max(entry?.lastInteractionAt ?? 0, entry?.updatedAt ?? 0);
23+
return activityAt > 0 && Date.now() - activityAt <= IDLE_GC_MS;
24+
} catch {
25+
return false;
26+
}
27+
}

0 commit comments

Comments
 (0)