Skip to content

Commit 6e5bf3e

Browse files
authored
fix(doctor): stop false failures on multi-agent profiles (#124010)
* fix(doctor): resolve multi-agent health owners * fix(doctor): keep bare json exit advisory
1 parent f0d2772 commit 6e5bf3e

22 files changed

Lines changed: 569 additions & 178 deletions

‎docs/cli/doctor.md‎

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -28,15 +28,15 @@ Related:
2828

2929
Doctor has five postures:
3030

31-
| Posture | Command | Behavior |
32-
| ------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------- |
33-
| Inspect | `openclaw doctor` | Human-oriented checks and guided prompts. |
34-
| Repair | `openclaw doctor --fix` | Applies supported repairs, using prompts unless non-interactive repair is safe. |
35-
| Lint | `openclaw doctor --json` | Read-only JSON findings for deployment preflight and CI gates. |
36-
| Shared SQLite maintenance | `openclaw doctor --state-sqlite compact` | Explicitly checkpoints, compacts, and verifies the canonical shared state DB. |
37-
| Session SQLite migration | `openclaw doctor --session-sqlite <mode>` | Inspects, imports, validates, compacts, recovers, or restores session state. |
31+
| Posture | Command | Behavior |
32+
| ------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------- |
33+
| Inspect | `openclaw doctor` / `openclaw doctor --json` | Advisory checks in human or machine-readable form. |
34+
| Repair | `openclaw doctor --fix` | Applies supported repairs, using prompts unless non-interactive repair is safe. |
35+
| Lint | `openclaw doctor --lint [--json]` | Read-only findings with threshold-based exit codes for CI gates. |
36+
| Shared SQLite maintenance | `openclaw doctor --state-sqlite compact` | Explicitly checkpoints, compacts, and verifies the canonical shared state DB. |
37+
| Session SQLite migration | `openclaw doctor --session-sqlite <mode>` | Inspects, imports, validates, compacts, recovers, or restores session state. |
3838

39-
Use `openclaw doctor --json` as the machine-readable deployment preflight. It runs the same read-only checks, JSON output, and exit codes as `openclaw doctor --lint --json`. Prefer `--fix` when a human operator wants doctor to edit config or state.
39+
Use `openclaw doctor --json` when an operator or script wants the advisory Doctor report as JSON. It exits successfully after producing a report; inspect `ok` and `findings` for health state. Use explicit `openclaw doctor --lint --json` when CI should exit nonzero for findings at the selected severity threshold. Prefer `--fix` when a human operator wants Doctor to edit config or state.
4040

4141
## Examples
4242

@@ -94,17 +94,19 @@ openclaw channels status --probe
9494
| `--session-sqlite-agent <id>` | With `--session-sqlite`: select one configured agent. |
9595
| `--session-sqlite-all-agents` | With `--session-sqlite`: select configured and discovered agent stores. |
9696
| `--github-issue` | With `--session-sqlite recover`: prepare a sanitized openclaw/openclaw issue report; doctor creates it with `gh` after `--yes` or interactive confirmation. |
97-
| `--json` | Run lint checks in read-only mode and emit JSON. With another machine mode, emit that mode's existing JSON report. |
97+
| `--json` | Emit read-only JSON. Bare `--json` is advisory; combine with `--lint` for threshold-based exit codes. With another machine mode, emit that mode's existing JSON report. |
9898
| `--severity-min <level>` | With `--lint`: drop findings below `info`, `warning`, or `error`. |
9999
| `--all` | With `--lint`: run all registered checks, including opt-in checks excluded from the default set. |
100100
| `--skip <id>` | With `--lint`: skip a check id. Repeatable. |
101101
| `--only <id>` | With `--lint`: run only the given check id(s). Repeatable. |
102102

103-
`--severity-min`, `--all`, `--only`, and `--skip` are only accepted together with `--lint`. Bare `--json` implies lint mode. It cannot be combined with `--repair`, `--fix`, or `--force` unless another machine mode owns the command.
103+
`--severity-min`, `--all`, `--only`, and `--skip` are only accepted together with `--lint`. Bare `--json` uses the default read-only lint check selection but keeps Doctor's advisory exit behavior. It cannot be combined with `--repair`, `--fix`, or `--force` unless another machine mode owns the command.
104104

105105
## Lint mode
106106

107-
`openclaw doctor --json` is the deployment-preflight form of lint mode. It is read-only and non-interactive: no prompts, repairs, or config/state rewrites. `openclaw doctor --lint --json` remains an equivalent explicit spelling.
107+
Bare `openclaw doctor --json` is read-only and non-interactive: no prompts, repairs, or config/state rewrites. It emits the same default findings as lint mode, but exits `0` after a report is produced so output formatting does not change ordinary Doctor's advisory success contract. Read the payload's `ok` and `findings` fields to determine health.
108+
109+
Explicit `openclaw doctor --lint` is the deployment-preflight posture. Add `--json` for machine-readable output without changing lint's threshold-based exit code.
108110

109111
```bash
110112
openclaw doctor --json
@@ -144,7 +146,7 @@ JSON output is the scripting surface:
144146
}
145147
```
146148

147-
Exit codes:
149+
Explicit lint exit codes:
148150

149151
| Code | Meaning |
150152
| ---- | ------------------------------------------------------------- |
@@ -154,6 +156,8 @@ Exit codes:
154156

155157
`--severity-min` controls both which findings print and the exit threshold: `openclaw doctor --lint --severity-min error` can print nothing and exit `0` even when lower-severity `info`/`warning` findings exist.
156158

159+
Bare `openclaw doctor --json` exits `0` once it emits a findings payload, including when `ok` is `false`. Argument errors or runtime failures before a payload can be produced remain nonzero.
160+
157161
`--all` controls which checks are selected before severity filtering. The default lint run excludes checks that are deep, historical, or more likely to surface repairable legacy residue; use `--all` for the complete inventory. `--only <id>` is the most precise selector and can run any registered check by id.
158162

159163
`core/doctor/local-audio-acceleration` reports the auto-selected local STT command, separate capable/requested/observed backend evidence, and fallback order without loading a speech model. It emits an informational finding, so include `--severity-min info` to display it.

‎docs/gateway/doctor.md‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -84,11 +84,12 @@ cat ~/.openclaw/openclaw.json
8484
`openclaw doctor --fix`. They share the same Doctor rule registry, but they do
8585
not select or act on rules in the same way:
8686

87-
| Mode | Prompts | Writes config/state | Output | Use it for |
88-
| ------------------------ | --------- | ----------------------- | ---------------------- | ------------------------------- |
89-
| `openclaw doctor` | yes | no | friendly health report | a human checking status |
90-
| `openclaw doctor --fix` | sometimes | yes, with repair policy | friendly repair log | applying approved repairs |
91-
| `openclaw doctor --lint` | no | no | structured findings | CI, preflight, and review gates |
87+
| Mode | Prompts | Writes config/state | Output | Use it for |
88+
| ------------------------ | --------- | ----------------------- | ---------------------- | -------------------------------- |
89+
| `openclaw doctor` | yes | no | friendly health report | a human checking status |
90+
| `openclaw doctor --json` | no | no | JSON advisory report | machine-readable operator checks |
91+
| `openclaw doctor --fix` | sometimes | yes, with repair policy | friendly repair log | applying approved repairs |
92+
| `openclaw doctor --lint` | no | no | structured findings | CI, preflight, and review gates |
9293

9394
Default `doctor --lint` runs the broad-safe automation profile: checks that are
9495
static, local, and useful in CI or preflight output. It skips opt-in checks that
@@ -134,13 +135,15 @@ Exit codes:
134135
| `1` | one or more findings met the selected threshold |
135136
| `2` | command/runtime failure before findings could be emitted |
136137

138+
These threshold-based exit codes belong to explicit `--lint` mode, with or without `--json`. Bare `openclaw doctor --json` preserves ordinary Doctor's advisory exit `0` after producing its payload; machine consumers should read `ok` and `findings`. Fatal errors before output remain nonzero.
139+
137140
Flags:
138141

139142
- `--severity-min info|warning|error` (default `warning`): controls both what prints and what causes a non-zero exit.
140143
- `--all`: runs every registered lint check, including opt-in checks excluded from the default automation set.
141144
- `--only <id>` (repeatable): run only the named check id(s); an unknown id is reported as an error finding.
142145
- `--skip <id>` (repeatable): exclude a check while keeping the rest of the run active.
143-
- `--json`, `--severity-min`, `--all`, `--only`, and `--skip` require `--lint`; plain `openclaw doctor` and `--fix` runs reject them.
146+
- `--severity-min`, `--all`, `--only`, and `--skip` require `--lint`. Bare `--json` is allowed for an advisory machine-readable report; `--fix` rejects it unless another machine mode owns the output.
144147

145148
## What it does (summary)
146149

‎extensions/memory-lancedb/doctor-contract-api.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,54 @@ describe("memory-lancedb doctor migration", () => {
7373
migratedConnection.close();
7474
});
7575

76+
test("assigns explicit-roster legacy rows to the configured system agent", async () => {
77+
const connection = await lancedb.connect(getDbPath());
78+
const table = await connection.createTable("memories", [
79+
{
80+
id: "12121212-1212-4121-8121-121212121212",
81+
text: "legacy system memory",
82+
vector: [1, 0],
83+
importance: 0.7,
84+
category: "fact",
85+
createdAt: 1,
86+
},
87+
]);
88+
table.close();
89+
connection.close();
90+
91+
const params = {
92+
config: {
93+
agents: {
94+
ownership: "explicit" as const,
95+
defaults: { systemAgent: { agentId: "Main Agent" } },
96+
entries: { "Main Agent": {}, helper: {}, third: {} },
97+
},
98+
plugins: {
99+
entries: { "memory-lancedb": { config: { dbPath: getDbPath() } } },
100+
},
101+
},
102+
env: { ...process.env, HOME: getTmpDir() },
103+
stateDir: getTmpDir(),
104+
oauthDir: path.join(getTmpDir(), "oauth"),
105+
context: unusedDoctorContext,
106+
};
107+
const migration = expectDefined(stateMigrations[0], "memory-lancedb state migration");
108+
109+
await expect(migration.detectLegacyState(params)).resolves.toMatchObject({
110+
preview: [expect.stringContaining("system agent main-agent")],
111+
});
112+
await expect(migration.migrateLegacyState(params)).resolves.toEqual({
113+
changes: ["Assigned 1 legacy Memory LanceDB row to system agent main-agent"],
114+
warnings: [],
115+
});
116+
117+
const migratedConnection = await lancedb.connect(getDbPath());
118+
const migratedTable = await migratedConnection.openTable("memories");
119+
await expect(migratedTable.countRows("agentId = 'main-agent'")).resolves.toBe(1);
120+
migratedTable.close();
121+
migratedConnection.close();
122+
});
123+
76124
test("deletes only structurally complete legacy envelope rows", async () => {
77125
const benignRows = [
78126
{

‎extensions/memory-lancedb/doctor-contract-api.ts‎

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import path from "node:path";
44
import { fileURLToPath } from "node:url";
55
import { resolveDefaultAgentId } from "openclaw/plugin-sdk/agent-scope-runtime";
66
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
7+
import { normalizeAgentId } from "openclaw/plugin-sdk/routing";
78
import type { PluginDoctorStateMigration } from "openclaw/plugin-sdk/runtime-doctor-migrations";
89
import { asOptionalRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
910
import {
@@ -20,6 +21,19 @@ type LanceDbTable = Awaited<ReturnType<LanceDbConnection["openTable"]>>;
2021

2122
const LEGACY_ENVELOPE_DELETE_BATCH_SIZE = 500;
2223

24+
function resolveLegacyMemoryOwner(config: OpenClawConfig): {
25+
agentId: string;
26+
label: "default" | "system";
27+
} {
28+
const explicitSystemAgentId =
29+
config.agents?.ownership === "explicit"
30+
? config.agents.defaults?.systemAgent?.agentId?.trim()
31+
: undefined;
32+
return explicitSystemAgentId
33+
? { agentId: normalizeAgentId(explicitSystemAgentId), label: "system" }
34+
: { agentId: resolveDefaultAgentId(config), label: "default" };
35+
}
36+
2337
// Doctor deletes rows containing a complete known legacy sentinel line, a legacy
2438
// label followed by a fenced JSON body, or the complete legacy external-content
2539
// header line. Bare label-like prose and partial header prefixes survive.
@@ -172,11 +186,11 @@ export function createMemoryLanceDbStateMigrations(
172186
if (!opened.table || hasAgentScopeColumn(await opened.table.schema())) {
173187
return null;
174188
}
175-
const defaultAgentId = resolveDefaultAgentId(params.config);
189+
const owner = resolveLegacyMemoryOwner(params.config);
176190
const count = await opened.table.countRows();
177191
return {
178192
preview: [
179-
`- Memory LanceDB: assign ${count} legacy ${count === 1 ? "row" : "rows"} at ${opened.dbPath} to default agent ${defaultAgentId}`,
193+
`- Memory LanceDB: assign ${count} legacy ${count === 1 ? "row" : "rows"} at ${opened.dbPath} to ${owner.label} agent ${owner.agentId}`,
180194
],
181195
};
182196
} finally {
@@ -190,23 +204,23 @@ export function createMemoryLanceDbStateMigrations(
190204
if (!opened.table || hasAgentScopeColumn(await opened.table.schema())) {
191205
return { changes: [], warnings: [] };
192206
}
193-
const defaultAgentId = resolveDefaultAgentId(params.config);
207+
const owner = resolveLegacyMemoryOwner(params.config);
194208
const rowCount = await opened.table.countRows();
195209
await opened.table.addColumns([
196210
{
197211
name: MEMORY_AGENT_ID_COLUMN,
198-
valueSql: quoteLanceSqlString(defaultAgentId),
212+
valueSql: quoteLanceSqlString(owner.agentId),
199213
},
200214
]);
201215
if (
202216
!hasAgentScopeColumn(await opened.table.schema()) ||
203-
(await opened.table.countRows(memoryAgentPredicate(defaultAgentId))) !== rowCount
217+
(await opened.table.countRows(memoryAgentPredicate(owner.agentId))) !== rowCount
204218
) {
205219
throw new Error("LanceDB agent-scope migration verification failed");
206220
}
207221
return {
208222
changes: [
209-
`Assigned ${rowCount} legacy Memory LanceDB ${rowCount === 1 ? "row" : "rows"} to default agent ${defaultAgentId}`,
223+
`Assigned ${rowCount} legacy Memory LanceDB ${rowCount === 1 ? "row" : "rows"} to ${owner.label} agent ${owner.agentId}`,
210224
],
211225
warnings: [],
212226
};

‎src/cli/program/register.maintenance.test.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -319,15 +319,17 @@ describe("registerMaintenanceCommands doctor action", () => {
319319
expect(runtime.exit).toHaveBeenCalledWith(1);
320320
});
321321

322-
it("treats bare --json as lint mode and emits machine-readable output", async () => {
322+
it("keeps bare --json advisory while preserving machine-readable findings", async () => {
323323
const output: string[] = [];
324324
const writeSpy = vi.spyOn(process.stdout, "write").mockImplementation((chunk) => {
325325
output.push(String(chunk));
326326
return true;
327327
});
328328
runDoctorLintCli.mockImplementationOnce(async () => {
329-
process.stdout.write('{"ok":true,"checksRun":1,"checksSkipped":0,"findings":[]}\n');
330-
return 0;
329+
process.stdout.write(
330+
'{"ok":false,"checksRun":1,"checksSkipped":0,"findings":[{"checkId":"core/example","severity":"error","message":"broken"}]}\n',
331+
);
332+
return 1;
331333
});
332334

333335
try {
@@ -344,10 +346,16 @@ describe("registerMaintenanceCommands doctor action", () => {
344346
deep: false,
345347
});
346348
expect(JSON.parse(output.join(""))).toEqual({
347-
ok: true,
349+
ok: false,
348350
checksRun: 1,
349351
checksSkipped: 0,
350-
findings: [],
352+
findings: [
353+
{
354+
checkId: "core/example",
355+
severity: "error",
356+
message: "broken",
357+
},
358+
],
351359
});
352360
expect(runtime.exit).toHaveBeenCalledWith(0);
353361
} finally {

‎src/cli/program/register.maintenance.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -86,11 +86,7 @@ export function registerMaintenanceCommands(program: Command) {
8686
"With --session-sqlite recover: prepare and optionally create an openclaw/openclaw issue",
8787
false,
8888
)
89-
.option(
90-
"--json",
91-
"Run read-only lint checks as JSON (or emit JSON for another machine mode)",
92-
false,
93-
)
89+
.option("--json", "Emit JSON; bare --json runs advisory read-only health checks", false)
9490
.option(
9591
"--severity-min <level>",
9692
"With --lint: drop findings below this severity (info|warning|error)",
@@ -145,7 +141,7 @@ export function registerMaintenanceCommands(program: Command) {
145141
allowExec: Boolean(opts.allowExec),
146142
deep: Boolean(opts.deep),
147143
});
148-
defaultRuntime.exit(exitCode);
144+
defaultRuntime.exit(jsonImpliesLint ? 0 : exitCode);
149145
},
150146
(err) => exitDoctorError(formatError(err), opts.json === true || !process.stdout.isTTY),
151147
);

‎src/commands/doctor-model-catalog-credentials.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,38 @@ describe("doctor model catalog credential migration", () => {
195195
expect(loadPersistedAuthProfileStore(childAgentDir)).toBeNull();
196196
});
197197

198+
it("scans an explicit multi-agent roster without requiring a legacy default", async () => {
199+
const state = createState();
200+
const helperAgentDir = path.join(state.stateDir, "agents", "helper", "agent");
201+
const thirdAgentDir = path.join(state.stateDir, "agents", "third", "agent");
202+
fs.mkdirSync(helperAgentDir, { recursive: true });
203+
fs.mkdirSync(thirdAgentDir, { recursive: true });
204+
fs.writeFileSync(
205+
path.join(helperAgentDir, "models.json"),
206+
`${JSON.stringify({ providers: { custom: provider("helper-catalog-secret") } })}\n`,
207+
);
208+
const cfg = {
209+
agents: {
210+
ownership: "explicit",
211+
defaults: { systemAgent: { agentId: "main" } },
212+
entries: {
213+
main: { agentDir: state.agentDir },
214+
helper: { agentDir: helperAgentDir },
215+
third: { agentDir: thirdAgentDir },
216+
},
217+
},
218+
} satisfies OpenClawConfig;
219+
220+
await expect(maybeMigrateModelCatalogCredentials(migrationParams(state, cfg))).resolves.toEqual(
221+
{ detected: 1, migrated: 1, warnings: [] },
222+
);
223+
expect(loadPersistedAuthProfileStore(helperAgentDir)?.profiles["custom:default"]).toMatchObject(
224+
{
225+
key: "helper-catalog-secret",
226+
},
227+
);
228+
});
229+
198230
it("allocates a global config profile that child stores cannot shadow", async () => {
199231
const state = createState();
200232
const childAgentDir = path.join(state.stateDir, "agents", "child", "agent");

0 commit comments

Comments
 (0)