Skip to content

Commit 562129d

Browse files
authored
fix(doctor): ignore channel metadata during plugin repair (#120891)
* fix(doctor): ignore channel metadata during plugin repair * test(doctor): avoid unsafe optional chain
1 parent a996a86 commit 562129d

39 files changed

Lines changed: 1005 additions & 1280 deletions

‎src/channels/config-metadata.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
const CHANNEL_CONFIG_METADATA_KEYS = new Set(["defaults", "modelByChannel"]);
2+
3+
/** Returns true when a channels key contains shared metadata rather than a channel entry. */
4+
export function isChannelConfigMetadataKey(value: string): boolean {
5+
return CHANNEL_CONFIG_METADATA_KEYS.has(value.trim());
6+
}

‎src/channels/config-presence.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import os from "node:os";
44
import path from "node:path";
55
import { afterEach, describe, expect, it } from "vitest";
66
import type { OpenClawConfig } from "../config/config.js";
7+
import { isChannelConfigMetadataKey } from "./config-metadata.js";
78
import {
89
hasMeaningfulChannelConfig,
910
listExplicitlyDisabledChannelIdsForConfig,
@@ -57,6 +58,25 @@ describe("config presence", () => {
5758
expect(hasMeaningfulChannelConfig({ homeserver: "https://matrix.example.org" })).toBe(true);
5859
});
5960

61+
it("excludes metadata and blank keys while trimming configured channel ids", () => {
62+
const cfg = {
63+
channels: {
64+
defaults: { token: "test-token" },
65+
modelByChannel: { discord: "openai/gpt-5.6-luna" },
66+
" ": { token: "dummy" },
67+
" matrix ": { homeserver: "https://matrix.example.org" },
68+
},
69+
} as unknown as OpenClawConfig;
70+
71+
expect(isChannelConfigMetadataKey(" modelByChannel ")).toBe(true);
72+
expectPotentialConfiguredChannelCase({
73+
cfg,
74+
env: {},
75+
expectedIds: ["matrix"],
76+
options: { includePersistedAuthState: false },
77+
});
78+
});
79+
6080
it("ignores enabled-only matrix config when listing configured channels", () => {
6181
const env = {} as NodeJS.ProcessEnv;
6282
const cfg = { channels: { matrix: { enabled: false } } };
@@ -76,6 +96,8 @@ describe("config presence", () => {
7696
telegram: { enabled: true },
7797
slack: { botToken: "token" },
7898
discord: false,
99+
modelByChannel: { enabled: false },
100+
" ": { enabled: false },
79101
},
80102
} as unknown as OpenClawConfig;
81103

‎src/channels/config-presence.ts‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,9 @@ import { hasNonEmptyString } from "../infra/outbound/channel-target.js";
1717
import type { PluginDiscoveryResult } from "../plugins/discovery.js";
1818
import { listOfficialExternalChannelEnvVars } from "../plugins/official-external-plugin-catalog.js";
1919
import { isRecord } from "../utils.js";
20+
import { isChannelConfigMetadataKey } from "./config-metadata.js";
2021
import { listBundledChannelIds } from "./plugins/bundled-ids.js";
2122

22-
const IGNORED_CHANNEL_CONFIG_KEYS = new Set(["defaults", "modelByChannel"]);
23-
2423
export type AmbientEnvTriggerPolicy = "allow" | "suppress";
2524

2625
type ChannelPresenceOptions = {
@@ -64,7 +63,9 @@ export function listExplicitlyDisabledChannelIdsForConfig(cfg: OpenClawConfig):
6463
}
6564
return Object.entries(channels)
6665
.filter(([, value]) => isRecord(value) && value.enabled === false)
67-
.map(([channelId]) => normalizeOptionalLowercaseString(channelId))
66+
.map(([channelId]) => channelId.trim())
67+
.filter((channelId) => channelId && !isChannelConfigMetadataKey(channelId))
68+
.map((channelId) => normalizeOptionalLowercaseString(channelId))
6869
.filter((channelId): channelId is string => Boolean(channelId));
6970
}
7071

@@ -139,15 +140,20 @@ export function listPotentialConfiguredChannelPresenceSignals(
139140
): ChannelPresenceSignal[] {
140141
const signals: ChannelPresenceSignal[] = [];
141142
const seenSignals = new Set<string>();
142-
const addSignal = (channelId: string, source: ChannelPresenceSignalSource) => {
143+
const configuredChannelIds = new Set<string>();
144+
const addSignal = (rawChannelId: string, source: ChannelPresenceSignalSource) => {
145+
const channelId = rawChannelId.trim();
146+
if (!channelId || isChannelConfigMetadataKey(channelId)) {
147+
return;
148+
}
143149
const key = `${source}:${channelId}`;
144150
if (seenSignals.has(key)) {
145151
return;
146152
}
147153
seenSignals.add(key);
154+
configuredChannelIds.add(channelId);
148155
signals.push({ channelId, source });
149156
};
150-
const configuredChannelIds = new Set<string>();
151157
const channelIds = options.channelIds ?? listBundledChannelIds(env, options.discovery);
152158
const channelEnvPrefixes = listChannelEnvPrefixes(channelIds);
153159
const scopedChannelIds = options.channelIds
@@ -163,13 +169,12 @@ export function listPotentialConfiguredChannelPresenceSignals(
163169
const channels = isRecord(cfg.channels) ? cfg.channels : null;
164170
if (channels) {
165171
for (const [key, value] of Object.entries(channels)) {
166-
if (IGNORED_CHANNEL_CONFIG_KEYS.has(key)) {
172+
if (isChannelConfigMetadataKey(key)) {
167173
continue;
168174
}
169175
// Shared channel defaults are not concrete channel configuration; only per-channel entries
170176
// with meaningful settings should produce presence signals.
171177
if (hasMeaningfulChannelConfig(value)) {
172-
configuredChannelIds.add(key);
173178
addSignal(key, "config");
174179
}
175180
}
@@ -182,13 +187,11 @@ export function listPotentialConfiguredChannelPresenceSignals(
182187
}
183188
for (const [prefix, channelId] of channelEnvPrefixes) {
184189
if (key.startsWith(prefix)) {
185-
configuredChannelIds.add(channelId);
186190
addSignal(channelId, "env");
187191
}
188192
}
189193
for (const { channelId, envVars } of officialExternalChannelEnvVars) {
190194
if (envVars.includes(key)) {
191-
configuredChannelIds.add(channelId);
192195
addSignal(channelId, "env");
193196
}
194197
}
@@ -200,7 +203,6 @@ export function listPotentialConfiguredChannelPresenceSignals(
200203
// when the state directory exists to keep startup/status checks cheap.
201204
for (const channelId of listPersistedAuthStateChannelIds(options)) {
202205
if (hasPersistedAuthState({ channelId, cfg, env, options })) {
203-
configuredChannelIds.add(channelId);
204206
addSignal(channelId, "persisted-auth");
205207
}
206208
}

‎src/channels/plugins/legacy-config.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,35 @@ describe("collectChannelLegacyConfigRules", () => {
159159
expect(listPluginDoctorLegacyConfigRulesMock).not.toHaveBeenCalled();
160160
});
161161

162+
it("keeps disabled channel migrations while excluding channel metadata and blank ids", () => {
163+
loadBundledChannelDoctorContractApiMock.mockImplementation((channelId: string) => ({
164+
legacyConfigRules: [
165+
{
166+
path: ["channels", channelId, "legacy"],
167+
message: `legacy ${channelId} rule`,
168+
},
169+
],
170+
}));
171+
172+
const rules = collectChannelLegacyConfigRules({
173+
plugins: { enabled: false },
174+
channels: {
175+
defaults: {},
176+
modelByChannel: { discord: "openai/gpt-5.6-luna" },
177+
" ": {},
178+
discord: { enabled: false, legacy: true },
179+
},
180+
});
181+
182+
expect(rules).toEqual([
183+
{
184+
path: ["channels", "discord", "legacy"],
185+
message: "legacy discord rule",
186+
},
187+
]);
188+
expect(loadBundledChannelDoctorContractApiMock).toHaveBeenCalledExactlyOnceWith("discord");
189+
});
190+
162191
it("scopes channel legacy scans to touched channels during dry-run validation", () => {
163192
loadBundledChannelDoctorContractApiMock.mockImplementation((channelId: string) => ({
164193
legacyConfigRules: [

‎src/channels/plugins/legacy-config.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import type { LegacyConfigRule } from "../../config/legacy.shared.js";
77
import type { OpenClawConfig } from "../../config/types.js";
88
import { listPluginDoctorLegacyConfigRules } from "../../plugins/doctor-contract-registry.js";
9+
import { isChannelConfigMetadataKey } from "../config-metadata.js";
910
import { getBootstrapChannelPlugin } from "./bootstrap-registry.js";
1011
import { loadBundledChannelDoctorContractApi } from "./doctor-contract-api.js";
1112
import type { ChannelId } from "./types.public.js";
@@ -19,7 +20,8 @@ function collectConfiguredChannelIds(raw: unknown): ChannelId[] {
1920
return [];
2021
}
2122
return Object.keys(channels)
22-
.filter((channelId) => channelId !== "defaults")
23+
.map((channelId) => channelId.trim())
24+
.filter((channelId) => channelId && !isChannelConfigMetadataKey(channelId))
2325
.map((channelId) => channelId as ChannelId);
2426
}
2527

@@ -65,12 +67,13 @@ function collectRelevantChannelIdsForTouchedPaths(params: {
6567
if (!second) {
6668
return filteredChannelIds;
6769
}
68-
if (second === "defaults") {
70+
const channelId = second.trim();
71+
if (!channelId || isChannelConfigMetadataKey(channelId)) {
6972
continue;
7073
}
7174
// Channel ids are the second segment under channels.*; deeper touched paths
7275
// still map back to the owning channel for rule collection.
73-
touchedChannelIds.add(second as ChannelId);
76+
touchedChannelIds.add(channelId as ChannelId);
7477
}
7578

7679
if (touchedChannelIds.size === 0) {

‎src/commands/doctor-legacy-config.migrations.test.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1474,7 +1474,10 @@ describe("normalizeCompatibilityConfigValues", () => {
14741474
fallbacks: ["anthropic/claude-sonnet-4-6", "openai/gpt-5.5"],
14751475
},
14761476
models: {
1477-
"anthropic/claude-opus-4-7": { alias: "Opus" },
1477+
"anthropic/claude-opus-4-7": {
1478+
alias: "Opus",
1479+
agentRuntime: { id: "auto", mode: "strict" },
1480+
},
14781481
},
14791482
},
14801483
},
@@ -1484,7 +1487,7 @@ describe("normalizeCompatibilityConfigValues", () => {
14841487
expect(res.config.agents?.defaults?.models).toEqual({
14851488
"anthropic/claude-opus-4-7": {
14861489
alias: "Opus",
1487-
agentRuntime: { id: "claude-cli" },
1490+
agentRuntime: { id: "claude-cli", mode: "strict" },
14881491
},
14891492
"anthropic/claude-sonnet-4-6": {
14901493
agentRuntime: { id: "claude-cli" },

‎src/commands/doctor/shared/channel-doctor.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,10 @@ describe("channel doctor compatibility mutations", () => {
140140
defaults: {
141141
enabled: true,
142142
},
143+
modelByChannel: {
144+
discord: "openai/gpt-5.6-luna",
145+
},
146+
" ": { token: "dummy" },
143147
},
144148
} as never);
145149

‎src/commands/doctor/shared/channel-doctor.ts‎

Lines changed: 7 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import type {
1414
} from "../../../channels/plugins/types.adapters.js";
1515
import type { OpenClawConfig } from "../../../config/types.openclaw.js";
1616
import { isUnresolvedSecretInputError } from "../../../config/types.secrets.js";
17+
import { listDoctorConfiguredChannelIds } from "./configured-channel-ids.js";
1718

1819
type ChannelDoctorEntry = {
1920
id: string;
@@ -65,34 +66,12 @@ export type ChannelDoctorEmptyAllowlistPolicyHooks = {
6566
};
6667

6768
function collectConfiguredChannelIds(cfg: OpenClawConfig): string[] {
68-
if (cfg.plugins?.enabled === false) {
69-
return [];
70-
}
71-
const channels =
72-
cfg.channels && typeof cfg.channels === "object" && !Array.isArray(cfg.channels)
73-
? cfg.channels
74-
: null;
75-
if (!channels) {
76-
return [];
77-
}
78-
const channelEntries = channels as Record<string, unknown>;
79-
return Object.keys(channels)
80-
.filter((channelId) => {
81-
if (channelId === "defaults") {
82-
return false;
83-
}
84-
if (isChannelDoctorBlockedByConfig(channelId, cfg)) {
85-
return false;
86-
}
87-
const entry = channelEntries[channelId];
88-
return (
89-
!entry ||
90-
typeof entry !== "object" ||
91-
Array.isArray(entry) ||
92-
(entry as { enabled?: unknown }).enabled !== false
93-
);
94-
})
95-
.toSorted();
69+
return listDoctorConfiguredChannelIds(cfg, {
70+
configEntryPolicy: "enabled",
71+
skipWhenPluginsDisabled: true,
72+
excludeExplicitlyDisabled: true,
73+
sort: "codepoint",
74+
}).filter((channelId) => !isChannelDoctorBlockedByConfig(channelId, cfg));
9675
}
9776

9877
function isChannelDoctorBlockedByConfig(channelId: string, cfg: OpenClawConfig): boolean {

‎src/commands/doctor/shared/channel-legacy-config-migrate.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,23 @@ function firstMigrationCall() {
4848
}
4949

5050
describe("bundled channel legacy config migrations", () => {
51+
it("does not treat channel metadata or blank ids as channel plugins", () => {
52+
collectRelevantDoctorPluginIds.mockReturnValue([]);
53+
applyPluginDoctorCompatibilityMigrations.mockReturnValue({ config: {}, changes: [] });
54+
55+
applyChannelDoctorCompatibilityMigrations({
56+
channels: {
57+
defaults: {},
58+
modelByChannel: { discord: "openai/gpt-5.6-luna" },
59+
" ": {},
60+
},
61+
});
62+
63+
expect(loadBundledChannelDoctorContractApi).not.toHaveBeenCalled();
64+
expect(getBootstrapChannelPlugin).not.toHaveBeenCalled();
65+
expect(applyPluginDoctorCompatibilityMigrations).not.toHaveBeenCalled();
66+
});
67+
5168
it("only renames heartbeat blocks that use the common visibility shape", () => {
5269
collectRelevantDoctorPluginIds.mockReturnValue([]);
5370
loadBundledChannelDoctorContractApi.mockReturnValue({

‎src/commands/doctor/shared/channel-legacy-config-migrate.ts‎

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
// Legacy config migration bridge for channel doctor compatibility contracts.
2+
3+
import { isChannelConfigMetadataKey } from "../../../channels/config-metadata.js";
24
import { getBootstrapChannelPlugin } from "../../../channels/plugins/bootstrap-registry.js";
35
import { loadBundledChannelDoctorContractApi } from "../../../channels/plugins/doctor-contract-api.js";
46
import type { OpenClawConfig } from "../../../config/types.js";
57
import {
68
applyPluginDoctorCompatibilityMigrations,
79
collectRelevantDoctorPluginIds,
810
} from "../../../plugins/doctor-contract-registry.js";
11+
import { listDoctorConfiguredChannelIds } from "./configured-channel-ids.js";
912
import { isRecord } from "./legacy-config-record-shared.js";
1013

1114
type ChannelDoctorCompatibilityMutation = {
@@ -17,16 +20,6 @@ type ChannelDoctorCompatibilityNormalizer = (params: {
1720
cfg: OpenClawConfig;
1821
}) => ChannelDoctorCompatibilityMutation;
1922

20-
function collectRelevantDoctorChannelIds(raw: unknown): string[] {
21-
const channels = isRecord(raw) && isRecord(raw.channels) ? raw.channels : null;
22-
if (!channels) {
23-
return [];
24-
}
25-
return Object.keys(channels)
26-
.filter((channelId) => channelId !== "defaults")
27-
.toSorted();
28-
}
29-
3023
function migrateHeartbeatVisibility(raw: Record<string, unknown>, changes: string[]): void {
3124
const channels = isRecord(raw.channels) ? raw.channels : null;
3225
if (!channels) {
@@ -59,7 +52,7 @@ function migrateHeartbeatVisibility(raw: Record<string, unknown>, changes: strin
5952
migrateEntry(defaults, "channels.defaults");
6053
}
6154
for (const [channelId, value] of Object.entries(channels)) {
62-
if (channelId === "defaults" || !isRecord(value)) {
55+
if (!channelId.trim() || isChannelConfigMetadataKey(channelId) || !isRecord(value)) {
6356
continue;
6457
}
6558
const preserveEmptyPluginBlock = channelId === "feishu";
@@ -116,7 +109,10 @@ export function applyChannelDoctorCompatibilityMigrations(cfg: Record<string, un
116109
migrateHeartbeatVisibility(cfg, changes);
117110
const unresolvedChannelIds: string[] = [];
118111

119-
for (const channelId of collectRelevantDoctorChannelIds(cfg)) {
112+
for (const channelId of listDoctorConfiguredChannelIds(cfg, {
113+
configEntryPolicy: "raw",
114+
sort: "codepoint",
115+
})) {
120116
const normalizeCompatibilityConfig = resolveBundledChannelCompatibilityNormalizer(channelId);
121117
if (!normalizeCompatibilityConfig) {
122118
unresolvedChannelIds.push(channelId);

0 commit comments

Comments
 (0)