From 66eb81f3d176b5531ca30e24c84d2dd0eaab9bc7 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 29 Sep 2026 22:04:12 +0800 Subject: [PATCH] Add exit codes 13 and 14 for config validation and safety blocks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- .agents/rules/cli-protocol.md | 8 +- AGENTS.md | 8 +- skills/seal-use/references/cli.md | 2 +- src/cli.test.ts | 6 +- src/cli/commands/webhook-replay.test.ts | 4 +- src/cli/commands/webhook.ts | 6 +- src/cli/errors.test.ts | 67 +++++++++++++- src/cli/errors.ts | 2 + src/core/errors.ts | 78 +++++++++++++++- src/domains/seal/regression/service.ts | 7 +- src/domains/seal/tools/webhook.ts | 116 ++---------------------- src/domains/seal/webhook-replay.ts | 7 +- 12 files changed, 177 insertions(+), 134 deletions(-) diff --git a/.agents/rules/cli-protocol.md b/.agents/rules/cli-protocol.md index 40c74f0..1b92e67 100644 --- a/.agents/rules/cli-protocol.md +++ b/.agents/rules/cli-protocol.md @@ -65,13 +65,15 @@ When developing or refactoring CLI commands under `src/cli/`: | Exit Code | Meaning | Example Scenario | | :--- | :--- | :--- | | `0` | **Success** | Successful query, preview, or completed mutation | -| `1` | **Domain / Upstream Failure** | Upstream HTTP 500, business logic rejection, quota insufficient | -| `2` | **Usage / Syntax Error** | Unknown subcommand, invalid JSON payload, invalid argument format | +| `1` | **Domain / Upstream Failure** | Upstream HTTP 500, business logic rejection, quota insufficient, lint score below threshold | +| `2` | **Usage / Syntax Error** | Unknown subcommand, invalid `--flag` value, malformed `--json` payload | | `10` | **Confirmation Required** | Mutating command invoked without `--confirm` or `--yes` | | `11` | **Authentication Missing / Invalid** | Upstream HTTP 401/403, or an expired/missing/invalid `token`/`bearer`/`session` (classified in `classifyCliError`) | | `12` | **Output Protection** | Response exceeds the size limit (`PayloadTooLargeError` from `printer.ts`); use `--summary`/`--fields`/`--count`/`--output-file`, or `--full` when the full payload is genuinely required | +| `13` | **Config / Input Validation** | Well-formed command with an unusable value: missing `--corp` in stateless mode, unparseable enterprise JSON, missing required parameter (Chinese-language usage wording), Zod/schema validation failure | +| `14` | **Safety Guard Block** | Target environment forbids the action: replay into a production tenant, regression matrix outside a test tenant. Requires a different target or an explicit override flag | -**Rule**: Never call `process.exit()` deep in domain functions. Throw structured errors and let `src/cli/runner.ts` handle error classification, stream routing, and exit code assignment. +**Rule**: Never call `process.exit()` deep in domain functions. Throw structured errors (`usageError` → 2, `validationError` → 13, `safetyBlocked` → 14, `confirmationRequired` → 10) and let `src/cli/runner.ts` handle error classification, stream routing, and exit code assignment. Domain failures and quality gates stay at `1`. --- diff --git a/AGENTS.md b/AGENTS.md index 0a7c281..40fbbf1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,15 +35,17 @@ Prefer small domain functions over broad utility modules. - **Machine Channel (`stdout`)**: Data commands MUST output clean, parseable JSON on `stdout`. Never dump human prose, raw logs, or progress banners into `stdout`. The Agent Harness parses `stdout` directly into typed payloads. - **Documented exception — document-output commands**: `seal-use --help` / `seal-use help ` (`src/cli/printer.ts`), `seal-use doctor guide` (`src/cli/commands/doctor.ts`), and `seal-use skill dump` (`src/cli/commands/skill.ts`) intentionally write Markdown to `stdout`, because their output *is* the payload the caller redirects or reads (e.g. `seal-use doctor guide > guide.md`, `seal-use skill dump > SKILL.md`). Never add a new prose-on-stdout command outside this list: return structured JSON and put the readable rendering on `stderr` instead. `src/probe.ts` is a local developer probe script rather than a `bin` entry point, so its `[probe] …` lines are outside this contract. - **Guidance & Diagnostic Channel (`stderr`)**: Use `stderr` for runtime logs, network probing status, self-healing notifications, and explicit **Next-Step Command Suggestions** (e.g. `👉 Next action: seal-use deploy hosecloud sync `). -- **Performance Contract & SWR Architecture**: Read-only discovery and version commands (`seal-use version`, `seal-use doctor`, `seal-use corps list`) MUST execute instantaneously (<10ms). Never block on external network I/O during routine invocations. Use the Stale-While-Revalidate (SWR) pattern: read local cache from `~/.config/seal-use/*.json` synchronously (<0.2ms), and refresh stale/missing data via detached, unref'd child processes (`triggerBackgroundUpdateCheck`, `unref()`). +- **Performance Contract & SWR Architecture**: Read-only discovery and version commands (`seal-use version`, `seal-use doctor`, `seal-use corps list`) MUST execute in under 50ms wall clock (Bun startup alone is ~7ms; runner dispatch uses lazy `await import()` per command area, so the version path never loads the Excel/zip tool chain). Never block on external network I/O during routine invocations. Use the Stale-While-Revalidate (SWR) pattern: read local cache from `~/.config/seal-use/*.json` synchronously (<0.2ms), and refresh stale/missing data via detached, unref'd child processes (`triggerBackgroundUpdateCheck`, `unref()`). - **Safety Guardrail & Mutation Preview (`--dry-run`)**: All potentially destructive or state-mutating commands (e.g. `rules push/clear`, `corps sync-test`, `preference update`, `webhook add/update`) MUST support `--dry-run` returning structured JSON previews with `preview: true` and a clean diff, without executing mutations. Live execution requires explicit `--yes` or `--confirm`. - **Exit Code Contract**: - `0`: Successful execution. - - `1`: Upstream API failure or domain business block. - - `2`: Parameter validation failure, unknown subcommand, or invalid JSON. + - `1`: Upstream API failure or domain business block (including quality gates such as a lint score below threshold). + - `2`: Malformed command line — parameter validation failure, unknown subcommand, or invalid JSON flag value. - `10`: Safety gate block requiring user confirmation (`--confirm` / `--yes`). - `11`: Missing or invalid authentication (HTTP 401/403, or an expired/missing/invalid `token`/`bearer`/`session`). - `12`: Output protection — response exceeds the size limit; use `--summary`/`--fields`/`--count`/`--output-file` (or `--full` when the full payload is genuinely required). + - `13`: Local configuration or input-data validation failure — well-formed command, but the value or config file is unusable (missing `--corp`, unparseable enterprise JSON, missing required parameter named in a Chinese-language error). + - `14`: Safety guard block — the target environment forbids the action (replay into production, regression outside a test tenant); requires a different target or an explicit override. - Never call `process.exit()` deep in domain functions; throw structured errors and let `src/cli/runner.ts` handle stream routing and exit code assignment. ## Testing Guidelines diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index 56bacc7..2c6a4dd 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -31,7 +31,7 @@ override that path. The legacy `current-corp` file is not read. - **`stdout`**: Pure, deterministic JSON for machine/Agent parsing. - **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** with the stable prefix `👉 Next action: seal-use ...`. -- **`Exit Code`**: `0` on success; `1` runtime/upstream failure, `2` usage/argument error, `10` explicit destructive-operation confirmation required, `11` missing/invalid authentication, and `12` output protection requiring a compact/file/query alternative. +- **`Exit Code`**: `0` on success; `1` runtime/upstream failure or quality-gate failure, `2` malformed command line (unknown subcommand, bad `--flag` value), `10` explicit destructive-operation confirmation required, `11` missing/invalid authentication, `12` output protection requiring a compact/file/query alternative, `13` local config/input validation failure (missing `--corp`, unparseable enterprise file, missing required parameter), `14` safety-guard block (target environment forbids the action, e.g. replay into production). ## Top-Level Commands diff --git a/src/cli.test.ts b/src/cli.test.ts index 5a9d2fb..8ebbd9e 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -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 "); }); @@ -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"); }); diff --git a/src/cli/commands/webhook-replay.test.ts b/src/cli/commands/webhook-replay.test.ts index 71eb9e9..df5b85c 100644 --- a/src/cli/commands/webhook-replay.test.ts +++ b/src/cli/commands/webhook-replay.test.ts @@ -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 diff --git a/src/cli/commands/webhook.ts b/src/cli/commands/webhook.ts index a44283b..f705f68 100644 --- a/src/cli/commands/webhook.ts +++ b/src/cli/commands/webhook.ts @@ -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 指定目标通道。`); + throw validationError(`当前租户存在多个 Webhook 通道 [${options}],请通过 --webhook 指定目标通道。`); } else { throw new CliError( "当前租户未配置任何 Webhook 集成通道。", diff --git a/src/cli/errors.test.ts b/src/cli/errors.test.ts index 84366b8..6911abc 100644 --- a/src/cli/errors.test.ts +++ b/src/cli/errors.test.ts @@ -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 "))).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 指定目标通道。")) + ).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 .")) + ).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 }); }); }); diff --git a/src/cli/errors.ts b/src/cli/errors.ts index 682dfa0..3134f9c 100644 --- a/src/cli/errors.ts +++ b/src/cli/errors.ts @@ -5,6 +5,8 @@ export { CliError, PayloadTooLargeError, usageError, + validationError, + safetyBlocked, confirmationRequired, classifyCliError } from "../core/errors.js"; diff --git a/src/core/errors.ts b/src/core/errors.ts index 458a845..05053b5 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -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; diff --git a/src/domains/seal/regression/service.ts b/src/domains/seal/regression/service.ts index ec60caa..b913a9d 100644 --- a/src/domains/seal/regression/service.ts +++ b/src/domains/seal/regression/service.ts @@ -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} ` ); } @@ -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" diff --git a/src/domains/seal/tools/webhook.ts b/src/domains/seal/tools/webhook.ts index fd1f986..014d176 100644 --- a/src/domains/seal/tools/webhook.ts +++ b/src/domains/seal/tools/webhook.ts @@ -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 集成通道。"); } diff --git a/src/domains/seal/webhook-replay.ts b/src/domains/seal/webhook-replay.ts index e4459f7..338a7a8 100644 --- a/src/domains/seal/webhook-replay.ts +++ b/src/domains/seal/webhook-replay.ts @@ -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 指定目标通道。`); + throw validationError(`当前租户存在多个 Webhook 通道 [${options}],请通过 --webhook 指定目标通道。`); } 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 ),或在确有需要时添加 --force。`, - 1, `seal-use webhook replay --target-corp ${sourceCorp.id !== targetCorp.id ? ` --source-corp ${sourceCorp.id}` : ""}` ); }