Harden post-write error codes, rules push recovery ledger, and capability param normalization

This commit is contained in:
gitea committed 2026-10-13 11:48:37 +08:00
1 parent 75017ab49c
commit 586ad521dc
17 files changed
+1102 -197

No files matched your search

+3 -1
View File
@@ -57,6 +57,7 @@ seal-use rules lint [--file <path>] [--linter <name|path>] [--version <number|la
seal-use rules linters [--corp <corpId>]
seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]
seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]
seal-use rules push status [--file <path>] [--corp <corpId>]
seal-use rules clear [--dry-run|--yes] [--corp <corpId>]
seal-use rules recode [--dry-run] --corp <corpId>
seal-use rules map [--version <number|latest>] [--code <code>] [--corp <corpId>]
@@ -302,7 +303,8 @@ Approval rule maintenance:
- `seal-use rules lint [--file <path>] [--linter <name|path>] [--version <number|latest>] [--code <code>] [--min-score <score>] [--level all|error|warning] [--summary] [--corp <corpId>]`
- `seal-use rules linters [--corp <corpId>]` (lists official and custom linters with directory specs: custom in `~/.config/seal-use/linters` and official in `~/.cache/seal-use/linters/official`)
- `seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]`
- `seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Run `--dry-run` first; a local file exported with `rules pull` is preferred.
- `seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Live execution persists a per-step recovery ledger (`status`: `not_started`, `partial`, `completed`, `uncertain`) and hydrates newly created IDs so an interrupted run can be inspected and resumed without duplicating rules.
- `seal-use rules push status [--file <path>] [--corp <corpId>]` (or `--check`) inspects the last push recovery ledger and reconciles remaining diff against the live draft without mutating state.
- `seal-use rules clear [--dry-run|--yes] [--corp <corpId>]`
- `seal-use rules recode [--dry-run] --corp <corpId>`: first returns an unexecuted numbering preview and a one-use credential (exit 10). Inspect the preview, then invoke the returned `nextCommand` separately. The credential is enterprise/environment/draft-bound, valid for five minutes, and cannot be replaced by `--yes`/`--confirm`. `--dry-run` only previews (exit 0). Recode does not publish; failed/uncertain executions require a draft read before another request. Do not script both phases into automatic consecutive execution.
- `seal-use rules map [--version <number|latest>] [--code <code>] [--corp <corpId>]` (reads local sync rule mapping snapshot)
+40 -12
View File
@@ -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(
+5 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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);
}
+29 -7
View File
@@ -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
View File
@@ -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;
+3 -1
View File
@@ -56,8 +56,10 @@ const USAGE_PREFIX =
// 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`.
// Deliberately excludes generic recovery verbs like "请先"/"请重试" so post-write
// or upstream failures that offer recovery advice stay at exit `1`.
const CN_USAGE =
/(?:请通过|请指定|参数提供|需要提供|必须提供|缺少合思凭证|模式需要提供|参数。|为必填项|不能使用|无法用于|必须包含|必须为|顶层必须|格式错误|格式不合法|不支持的|未知的|无效的|请改用|请使用|请提供|请重试|请先)/;
/(?:请通过|请指定|参数提供|需要提供|必须提供|缺少合思凭证|模式需要提供|参数。|为必填项|不能使用|无法用于|必须包含|必须为|顶层必须|格式错误|格式不合法|不支持的|未知的|无效的|请改用|请使用 --|请提供)/;
// Enterprise-selection failures: the caller must pass --corp or fix config. Exit `13`.
const CORP_SELECTION =
+4 -7
View File
@@ -27,6 +27,7 @@ import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
import type { LocalRuleItem } from "../rules/local.js";
import { loadRuleMappingSnapshot } from "../rules/mapping.js";
import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js";
import { validationError } from "../../../core/errors.js";
export type CapabilityContext = {
corp: CorpConfig;
@@ -169,21 +170,17 @@ export function buildRulePushPlan(
if (localRule.id) {
remoteRule = remoteById.get(localRule.id);
if (!remoteRule) {
throw new Error(
`本地规则 ${localRule.id} 不存在于当前草稿。请先用 rules pull 获取当前草稿,再重新应用修改。`
);
throw validationError(`本地规则 ${localRule.id} 不存在于当前草稿。请先用 rules pull 获取当前草稿,再重新应用修改。`);
}
if (usedRemoteIds.has(localRule.id)) {
throw new Error(`本地规则文件包含重复的规则 ID:${localRule.id}`);
throw validationError(`本地规则文件包含重复的规则 ID:${localRule.id}`);
}
} else {
const matches = remoteRules.filter(
(candidate) => !usedRemoteIds.has(candidate.id) && rulesHaveSameContent(candidate, localRule)
);
if (matches.length > 1) {
throw new Error(
`本地规则“${localRule.description}”无法唯一匹配远端草稿,请在规则文件中补充稳定的 id。`
);
throw validationError(`本地规则“${localRule.description}”无法唯一匹配远端草稿,请在规则文件中补充稳定的 id。`);
}
remoteRule = matches[0];
}
+7 -108
View File
@@ -2,6 +2,7 @@ import { z } from "zod";
import type { KyInstance } from "ky";
import * as api from "../api.js";
import { recodeRules, type RecodeOptions } from "../rules/recode.js";
import { executeRulePush } from "../rules/push.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import { loadGlobalConfig } from "../../../core/config/loader.js";
import { validationError } from "../../../core/errors.js";
@@ -17,8 +18,7 @@ import {
type LocalRuleItem
} from "../rules/local.js";
import {
type ApprovalRule,
type RuleSetVersion
type ApprovalRule
} from "../types.js";
import type {
CapabilityContext,
@@ -28,8 +28,6 @@ import * as helpers from "./helpers.js";
const {
projectApprovalRules,
buildRulePushPlan,
normalizeRuleStrictness,
mutationPreview,
summarizeRuleVersion,
resolveRuleVersionForLookup,
@@ -656,13 +654,14 @@ export const rulesCapabilities = [
},
{
name: "sealApprovalRulesPush",
description: "将本地规则文件增量同步到远端草稿;按规则 ID 更新/删除并保留未变更规则,支持直接发布为正式版本",
description: "将本地规则文件增量同步到远端草稿;支持持久化步骤恢复记录、状态核对(--status)与直接发布正式版本",
parameters: z.object({
file: z.string().optional().describe("要推送的本地规则文件路径,默认为 ./rules.local.json"),
dryRun: z.boolean().optional().describe("是否仅预览变更而不实际写入远端(默认 true,传 --yes 或 confirm: true 执行写入)"),
confirm: z.boolean().optional().describe("确认覆盖写入远端草稿"),
publish: z.boolean().optional().describe("写入草稿后是否直接发布为一个正式版本"),
versionName: z.string().optional().describe("发布版本的名称(仅在 publish=true 时有效)")
versionName: z.string().optional().describe("发布版本的名称(仅在 publish=true 时有效)"),
statusOnly: z.boolean().optional().describe("仅查询最近一次 rules push 的持久化步骤记录并与远端草稿核对,不执行写入")
}),
handler: async (
client: KyInstance,
@@ -672,110 +671,10 @@ export const rulesCapabilities = [
confirm?: boolean;
publish?: boolean;
versionName?: string;
statusOnly?: boolean;
},
context: CapabilityContext
) => {
const filePath = params.file ?? "./rules.local.json";
let local: ReturnType<typeof loadLocalRulesFile>;
try {
local = loadLocalRulesFile(filePath);
} catch (err) {
if (params.publish && !params.file) {
const suggestedName = params.versionName ?? "新版本";
throw new Error(
`${err instanceof Error ? err.message : String(err)}\n👉 Next action: 若您已直接修改远端草稿、仅需发布正式版本,请执行 seal-use rules publish "${suggestedName}" --corp ${context.corp.id}`
);
}
throw err;
}
const isConfirmed = params.confirm === true;
// Fail closed: without an explicit confirm the push always previews, even when dryRun=false.
const isDryRun = !isConfirmed || params.dryRun === true;
const before = await api.listApprovalRules(client);
const plan = buildRulePushPlan(before.rules, local.rules);
if (isDryRun) {
return {
...mutationPreview(
context,
"api/v1/rules",
before.rules,
local.rules.map((rule) => ({
description: rule.description,
scope: rule.scope ?? "ALL",
strictness: rule.strictness ?? "MUST_FOLLOW"
})),
before.rules.length + local.rules.length
),
corpId: context.corp.id,
dryRun: true,
localFile: local.resolvedPath,
localRulesCount: local.rules.length,
remoteDraftCount: before.rules.length,
changes: plan,
impactCount: plan.created.length + plan.updated.length + plan.deleted.length,
preservedRuleIds: [
...plan.updated.map((change) => change.id),
...plan.unchanged.map((rule) => rule.id)
],
warning: "Incremental mode preserves matched rule IDs and does not recode the draft rule set.",
willPublish: Boolean(params.publish),
message: "Preview mode. Use --yes or confirm=true to apply the listed incremental changes to the remote draft."
};
}
for (const rule of plan.deleted) {
await api.deleteApprovalRule(client, rule.id);
}
const created: Array<{ id: string; description: string; code?: string | number }> = [];
for (const rule of plan.created) {
const newRule = await api.createApprovalRule(client, {
description: rule.description,
scope: rule.scope ?? "ALL",
strictness: normalizeRuleStrictness(rule.strictness)
});
created.push({ id: newRule.id, description: newRule.description, code: newRule.code });
}
const updated: string[] = [];
for (const change of plan.updated) {
await api.updateApprovalRule(client, change.id, {
description: change.rule.description,
scope: change.rule.scope ?? "ALL",
strictness: normalizeRuleStrictness(change.rule.strictness)
});
updated.push(change.id);
}
let publishedVersion: unknown = undefined;
if (params.publish) {
const dateStr = formatBeijingIso().slice(0, 10).replace(/-/g, "");
const name = params.versionName || `v-local-${dateStr}-${Date.now().toString().slice(-4)}`;
publishedVersion = await api.publishApprovalRuleVersion(client, name);
try {
const draft = await api.listApprovalRules(client);
savePublishedRuleVersionSnapshot(context.corp.id, (publishedVersion as { version: RuleSetVersion }).version, draft.rules);
} catch {}
}
return {
corpId: context.corp.id,
dryRun: false,
localFile: local.resolvedPath,
deletedRules: plan.deleted.length,
createdRules: created.length,
updatedRules: updated.length,
unchangedRules: plan.unchanged.length,
preservedRuleIds: [
...updated,
...plan.unchanged.map((rule) => rule.id)
],
recoded: false,
published: publishedVersion ?? false
};
}
) => executeRulePush(client, params, context)
},
{
name: "sealApprovalDocumentsList",
+28 -23
View File
@@ -21,13 +21,11 @@ function rejectsWith(toolName: string, params: Record<string, unknown>): string
}
describe("parseCapabilityParams", () => {
test("accepts valid params and returns the exact object it was given", () => {
test("accepts valid params and returns normalized values without mutating caller input", () => {
const target = tool("sealUserCreate");
const params = { name: "张三", phone: "13800001111", departmentIds: ["d1"] };
// Identity matters: handlers read keys the schema does not declare, so the
// gate must pass its input through, never zod's (stripped) parse output.
expect(parseCapabilityParams(target, params)).toBe(params);
expect(parseCapabilityParams(target, params)).toEqual(params);
});
test("names the missing required field instead of letting the handler crash on undefined", () => {
@@ -42,14 +40,14 @@ describe("parseCapabilityParams", () => {
expect(message).toContain("limit");
});
test("coerces query-string values before checking, without touching the original", () => {
test("coerces query-string values and returns the coerced types without mutating the original", () => {
const target = tool("sealApprovalRunsSearch");
const params = { limit: "50", includeBridge: "true" } as Record<string, unknown>;
// /v1/* passes url.searchParams through: everything arrives as a string,
// but the schema declares z.number() / z.boolean(). Without coercion every
// REST route would 400 on its own documented query params.
expect(parseCapabilityParams(target, params)).toBe(params);
// but the schema declares z.number() / z.boolean(). Returning the coerced
// values ensures the handler receives the exact types the schema validated.
expect(parseCapabilityParams(target, params)).toEqual({ limit: 50, includeBridge: true });
expect(params.limit).toBe("50");
expect(params.includeBridge).toBe("true");
});
@@ -59,33 +57,40 @@ describe("parseCapabilityParams", () => {
expect(message).toContain("limit");
});
test("coerces a comma-separated query value into the array the schema wants", () => {
// `?fields=id,code` on /v1/approval/rules: today the handler receives a
// string and pickRuleFields iterates its characters, returning empty
// objects. Validation splits it so the documented form actually works.
test("coerces a comma-separated query value into the array the schema and handler want", () => {
// `?fields=id,code` on /v1/approval/rules: validation splits the string and
// hands the array to the handler so pickRuleFields iterates field names,
// not individual characters.
expect(parseCapabilityParams(tool("sealApprovalRulesList"), { fields: "id,code" })).toEqual({
fields: "id,code"
fields: ["id", "code"]
});
expect(rejectsWith("sealApprovalRulesList", { fields: "id,not-a-field" })).toContain("fields");
});
test("ignores undeclared keys rather than rejecting the request", () => {
// z.object is non-strict: an extra HTTP body key is a compatibility
// non-event, not an error. This gate checks declared params only.
test("preserves undeclared compatibility keys alongside normalized schema fields", () => {
// z.object is non-strict: an extra HTTP body key or legacy alias is kept
// while declared fields are coerced and defaulted.
const target = tool("sealApprovalRunsSearch");
expect(parseCapabilityParams(target, { status: "TERMINATED", corp: "corp-a", stray: 1 })).toBeTypeOf("object");
expect(parseCapabilityParams(target, { status: "TERMINATED", limit: "10", corp: "corp-a", stray: 1 })).toEqual({
status: "TERMINATED",
limit: 10,
corp: "corp-a",
stray: 1
});
});
test("lets the legacy credential aliases through to the handler that supports them", () => {
// sealDeployHosecloudConfigure has always accepted appKey/appSecurity
// alongside apiKey/apiSecret; a schema that declared only apiKey as
// required would have blocked that documented path.
expect(() =>
test("lets the legacy credential aliases through to the handler and populates schema defaults", () => {
expect(
parseCapabilityParams(tool("sealDeployHosecloudConfigure"), {
appKey: "key-1",
appSecurity: "secret-1",
mode: "assisted"
})
).not.toThrow();
).toEqual({
appKey: "key-1",
appSecurity: "secret-1",
mode: "assisted",
apiOrigin: "production"
});
});
});
+20 -21
View File
@@ -4,34 +4,33 @@ import type { SealCapability } from "./index.js";
/**
* Checks one invocation's params against the schema its tool declares, then
* returns the params unchanged.
* returns the normalized params (wire-format coercion + schema defaults applied,
* while preserving undeclared keys for legacy compatibility).
*
* Both dispatch paths — `runCapabilityResult` (every CLI command) and
* `executeSealCapability` (`POST /api/tool/:name`, every `/v1/*` route) — used to
* hand `params` straight to `handler`, so a required field could be missing, a
* limit could be `999999`, or a typo'd HTTP body key could sail through and
* surface later as an opaque upstream error or a `Cannot read properties of
* undefined`. The schema is now the gate, failing fast with the offending field
* path (exit `13` on the CLI, HTTP `400` behind the adapter).
* `executeSealCapability` — hand the returned object to `handler`, so the
* values that passed validation are the exact values the handler executes with.
*
* Two deliberate properties:
*
* - **Original params are returned, not `result.data`.** Handlers read keys the
* schema does not declare — `sealDeployHosecloudConfigure` accepts the
* legacy `appKey`/`appSecurity` aliases alongside `apiKey`/`apiSecret` — and
* zod's default strip would silently drop them. Validation must never change
* what a working handler receives, only block what would have failed anyway.
* - **Undeclared keys never fail.** `z.object` is non-strict, so an extra HTTP
* body key is ignored rather than rejected; this is a correctness check, not
* an API-compatibility verdict.
*
* Before rejecting, wire-format values are coerced to the shape the schema
* declares (see {@link coerceWireTypes}) because `/v1/*` query strings arrive
* entirely as strings while the schema says `z.number()`.
* - **Normalized declared keys + preserved undeclared keys.** Wire strings like
* `"50"`, `"true"`, or `"id,code"` are coerced to `50`, `true`, `["id", "code"]`
* and schema `.default(...)` values are filled in, while undeclared keys
* (such as legacy compatibility aliases) are kept rather than stripped.
* - **Caller input is not mutated in place.** A fresh object is returned.
*/
export function parseCapabilityParams(tool: SealCapability, params: Record<string, unknown>): Record<string, unknown> {
const result = tool.parameters.safeParse(coerceWireTypes(tool.parameters, params));
if (result.success) return params;
const coerced = coerceWireTypes(tool.parameters, params);
const result = tool.parameters.safeParse(coerced);
if (result.success) {
const parsedData =
result.data && typeof result.data === "object"
? Object.fromEntries(
Object.entries(result.data as Record<string, unknown>).filter(([, value]) => value !== undefined)
)
: {};
return { ...params, ...coerced, ...parsedData };
}
const detail = result.error.issues
.map((issue) => `${issue.path.length ? issue.path.join(".") : "(root)"}: ${issue.message}`)
+349
View File
@@ -0,0 +1,349 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../../core/config/types.js";
import { classifyCliError } from "../../../core/errors.js";
import { handleRulesCommand } from "../../../cli/commands/rules.js";
import { parseArgs } from "../../../cli/parser.js";
import type { ApprovalRule } from "../types.js";
import {
executeRulePush,
inspectRulePushStatus,
RulePushExecutionError,
RulePushJournalStore
} from "./push.js";
const ORIGINAL_JOURNAL = process.env.SEAL_USE_PUSH_JOURNAL;
const tempDirs: string[] = [];
afterEach(() => {
if (ORIGINAL_JOURNAL === undefined) delete process.env.SEAL_USE_PUSH_JOURNAL;
else process.env.SEAL_USE_PUSH_JOURNAL = ORIGINAL_JOURNAL;
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
function createPushFixture() {
const dir = mkdtempSync(join(tmpdir(), "seal-rules-push-"));
tempDirs.push(dir);
const journalPath = join(dir, "push-journal.json");
const localFilePath = join(dir, "rules.local.json");
process.env.SEAL_USE_PUSH_JOURNAL = journalPath;
const corp: CorpConfig = {
id: "push-corp",
name: "Push Test Corp",
environment: "test",
auth: { refreshTtl: 300 },
source: {
type: "seal",
token: "test-token",
sealUrl: "https://staging.sealai.cc",
expiresIn: 3600,
staffId: "seal"
},
seal: {
url: "https://staging.sealai.cc",
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
}
};
const remoteRules: ApprovalRule[] = [
{
id: "r-keep",
tenantId: "t1",
code: 0,
description: "Existing rule to update",
scope: "ALL",
strictness: "MUST_FOLLOW",
status: "ACTIVE"
},
{
id: "r-delete",
tenantId: "t1",
code: 1,
description: "Obsolete rule to delete",
scope: "ALL",
strictness: "SHOULD_FOLLOW",
status: "ACTIVE"
}
];
writeFileSync(
localFilePath,
JSON.stringify({
corpId: corp.id,
rules: [
{
id: "r-keep",
description: "Existing rule updated locally",
scope: "ALL",
strictness: "MUST_FOLLOW"
},
{
description: "New rule alpha",
scope: "travel",
strictness: "MUST_FOLLOW"
},
{
description: "New rule beta",
scope: "meal",
strictness: "SHOULD_FOLLOW"
}
]
})
);
let nextCreatedIdx = 1;
let failOnDeleteId: string | undefined;
let failOnCreateCall: number | undefined;
let failWithTimeout = false;
let applyBeforeTimeout = false;
let createCalls = 0;
const client = {
get: async (url: string) => {
if (url === "api/v1/rules") {
return Response.json({
data: { rules: structuredClone(remoteRules), hasPendingDeletes: false }
});
}
throw new Error(`Unexpected GET ${url}`);
},
delete: async (url: string) => {
const id = url.split("/").pop()!;
if (failOnDeleteId === id) {
const err = new Error(failWithTimeout ? "upstream timeout" : "Forbidden delete") as Error & {
response?: { status: number };
};
if (!failWithTimeout) err.response = { status: 400 };
throw err;
}
const idx = remoteRules.findIndex((rule) => rule.id === id);
if (idx >= 0) remoteRules.splice(idx, 1);
return Response.json({ data: { deleted: true } });
},
post: async (url: string, options?: { json?: Record<string, unknown> }) => {
if (url === "api/v1/rules") {
createCalls += 1;
const body = options?.json ?? {};
const createdRule: ApprovalRule = {
id: `r-new-${nextCreatedIdx++}`,
tenantId: "t1",
code: remoteRules.length,
description: String(body.description ?? ""),
scope: String(body.scope ?? "ALL"),
strictness: String(body.strictness ?? "MUST_FOLLOW"),
status: "DRAFT"
};
if (failOnCreateCall === createCalls) {
if (applyBeforeTimeout) {
remoteRules.push(createdRule);
}
const err = new Error(
failWithTimeout ? "socket hang up: request timed out" : "Duplicate rule rejected"
) as Error & { response?: { status: number } };
if (!failWithTimeout) err.response = { status: 422 };
throw err;
}
remoteRules.push(createdRule);
return Response.json({ data: createdRule });
}
throw new Error(`Unexpected POST ${url}`);
},
put: async (url: string, options?: { json?: Record<string, unknown> }) => {
const id = url.split("/").pop()!;
const target = remoteRules.find((rule) => rule.id === id);
if (!target) throw new Error(`Rule not found: ${id}`);
const body = options?.json ?? {};
if (typeof body.description === "string") target.description = body.description;
if (typeof body.scope === "string") target.scope = body.scope;
if (typeof body.strictness === "string") target.strictness = body.strictness;
return Response.json({ data: target });
}
} as unknown as KyInstance;
return {
corp,
client,
localFilePath,
journalPath,
remoteRules,
setFailOnDelete(id?: string, options?: { timeout?: boolean }) {
failOnDeleteId = id;
failWithTimeout = options?.timeout === true;
},
setFailOnCreate(callNumber?: number, options?: { timeout?: boolean; applyBeforeTimeout?: boolean }) {
failOnCreateCall = callNumber;
failWithTimeout = options?.timeout === true;
applyBeforeTimeout = options?.applyBeforeTimeout === true;
}
};
}
describe("rules push execution and recovery protocol", () => {
test("distinguishes not_started when the first write is rejected before any mutation", async () => {
const f = createPushFixture();
f.setFailOnDelete("r-delete");
try {
await executeRulePush(f.client, { file: f.localFilePath, confirm: true }, { corp: f.corp });
expect.unreachable();
} catch (error) {
expect(error).toBeInstanceOf(RulePushExecutionError);
const pushErr = error as RulePushExecutionError;
expect(classifyCliError(pushErr).exitCode).toBe(1);
expect(pushErr.journal.status).toBe("not_started");
expect(pushErr.recoveryPayload).toMatchObject({
status: "not_started",
executed: false,
deletedRules: 0,
createdRules: 0,
updatedRules: 0,
failedStep: {
stage: "delete",
targetId: "r-delete",
outcome: "failed"
}
});
}
const store = new RulePushJournalStore(f.journalPath);
expect(store.get(f.corp.id)?.status).toBe("not_started");
});
test("records partial completion, reconciles via status, and resumes idempotently without duplicating rules", async () => {
const f = createPushFixture();
// Delete succeeds, 1st create ("New rule alpha") succeeds, 2nd create ("New rule beta") fails with 422.
f.setFailOnCreate(2);
try {
await executeRulePush(f.client, { file: f.localFilePath, confirm: true }, { corp: f.corp });
expect.unreachable();
} catch (error) {
const pushErr = error as RulePushExecutionError;
expect(pushErr.journal.status).toBe("partial");
expect(pushErr.recoveryPayload).toMatchObject({
status: "partial",
executed: true,
deletedRules: 1,
createdRules: 1,
updatedRules: 0,
failedStep: {
stage: "create",
localIndex: 2,
description: "New rule beta",
outcome: "failed"
},
remaining: {
deleteIds: [],
createIndices: [2],
updateIds: ["r-keep"]
}
});
}
// Inspect status and reconcile against the live remote draft
const statusView = await inspectRulePushStatus(f.client, f.corp, f.localFilePath);
expect(statusView).toMatchObject({
corpId: f.corp.id,
status: "partial",
remoteDraftCount: 2,
reconciliation: {
verifiedDeletedIds: ["r-delete"],
stillPresentDeletedIds: [],
verifiedCreatedIds: ["r-new-1"],
missingCreatedIds: [],
remainingCounts: {
toDelete: 0,
toCreate: 1,
toUpdate: 1,
unchanged: 1
}
}
});
// Clear failure and resume: even if local file wasn't manually edited with r-new-1's ID,
// journal hydration binds r-new-1 to localIndex 1 so only "New rule beta" is created.
f.setFailOnCreate(undefined);
const resumed = await executeRulePush(
f.client,
{ file: f.localFilePath, confirm: true },
{ corp: f.corp }
);
expect(resumed).toMatchObject({
status: "completed",
deletedRules: 0,
createdRules: 1,
updatedRules: 1,
unchangedRules: 1
});
expect(f.remoteRules.map((r) => r.description)).toEqual([
"Existing rule updated locally",
"New rule alpha",
"New rule beta"
]);
});
test("marks timeout during mutation as uncertain and status resolves whether the server applied it", async () => {
const f = createPushFixture();
// Simulate a timeout on the 2nd create AFTER the server already committed the rule.
f.setFailOnCreate(2, { timeout: true, applyBeforeTimeout: true });
try {
await executeRulePush(f.client, { file: f.localFilePath, confirm: true }, { corp: f.corp });
expect.unreachable();
} catch (error) {
const pushErr = error as RulePushExecutionError;
expect(pushErr.journal.status).toBe("uncertain");
expect(pushErr.journal.failedStep).toMatchObject({
stage: "create",
description: "New rule beta",
outcome: "uncertain"
});
}
const statusView = await inspectRulePushStatus(f.client, f.corp, f.localFilePath);
expect(statusView.status).toBe("uncertain");
expect(statusView.reconciliation).toMatchObject({
uncertainStepResolution: "applied",
remainingCounts: {
toDelete: 0,
toCreate: 0,
toUpdate: 1,
unchanged: 2
}
});
});
test("CLI prints structured recovery JSON to stdout before throwing exit 1 on partial failure", async () => {
const f = createPushFixture();
f.setFailOnCreate(2);
const lines: string[] = [];
const originalLog = console.log;
console.log = (...values: unknown[]) => {
lines.push(values.map(String).join(" "));
};
try {
const args = parseArgs(["rules", "push", "--file", f.localFilePath, "--corp", f.corp.id, "--yes"]);
await expect(
handleRulesCommand("push", undefined, f.client, f.corp, args)
).rejects.toMatchObject({ exitCode: 1 });
const payload = JSON.parse(lines.join("\n"));
expect(payload).toMatchObject({
corpId: f.corp.id,
status: "partial",
executed: true,
deletedRules: 1,
createdRules: 1
});
expect(payload.nextCommand).toContain("rules push status");
} finally {
console.log = originalLog;
}
});
});
+533
View File
@@ -0,0 +1,533 @@
import { randomBytes } from "node:crypto";
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import type { KyInstance } from "ky";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { CliError } from "../../../core/errors.js";
import { SEAL_STATE_DIR } from "../../../core/paths.js";
import { redactSensitiveText } from "../../../core/redact.js";
import * as api from "../api.js";
import {
buildRulePushPlan,
mutationPreview,
normalizeRuleStrictness,
type CapabilityContext,
type RulePushPlan
} from "../capabilities/helpers.js";
import type { ApprovalRule, RuleSetVersion } from "../types.js";
import { loadLocalRulesFile, type LocalRuleItem } from "./local.js";
import { savePublishedRuleVersionSnapshot } from "./version-snapshot.js";
export type RulePushStatus = "preview" | "not_started" | "partial" | "completed" | "uncertain";
export type RulePushFailedStep = {
stage: "delete" | "create" | "update" | "publish";
targetId?: string;
localIndex?: number;
description?: string;
outcome: "failed" | "uncertain";
error: string;
};
export type RulePushCreatedRecord = {
localIndex: number;
id: string;
code?: string | number;
description: string;
scope: string;
strictness: string;
};
export type RulePushJournalEntry = {
operationId: string;
corpId: string;
localFile: string;
startedAt: string;
updatedAt: string;
status: Exclude<RulePushStatus, "preview">;
planned: {
deleteIds: string[];
createIndices: number[];
updateIds: string[];
publish: boolean;
};
completed: {
deletedIds: string[];
created: RulePushCreatedRecord[];
updatedIds: string[];
published: unknown;
};
failedStep?: RulePushFailedStep;
remaining: {
deleteIds: string[];
createIndices: number[];
updateIds: string[];
publish: boolean;
};
};
export class RulePushExecutionError extends CliError {
readonly journal: RulePushJournalEntry;
readonly recoveryPayload: Record<string, unknown>;
constructor(journal: RulePushJournalEntry, corpId: string) {
const quotedCorp = `'${corpId.replace(/'/g, "'\\''")}'`;
const nextAction = `seal-use rules push status --corp ${quotedCorp}`;
const label =
journal.status === "not_started"
? "未完成任何写入"
: journal.status === "uncertain"
? "存在结果不确定的写入请求"
: "仅完成部分写入";
super(
`rules push 中途失败(${label},阶段: ${journal.failedStep?.stage ?? "unknown"}):${journal.failedStep?.error ?? "未知错误"}`,
1,
nextAction
);
this.name = "RulePushExecutionError";
this.journal = journal;
this.recoveryPayload = {
corpId: journal.corpId,
dryRun: false,
executed:
journal.completed.deletedIds.length > 0 ||
journal.completed.created.length > 0 ||
journal.completed.updatedIds.length > 0 ||
Boolean(journal.completed.published),
status: journal.status,
operationId: journal.operationId,
localFile: journal.localFile,
deletedRules: journal.completed.deletedIds.length,
createdRules: journal.completed.created.length,
updatedRules: journal.completed.updatedIds.length,
completed: journal.completed,
failedStep: journal.failedStep,
remaining: journal.remaining,
nextCommand: nextAction
};
}
}
export class RulePushJournalStore {
constructor(
private readonly path = process.env.SEAL_USE_PUSH_JOURNAL?.trim() ||
join(SEAL_STATE_DIR, "rules-push-journal.json")
) {}
private readAll(): Record<string, RulePushJournalEntry> {
if (!existsSync(this.path)) return {};
try {
const parsed = JSON.parse(readFileSync(this.path, "utf8"));
return parsed && typeof parsed === "object" ? (parsed as Record<string, RulePushJournalEntry>) : {};
} catch {
return {};
}
}
get(corpId: string): RulePushJournalEntry | undefined {
return this.readAll()[corpId];
}
save(entry: RulePushJournalEntry): void {
mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
const all = this.readAll();
all[entry.corpId] = entry;
writeFileSync(this.path, `${JSON.stringify(all, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
try {
chmodSync(this.path, 0o600);
} catch {}
}
}
function isUncertainMutationError(error: unknown): boolean {
if (error && typeof error === "object" && "response" in error) {
const response = (error as { response?: { status?: unknown } }).response;
const status = typeof response?.status === "number" ? response.status : undefined;
if (status !== undefined) {
if (status >= 400 && status < 500) return false;
if (status === 502 || status === 503 || status === 504) return true;
}
}
const message = error instanceof Error ? error.message : String(error);
return /(?:timeout|timed out|hang up|econnreset|etimedout|network|fetch failed|aborted|502|503|504)/i.test(
message
);
}
/**
* Hydrates local rules with IDs recorded during a prior partial/uncertain push
* on the same file when those rule IDs now exist in the remote draft. This
* allows a retry of `rules push` to recognize rules it already created without
* duplicating them or failing on duplicate descriptions.
*/
export function hydrateLocalRulesFromJournal(
localRules: LocalRuleItem[],
resolvedPath: string,
remoteRules: ApprovalRule[],
journal?: RulePushJournalEntry
): LocalRuleItem[] {
if (!journal || journal.localFile !== resolvedPath) return localRules;
if (journal.status !== "partial" && journal.status !== "uncertain") return localRules;
if (!journal.completed.created.length) return localRules;
const remoteById = new Map(remoteRules.map((rule) => [rule.id, rule]));
const usedIds = new Set(localRules.map((rule) => rule.id).filter((id): id is string => Boolean(id)));
const cloned = localRules.map((rule) => ({ ...rule }));
for (const record of journal.completed.created) {
if (usedIds.has(record.id)) continue;
const remote = remoteById.get(record.id);
if (!remote) continue;
const candidate = cloned[record.localIndex];
if (candidate && !candidate.id) {
candidate.id = record.id;
usedIds.add(record.id);
}
}
return cloned;
}
export async function inspectRulePushStatus(
client: KyInstance,
corp: CorpConfig,
filePath = "./rules.local.json"
) {
const store = new RulePushJournalStore();
const lastOperation = store.get(corp.id) ?? null;
const remote = await api.listApprovalRules(client);
const remoteById = new Map(remote.rules.map((rule) => [rule.id, rule]));
const targetFile = lastOperation?.localFile ?? filePath;
let local: ReturnType<typeof loadLocalRulesFile> | undefined;
let remainingPlan: RulePushPlan | undefined;
try {
local = loadLocalRulesFile(targetFile);
const hydrated = hydrateLocalRulesFromJournal(
local.rules,
local.resolvedPath,
remote.rules,
lastOperation ?? undefined
);
remainingPlan = buildRulePushPlan(remote.rules, hydrated);
} catch {
// Local file may have been moved or may need manual fix; still report remote vs journal reconciliation.
}
let reconciliation: Record<string, unknown> | null = null;
if (lastOperation) {
const verifiedDeletedIds = lastOperation.completed.deletedIds.filter((id) => !remoteById.has(id));
const stillPresentDeletedIds = lastOperation.completed.deletedIds.filter((id) => remoteById.has(id));
const verifiedCreatedIds = lastOperation.completed.created
.map((item) => item.id)
.filter((id) => remoteById.has(id));
const missingCreatedIds = lastOperation.completed.created
.map((item) => item.id)
.filter((id) => !remoteById.has(id));
let uncertainStepResolution: "applied" | "not_applied" | "unknown" | undefined;
if (lastOperation.failedStep?.outcome === "uncertain") {
const step = lastOperation.failedStep;
if (step.stage === "delete" && step.targetId) {
uncertainStepResolution = remoteById.has(step.targetId) ? "not_applied" : "applied";
} else if (step.stage === "update" && step.targetId && local && step.localIndex !== undefined) {
const remoteRule = remoteById.get(step.targetId);
const localRule = local.rules[step.localIndex];
if (remoteRule && localRule) {
uncertainStepResolution =
remoteRule.description === localRule.description.trim() &&
remoteRule.scope === (localRule.scope ?? "ALL") &&
remoteRule.strictness === normalizeRuleStrictness(localRule.strictness)
? "applied"
: "not_applied";
} else {
uncertainStepResolution = "unknown";
}
} else if (step.stage === "create" && step.description) {
const matched = remote.rules.some((rule) => rule.description === step.description);
uncertainStepResolution = matched ? "applied" : "not_applied";
} else {
uncertainStepResolution = "unknown";
}
}
reconciliation = {
verifiedDeletedIds,
stillPresentDeletedIds,
verifiedCreatedIds,
missingCreatedIds,
...(uncertainStepResolution ? { uncertainStepResolution } : {}),
...(remainingPlan
? {
remainingCounts: {
toDelete: remainingPlan.deleted.length,
toCreate: remainingPlan.created.length,
toUpdate: remainingPlan.updated.length,
unchanged: remainingPlan.unchanged.length
}
}
: {})
};
}
return {
corpId: corp.id,
status: lastOperation?.status ?? ("not_started" as const),
remoteDraftCount: remote.rules.length,
lastOperation,
reconciliation
};
}
export async function executeRulePush(
client: KyInstance,
params: {
file?: string;
dryRun?: boolean;
confirm?: boolean;
publish?: boolean;
versionName?: string;
statusOnly?: boolean;
},
context: CapabilityContext
) {
if (params.statusOnly) {
return inspectRulePushStatus(client, context.corp, params.file);
}
const filePath = params.file ?? "./rules.local.json";
let local: ReturnType<typeof loadLocalRulesFile>;
try {
local = loadLocalRulesFile(filePath);
} catch (err) {
if (params.publish && !params.file) {
const suggestedName = params.versionName ?? "新版本";
throw new Error(
`${err instanceof Error ? err.message : String(err)}\n👉 Next action: 若您已直接修改远端草稿、仅需发布正式版本,请执行 seal-use rules publish "${suggestedName}" --corp ${context.corp.id}`
);
}
throw err;
}
const isConfirmed = params.confirm === true;
// Fail closed: without an explicit confirm the push always previews, even when dryRun=false.
const isDryRun = !isConfirmed || params.dryRun === true;
const store = new RulePushJournalStore();
const previousJournal = store.get(context.corp.id);
const before = await api.listApprovalRules(client);
const effectiveLocalRules = hydrateLocalRulesFromJournal(
local.rules,
local.resolvedPath,
before.rules,
previousJournal
);
const plan = buildRulePushPlan(before.rules, effectiveLocalRules);
if (isDryRun) {
return {
...mutationPreview(
context,
"api/v1/rules",
before.rules,
effectiveLocalRules.map((rule) => ({
description: rule.description,
scope: rule.scope ?? "ALL",
strictness: rule.strictness ?? "MUST_FOLLOW"
})),
before.rules.length + effectiveLocalRules.length
),
corpId: context.corp.id,
dryRun: true,
status: "preview" as const,
localFile: local.resolvedPath,
localRulesCount: effectiveLocalRules.length,
remoteDraftCount: before.rules.length,
changes: plan,
impactCount: plan.created.length + plan.updated.length + plan.deleted.length,
preservedRuleIds: [
...plan.updated.map((change) => change.id),
...plan.unchanged.map((rule) => rule.id)
],
warning: "Incremental mode preserves matched rule IDs and does not recode the draft rule set.",
willPublish: Boolean(params.publish),
message: "Preview mode. Use --yes or confirm=true to apply the listed incremental changes to the remote draft."
};
}
// Map each planned creation back to its index in effectiveLocalRules so the
// recovery journal can bind the newly created remote ID on resume.
const createdLocalIndices: number[] = [];
const usedLocalIndices = new Set<number>();
for (const createdRule of plan.created) {
const idx = effectiveLocalRules.findIndex(
(candidate, index) => !usedLocalIndices.has(index) && candidate === createdRule
);
const resolvedIdx = idx >= 0 ? idx : createdLocalIndices.length;
usedLocalIndices.add(resolvedIdx);
createdLocalIndices.push(resolvedIdx);
}
const startedAt = formatBeijingIso();
const journal: RulePushJournalEntry = {
operationId: `push-${Date.now()}-${randomBytes(3).toString("hex")}`,
corpId: context.corp.id,
localFile: local.resolvedPath,
startedAt,
updatedAt: startedAt,
status: "not_started",
planned: {
deleteIds: plan.deleted.map((rule) => rule.id),
createIndices: [...createdLocalIndices],
updateIds: plan.updated.map((change) => change.id),
publish: Boolean(params.publish)
},
completed: {
deletedIds: [],
created: [],
updatedIds: [],
published: false
},
remaining: {
deleteIds: plan.deleted.map((rule) => rule.id),
createIndices: [...createdLocalIndices],
updateIds: plan.updated.map((change) => change.id),
publish: Boolean(params.publish)
}
};
store.save(journal);
const failStep = (
stage: RulePushFailedStep["stage"],
error: unknown,
meta: { targetId?: string; localIndex?: number; description?: string } = {}
): never => {
const outcome = isUncertainMutationError(error) ? "uncertain" : "failed";
const completedCount =
journal.completed.deletedIds.length +
journal.completed.created.length +
journal.completed.updatedIds.length +
(journal.completed.published ? 1 : 0);
journal.status =
outcome === "uncertain"
? "uncertain"
: completedCount === 0
? "not_started"
: "partial";
journal.updatedAt = formatBeijingIso();
journal.failedStep = {
stage,
...meta,
outcome,
error: redactSensitiveText(error instanceof Error ? error.message : String(error))
};
store.save(journal);
throw new RulePushExecutionError(journal, context.corp.id);
};
for (const rule of plan.deleted) {
try {
await api.deleteApprovalRule(client, rule.id);
journal.completed.deletedIds.push(rule.id);
journal.remaining.deleteIds = journal.remaining.deleteIds.filter((id) => id !== rule.id);
journal.status = "partial";
journal.updatedAt = formatBeijingIso();
store.save(journal);
} catch (error) {
failStep("delete", error, { targetId: rule.id, description: rule.description });
}
}
for (let i = 0; i < plan.created.length; i++) {
const rule = plan.created[i]!;
const localIndex = createdLocalIndices[i] ?? i;
const scope = rule.scope ?? "ALL";
const strictness = normalizeRuleStrictness(rule.strictness);
try {
const newRule = await api.createApprovalRule(client, {
description: rule.description,
scope,
strictness
});
journal.completed.created.push({
localIndex,
id: newRule.id,
code: newRule.code,
description: newRule.description,
scope,
strictness
});
journal.remaining.createIndices = journal.remaining.createIndices.filter((idx) => idx !== localIndex);
journal.status = "partial";
journal.updatedAt = formatBeijingIso();
store.save(journal);
} catch (error) {
failStep("create", error, { localIndex, description: rule.description });
}
}
for (const change of plan.updated) {
const localIndex = effectiveLocalRules.indexOf(change.rule);
try {
await api.updateApprovalRule(client, change.id, {
description: change.rule.description,
scope: change.rule.scope ?? "ALL",
strictness: normalizeRuleStrictness(change.rule.strictness)
});
journal.completed.updatedIds.push(change.id);
journal.remaining.updateIds = journal.remaining.updateIds.filter((id) => id !== change.id);
journal.status = "partial";
journal.updatedAt = formatBeijingIso();
store.save(journal);
} catch (error) {
failStep("update", error, {
targetId: change.id,
...(localIndex >= 0 ? { localIndex } : {}),
description: change.rule.description
});
}
}
let publishedVersion: unknown = undefined;
if (params.publish) {
const dateStr = formatBeijingIso().slice(0, 10).replace(/-/g, "");
const name = params.versionName || `v-local-${dateStr}-${Date.now().toString().slice(-4)}`;
try {
publishedVersion = await api.publishApprovalRuleVersion(client, name);
journal.completed.published = publishedVersion;
journal.remaining.publish = false;
} catch (error) {
failStep("publish", error, { description: name });
}
try {
const draft = await api.listApprovalRules(client);
savePublishedRuleVersionSnapshot(
context.corp.id,
(publishedVersion as { version: RuleSetVersion }).version,
draft.rules
);
} catch {}
}
journal.status = "completed";
journal.updatedAt = formatBeijingIso();
store.save(journal);
return {
corpId: context.corp.id,
dryRun: false,
status: "completed" as const,
operationId: journal.operationId,
localFile: local.resolvedPath,
deletedRules: plan.deleted.length,
createdRules: journal.completed.created.length,
updatedRules: journal.completed.updatedIds.length,
unchangedRules: plan.unchanged.length,
preservedRuleIds: [
...journal.completed.updatedIds,
...plan.unchanged.map((rule) => rule.id)
],
recoded: false,
published: publishedVersion ?? false
};
}
+34 -2
View File
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os"
import { join } from "node:path"
import type { KyInstance } from "ky"
import type { CorpConfig } from "../../../core/config/types.js"
import { classifyCliError } from "../../../core/errors.js"
import { recodeRules } from "./recode.js"
import { recodeApprovalRules } from "../api.js"
import type { ApprovalRulesData } from "../types.js"
@@ -140,12 +141,43 @@ describe("two-phase rules recode", () => {
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(1)
})
test("readback detects a concurrent content change after the POST", async () => {
test("readback detects a concurrent content change after the POST and classifies as exit 1 (never 13)", async () => {
const f = fixture()
const code = await ticket(f)
await Bun.sleep(510)
f.corruptReadback()
await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow("回读规则与预览不一致")
try {
await recodeRules(f.client, f.corp, { confirmCode: code })
expect.unreachable()
} catch (error) {
expect((error as Error).message).toContain("回读规则与预览不一致")
expect(classifyCliError(error)).toEqual({
exitCode: 1,
nextAction: "seal-use rules list --corp 'recode-test' --summary"
})
}
})
test("backend contract: handles server placing newly created DRAFT rules ahead of older ACTIVE rules", async () => {
const f = fixture()
f.state.rules = [
{ id: "active-old", tenantId: "tenant-a", code: 2, description: "Existing active rule", scope: "ALL", strictness: "MUST_FOLLOW", status: "ACTIVE", updatedAt: 100 },
{ id: "draft-new", tenantId: "tenant-a", code: 9, description: "New draft rule placed first by server", scope: "ALL", strictness: "SHOULD_FOLLOW", status: "DRAFT", updatedAt: 200 }
]
const code = await ticket(f)
f.reorderOnServer()
await Bun.sleep(510)
const result = await recodeRules(f.client, f.corp, { confirmCode: code })
expect(result).toMatchObject({
executed: true,
phase: "executed",
mappingAvailable: true,
impactCount: 2,
changes: [
{ beforeCode: "0002", afterCode: "0001" },
{ beforeCode: "0009", afterCode: "0000" }
]
})
})
test("legacy auto-recode refuses a nonempty draft", async () => {
+7 -3
View File
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto"
import type { KyInstance } from "ky"
import type { CorpConfig } from "../../../core/config/types.js"
import { formatBeijingIso } from "../../../core/config/timestamps.js"
import { validationError } from "../../../core/errors.js"
import { CliError, validationError } from "../../../core/errors.js"
import * as api from "../api.js"
import { ApprovalRulesDataSchema, type ApprovalRule, type ApprovalRulesData } from "../types.js"
import { RecodeTicketStore } from "./recode-tickets.js"
@@ -76,9 +76,9 @@ export async function recodeRules(client: KyInstance, corp: CorpConfig, options:
const target = JSON.stringify(["rules-recode", corp.id, new URL(baseUrl).href, corp.environment, me.tenant.id])
const tickets = new RecodeTicketStore()
const draftFingerprint = fingerprint(before)
const quotedCorp = `'${corp.id.replace(/'/g, "'\\''")}'`
if (options.confirmCode === undefined) {
const ticket = tickets.issue(target, draftFingerprint)
const quotedCorp = `'${corp.id.replace(/'/g, "'\\''")}'`
return {
...preview,
phase: "confirmation_required" as const,
@@ -100,7 +100,11 @@ export async function recodeRules(client: KyInstance, corp: CorpConfig, options:
const actual = byId.get(rule.id)
return !actual || !sameContent(rule, actual)
})) {
throw new Error("重排请求已发送,但回读规则与预览不一致。请先核对当前草稿,勿重复执行旧确认码。")
throw new CliError(
"重排请求已发送,但回读规则与预览不一致。请先核对当前草稿,勿重复执行旧确认码。",
1,
`seal-use rules list --corp ${quotedCorp} --summary`
)
}
const changes = rules.map(rule => ({ beforeCode: codeLabel(codeNumber(rule)), afterCode: codeLabel(codeNumber(byId.get(rule.id)!)) }))
return {
+4 -3
View File
@@ -172,9 +172,10 @@ export function startServer(): StdioServerHandle {
export { tokenizeCommand };
function cliResult(result: { stdout: string; stderr: string; isError: boolean; exitCode: number }): CallToolResult {
// Confirmation-required commands can carry a structured, unexecuted preview.
// Preserve it for MCP consumers instead of returning only the next-step prose.
if (result.exitCode === 10 && result.stdout) {
// Confirmation-required (exit 10) or partially-executed write commands (exit 1)
// can emit a structured JSON payload on stdout alongside stderr guidance.
// Preserve both for MCP consumers instead of returning only the prose.
if (result.isError && result.stdout) {
return {
content: [
{ type: "text", text: result.stdout },