Skip to content

Commit 096c929

Browse files
fix(doctor): audit every agent workspace (#111840)
Co-authored-by: Vincent Koc <[email protected]> Co-authored-by: juyaohuidt <[email protected]>
1 parent baeaca2 commit 096c929

5 files changed

Lines changed: 255 additions & 18 deletions

‎src/flows/doctor-core-checks.ts‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import { resolveSkillWorkshopConfig } from "../skills/workshop/config.js";
4343
import { detectSkillWorkshopToolPolicyDiagnostic } from "../skills/workshop/tool-policy-diagnostic.js";
4444
import { hasActiveGatewayExecCredential } from "./doctor-gateway-exec-credential.js";
4545
import { removedWorkspacesStateCheck } from "./doctor-removed-workspaces-state-check.js";
46+
import { resolveDoctorWorkspaceSuggestionScopes } from "./doctor-workspace-suggestion-scopes.js";
4647
import type { SplitHealthCheckInput } from "./health-check-runner-types.js";
4748
import type {
4849
HealthCheck,
@@ -639,6 +640,7 @@ function noteTextToFinding(params: {
639640
checkId: string;
640641
severity: HealthFinding["severity"];
641642
text: string;
643+
target?: string;
642644
}): HealthFinding {
643645
const lines = params.text.split("\n");
644646
const first = normalizeDoctorNoteLine(lines[0] ?? params.text);
@@ -647,6 +649,7 @@ function noteTextToFinding(params: {
647649
checkId: params.checkId,
648650
severity: params.severity,
649651
message: first,
652+
...(params.target ? { target: params.target } : {}),
650653
...(rest ? { fixHint: rest } : {}),
651654
};
652655
}
@@ -1240,15 +1243,22 @@ function createWorkspaceSuggestionsCheck(
12401243
defaultEnabled: false,
12411244
source: "doctor",
12421245
async detect(ctx) {
1243-
const workspaceDir = resolveAgentWorkspaceDir(ctx.cfg, resolveDefaultAgentId(ctx.cfg));
1244-
const notes = await deps.collectWorkspaceSuggestionNotes(workspaceDir);
1245-
return notes.map((text) =>
1246-
noteTextToFinding({
1247-
checkId: "core/doctor/workspace-suggestions",
1248-
severity: "info",
1249-
text,
1246+
const scopes = resolveDoctorWorkspaceSuggestionScopes(ctx.cfg);
1247+
const findings = await Promise.all(
1248+
scopes.map(async ({ agentId, workspaceDir, labelAgent }) => {
1249+
const prefix = labelAgent ? `Agent "${agentId}": ` : "";
1250+
const notes = await deps.collectWorkspaceSuggestionNotes(workspaceDir);
1251+
return notes.map((text) =>
1252+
noteTextToFinding({
1253+
checkId: "core/doctor/workspace-suggestions",
1254+
severity: "info",
1255+
text: `${prefix}${text}`,
1256+
...(labelAgent ? { target: agentId } : {}),
1257+
}),
1258+
);
12501259
}),
12511260
);
1261+
return findings.flat();
12521262
},
12531263
};
12541264
}

‎src/flows/doctor-health-contribution-runners.workspace.ts‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { DoctorOptions } from "../commands/doctor-prompter.js";
22
import type { OpenClawConfig } from "../config/types.openclaw.js";
33
import type { DoctorHealthFlowContext } from "./doctor-health-contribution-types.js";
4+
import { resolveDoctorWorkspaceSuggestionScopes } from "./doctor-workspace-suggestion-scopes.js";
45
import type { HealthCheckContext, HealthFinding } from "./health-checks.js";
56

67
type PluginVersionDriftReport =
@@ -230,15 +231,20 @@ export async function runWorkspaceSuggestionsHealth(ctx: DoctorHealthFlowContext
230231
if (ctx.options.workspaceSuggestions === false) {
231232
return;
232233
}
233-
const { resolveAgentWorkspaceDir, resolveDefaultAgentId } =
234-
await import("../agents/agent-scope.js");
235-
const { noteWorkspaceBackupTip } = await loadDoctorStateIntegrityModule();
234+
const { collectWorkspaceBackupTip } = await loadDoctorStateIntegrityModule();
236235
const { MEMORY_SYSTEM_PROMPT, shouldSuggestMemorySystem } =
237236
await import("../commands/doctor-workspace.js");
238237
const { note } = await import("../../packages/terminal-core/src/note.js");
239-
const workspaceDir = resolveAgentWorkspaceDir(ctx.cfg, resolveDefaultAgentId(ctx.cfg));
240-
noteWorkspaceBackupTip(workspaceDir);
241-
if (await shouldSuggestMemorySystem(workspaceDir)) {
242-
note(MEMORY_SYSTEM_PROMPT, "Workspace");
238+
for (const { agentId, workspaceDir, labelAgent } of resolveDoctorWorkspaceSuggestionScopes(
239+
ctx.cfg,
240+
)) {
241+
const prefix = labelAgent ? `Agent "${agentId}": ` : "";
242+
const backupTip = collectWorkspaceBackupTip(workspaceDir);
243+
if (backupTip) {
244+
note(`${prefix}${backupTip}`, "Workspace");
245+
}
246+
if (await shouldSuggestMemorySystem(workspaceDir)) {
247+
note(`${prefix}${MEMORY_SYSTEM_PROMPT}`, "Workspace");
248+
}
243249
}
244250
}

‎src/flows/doctor-health-contributions.test.ts‎

Lines changed: 73 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,11 @@ const mocks = vi.hoisted(() => ({
9292
maybeRepairLegacyPluginManifestContracts: vi.fn().mockResolvedValue(undefined),
9393
detectLegacyClawdBrowserProfileResidue: vi.fn(),
9494
maybeArchiveLegacyClawdBrowserProfileResidue: vi.fn(),
95-
resolveAgentWorkspaceDir: vi.fn(() => "/tmp/openclaw-workspace"),
96-
resolveDefaultAgentId: vi.fn(() => "default"),
95+
listAgentIds: vi.fn<(_cfg: OpenClawConfig) => string[]>(() => ["default"]),
96+
resolveAgentWorkspaceDir: vi.fn<(_cfg: OpenClawConfig, agentId: string) => string>(
97+
() => "/tmp/openclaw-workspace",
98+
),
99+
resolveDefaultAgentId: vi.fn<(_cfg: OpenClawConfig) => string>(() => "default"),
97100
resolveAgentContextLimits: vi.fn(
98101
(cfg: { agents?: { defaults?: { contextLimits?: unknown } } }) =>
99102
cfg.agents?.defaults?.contextLimits ?? {},
@@ -117,8 +120,8 @@ const mocks = vi.hoisted(() => ({
117120
gatherDaemonStatus: vi.fn(),
118121
noteWorkspaceStatus: vi.fn(),
119122
collectWorkspaceStatusHealthFindings: vi.fn().mockResolvedValue([]),
120-
collectWorkspaceBackupTip: vi.fn((): string | undefined => undefined),
121-
shouldSuggestMemorySystem: vi.fn(async () => false),
123+
collectWorkspaceBackupTip: vi.fn<(workspaceDir: string) => string | undefined>(() => undefined),
124+
shouldSuggestMemorySystem: vi.fn<(workspaceDir: string) => Promise<boolean>>(async () => false),
122125
collectDiskSpaceHealthFindings: vi.fn((): readonly HealthFinding[] => []),
123126
collectHeartbeatCadenceMigrationFindings: vi.fn(async () => [] as unknown[]),
124127
maybeMigrateHeartbeatCadenceToCron: vi.fn().mockResolvedValue({ changes: [], warnings: [] }),
@@ -362,6 +365,7 @@ vi.mock("../commands/doctor-browser.js", () => ({
362365
}));
363366

364367
vi.mock("../agents/agent-scope.js", () => ({
368+
listAgentIds: mocks.listAgentIds,
365369
resolveAgentWorkspaceDir: mocks.resolveAgentWorkspaceDir,
366370
resolveDefaultAgentId: mocks.resolveDefaultAgentId,
367371
resolveAgentContextLimits: mocks.resolveAgentContextLimits,
@@ -673,6 +677,8 @@ describe("doctor health contributions", () => {
673677
});
674678
mocks.resolveAgentWorkspaceDir.mockReset();
675679
mocks.resolveAgentWorkspaceDir.mockReturnValue("/tmp/openclaw-workspace");
680+
mocks.listAgentIds.mockReset();
681+
mocks.listAgentIds.mockReturnValue(["default"]);
676682
mocks.resolveDefaultAgentId.mockReset();
677683
mocks.resolveDefaultAgentId.mockReturnValue("default");
678684
mocks.resolveAgentContextLimits.mockReset();
@@ -2268,6 +2274,69 @@ describe("doctor health contributions", () => {
22682274
expect(mocks.collectWorkspaceBackupTip).toHaveBeenCalledWith("/tmp/openclaw-workspace");
22692275
});
22702276

2277+
it("labels normal workspace suggestions for secondary agents", async () => {
2278+
const contribution = requireDoctorContribution("doctor:workspace-suggestions");
2279+
const cfg = {} as OpenClawConfig;
2280+
const ctx = {
2281+
cfg,
2282+
cfgForPersistence: cfg,
2283+
configResult: { cfg },
2284+
configPath: "/tmp/fake-openclaw.json",
2285+
sourceConfigValid: true,
2286+
prompter: buildDoctorPrompter(false),
2287+
runtime: { log: vi.fn(), error: vi.fn(), exit: vi.fn() },
2288+
options: {},
2289+
env: {},
2290+
} as DoctorContributionRunContext;
2291+
mocks.listAgentIds.mockReturnValue(["default", "secondary"]);
2292+
mocks.resolveAgentWorkspaceDir.mockImplementation((_cfg, agentId) => `/tmp/${agentId}`);
2293+
mocks.collectWorkspaceBackupTip.mockImplementation((workspaceDir) =>
2294+
workspaceDir === "/tmp/secondary" ? "- Back up this workspace." : undefined,
2295+
);
2296+
mocks.shouldSuggestMemorySystem.mockImplementation(
2297+
async (workspaceDir) => workspaceDir === "/tmp/secondary",
2298+
);
2299+
2300+
await contribution.run(ctx);
2301+
2302+
expect(mocks.note).toHaveBeenCalledWith(
2303+
'Agent "secondary": - Back up this workspace.',
2304+
"Workspace",
2305+
);
2306+
expect(mocks.note).toHaveBeenCalledWith(
2307+
'Agent "secondary": Enable memory system for better recall.',
2308+
"Workspace",
2309+
);
2310+
expect(mocks.note).toHaveBeenCalledTimes(2);
2311+
});
2312+
2313+
it("keeps single-agent workspace suggestion wording unchanged", async () => {
2314+
const contribution = requireDoctorContribution("doctor:workspace-suggestions");
2315+
const cfg = {} as OpenClawConfig;
2316+
const ctx = {
2317+
cfg,
2318+
cfgForPersistence: cfg,
2319+
configResult: { cfg },
2320+
configPath: "/tmp/fake-openclaw.json",
2321+
sourceConfigValid: true,
2322+
prompter: buildDoctorPrompter(false),
2323+
runtime: { log: vi.fn(), error: vi.fn(), exit: vi.fn() },
2324+
options: {},
2325+
env: {},
2326+
} as DoctorContributionRunContext;
2327+
mocks.collectWorkspaceBackupTip.mockReturnValue("- Back up this workspace.");
2328+
mocks.shouldSuggestMemorySystem.mockResolvedValue(true);
2329+
2330+
await contribution.run(ctx);
2331+
2332+
expect(mocks.note).toHaveBeenNthCalledWith(1, "- Back up this workspace.", "Workspace");
2333+
expect(mocks.note).toHaveBeenNthCalledWith(
2334+
2,
2335+
"Enable memory system for better recall.",
2336+
"Workspace",
2337+
);
2338+
});
2339+
22712340
it("keeps disk space opt-in for default lint selection", async () => {
22722341
const contributionChecks = await resolveDoctorContributionHealthChecks();
22732342
const diskSpaceCheck = contributionChecks.find(
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import {
2+
listAgentIds,
3+
resolveAgentWorkspaceDir,
4+
resolveDefaultAgentId,
5+
} from "../agents/agent-scope.js";
6+
import type { OpenClawConfig } from "../config/types.openclaw.js";
7+
8+
type DoctorWorkspaceSuggestionScope = {
9+
agentId: string;
10+
workspaceDir: string;
11+
labelAgent: boolean;
12+
};
13+
14+
/** Resolves every configured agent workspace while preserving invalid empty-roster failures. */
15+
export function resolveDoctorWorkspaceSuggestionScopes(
16+
cfg: OpenClawConfig,
17+
): DoctorWorkspaceSuggestionScope[] {
18+
const listedAgentIds = listAgentIds(cfg);
19+
const agentIds = listedAgentIds.length > 0 ? listedAgentIds : [resolveDefaultAgentId(cfg)];
20+
const labelAgent = agentIds.length > 1;
21+
return agentIds.map((agentId) => ({
22+
agentId,
23+
workspaceDir: resolveAgentWorkspaceDir(cfg, agentId),
24+
labelAgent,
25+
}));
26+
}
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
import { describe, expect, it } from "vitest";
2+
import type { SkillStatusEntry } from "../skills/discovery/status.js";
3+
import { createCoreHealthChecks, type CoreHealthCheckDeps } from "./doctor-core-checks.js";
4+
import type { HealthCheck } from "./health-checks.js";
5+
6+
const runtime = { log() {}, error() {}, exit() {} };
7+
8+
function createDeps(
9+
collectWorkspaceSuggestionNotes: CoreHealthCheckDeps["collectWorkspaceSuggestionNotes"],
10+
): CoreHealthCheckDeps {
11+
return {
12+
async detectUnavailableSkills(): Promise<readonly SkillStatusEntry[]> {
13+
return [];
14+
},
15+
async collectSecurityWarnings() {
16+
return [];
17+
},
18+
collectWorkspaceSuggestionNotes,
19+
async collectRuntimeToolSchemaFindings() {
20+
return [];
21+
},
22+
async collectProviderCatalogProjectionFindings() {
23+
return [];
24+
},
25+
async collectLocalAudioAccelerationFindings() {
26+
return [];
27+
},
28+
async collectGatewayHealthFindings() {
29+
return [];
30+
},
31+
async collectGatewayDaemonFindings() {
32+
return [];
33+
},
34+
async listGatewayCronJobs() {
35+
return [];
36+
},
37+
};
38+
}
39+
40+
function createWorkspaceSuggestionsCheck(
41+
collectWorkspaceSuggestionNotes: CoreHealthCheckDeps["collectWorkspaceSuggestionNotes"],
42+
): HealthCheck {
43+
const check = createCoreHealthChecks(createDeps(collectWorkspaceSuggestionNotes)).find(
44+
(candidate) => candidate.id === "core/doctor/workspace-suggestions",
45+
);
46+
if (!check || !("detect" in check)) {
47+
throw new Error("workspace suggestions check not found");
48+
}
49+
return check;
50+
}
51+
52+
describe("core/doctor/workspace-suggestions", () => {
53+
it("labels secondary-agent findings with structured targets", async () => {
54+
const check = createWorkspaceSuggestionsCheck(async (workspaceDir) =>
55+
workspaceDir === "/tmp/secondary"
56+
? ["- Back up this workspace.", "Memory system not found in workspace."]
57+
: [],
58+
);
59+
60+
const findings = await check.detect({
61+
mode: "lint",
62+
runtime,
63+
cfg: {
64+
agents: {
65+
entries: {
66+
main: { default: true, workspace: "/tmp/main" },
67+
secondary: { workspace: "/tmp/secondary" },
68+
},
69+
},
70+
},
71+
});
72+
73+
expect(findings).toEqual([
74+
expect.objectContaining({
75+
message: 'Agent "secondary": - Back up this workspace.',
76+
target: "secondary",
77+
}),
78+
expect.objectContaining({
79+
message: 'Agent "secondary": Memory system not found in workspace.',
80+
target: "secondary",
81+
}),
82+
]);
83+
});
84+
85+
it("keeps shared workspace suggestions agent-scoped", async () => {
86+
const check = createWorkspaceSuggestionsCheck(async () => [
87+
"Memory system not found in workspace.",
88+
]);
89+
90+
const findings = await check.detect({
91+
mode: "lint",
92+
runtime,
93+
cfg: {
94+
agents: {
95+
entries: {
96+
main: { default: true, workspace: "/tmp/shared" },
97+
secondary: { workspace: "/tmp/shared" },
98+
},
99+
},
100+
},
101+
});
102+
103+
expect(findings).toEqual([
104+
expect.objectContaining({
105+
message: 'Agent "main": Memory system not found in workspace.',
106+
target: "main",
107+
}),
108+
expect.objectContaining({
109+
message: 'Agent "secondary": Memory system not found in workspace.',
110+
target: "secondary",
111+
}),
112+
]);
113+
});
114+
115+
it("preserves the explicit empty-roster failure", async () => {
116+
const check = createWorkspaceSuggestionsCheck(async () => []);
117+
118+
await expect(
119+
check.detect({
120+
mode: "lint",
121+
runtime,
122+
cfg: { agents: { entries: {} } },
123+
}),
124+
).rejects.toThrow("No agents configured");
125+
});
126+
});

0 commit comments

Comments
 (0)