Skip to content

Commit ee2027a

Browse files
authored
fix(skills): target the canonical workspace from worktree sessions and survive missing drafts (#125737)
Skill proposals created in ephemeral session worktrees targeted the throwaway copy — applied autolearn updates were silently lost — and a missing durable draft failed the whole skill_workshop list action. The session producer now records the selected canonical workspace (projectRoot/requestedCwd/agent workspace) when it swaps cwd into a managed worktree, capture and the workshop tool prefer that recorded fact, persisted pre-upgrade session records are backfilled idempotently at the startup migration owner, and missing-draft proposals render a degraded state with actionable inspect/apply errors instead of dead-ending. Fixes #125653
1 parent 0c493f6 commit ee2027a

21 files changed

Lines changed: 891 additions & 424 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { AsyncLocalStorage } from "node:async_hooks";
2+
3+
const canonicalSkillWorkspace = new AsyncLocalStorage<string>();
4+
5+
export function runWithCanonicalSkillWorkspace<T>(
6+
canonicalWorkspaceDir: string | undefined,
7+
run: () => T,
8+
): T {
9+
return canonicalWorkspaceDir ? canonicalSkillWorkspace.run(canonicalWorkspaceDir, run) : run();
10+
}
11+
12+
export function getCanonicalSkillWorkspace(): string | undefined {
13+
return canonicalSkillWorkspace.getStore();
14+
}

‎src/agents/tools/skill-workshop-tool-factory.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
22
import type { OpenClawConfig } from "../../config/types.openclaw.js";
33
import type { SkillProposalOrigin, SkillWorkshopRunOptions } from "../../skills/workshop/types.js";
4+
import { getCanonicalSkillWorkspace } from "../skill-workshop-workspace-context.js";
45
import { createSkillWorkshopTool } from "./skill-workshop-tool.js";
56

67
export function createConfiguredSkillWorkshopTool(params: {
@@ -18,7 +19,7 @@ export function createConfiguredSkillWorkshopTool(params: {
1819
params.messageId === undefined ? undefined : String(params.messageId),
1920
);
2021
return createSkillWorkshopTool({
21-
workspaceDir: params.workspaceDir,
22+
workspaceDir: getCanonicalSkillWorkspace() ?? params.workspaceDir,
2223
config: params.config,
2324
env: params.run?.env,
2425
agentId: params.agentId,

‎src/agents/tools/skill-workshop-tool-presentation.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ export function formatProposalList(proposals: readonly SkillProposalManifestEntr
7070
return proposals
7171
.map(
7272
(proposal) =>
73-
`- ${proposal.id} [${proposal.status}, ${proposal.kind}, ${proposal.scanState}${proposal.workspaceMismatch ? ", previous workspace" : ""}] ${proposal.skillKey}: ${proposal.title}`,
73+
`- ${proposal.id} [${proposal.status}, ${proposal.kind}, ${proposal.scanState}${proposal.workspaceMismatch ? ", previous workspace" : ""}${proposal.degradedState === "draft-missing" ? ", draft missing — reject and re-propose" : ""}] ${proposal.skillKey}: ${proposal.title}`,
7474
)
7575
.join("\n");
7676
}

‎src/agents/tools/skill-workshop-tool.list.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,45 @@ afterEach(async () => {
5151
});
5252

5353
describe("skill_workshop list", () => {
54+
it("lists a pending proposal whose draft is missing", async () => {
55+
const workspaceDir = await tempDirs.make("openclaw-skill-workshop-missing-draft-");
56+
const tool = createSkillWorkshopTool({
57+
workspaceDir,
58+
config: {},
59+
agentId: "main",
60+
env: testState.env,
61+
});
62+
const created = await tool.execute("call-create", {
63+
action: "create",
64+
name: "Missing Draft",
65+
description: "Proposal with a missing draft artifact.",
66+
proposal_content: "# Missing Draft\n",
67+
});
68+
const proposalId = (created.details as { id: string }).id;
69+
await fs.rm(
70+
path.join(testState.stateDir, "skill-workshop", "proposals", proposalId, "PROPOSAL.md"),
71+
);
72+
73+
const listed = await tool.execute("call-list", { action: "list" });
74+
const listText = (listed.content[0] as { text: string }).text;
75+
expect(listText).toContain(proposalId);
76+
expect(listText).toContain("draft missing");
77+
expect(listed.details).toMatchObject({
78+
proposals: [
79+
{ id: proposalId, status: "pending", kind: "create", degradedState: "draft-missing" },
80+
],
81+
});
82+
await expect(
83+
tool.execute("call-inspect", { action: "inspect", proposal_id: proposalId }),
84+
).rejects.toThrow(`Skill proposal draft is missing: ${proposalId}. Reject and re-propose it.`);
85+
await expect(
86+
tool.execute("call-apply", { action: "apply", proposal_id: proposalId }),
87+
).rejects.toThrow(`Skill proposal draft is missing: ${proposalId}. Reject and re-propose it.`);
88+
await expect(
89+
tool.execute("call-reject", { action: "reject", proposal_id: proposalId }),
90+
).resolves.toMatchObject({ details: { id: proposalId, status: "rejected" } });
91+
});
92+
5493
it.each([0, 1.5, "1.5", "25items", "many"])(
5594
"rejects invalid list limit %s before touching proposal state",
5695
async (limit) => {

‎src/config/sessions/startup-migration.registry-recovery.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,11 +74,13 @@ it("re-registers durable lineage children before configured-only runtime reads",
7474
),
7575
).toBe(false);
7676

77+
const migrateManagedWorktreeCanonicalWorkspaces = vi.fn(async () => 0);
7778
await runSessionStartupMigration({
7879
cfg,
7980
env,
8081
log: { info: vi.fn(), warn: vi.fn() },
8182
deps: {
83+
migrateManagedWorktreeCanonicalWorkspaces,
8284
migrateLegacyMainSessionKeys: vi.fn(async () => ({
8385
armed: false,
8486
changes: [],
@@ -94,6 +96,7 @@ it("re-registers durable lineage children before configured-only runtime reads",
9496
sweepOrphanSessionStoreTemps: vi.fn(async () => 0),
9597
},
9698
});
99+
expect(migrateManagedWorktreeCanonicalWorkspaces).toHaveBeenCalled();
97100

98101
expect(listOpenClawRegisteredAgentDatabases({ env })).toContainEqual(
99102
expect.objectContaining({ agentId: "codex", path: childDatabasePath }),

‎src/config/sessions/startup-migration.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { setCanonicalSqliteSessionMainKey } from "./session-canonical-key.js";
1313
import { resolveSqliteTargetFromSessionStorePath } from "./session-sqlite-target.js";
1414
import { sweepOrphanSessionStoreTemps } from "./store-temp-cleanup.js";
1515
import { resolveAllAgentSessionStoreTargetsSync } from "./targets.js";
16+
import { migrateManagedWorktreeCanonicalWorkspaces } from "./worktree-workspace-migration.js";
1617

1718
export type SessionStartupMigrationLogger = Record<"info" | "warn", (message: string) => void>;
1819

@@ -30,6 +31,7 @@ export async function runSessionStartupMigration(params: {
3031
migrateOrphanedSessionKeys?: typeof migrateOrphanedSessionKeys;
3132
migrateLegacyMainSessionKeys?: typeof migrateLegacyMainSessionKeys;
3233
prepareLegacySessionSurfaces?: PrepareLegacySessionSurfaces;
34+
migrateManagedWorktreeCanonicalWorkspaces?: typeof migrateManagedWorktreeCanonicalWorkspaces;
3335
resolveAllAgentSessionStoreTargetsSync?: typeof resolveAllAgentSessionStoreTargetsSync;
3436
sweepOrphanSessionStoreTemps?: typeof sweepOrphanSessionStoreTemps;
3537
};
@@ -109,6 +111,7 @@ export async function runSessionStartupMigration(params: {
109111
const sweepTemps = params.deps?.sweepOrphanSessionStoreTemps ?? sweepOrphanSessionStoreTemps;
110112
try {
111113
let removedFiles = 0;
114+
let migratedWorktreeSessions = 0;
112115
for (const target of targets) {
113116
const path = resolveSqliteTargetFromSessionStorePath(target.storePath, {
114117
agentId: target.agentId,
@@ -117,6 +120,21 @@ export async function runSessionStartupMigration(params: {
117120
const alreadyOpen = isOpenClawAgentDatabaseOpen(path);
118121
const database = openOpenClawAgentDatabase({ agentId: target.agentId, path });
119122
setCanonicalSqliteSessionMainKey(database, params.cfg.session?.mainKey);
123+
const migrateWorktreeSessions =
124+
params.deps?.migrateManagedWorktreeCanonicalWorkspaces ??
125+
migrateManagedWorktreeCanonicalWorkspaces;
126+
try {
127+
migratedWorktreeSessions += await migrateWorktreeSessions({
128+
agentId: target.agentId,
129+
cfg: params.cfg,
130+
env,
131+
storePath: target.storePath,
132+
});
133+
} catch (error) {
134+
params.log.warn(
135+
`session: managed-worktree workspace migration failed for ${target.agentId}; continuing: ${String(error)}`,
136+
);
137+
}
120138
if (!alreadyOpen) {
121139
closeOpenClawAgentDatabaseByPath(path);
122140
}
@@ -125,6 +143,11 @@ export async function runSessionStartupMigration(params: {
125143
if (removedFiles > 0) {
126144
params.log.info(`session: removed ${removedFiles} stale session store temp file(s)`);
127145
}
146+
if (migratedWorktreeSessions > 0) {
147+
params.log.info(
148+
`session: recorded canonical workspaces for ${migratedWorktreeSessions} managed-worktree session(s)`,
149+
);
150+
}
128151
} catch (err) {
129152
params.log.warn(
130153
`session: stale session store temp cleanup failed during startup; continuing: ${String(err)}`,
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import fs from "node:fs/promises";
2+
import path from "node:path";
3+
import { afterEach, expect, it } from "vitest";
4+
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
5+
import { insertRegistryWorktree } from "../../agents/worktrees/registry.js";
6+
import { closeOpenClawAgentDatabasesForTest } from "../../state/openclaw-agent-db.js";
7+
import { closeOpenClawStateDatabaseForTest } from "../../state/openclaw-state-db.js";
8+
import type { OpenClawConfig } from "../types.openclaw.js";
9+
import { loadSessionEntry, replaceSessionEntry } from "./session-accessor.js";
10+
import { migrateManagedWorktreeCanonicalWorkspaces } from "./worktree-workspace-migration.js";
11+
12+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
13+
14+
afterEach(() => {
15+
closeOpenClawAgentDatabasesForTest();
16+
closeOpenClawStateDatabaseForTest();
17+
});
18+
19+
it("backfills a nested requested workspace once instead of using the agent default", async () => {
20+
const root = tempDirs.make("openclaw-worktree-workspace-migration-");
21+
const stateDir = path.join(root, "state");
22+
const repoRoot = path.join(root, "repo");
23+
const agentWorkspace = path.join(repoRoot, "agent-default");
24+
const requestedWorkspace = path.join(repoRoot, "packages", "app");
25+
const worktreeRoot = path.join(stateDir, "worktrees", "legacy");
26+
const spawnedCwd = path.join(worktreeRoot, "packages", "app");
27+
await Promise.all([
28+
fs.mkdir(agentWorkspace, { recursive: true }),
29+
fs.mkdir(requestedWorkspace, { recursive: true }),
30+
fs.mkdir(spawnedCwd, { recursive: true }),
31+
]);
32+
const env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };
33+
const storePath = path.join(stateDir, "agents", "main", "sessions", "sessions.json");
34+
const sessionKey = "agent:main:dashboard:legacy-worktree";
35+
const cfg: OpenClawConfig = {
36+
agents: { list: [{ id: "main", default: true, workspace: agentWorkspace }] },
37+
session: { store: storePath },
38+
};
39+
insertRegistryWorktree(env, {
40+
id: "legacy",
41+
name: "legacy",
42+
repoFingerprint: "0123456789abcdef",
43+
repoRoot,
44+
path: worktreeRoot,
45+
branch: "openclaw/legacy",
46+
baseRef: "HEAD",
47+
ownerKind: "session",
48+
ownerId: sessionKey,
49+
createdAt: 1,
50+
lastActiveAt: 1,
51+
});
52+
await replaceSessionEntry(
53+
{ agentId: "main", env, sessionKey, storePath },
54+
{
55+
sessionId: "legacy-session",
56+
updatedAt: 10,
57+
spawnedCwd,
58+
worktree: { id: "legacy", branch: "openclaw/legacy", repoRoot },
59+
},
60+
);
61+
62+
const runMigration = async () =>
63+
await migrateManagedWorktreeCanonicalWorkspaces({
64+
agentId: "main",
65+
cfg,
66+
env,
67+
storePath,
68+
});
69+
70+
await runMigration();
71+
const first = loadSessionEntry({ agentId: "main", env, sessionKey, storePath });
72+
expect(first?.worktree?.canonicalWorkspaceDir).toBe(requestedWorkspace);
73+
expect(first?.updatedAt).toBe(10);
74+
75+
await runMigration();
76+
expect(loadSessionEntry({ agentId: "main", env, sessionKey, storePath })).toEqual(first);
77+
});

‎src/config/sessions/types.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,13 @@ type SessionEntryCore = SessionRestartRecoveryState &
374374
* Managed worktree bound to this session; set with spawnedCwd at worktree
375375
* creation and cleared together when a plain New Chat detaches the checkout.
376376
*/
377-
worktree?: { id: string; branch: string; repoRoot: string };
377+
worktree?: {
378+
id: string;
379+
branch: string;
380+
repoRoot: string;
381+
/** Durable skill workspace prepared when this session runs from a managed worktree. */
382+
canonicalWorkspaceDir?: string;
383+
};
378384
/** Project registry id selected when this logical session node was created. */
379385
projectId?: string;
380386
/** Explicit parent session linkage for dashboard-created child sessions. */
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import path from "node:path";
2+
import { resolveAgentWorkspaceDir } from "../../agents/agent-scope.js";
3+
import { listRegistryWorktreesForMigration } from "../../agents/worktrees/registry.js";
4+
import { resolveProjectRegistry } from "../../projects/project-registry.js";
5+
import type { OpenClawConfig } from "../types.openclaw.js";
6+
import { listSessionEntriesReadOnly, patchSessionEntryCore } from "./session-accessor.js";
7+
import type { SessionEntry } from "./types.js";
8+
9+
function isInside(root: string, target: string): boolean {
10+
const relative = path.relative(root, target);
11+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
12+
}
13+
14+
function resolveLegacyCanonicalWorkspace(params: {
15+
agentId: string;
16+
cfg: OpenClawConfig;
17+
entry: SessionEntry;
18+
env: NodeJS.ProcessEnv;
19+
sessionKey: string;
20+
worktrees: ReturnType<typeof listRegistryWorktreesForMigration>;
21+
}): string | undefined {
22+
const worktree = params.entry.worktree;
23+
if (!worktree || worktree.canonicalWorkspaceDir) {
24+
return undefined;
25+
}
26+
const recordedRepoRoot = path.resolve(worktree.repoRoot);
27+
if (params.entry.projectId) {
28+
const project = resolveProjectRegistry(params.cfg, params.entry.projectId, { env: params.env });
29+
const projectRoot = project ? path.resolve(project.repoRoot) : undefined;
30+
return projectRoot && isInside(recordedRepoRoot, projectRoot) ? projectRoot : undefined;
31+
}
32+
const record = params.worktrees.find((candidate) => candidate.id === worktree.id);
33+
const spawnedCwd = params.entry.spawnedCwd;
34+
if (
35+
record?.ownerKind === "session" &&
36+
record.ownerId === params.sessionKey &&
37+
spawnedCwd &&
38+
path.resolve(record.repoRoot) === path.resolve(worktree.repoRoot)
39+
) {
40+
const relative = path.relative(path.resolve(record.path), path.resolve(spawnedCwd));
41+
if (relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative))) {
42+
return path.resolve(recordedRepoRoot, relative);
43+
}
44+
}
45+
const agentWorkspace = path.resolve(
46+
resolveAgentWorkspaceDir(params.cfg, params.agentId, params.env),
47+
);
48+
return agentWorkspace && agentWorkspace === recordedRepoRoot ? agentWorkspace : undefined;
49+
}
50+
51+
export async function migrateManagedWorktreeCanonicalWorkspaces(params: {
52+
agentId: string;
53+
cfg: OpenClawConfig;
54+
env?: NodeJS.ProcessEnv;
55+
storePath: string;
56+
}): Promise<number> {
57+
const env = params.env ?? process.env;
58+
const worktrees = listRegistryWorktreesForMigration(env);
59+
let migrated = 0;
60+
for (const { entry, sessionKey } of listSessionEntriesReadOnly({
61+
agentId: params.agentId,
62+
env,
63+
storePath: params.storePath,
64+
readConsistency: "latest",
65+
})) {
66+
const canonicalWorkspaceDir = resolveLegacyCanonicalWorkspace({
67+
agentId: params.agentId,
68+
cfg: params.cfg,
69+
entry,
70+
env,
71+
sessionKey,
72+
worktrees,
73+
});
74+
if (!canonicalWorkspaceDir) {
75+
continue;
76+
}
77+
const updated = await patchSessionEntryCore(
78+
{ agentId: params.agentId, env, sessionKey, storePath: params.storePath },
79+
(current) => {
80+
if (
81+
!current.worktree ||
82+
current.worktree.id !== entry.worktree?.id ||
83+
current.worktree.canonicalWorkspaceDir
84+
) {
85+
return null;
86+
}
87+
return {
88+
worktree: { ...current.worktree, canonicalWorkspaceDir },
89+
};
90+
},
91+
{ preserveActivity: true, skipMaintenance: true },
92+
);
93+
if (updated?.worktree?.canonicalWorkspaceDir === canonicalWorkspaceDir) {
94+
migrated += 1;
95+
}
96+
}
97+
return migrated;
98+
}

0 commit comments

Comments
 (0)