Harden post-write error codes, rules push recovery ledger, and capability param normalization
This commit is contained in:
1 parent
75017ab49c
commit
586ad521dc
17 files changed
+1102
-197
No files matched your search
+40
-12
@@ -2,6 +2,7 @@ import { readFileSync } from "node:fs";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { filterRuleMapping, loadRuleMappingSnapshot } from "../../domains/seal/rules/mapping.js";
|
||||
import { RulePushExecutionError } from "../../domains/seal/rules/push.js";
|
||||
import {
|
||||
listAvailableLinters,
|
||||
PRIMARY_LINTERS_DIR,
|
||||
@@ -338,7 +339,26 @@ export async function handleRulesCommand(
|
||||
}
|
||||
|
||||
if (action === "push") {
|
||||
const file = stringOption(args.options.file) ?? stringOption(args.options.f) ?? maybeName;
|
||||
const statusOnly =
|
||||
maybeName === "status" ||
|
||||
booleanOption(args.options.check) === true ||
|
||||
args.options.status === "true" ||
|
||||
args.options.status === true;
|
||||
const file =
|
||||
stringOption(args.options.file) ??
|
||||
stringOption(args.options.f) ??
|
||||
(maybeName && maybeName !== "status" && !maybeName.startsWith("-") ? maybeName : undefined);
|
||||
if (statusOnly) {
|
||||
await runCapability(
|
||||
"sealApprovalRulesPush",
|
||||
client!,
|
||||
corp,
|
||||
{ file, statusOnly: true },
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const confirmed = booleanOption(args.options.yes) === true;
|
||||
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) ?? !confirmed;
|
||||
const publish = booleanOption(args.options.publish);
|
||||
@@ -351,18 +371,26 @@ export async function handleRulesCommand(
|
||||
);
|
||||
}
|
||||
|
||||
const result = await runCapabilityResult(
|
||||
"sealApprovalRulesPush",
|
||||
client!,
|
||||
corp,
|
||||
{
|
||||
file,
|
||||
dryRun,
|
||||
confirm: confirmed,
|
||||
publish,
|
||||
versionName
|
||||
let result: unknown;
|
||||
try {
|
||||
result = await runCapabilityResult(
|
||||
"sealApprovalRulesPush",
|
||||
client!,
|
||||
corp,
|
||||
{
|
||||
file,
|
||||
dryRun,
|
||||
confirm: confirmed,
|
||||
publish,
|
||||
versionName
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof RulePushExecutionError) {
|
||||
printJson(error.recoveryPayload, outputOptions(args.options));
|
||||
}
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (!confirmed && dryRun && result && typeof result === "object") {
|
||||
printJson(
|
||||
|
||||
@@ -91,12 +91,16 @@ describe("CLI semantic errors", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps domain failures and quality gates at exit 1", () => {
|
||||
test("keeps domain failures, post-mutation recovery errors, 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 });
|
||||
expect(
|
||||
classifyCliError(new Error("重排请求已发送,但回读规则与预览不一致。请先核对当前草稿,勿重复执行旧确认码。"))
|
||||
).toEqual({ exitCode: 1 });
|
||||
expect(classifyCliError(new Error("上游网关响应超时,请重试或检查网络连接。"))).toEqual({ exitCode: 1 });
|
||||
});
|
||||
});
|
||||
+5
-2
@@ -343,8 +343,11 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
},
|
||||
{
|
||||
name: "push",
|
||||
summary: "Push rules from local JSON file to enterprise draft space",
|
||||
usage: ["seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]"]
|
||||
summary: "Push rules from local JSON file to enterprise draft space (with step recovery & status check)",
|
||||
usage: [
|
||||
"seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]",
|
||||
"seal-use rules push status [--file <path>] [--corp <corpId>]"
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "clear",
|
||||
|
||||
+14
-4
@@ -65,10 +65,11 @@ export async function runCapabilityResult(
|
||||
);
|
||||
// Schema gate: a missing required field or an out-of-range value fails here
|
||||
// with exit 13 instead of reaching the handler as `undefined` and surfacing
|
||||
// as an opaque upstream error. Valid params pass through untouched.
|
||||
parseCapabilityParams(tool, compactParams);
|
||||
// as an opaque upstream error. Valid params are normalized so the handler
|
||||
// executes with the exact coerced/defaulted values that passed validation.
|
||||
const normalizedParams = parseCapabilityParams(tool, compactParams);
|
||||
const handler = tool.handler as SealCapability["handler"];
|
||||
return handler(client, compactParams as never, { corp });
|
||||
return handler(client, normalizedParams as never, { corp });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,6 +99,15 @@ export async function runLangfuseCapability(
|
||||
throw validationError(`Invalid parameters for ${tool.name}: ${detail}`);
|
||||
}
|
||||
|
||||
const normalizedParams =
|
||||
parsed.data && typeof parsed.data === "object"
|
||||
? {
|
||||
...compactParams,
|
||||
...Object.fromEntries(
|
||||
Object.entries(parsed.data as Record<string, unknown>).filter(([, value]) => value !== undefined)
|
||||
)
|
||||
}
|
||||
: compactParams;
|
||||
const handler = tool.handler as (params: never, service: LangfuseService) => Promise<unknown>;
|
||||
printJson(await handler(compactParams as never, createLangfuseService()), options);
|
||||
printJson(await handler(normalizedParams as never, createLangfuseService()), options);
|
||||
}
|
||||
@@ -26,6 +26,7 @@ describe("CLI read-only classification", () => {
|
||||
"auth status",
|
||||
"auth test",
|
||||
"auth doctor",
|
||||
"auth seal-link list",
|
||||
"doctor auth"
|
||||
]);
|
||||
|
||||
@@ -134,21 +135,34 @@ describe("CLI read-only classification", () => {
|
||||
expect(isReadOnlyCliCommand(["probe", "corp-a", "extra"])).toBe(false);
|
||||
});
|
||||
|
||||
test("allows rules push status / --check as read-only while refusing mutating rules push forms", () => {
|
||||
expect(isReadOnlyCliCommand(["rules", "push", "status", "--corp", "corp-a"])).toBe(true);
|
||||
expect(isReadOnlyCliCommand(["rules", "push", "--check", "--corp", "corp-a"])).toBe(true);
|
||||
expect(isReadOnlyCliCommand(["rules", "push", "--corp", "corp-a"])).toBe(false);
|
||||
expect(isReadOnlyCliCommand(["rules", "push", "status", "--yes", "--corp", "corp-a"])).toBe(false);
|
||||
});
|
||||
|
||||
test("refuses command lines that cannot be parsed", () => {
|
||||
expect(isReadOnlyCliCommand(["--json"])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// The two classifications are maintained by hand, in different files: the CLI allow-list here and
|
||||
// The two classifications are maintained in different files: the CLI allow-list here and
|
||||
// SEAL_READ_ONLY_CAPABILITIES in the tool registry. Nothing stopped them from disagreeing, and they did —
|
||||
// `analytics analyze` was allow-listed while its tool POSTs, and three read-only approval-runs verbs
|
||||
// were simply missing. This derives one from the other and fails on any new disagreement.
|
||||
// were simply missing. This scans both `runCapability` and `runCapabilityResult` and fails on any disagreement.
|
||||
describe("CLI allow-list agrees with the tool registry", () => {
|
||||
// `deploy` only accepts `deploy hosecloud <action>`; the short `deploy <action>` form throws
|
||||
// "未知的发布目标系统" at runtime, so these pairs are unreachable rather than refused.
|
||||
const UNREACHABLE_CLI_FORMS = new Set(["deploy requirements", "deploy list", "deploy status"]);
|
||||
// "未知的发布目标系统" at runtime. `auth seal-link` only calls `sealDelegationList` when the
|
||||
// third token `list` is present (`auth seal-link list`); bare `auth seal-link` mints a token.
|
||||
const UNREACHABLE_CLI_FORMS = new Set([
|
||||
"deploy requirements",
|
||||
"deploy list",
|
||||
"deploy status",
|
||||
"auth seal-link"
|
||||
]);
|
||||
|
||||
test("every CLI verb dispatching to a read-only tool is itself read-only", () => {
|
||||
test("every CLI verb dispatching to a read-only tool is itself read-only, and mutating tools are not read-only", () => {
|
||||
const files = readdirSync(join(import.meta.dir, "commands")).filter(
|
||||
(f) => f.endsWith(".ts") && !f.endsWith(".test.ts")
|
||||
);
|
||||
@@ -157,7 +171,8 @@ describe("CLI allow-list agrees with the tool registry", () => {
|
||||
for (const file of files) {
|
||||
const area = file.replace(/\.ts$/, "");
|
||||
const source = readFileSync(join(import.meta.dir, "commands", file), "utf8");
|
||||
const pattern = /action === "([a-z0-9-]+)"[\s\S]{0,600}?runCapability\(\s*"(seal[A-Z][A-Za-z0-9]*)"/g;
|
||||
const pattern =
|
||||
/if\s*\(\s*action === "([a-z0-9-]+)"(?:(?!\bif\s*\(\s*action\b)[\s\S]){0,600}?runCapability(?:Result)?\(\s*"(seal[A-Z][A-Za-z0-9]*)"/g;
|
||||
let match;
|
||||
while ((match = pattern.exec(source))) {
|
||||
pairs.push({ area, action: match[1]!, tool: match[2]! });
|
||||
@@ -165,7 +180,7 @@ describe("CLI allow-list agrees with the tool registry", () => {
|
||||
}
|
||||
|
||||
// If the dispatch shape changes this silently finds nothing, which would make the test vacuous.
|
||||
expect(pairs.length).toBeGreaterThan(50);
|
||||
expect(pairs.length).toBeGreaterThan(55);
|
||||
|
||||
const disagreements = pairs
|
||||
.filter((pair) => SEAL_READ_ONLY_CAPABILITIES.has(pair.tool))
|
||||
@@ -174,5 +189,12 @@ describe("CLI allow-list agrees with the tool registry", () => {
|
||||
.map((pair) => `${pair.area} ${pair.action} -> ${pair.tool}`);
|
||||
|
||||
expect(disagreements).toEqual([]);
|
||||
|
||||
const unsafeMutating = pairs
|
||||
.filter((pair) => SEAL_MUTATING_CAPABILITIES.has(pair.tool))
|
||||
.filter((pair) => isReadOnlyCliCommand([pair.area, pair.action]))
|
||||
.map((pair) => `${pair.area} ${pair.action} -> ${pair.tool}`);
|
||||
|
||||
expect(unsafeMutating).toEqual([]);
|
||||
});
|
||||
});
|
||||
+17
-2
@@ -37,6 +37,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
||||
"count",
|
||||
"export",
|
||||
"flow",
|
||||
"hose-flow",
|
||||
"list",
|
||||
// `search` is an accepted alias of `list` in the dispatcher but has no help-registry entry.
|
||||
"search",
|
||||
@@ -68,8 +69,8 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
||||
// read forms cannot be separated from the value-taking write forms. `config get` returns
|
||||
// the same summary (mode + lint included), so read access loses nothing.
|
||||
config: ["paths", "get"],
|
||||
auth: ["check", "diagnose", "status", "test", "doctor", "link list"],
|
||||
users: ["search", "get", "delegation"],
|
||||
auth: ["check", "diagnose", "status", "test", "doctor", "link list", "seal-link list"],
|
||||
users: ["search", "get"],
|
||||
contacts: ["departments", "children", "users", "sync-time"],
|
||||
data: ["expenses", "invoices"],
|
||||
llm: ["config", "providers"],
|
||||
@@ -126,7 +127,10 @@ export function describeCliCommand(argv: string[]): { area: string; actionTokens
|
||||
export function isReadOnlyCliCommand(argv: string[]): boolean {
|
||||
let area: string;
|
||||
let actionTokens: string[];
|
||||
let options: Record<string, unknown>;
|
||||
try {
|
||||
const parsed = parseArgs(argv);
|
||||
options = parsed.options;
|
||||
({ area, actionTokens } = describeCliCommand(argv));
|
||||
} catch {
|
||||
// Unparsable command lines are refused rather than guessed at.
|
||||
@@ -136,6 +140,17 @@ export function isReadOnlyCliCommand(argv: string[]): boolean {
|
||||
if (actionTokens.length === 0 && TOP_LEVEL_READ_ONLY.has(area)) return true;
|
||||
// The `<corpId>` selector form; the bare form falls through to the `""` entry.
|
||||
if (SELECTOR_POSITIONAL_AREAS.has(area) && actionTokens.length === 1) return true;
|
||||
// `rules push status` / `rules push --check` inspects the recovery journal and
|
||||
// reconciles against the remote draft without mutating anything.
|
||||
if (
|
||||
area === "rules" &&
|
||||
actionTokens[0] === "push" &&
|
||||
(actionTokens[1] === "status" || options.check === true || options.status === "true") &&
|
||||
!options.yes &&
|
||||
!options.confirm
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const allowed = READ_ONLY_COMMANDS[area];
|
||||
if (!allowed) return false;
|
||||
|
||||
Reference in new issue
Block a user