Add exit codes 13 and 14 for config validation and safety blocks

The classifier only matched English usage wording, so every Chinese-language
usage error, every enterprise-selection failure, and every Zod/SyntaxError
fell through to exit 1 ("upstream failure"), while environment safety guards
were reported as exit 2 or 1. Add two semantic codes:

- 13 (validationError): well-formed command, unusable value — missing --corp,
  unparseable enterprise JSON, missing required parameter, ambiguous webhook
  channel selection.
- 14 (safetyBlocked): the target environment forbids the action — replaying
  into production, regression outside a test tenant.

classifyCliError now recognises Chinese usage wording, enterprise-selection
phrasing, local file problems, Zod issue lists (structural, not textual) and
SyntaxError; English Usage:/Unknown-command stays 2, domain failures and
quality gates stay 1. Docs (AGENTS, cli-protocol, skill cli.md) and the exit
code assertions follow.
This commit is contained in:
gitea committed 2026-09-29 22:04:12 +08:00
1 parent 5f4906758e
commit 66eb81f3d1
12 files changed
+177 -134

No files matched your search

+4 -2
View File
@@ -84,7 +84,9 @@ describe("CLI version & help handling", () => {
const env = makeConfigEnv();
const result = runCli(["corps", "current"], env);
expect(result.status).toBe(1);
// 13: enterprise-selection failure — the command line is well-formed, the
// local config/argument is incomplete.
expect(result.status).toBe(13);
expect(result.stderr).toContain("Stateless mode is enabled");
expect(result.stderr).toContain("--corp <corpId>");
});
@@ -145,7 +147,7 @@ describe("CLI version & help handling", () => {
expect(mode.status).toBe(0);
expect(JSON.parse(mode.stdout)).toMatchObject({ mode: "stateless" });
expect(JSON.parse(mode.stdout)).not.toHaveProperty("defaultCorpId");
expect(current.status).toBe(1);
expect(current.status).toBe(13);
expect(current.stderr).toContain("Stateless mode is enabled");
});
+3 -1
View File
@@ -387,7 +387,9 @@ describe("seal-use webhook replay CLI", () => {
"--dry-run"
]);
expect(blockedResult.isError).toBe(true);
expect(blockedResult.exitCode).toBe(1);
// 14: safety block — the target environment forbids the action, not the
// shape of the command line.
expect(blockedResult.exitCode).toBe(14);
expect(blockedResult.stderr).toContain("标记为生产正式环境");
// With --force
+3 -3
View File
@@ -6,7 +6,7 @@ import { existsSync } from "node:fs";
import { runTool, selectCorp } from "../helpers.js";
import * as api from "../../domains/seal/api.js";
import { findWebhookIntegration } from "../../domains/seal/api.js";
import type { ApprovalRun, WebhookIntegration } from "../../domains/seal/types.js";
import type { WebhookIntegration } from "../../domains/seal/types.js";
import {
executeApprovalRunsReplay,
resolveReplayCorpPair,
@@ -31,7 +31,7 @@ import {
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import type { MaterialPackFilePolicyPatch } from "../../domains/seal/material-pack/policy.js";
import { CliError, confirmationRequired, usageError } from "../errors.js";
import { CliError, confirmationRequired, usageError, validationError } from "../errors.js";
export async function handleWebhookResourcePackPreview(
filePath: string,
@@ -295,7 +295,7 @@ export async function handleWebhookCommand(
console.error(`👉 自动锁定唯一可用 Webhook 通道: ${integration.name} (${integration.id})`);
} else if (integrations.length > 1) {
const options = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
throw new Error(`当前租户存在多个 Webhook 通道 [${options}],请通过 --webhook <idOrName> 指定目标通道。`);
throw validationError(`当前租户存在多个 Webhook 通道 [${options}],请通过 --webhook <idOrName> 指定目标通道。`);
} else {
throw new CliError(
"当前租户未配置任何 Webhook 集成通道。",
+66 -1
View File
@@ -1,5 +1,12 @@
import { describe, expect, test } from "bun:test";
import { CliError, classifyCliError, confirmationRequired, PayloadTooLargeError } from "./errors.js";
import {
CliError,
classifyCliError,
confirmationRequired,
PayloadTooLargeError,
safetyBlocked,
validationError
} from "./errors.js";
describe("CLI semantic errors", () => {
test("preserves explicit exit codes and next actions", () => {
@@ -33,5 +40,63 @@ describe("CLI semantic errors", () => {
expect(classifyCliError(new Error("Unknown billing command: invalid"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown webhook command: invalid"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Usage: seal-use contacts children <departmentId>"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Invalid boolean: now"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown deploy hosecloud action: x"))).toEqual({ exitCode: 2 });
});
test("classifies local config and input-data failures as validation errors (13)", () => {
// Chinese-language usage wording: the message names a flag/parameter to supply.
expect(
classifyCliError(new Error("当前租户存在多个 Webhook 通道 [\"a\" (1)],请通过 --webhook <idOrName> 指定目标通道。"))
).toEqual({ exitCode: 13 });
expect(classifyCliError(new Error("必须提供 target、recordId 或 sourceDocumentSN 参数。"))).toEqual({ exitCode: 13 });
// Enterprise selection: well-formed command, incomplete local config.
expect(
classifyCliError(new Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>."))
).toEqual({ exitCode: 13 });
expect(classifyCliError(new Error("No enterprise config found for nope"))).toEqual({ exitCode: 13 });
expect(
classifyCliError(new Error("rules lint requires an authenticated enterprise. Run 'seal-use corps list' to select one."))
).toEqual({ exitCode: 13 });
// Local file input the caller must fix.
expect(classifyCliError(new Error("File not found: /tmp/missing.json"))).toEqual({ exitCode: 13 });
expect(
classifyCliError(new Error("本地规则文件格式错误: 顶层必须为规则数组或包含 'rules' 数组的对象"))
).toEqual({ exitCode: 13 });
// Structural signals that carry no message prefix.
expect(classifyCliError(new SyntaxError("JSON Parse error: Expected '}'"))).toEqual({ exitCode: 13 });
expect(classifyCliError({ issues: [{ path: ["environment"], message: "Invalid option" }] })).toEqual({ exitCode: 13 });
});
test("classifies safety-guard blocks distinctly (14)", () => {
expect(
classifyCliError(new Error("目标企业「生产目标企业」(prod) 标记为生产正式环境 (production)。"))
).toEqual({ exitCode: 14 });
expect(classifyCliError(new Error("重放目标企业「T」(t) 的环境为「production」,非测试环境!"))).toEqual({
exitCode: 14
});
expect(classifyCliError(safetyBlocked("blocked by environment guard", "seal-use webhook replay --force"))).toEqual({
exitCode: 14,
nextAction: "seal-use webhook replay --force"
});
});
test("validationError helper carries exit 13 with next action", () => {
expect(classifyCliError(validationError("请选择目标通道", "seal-use webhook list"))).toEqual({
exitCode: 13,
nextAction: "seal-use webhook list"
});
});
test("keeps domain failures and quality gates at exit 1", () => {
expect(classifyCliError(new Error("未找到指定的规则版本: 99"))).toEqual({ exitCode: 1 });
expect(classifyCliError(new Error("[Linter 质量门禁未通过] 综合评分 80 低于要求的最低分 85 分"))).toEqual({
exitCode: 1
});
expect(classifyCliError(new Error("Webhook 单据推送失败 (500): internal"))).toEqual({ exitCode: 1 });
expect(classifyCliError(new Error("测试企业「T」AI 审批额度不足:当前剩余 200 点"))).toEqual({ exitCode: 1 });
});
});
+2
View File
@@ -5,6 +5,8 @@ export {
CliError,
PayloadTooLargeError,
usageError,
validationError,
safetyBlocked,
confirmationRequired,
classifyCliError
} from "../core/errors.js";
+76 -2
View File
@@ -1,4 +1,4 @@
export type CliExitCode = 1 | 2 | 10 | 11 | 12;
export type CliExitCode = 1 | 2 | 10 | 11 | 12 | 13 | 14;
export class CliError extends Error {
readonly exitCode: CliExitCode;
@@ -23,10 +23,54 @@ export function usageError(message: string, nextAction?: string): CliError {
return new CliError(message, 2, nextAction);
}
/**
* Local configuration/argument validation failure: the CLI was handed a value
* it cannot use (bad `--env` value, unparseable enterprise file, missing
* required parameter). Distinct from `2` (malformed command line) so callers
* can tell "your command line is wrong" from "your config/input data is wrong".
*/
export function validationError(message: string, nextAction?: string): CliError {
return new CliError(message, 13, nextAction);
}
/**
* Safety gate: the requested action is blocked by an environment guard rather
* than by the caller's input — replaying into production, running a regression
* matrix outside a test tenant. Passing the guard requires changing target or
* setting an explicit override flag.
*/
export function safetyBlocked(message: string, nextAction?: string): CliError {
return new CliError(message, 14, nextAction);
}
export function confirmationRequired(message: string, nextAction: string): CliError {
return new CliError(message, 10, nextAction);
}
/**
* Malformed command line: the invocation itself is wrong (unknown subcommand,
* bad flag value, missing positional). Exit `2` — the caller must retype.
*/
const USAGE_PREFIX =
/^(?:Usage:|Unknown (?:[a-z0-9_-]+ )*(?:command|action|subcommand|target)|Invalid (?:number|boolean|command)|--json must|Missing required JSON field|Invalid JSON:)/i;
// Wording a Chinese-language usage error uses when it names a flag/parameter
// the caller must supply, or rejects a value the caller chose. Exit `13`.
const CN_USAGE =
/(?:请通过|请指定|参数提供|需要提供|必须提供|缺少合思凭证|模式需要提供|参数。|为必填项|不能使用|无法用于|必须包含|必须为|顶层必须|格式错误|格式不合法|不支持的|未知的|无效的|请改用|请使用|请提供|请重试|请先)/;
// Enterprise-selection failures: the caller must pass --corp or fix config. Exit `13`.
const CORP_SELECTION =
/^(?:Stateless mode is enabled\.|No enterprise config found|.*requires an authenticated enterprise|.*requires an enterprise\.)/;
// Local file input problems that are the caller's responsibility to fix. Exit `13`.
const LOCAL_FILE_INPUT =
/^(?:File not found:|本地规则文件(?: JSON 解析失败|格式错误|包含重复)|未找到本地规则文件|第 \d+ 条规则(?:格式错误|缺少有效的)|ZIP 根目录缺少|起始时间 .* 不能晚于结束时间)/;
// Safety-guard wording: blocked by target environment, not by input shape. Exit `14`.
const SAFETY_GUARD =
/(?:标记为生产正式环境|非测试环境|严禁在生产环境|禁止向生产环境)/;
export function classifyCliError(error: unknown): {
exitCode: CliExitCode;
nextAction?: string;
@@ -40,15 +84,45 @@ export function classifyCliError(error: unknown): {
if (status === 401 || status === 403 || /(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(value)) {
return { exitCode: 11 };
}
if (/^(?:Usage:|Unknown (?:[a-z0-9_-]+ )?command|Invalid (?:number|boolean|command)|--json must|Missing required JSON field)/i.test(value)) {
if (USAGE_PREFIX.test(value)) {
return { exitCode: 2 };
}
if (/^Refusing to (?:clear|delete)|without --yes|without confirm=true/i.test(value)) {
return { exitCode: 10 };
}
if (SAFETY_GUARD.test(value)) {
return { exitCode: 14 };
}
if (CN_USAGE.test(value) || CORP_SELECTION.test(value) || LOCAL_FILE_INPUT.test(value)) {
return { exitCode: 13 };
}
// Structural validation: a ZodError carries an `issues` array rather than a
// message prefix, so it never matches a text pattern.
if (isValidationIssueList(error)) {
return { exitCode: 13 };
}
// JSON.parse failures (unquoted config, truncated file) are SyntaxErrors with
// no stable English wording across runtimes ("JSON Parse error: ..." under
// Bun, "Unexpected token ..." under Node).
if (error instanceof SyntaxError) {
return { exitCode: 13 };
}
return { exitCode: 1 };
}
function isValidationIssueList(error: unknown): boolean {
if (!error || typeof error !== "object") return false;
const issues = (error as { issues?: unknown }).issues;
if (!Array.isArray(issues)) return false;
return issues.every(
(issue) =>
issue &&
typeof issue === "object" &&
"path" in issue &&
"message" in issue
);
}
function responseStatus(error: unknown): number | undefined {
if (!error || typeof error !== "object") return undefined;
const response = (error as { response?: unknown }).response;
+3 -4
View File
@@ -1,5 +1,5 @@
import type { KyInstance } from "ky";
import { CliError } from "../../../core/errors.js";
import { CliError, safetyBlocked } from "../../../core/errors.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
@@ -98,10 +98,9 @@ export async function runRegressionTest(
// 1. Red Line 1: Enterprise Isolation Guard
if (targetCorp.environment !== "test") {
throw new CliError(
throw safetyBlocked(
`重放目标企业「${targetCorp.name}」(${targetCorp.id}) 的环境为「${targetCorp.environment}」,非测试环境!\n` +
`硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。`,
2,
`seal-use corps bind-test ${sourceCorp.id} <testCorpId>`
);
}
@@ -365,7 +364,7 @@ export async function runRegressionTest(
}
export function formatRegressionDashboard(result: RegressionTestResult): string {
const { sourceCorp, targetCorp, verdict, safeToPublish, metrics, quota, flips, records } = result;
const { sourceCorp, targetCorp, verdict, safeToPublish, metrics, quota, flips } = result;
const verdictBadge =
verdict === "CLEAN"
+6 -110
View File
@@ -1,25 +1,12 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import * as api from "../api.js";
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { validationError } from "../../../core/errors.js";
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
import { resolveCorpConfig } from "../../../core/config/manager.js";
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
import { createSealClient } from "../../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import { searchApprovalContent } from "../search.js";
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
import {
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets,
type LocalRuleItem
} from "../rules-local.js";
import {
checkWebhookReadiness,
previewMaterialPack,
@@ -27,110 +14,19 @@ import {
readMaterialPackFile
} from "../material-pack/index.js";
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
import { extractApprovalRunAttachments } from "../attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow
} from "../../hose/index.js";
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
import {
ThinkingPolicySchema,
type ApprovalRule,
type ApprovalRun,
type RuleSetVersion,
type SimulationBatch,
type WebhookIntegration,
type WebhookMode,
type ThinkingPolicy,
type DecisionPreferences,
type HosecloudConfigInput
type WebhookMode
} from "../types.js";
import type {
ToolContext,
SealToolDefinition,
ApprovalRunSummary,
ApprovalRunsSummaryOptions,
RuleField,
RulePushPlan,
SimulationBatchCreateInput,
HumanResultMatch
ToolContext
} from "./helpers.js";
import * as helpers from "./helpers.js";
const {
presentWebhookIntegration,
getConfiguredSealBaseUrl,
projectApprovalRules,
pickRuleFields,
buildRulePushPlan,
rulesHaveSameContent,
ruleChangedFields,
normalizeRuleStrictness,
parseDurationMs,
redactIntegrationSecrets,
mutationPreview,
redactPreviewValue,
buildSimulationBatchParams,
summarizeSimulationBatch,
summarizeApprovalRun,
summarizeApprovalRuns,
parseFieldPaths,
pickRunFields,
approvalRunMetadata,
summarizeApprovalRunDetail,
summarizeApprovalRunResult,
summarizeApprovalRunDocument,
extractCitedRules,
firstPath,
countPathCandidates,
getPath,
setPath,
compactObject,
asRecord,
numberFromUnknown,
flattenDocumentFields,
collectDocumentFields,
firstByLabel,
collectInvoiceSummary,
collectInvoiceObjects,
findKeywordLines,
summarizeRunBridge,
summarizeRuleVersion,
resolveRuleVersionForLookup,
findRuleInVersion,
normalizeRuleCode,
runtimeRuleIndex,
runtimeRuleIdToCode,
formatRuleCode,
pickApprovalRunCandidate,
resolveApprovalRunForUrl,
resolveSealBaseUrl,
normalizeUrl,
stringFromUnknown,
pickApprovalRuns,
timestampOf,
resolveRuleVersion,
resolveRuleVersionSelector,
filterRuns,
scalarIncludes,
objectContainsScalar,
filterRunsByHumanResult,
withApprovalRunFilters,
resolveManualApprovalStatus,
prepareApprovalRuns,
approvalRunAliases,
extractHumanResult,
findHumanResultValue,
isHumanResultKey,
stringifyHumanResultValue,
matchesRunLookup,
countBy,
localDateKey,
formatLocalDateTime,
toDate,
localParts
mutationPreview
} = helpers;
export const webhookTools = [
@@ -444,7 +340,7 @@ export const webhookTools = [
integration = integrations[0]!;
} else if (integrations.length > 1) {
const options = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
throw new Error(`当前租户存在多个 Webhook 通道 [${options}],请通过 webhook 参数指定目标通道。`);
throw validationError(`当前租户存在多个 Webhook 通道 [${options}],请通过 webhook 参数指定目标通道。`);
} else {
throw new Error("当前租户未配置任何 Webhook 集成通道。");
}
+3 -4
View File
@@ -2,7 +2,7 @@ import type { KyInstance } from "ky";
import type { ApprovalRun, WebhookIntegration } from "./types.js";
import type { MaterialField } from "./material-pack/types.js";
import { webhookHeaders } from "./material-pack/signature.js";
import { CliError } from "../../core/errors.js";
import { CliError, safetyBlocked, validationError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import * as api from "./api.js";
@@ -198,7 +198,7 @@ export function selectWebhookIntegration(
return replayHook;
}
const options = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
throw new Error(`当前租户存在多个 Webhook 通道 [${options}],请通过 --webhook <idOrName> 指定目标通道。`);
throw validationError(`当前租户存在多个 Webhook 通道 [${options}],请通过 --webhook <idOrName> 指定目标通道。`);
}
throw new CliError(
@@ -274,10 +274,9 @@ export function resolveReplayCorpPair(
// Safety guard: prevent pushing replay test records to production
if (targetCorp.environment === "production" && !force) {
throw new CliError(
throw safetyBlocked(
`目标企业「${targetCorp.name}」(${targetCorp.id}) 标记为生产正式环境 (production)。\n` +
`为防止测试单据污染生产审批流,禁止向生产环境重放单据。请指定测试企业 (--target-corp <testCorpId>),或在确有需要时添加 --force。`,
1,
`seal-use webhook replay --target-corp <testCorpId>${sourceCorp.id !== targetCorp.id ? ` --source-corp ${sourceCorp.id}` : ""}`
);
}