Skip to content

Commit 73bdb4b

Browse files
authored
feat(agents): record run-end worktree cleanup outcome; prove Workboard dirty retention (#120434)
* feat(agents): record run-end worktree cleanup outcome Persist removed, retained, and failed run-end cleanup outcomes on managed worktree records. Operators and QA can inspect the durable fact through worktrees.list and openclaw worktrees list --json. Release note: Managed worktree run-end cleanup now records why a checkout was removed or retained in worktree list JSON. * test(qa): prove dirty worktree retention outcome * chore(protocol): regenerate swift gateway models * fix(agents): harden worktree cleanup recovery Register run_end_cleanup_json as a lazy compatible column so same-version v6 index repair and read-only doctor migration can recover databases created before the column existed. Type removal contention at the registry boundary; unexpected claim failures now best-effort record a bounded failed outcome and rethrow the original error. * fix(ci): clear repo-wide lint debt blocking merge gates The red-main landing rule requires this PR to repair repository-wide merge-gate debt instead of bypassing it. Apply the current lint contracts mechanically and split turn-transition coverage into a concept-named sibling with per-file-safe test state. Exact line delta: +676/-574 (net +102) across 44 test/support files. * fix(ci): preserve cached health refresh proof Require the public refresh call to exist before accepting that sensitive fields were omitted, so the boundary proof cannot pass on a missing call. * fix(ci): correct test typing left by the lint sweep Literal-widened totalTokensVersion fixtures, a WebSocket RawData overload mismatch, and the protocol schema document cast broke check-test-types after the repo-wide lint repair. Aligns the fixtures with SessionEntry, narrows Buffer handling per RawData, and keeps the JSON-shaped undefined omission under structuredClone. * test(agents): reuse upstream resource-loader test support The session-loop split and #120463's helper extraction landed the same createResourceLoader/createCompactionHandlers twice; the rebase kept both, orphaning main's agent-session-loop-resource-loader.test-support.ts and failing the dead-code gate. Import the upstream helpers and delete the duplicates. * fix(agents): reject finalized rows at the worktree removal claim Address the accepted ClawSweeper late-claim finding by rereading and rejecting missing or finalized worktree rows inside the synchronous removal-claim transaction. Preserve the authoritative cleanup invariant: finalized contenders record nothing, while retained-busy is written only while the row remains live. * refactor(agents): reuse registry update for busy outcomes Keep the live-row conditional write in the canonical registry update path so the finalized-claim repair stays below the registry max-lines ratchet without weakening the authoritative-outcome invariant. * test(agents): drop session test duplicates after rebase Keep current main as the canonical owner of next-turn lifecycle coverage and correctness test support after replaying the older lint-debt split. * fix(agents): guard post-abort cleanup outcomes against finalization After abortWorktreeRemoval releases a stale remover's claim, its retained or failed write raced a finalizing remover and could overwrite the authoritative removed-lossless fact. Route every retained/failed write through the live-row condition; only the finalizing remover's own removed-lossless write stays unconditional. * fix(agents): persist the removal outcome atomically with finalization A delayed removed-lossless write after remove() finalized could race a restore plus newer cleanup and overwrite the newer operator-visible fact. The run-end outcome now rides remove()'s finalization update; every other cleanup write stays live-row conditional, so no post-finalize write path remains. * test(qa): restore strict cached-health contract assertions The lint sweep's Boolean() coercions let truthy non-booleans satisfy the wire-typed cached-meta contract. Assert the literal boolean for unknown-typed fields and use nullish-coalesced strict equivalents for boolean chains. * fix(agents): clear the stale cleanup outcome when restoring a worktree A restored checkout begins a new lifecycle; leaving the removed-lossless fact on the live row showed operators a stale result until the next cleanup. Restore clears the recorded outcome and the regression asserts the cleared state before the next cleanup records fresh truth. * fix(agents): scope stale cleanup outcomes to their observed lifecycle A stale remover's retained/failed write raced a concurrent remove-plus- restore: the revived row is live again, so the live-row condition alone could stamp a prior-lifecycle outcome. Condition those writes on the activity stamp the remover observed; restore bumps lastActiveAt, making any prior-lifecycle write a no-op. * fix(agents): advance the restore activity stamp within one millisecond Stale cleanup writes fence on the activity stamp they observed; a restore completing in the same millisecond could revive the row with an identical stamp and let the fence match. Restore now always advances past the stored value, and the ABA regression pins the clock to prove the same-millisecond case.
1 parent c2e7c81 commit 73bdb4b

57 files changed

Lines changed: 845 additions & 209 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2948,6 +2948,7 @@ public struct WorktreeRecord: Codable, Sendable {
29482948
public let createdat: Int
29492949
public let lastactiveat: Int
29502950
public let removedat: Int?
2951+
public let runendcleanup: AnyCodable?
29512952

29522953
public init(
29532954
id: String,
@@ -2962,7 +2963,8 @@ public struct WorktreeRecord: Codable, Sendable {
29622963
snapshotref: String? = nil,
29632964
createdat: Int,
29642965
lastactiveat: Int,
2965-
removedat: Int? = nil)
2966+
removedat: Int? = nil,
2967+
runendcleanup: AnyCodable? = nil)
29662968
{
29672969
self.id = id
29682970
self.name = name
@@ -2977,6 +2979,7 @@ public struct WorktreeRecord: Codable, Sendable {
29772979
self.createdat = createdat
29782980
self.lastactiveat = lastactiveat
29792981
self.removedat = removedat
2982+
self.runendcleanup = runendcleanup
29802983
}
29812984

29822985
private enum CodingKeys: String, CodingKey {
@@ -2993,6 +2996,7 @@ public struct WorktreeRecord: Codable, Sendable {
29932996
case createdat = "createdAt"
29942997
case lastactiveat = "lastActiveAt"
29952998
case removedat = "removedAt"
2999+
case runendcleanup = "runEndCleanup"
29963000
}
29973001
}
29983002

‎docs/concepts/managed-worktrees.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,8 @@ OpenClaw applies these cleanup rules:
6868
- Snapshot records remain restorable for 30 days. Cleanup then deletes the snapshot ref and registry row.
6969
- A live OpenClaw process lock and any foreign or unrecognized git worktree lock protect a worktree from garbage collection.
7070

71+
Run-end cleanup records its outcome on the worktree record: lossless removal, retention because the checkout is busy, dirty, unpushed, or has provisioned-file drift, or failure with an error reason. Inspect the recorded outcome with `openclaw worktrees list --json` or `worktrees.list`.
72+
7173
Restore recreates `openclaw/<name>` at the original pre-snapshot commit, then rebuilds the snapshot differences as unstaged modifications and untracked files. This keeps the synthetic snapshot commit out of branch history. The snapshot ref remains recorded as provenance.
7274

7375
## CLI

‎packages/gateway-protocol/src/schema/worktrees.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,26 @@ import { NonEmptyString } from "./primitives.js";
55

66
const WorktreeNameSchema = Type.String({ pattern: "^[a-z0-9][a-z0-9-]{0,63}$" });
77

8+
const WorktreeRunEndCleanupSchema = Type.Union([
9+
closedObject({
10+
outcome: Type.String({
11+
enum: [
12+
"removed-lossless",
13+
"retained-busy",
14+
"retained-dirty",
15+
"retained-unpushed",
16+
"retained-provisioned-drift",
17+
],
18+
}),
19+
at: Type.Integer({ minimum: 0 }),
20+
}),
21+
closedObject({
22+
outcome: Type.Literal("failed"),
23+
at: Type.Integer({ minimum: 0 }),
24+
reason: Type.String({ minLength: 1, maxLength: 500 }),
25+
}),
26+
]);
27+
828
export const WorktreeRecordSchema = closedObject({
929
id: NonEmptyString,
1030
name: WorktreeNameSchema,
@@ -19,6 +39,7 @@ export const WorktreeRecordSchema = closedObject({
1939
createdAt: Type.Integer({ minimum: 0 }),
2040
lastActiveAt: Type.Integer({ minimum: 0 }),
2141
removedAt: Type.Optional(Type.Integer({ minimum: 0 })),
42+
runEndCleanup: Type.Optional(WorktreeRunEndCleanupSchema),
2243
});
2344

2445
export const WorktreesListParamsSchema = closedObject({});

‎qa/scenarios/runtime/managed-worktrees-workboard-lifecycle.yaml‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,22 @@ scenario:
77
coverage:
88
primary:
99
- agent-runtime.managed-worktrees-workboard-lifecycle
10-
objective: Prove the real child gateway materializes a Workboard card workspace as a managed wb-<card-id> worktree, writes the resolved checkout and branch back to the card, runs its subagent, and removes the clean checkout losslessly at run end.
10+
objective: Prove the real child gateway materializes Workboard card workspaces as managed wb-<card-id> worktrees, writes the resolved checkout and branch back to each card, runs their subagents, removes a clean checkout losslessly, and retains a dirty checkout with a recorded cleanup outcome.
1111
successCriteria:
1212
- Dispatch materializes the card's source workspace under the managed state directory as wb-<card-id> on branch openclaw/wb-<card-id>.
1313
- The dispatched card persists the resolved managed checkout path and branch while retaining its source workspace metadata.
14-
- The real mock-provider subagent run reaches a terminal outcome and run-end cleanup removes the clean checkout losslessly.
14+
- A real mock-provider subagent run reaches a terminal outcome, and run-end cleanup removes its clean checkout losslessly with a recorded removed-lossless outcome.
15+
- A second real subagent run leaves an untracked file, and run-end cleanup records retained-dirty while keeping the live checkout intact.
1516
docsRefs:
1617
- docs/concepts/managed-worktrees.md
1718
- docs/concepts/qa-e2e-automation.md
1819
codeRefs:
1920
- src/agents/worktrees/service.ts
21+
- src/agents/worktrees/service.run-end-cleanup.test.ts
2022
- extensions/workboard/src/dispatcher.ts
2123
- extensions/workboard/src/dispatcher-workspace.ts
2224
- test/e2e/qa-lab/runtime/managed-worktrees-workboard-lifecycle-product-proof.e2e.test.ts
2325
execution:
2426
kind: vitest
2527
path: test/e2e/qa-lab/runtime/managed-worktrees-workboard-lifecycle-product-proof.e2e.test.ts
26-
summary: Run the real child gateway through Workboard card worktree materialization, workspace writeback, subagent completion, and run-end lossless removal.
28+
summary: Run the real child gateway through Workboard card worktree materialization, workspace writeback, subagent completion, clean removal, and dirty retention with recorded cleanup outcomes.

‎src/agents/worktrees/registry.ts‎

Lines changed: 87 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { DatabaseSync } from "node:sqlite";
2+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
23
import type { Insertable, Selectable } from "kysely";
34
import { executeSqliteQuerySync, getNodeSqliteKysely } from "../../infra/kysely-sync.js";
45
import { isLockOwnerDefinitelyStale } from "../../infra/stale-lock-file.js";
@@ -12,6 +13,7 @@ import {
1213
import type {
1314
ManagedWorktreeOwnerKind,
1415
ManagedWorktreeRecord,
16+
ManagedWorktreeRunEndCleanup,
1517
ProvisionedFileState,
1618
} from "./types.js";
1719

@@ -40,7 +42,41 @@ function kyselyLeaseFor(db: DatabaseSync) {
4042
return getNodeSqliteKysely<WorktreeLeaseDatabase>(db);
4143
}
4244

45+
function parseRunEndCleanup(
46+
raw: string | null | undefined,
47+
): ManagedWorktreeRunEndCleanup | undefined {
48+
if (raw == null) {
49+
return undefined;
50+
}
51+
try {
52+
const parsed = JSON.parse(raw) as unknown;
53+
if (!isRecord(parsed) || !Number.isInteger(parsed.at) || (parsed.at as number) < 0) {
54+
return undefined;
55+
}
56+
const at = parsed.at as number;
57+
switch (parsed.outcome) {
58+
case "failed":
59+
return typeof parsed.reason === "string" &&
60+
parsed.reason.length > 0 &&
61+
parsed.reason.length <= 500
62+
? { outcome: parsed.outcome, at, reason: parsed.reason }
63+
: undefined;
64+
case "removed-lossless":
65+
case "retained-busy":
66+
case "retained-dirty":
67+
case "retained-unpushed":
68+
case "retained-provisioned-drift":
69+
return parsed.reason === undefined ? { outcome: parsed.outcome, at } : undefined;
70+
default:
71+
return undefined;
72+
}
73+
} catch {
74+
return undefined;
75+
}
76+
}
77+
4378
function rowToRecord(row: WorktreeRow): ManagedWorktreeRecord {
79+
const runEndCleanup = parseRunEndCleanup(row.run_end_cleanup_json);
4480
return {
4581
id: row.id,
4682
name: row.path.split(/[\\/]/).at(-1) ?? row.id,
@@ -55,6 +91,7 @@ function rowToRecord(row: WorktreeRow): ManagedWorktreeRecord {
5591
createdAt: row.created_at,
5692
lastActiveAt: row.last_active_at,
5793
...(row.removed_at == null ? {} : { removedAt: row.removed_at }),
94+
...(runEndCleanup ? { runEndCleanup } : {}),
5895
};
5996
}
6097

@@ -77,6 +114,8 @@ function recordToRow(
77114
removed_at: record.removedAt ?? null,
78115
provisioned_paths_json:
79116
provisionedPaths === undefined ? null : JSON.stringify(provisionedPaths),
117+
run_end_cleanup_json:
118+
record.runEndCleanup === undefined ? null : JSON.stringify(record.runEndCleanup),
80119
};
81120
}
82121

@@ -356,10 +395,13 @@ export function insertRegistryWorktree(
356395
export function updateRegistryWorktree(
357396
env: NodeJS.ProcessEnv,
358397
id: string,
359-
patch: Partial<Pick<ManagedWorktreeRecord, "lastActiveAt" | "removedAt" | "snapshotRef">> & {
398+
patch: Partial<
399+
Pick<ManagedWorktreeRecord, "lastActiveAt" | "removedAt" | "runEndCleanup" | "snapshotRef">
400+
> & {
360401
provisionedPaths?: readonly string[];
361402
provisionedState?: readonly ProvisionedFileState[];
362403
},
404+
options: { onlyIfLive?: boolean; onlyIfActiveAt?: number } = {},
363405
): void {
364406
const db = dbFor(env);
365407
const values: Partial<WorktreeRow> = {};
@@ -372,16 +414,28 @@ export function updateRegistryWorktree(
372414
if ("snapshotRef" in patch) {
373415
values.snapshot_ref = patch.snapshotRef ?? null;
374416
}
417+
if ("runEndCleanup" in patch) {
418+
values.run_end_cleanup_json =
419+
patch.runEndCleanup === undefined ? null : JSON.stringify(patch.runEndCleanup);
420+
}
375421
if (patch.provisionedState !== undefined) {
376422
values.provisioned_paths_json = JSON.stringify(patch.provisionedState);
377423
} else if (patch.provisionedPaths !== undefined) {
378424
values.provisioned_paths_json = JSON.stringify(patch.provisionedPaths);
379425
}
380426
runOpenClawStateWriteTransaction(() => {
381-
executeSqliteQuerySync(
382-
db,
383-
kyselyFor(db).updateTable("worktrees").set(values).where("id", "=", id),
384-
);
427+
let update = kyselyFor(db).updateTable("worktrees").set(values).where("id", "=", id);
428+
// Busy/retained/failed outcomes are authoritative only for the lifecycle the
429+
// writer observed: the live condition blocks post-finalization overwrites, and
430+
// the activity condition blocks prior-lifecycle writes after a concurrent
431+
// remove-plus-restore revives the row (restore bumps last_active_at).
432+
if (options.onlyIfLive) {
433+
update = update.where("removed_at", "is", null);
434+
}
435+
if (options.onlyIfActiveAt !== undefined) {
436+
update = update.where("last_active_at", "=", options.onlyIfActiveAt);
437+
}
438+
executeSqliteQuerySync(db, update);
385439
});
386440
}
387441

@@ -401,6 +455,16 @@ export function deleteRegistryWorktree(env: NodeJS.ProcessEnv, id: string): void
401455
const WORKTREE_RUN_LEASE_SCOPE_PREFIX = "worktree-run:";
402456
const WORKTREE_REMOVING_LEASE_KEY = "__removing__";
403457

458+
export class WorktreeRemovalContentionError extends Error {
459+
constructor(
460+
readonly kind: "busy" | "finalized",
461+
message: string,
462+
) {
463+
super(message);
464+
this.name = "WorktreeRemovalContentionError";
465+
}
466+
}
467+
404468
export type RunLeaseOwnerChecks = {
405469
isPidDefinitelyDead?: (pid: number) => boolean;
406470
getProcessStartTime?: (pid: number) => number | null;
@@ -547,14 +611,30 @@ export function claimWorktreeRemovalRow(
547611
const db = database.db;
548612
const k = kyselyLeaseFor(db);
549613
const scope = worktreeRunLeaseScope(params.worktreeId);
614+
const record = executeSqliteQuerySync(
615+
db,
616+
k
617+
.selectFrom("worktrees")
618+
.select(["id", "path", "removed_at"])
619+
.where("id", "=", params.worktreeId),
620+
).rows[0];
621+
if (!record || record.removed_at != null) {
622+
throw new WorktreeRemovalContentionError(
623+
"finalized",
624+
`managed worktree was removed: ${record?.path ?? params.worktreeId}`,
625+
);
626+
}
550627
const { livePids, removingToken } = collectLiveRunLeases(db, k, scope, params.checks ?? {});
551628
if (!params.force && livePids.length > 0) {
552-
throw new Error(`worktree is busy: locked by live pid ${livePids[0]}`);
629+
throw new WorktreeRemovalContentionError(
630+
"busy",
631+
`worktree is busy: locked by live pid ${livePids[0]}`,
632+
);
553633
}
554634
// The removal claim is exclusive: a live marker owned by a different token means
555635
// another remover is mid-operation, so this remover must not enter it too.
556636
if (removingToken !== undefined && removingToken !== params.token) {
557-
throw new Error("worktree removal is already in progress");
637+
throw new WorktreeRemovalContentionError("busy", "worktree removal is already in progress");
558638
}
559639
const payloadJson = JSON.stringify({
560640
pid: params.pid,

0 commit comments

Comments
 (0)