Isolate malformed enterprise config files instead of failing every command
loadCorpConfigs parsed every file with a bare Schema.parse, so one hand- edited JSON aborted the whole directory: every corps/rules/webhook command died with a raw parse error and no hint which file was at fault. Each file now parses inside its own try/catch — bad files are skipped and reported once per process on stderr with the offending path; the remaining enterprises stay usable. loadGlobalConfig falls back to defaults (warning on stderr) so config paths / corps list keep working for diagnosis. doctor gains a config_parseability check that names unparseable files.
This commit is contained in:
1 parent
66eb81f3d1
commit
b5d1bbda15
4 files changed
+144
-5
No files matched your search
@@ -19,6 +19,12 @@ describe("seal-use doctor CLI", () => {
|
||||
expect(data.knowledge).toBeDefined();
|
||||
expect(data.knowledge.guideCommand).toBe("seal-use doctor guide");
|
||||
expect(data.checks.some((c: any) => c.id === "rule_linter")).toBe(true);
|
||||
// A malformed enterprise file used to abort the whole directory load with a
|
||||
// bare JSON error. The doctor must name the bad file instead.
|
||||
const parseCheck = data.checks.find((c: any) => c.id === "config_parseability");
|
||||
expect(parseCheck).toBeDefined();
|
||||
expect(["ok", "warn"]).toContain(parseCheck.status);
|
||||
expect(parseCheck.message.length).toBeGreaterThan(0);
|
||||
|
||||
// stderr must contain human-friendly dashboard
|
||||
expect(result.stderr).toContain("Seal Use Doctor");
|
||||
|
||||
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
findCorpConfigFile,
|
||||
getLastCorpConfigLoadIssues,
|
||||
loadCorpConfigs,
|
||||
loadGlobalConfig,
|
||||
resolveEnterprisesDir,
|
||||
@@ -186,6 +187,53 @@ describe("loadCorpConfigs", () => {
|
||||
const reloadedAfterClear = loadCorpConfigs().find((c) => c.id === "alpha");
|
||||
expect(reloadedAfterClear?.testCorpId).toBeUndefined();
|
||||
});
|
||||
|
||||
test("skips a malformed file without dropping the other enterprises in the directory", () => {
|
||||
const dir = makeTempDir();
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
|
||||
writeCorpConfig(join(dir, "good.json"), "good", "Good Corp");
|
||||
// A hand-edited or truncated file must not abort the whole directory load.
|
||||
writeFileSync(join(dir, "broken.json"), "{ not json at all");
|
||||
writeFileSync(join(dir, "wrong-shape.json"), JSON.stringify({ id: "wrong-shape" }));
|
||||
|
||||
expect(loadCorpConfigs().map((corp) => corp.id)).toEqual(["good"]);
|
||||
|
||||
const issues = getLastCorpConfigLoadIssues();
|
||||
expect(issues.map((issue) => issue.file).sort()).toEqual(["broken.json", "wrong-shape.json"]);
|
||||
expect(issues.map((issue) => issue.dir)).toEqual([dir, dir]);
|
||||
});
|
||||
|
||||
test("reports no issues when every file parses", () => {
|
||||
const dir = makeTempDir();
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
|
||||
writeCorpConfig(join(dir, "alpha.json"), "alpha", "Alpha Corp");
|
||||
|
||||
expect(loadCorpConfigs()).toHaveLength(1);
|
||||
expect(getLastCorpConfigLoadIssues()).toEqual([]);
|
||||
});
|
||||
|
||||
test("warns about a malformed file only once per process", () => {
|
||||
const dir = makeTempDir();
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
|
||||
writeFileSync(join(dir, "broken-once.json"), "{ nope");
|
||||
|
||||
const errors: string[] = [];
|
||||
const originalError = console.error;
|
||||
console.error = (...values: unknown[]) => {
|
||||
errors.push(values.map((value) => String(value)).join(" "));
|
||||
};
|
||||
try {
|
||||
loadCorpConfigs();
|
||||
loadCorpConfigs();
|
||||
loadCorpConfigs();
|
||||
} finally {
|
||||
console.error = originalError;
|
||||
}
|
||||
|
||||
const skipWarnings = errors.filter((line) => line.includes("跳过"));
|
||||
expect(skipWarnings).toHaveLength(1);
|
||||
expect(skipWarnings[0]).toContain("broken-once.json");
|
||||
});
|
||||
});
|
||||
|
||||
describe("syncLegacyEnterprisesDir", () => {
|
||||
|
||||
@@ -85,20 +85,59 @@ export function syncLegacyEnterprisesDir(
|
||||
return { copied, deletedLegacyDir };
|
||||
}
|
||||
|
||||
export type CorpConfigLoadIssue = { dir: string; file: string; reason: string };
|
||||
|
||||
let lastCorpLoadIssues: CorpConfigLoadIssue[] = [];
|
||||
// Files already warned about this process: loadCorpConfigs runs several times
|
||||
// per invocation (selection, dispatch, tool handlers), so warn each file once.
|
||||
const warnedCorpFiles = new Set<string>();
|
||||
|
||||
/**
|
||||
* Issues from the most recent loadCorpConfigs() call. A malformed file must not
|
||||
* abort the directory: the remaining enterprises stay usable and the caller
|
||||
* reports the bad file by name instead of failing every command with a bare
|
||||
* JSON parse error.
|
||||
*/
|
||||
export function getLastCorpConfigLoadIssues(): CorpConfigLoadIssue[] {
|
||||
return lastCorpLoadIssues;
|
||||
}
|
||||
|
||||
export function loadCorpConfigs(): CorpConfig[] {
|
||||
const dirs = resolveEnterprisesDirs();
|
||||
const byId = new Map<string, CorpConfig>();
|
||||
const issues: CorpConfigLoadIssue[] = [];
|
||||
|
||||
for (const dir of dirs) {
|
||||
for (const file of readdirSync(dir)
|
||||
.filter((item) => item.endsWith(".json"))
|
||||
.filter((item) => !item.startsWith("example."))) {
|
||||
const content = readFileSync(join(dir, file), "utf-8");
|
||||
const corp = CorpConfigSchema.parse(JSON.parse(content));
|
||||
const fullPath = join(dir, file);
|
||||
let corp: CorpConfig;
|
||||
try {
|
||||
const content = readFileSync(fullPath, "utf-8");
|
||||
corp = CorpConfigSchema.parse(JSON.parse(content));
|
||||
} catch (error) {
|
||||
issues.push({ dir, file, reason: error instanceof Error ? error.message : String(error) });
|
||||
continue;
|
||||
}
|
||||
byId.set(corp.id, corp);
|
||||
}
|
||||
}
|
||||
|
||||
lastCorpLoadIssues = issues;
|
||||
const fresh = issues.filter((issue) => {
|
||||
const key = `${issue.dir}/${issue.file}`;
|
||||
if (warnedCorpFiles.has(key)) return false;
|
||||
warnedCorpFiles.add(key);
|
||||
return true;
|
||||
});
|
||||
if (fresh.length) {
|
||||
console.error(
|
||||
`⚠️ 跳过 ${fresh.length} 个无法解析的企业配置: ${fresh.map((item) => `${item.dir}/${item.file}`).join(", ")}`
|
||||
);
|
||||
console.error(`👉 Next action: seal-use doctor (检查配置文件格式与权限)`);
|
||||
}
|
||||
|
||||
return Array.from(byId.values());
|
||||
}
|
||||
|
||||
@@ -166,13 +205,36 @@ export function resolveGlobalConfigFile(): string {
|
||||
return PRIMARY_GLOBAL_CONFIG_FILE;
|
||||
}
|
||||
|
||||
let lastGlobalConfigIssue: { file: string; reason: string } | undefined;
|
||||
|
||||
/**
|
||||
* Issue from the most recent loadGlobalConfig() call, if the configured file
|
||||
* existed but could not be parsed. `doctor` reads this to surface the bad file;
|
||||
* commands otherwise continue on defaults instead of failing outright.
|
||||
*/
|
||||
export function getLastGlobalConfigIssue(): { file: string; reason: string } | undefined {
|
||||
return lastGlobalConfigIssue;
|
||||
}
|
||||
|
||||
export function loadGlobalConfig(): GlobalConfig {
|
||||
const file = resolveGlobalConfigFile();
|
||||
lastGlobalConfigIssue = undefined;
|
||||
if (!existsSync(file)) {
|
||||
return GlobalConfigSchema.parse({});
|
||||
}
|
||||
|
||||
return GlobalConfigSchema.parse(JSON.parse(readFileSync(file, "utf-8")));
|
||||
try {
|
||||
return GlobalConfigSchema.parse(JSON.parse(readFileSync(file, "utf-8")));
|
||||
} catch (error) {
|
||||
// A hand-edited config.json must not brick every command: fall back to
|
||||
// defaults so the user can still run `seal-use config paths` / `corps list`
|
||||
// to find and fix the file.
|
||||
const reason = error instanceof Error ? error.message : String(error);
|
||||
lastGlobalConfigIssue = { file, reason };
|
||||
console.error(`⚠️ 全局配置无法解析,已回退默认值: ${file} (${reason})`);
|
||||
console.error(`👉 Next action: seal-use config paths (检查配置文件)`);
|
||||
return GlobalConfigSchema.parse({});
|
||||
}
|
||||
}
|
||||
|
||||
export function saveGlobalConfig(config: GlobalConfigInput): GlobalConfig {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { PRIMARY_LINTERS_DIR, OFFICIAL_LINTERS_DIR } from "../paths.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { loadCorpConfigs, loadGlobalConfig } from "../config/loader.js";
|
||||
import { getLastCorpConfigLoadIssues, getLastGlobalConfigIssue, loadCorpConfigs, loadGlobalConfig } from "../config/loader.js";
|
||||
import { formatBeijingIso } from "../config/timestamps.js";
|
||||
import { getDefaultGlobalSkillDir } from "../embedded-skill.js";
|
||||
import { resolveUsageFilePath } from "../stats/usage-tracker.js";
|
||||
@@ -208,6 +208,11 @@ export function diagnoseSystem(): DoctorDiagnosis {
|
||||
const currentCorpId = globalConfig.defaultCorpId ?? corps[0]?.id;
|
||||
const currentCorp = corps.find((c) => c.id === currentCorpId);
|
||||
|
||||
// Captured immediately after the loaders run: the issues are per-load state
|
||||
// and any later loadCorpConfigs() call would overwrite them.
|
||||
const corpConfigIssues = getLastCorpConfigLoadIssues();
|
||||
const globalConfigIssue = getLastGlobalConfigIssue();
|
||||
|
||||
const testCount = corps.filter((c) => (c.environment ?? "production").toLowerCase() === "test").length;
|
||||
const prodCount = corps.length - testCount;
|
||||
|
||||
@@ -300,7 +305,25 @@ export function diagnoseSystem(): DoctorDiagnosis {
|
||||
: `${looseCredentialFiles.length} 个凭据文件权限宽于 0600(同机其他用户可读,取决于父目录权限),建议 chmod 600:${looseCredentialFiles.join("、")}`
|
||||
});
|
||||
|
||||
// Check 6: Rule Linter configuration
|
||||
// Check 6: Config file parseability. A single malformed JSON file otherwise
|
||||
// silently removes that enterprise from every command; surface it by name.
|
||||
const configIssues = [
|
||||
...(globalConfigIssue ? [{ file: globalConfigIssue.file, reason: globalConfigIssue.reason }] : []),
|
||||
...corpConfigIssues.map((issue) => ({ file: join(issue.dir, issue.file), reason: issue.reason }))
|
||||
];
|
||||
checks.push({
|
||||
id: "config_parseability",
|
||||
title: "配置文件格式",
|
||||
status: configIssues.length === 0 ? "ok" : "warn",
|
||||
message:
|
||||
configIssues.length === 0
|
||||
? "所有企业与全局配置文件均可正常解析"
|
||||
: `${configIssues.length} 个配置文件无法解析(对应企业不可用,已从列表中跳过):${configIssues
|
||||
.map((issue) => `${issue.file} (${issue.reason})`)
|
||||
.join("、")}`
|
||||
});
|
||||
|
||||
// Check 7: Rule Linter configuration
|
||||
const lintConfig = globalConfig.lint ?? { enabled: false, activeLinter: "builtin", minScore: 0 };
|
||||
if (lintConfig.enabled) {
|
||||
checks.push({
|
||||
|
||||
Reference in new issue
Block a user