Release v0.10.39: Standardize 0-based 00xx rule codes, draft-default rules CLI, and documents domain

This commit is contained in:
gitea committed 2026-09-28 11:49:31 +08:00
1 parent f8e083f3b2
commit 69fe2415a1
33 files changed
+1377 -777

No files matched your search

+20 -4
View File
@@ -97,12 +97,28 @@ describe("CLI version & help handling", () => {
expect(JSON.parse(result.stdout)).toMatchObject({ id: "corp-a" });
});
test("keeps the fine-grained tool command reachable in stateless mode", () => {
test("keeps the documents domain reachable in stateless mode", () => {
const env = makeConfigEnv();
const result = runCli(["tool", "unknown-tool", "--corp", "corp-a"], env);
const result = runCli(["documents", "get", "--corp", "corp-a"], env);
expect(result.status).toBe(1);
expect(result.stderr).toContain("Unknown Seal tool: unknown-tool");
expect(result.status).toBe(2);
expect(result.stderr).toContain("Usage: seal-use documents get <documentId>");
});
test("requires --yes confirmation on documents delete", () => {
const env = makeConfigEnv();
const result = runCli(["documents", "delete", "doc-123", "--corp", "corp-a"], env);
expect(result.status).toBe(10);
expect(result.stderr).toContain("Refusing to delete document 'doc-123' without --yes.");
});
test("does not hijack --version option when passed to subcommands like rules", () => {
const env = makeConfigEnv();
const result = runCli(["rules", "get", "--version", "latest", "--corp", "corp-a"], env);
expect(result.status).toBe(2);
expect(result.stderr).toContain("Usage: seal-use rules get <code>");
});
test("can enable stateful mode and select a default corp", () => {
+234
View File
@@ -0,0 +1,234 @@
import { readFileSync } from "node:fs";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { confirmationRequired } from "../errors.js";
import { runTool } from "../helpers.js";
import {
booleanOption,
jsonObject,
numberOption,
splitOption,
stringOption
} from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
function readContentInput(args: ParsedArgs, payload: Record<string, unknown>): string | undefined {
const filePath =
stringOption(args.options.contentFile) ??
stringOption(args.options["content-file"]) ??
stringOption(args.options.file) ??
stringOption(args.options.f);
if (filePath) {
return readFileSync(filePath, "utf8");
}
const direct = stringOption(args.options.content);
if (direct !== undefined) return direct;
return typeof payload.content === "string" ? payload.content : undefined;
}
export async function handleDocumentsCommand(
action: string | undefined,
maybeName: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (!action || action === "list") {
const scenarios = splitOption(args.options.scenarios);
const limit = numberOption(args.options.limit);
const offset = numberOption(args.options.offset);
await runTool(
"seal_approval_documents_list",
client,
corp,
{ scenarios, limit, offset },
outputOptions(args.options)
);
return;
}
if (action === "get") {
const documentId =
(maybeName && !maybeName.startsWith("-") ? maybeName : undefined) ??
stringOption(args.options.documentId) ??
stringOption(args.options["document-id"]) ??
stringOption(args.options.id);
if (!documentId) {
throw new Error("Usage: seal-use documents get <documentId> [--corp <corpId>]");
}
await runTool(
"seal_approval_document_get",
client,
corp,
{ documentId },
outputOptions(args.options)
);
return;
}
if (action === "search") {
const keyword = maybeName ?? stringOption(args.options.query);
if (!keyword) {
throw new Error("Usage: seal-use documents search <keyword> [--maxResults 20] [--corp <corpId>]");
}
await runTool(
"seal_approval_search",
client,
corp,
{
keywords: [keyword],
areas: ["documents"],
maxResults: numberOption(args.options.maxResults),
contextLines: numberOption(args.options.contextLines),
refresh: booleanOption(args.options.refresh),
snippetOnly: booleanOption(args.options.snippetOnly) ?? booleanOption(args.options["snippet-only"]),
maxChars: numberOption(args.options.maxChars) ?? numberOption(args.options["max-chars"]),
fields: splitOption(args.options.fields)
},
outputOptions(args.options)
);
return;
}
if (action === "create") {
const payload = jsonObject(args.json);
const title = stringOption(args.options.title) ?? (typeof payload.title === "string" ? payload.title : undefined);
const purpose = stringOption(args.options.purpose) ?? (typeof payload.purpose === "string" ? payload.purpose : undefined);
const content = readContentInput(args, payload);
const contentType =
stringOption(args.options.type) ??
stringOption(args.options.contentType) ??
stringOption(args.options["content-type"]) ??
(typeof payload.contentType === "string" ? payload.contentType : "policy");
const status =
stringOption(args.options.status) ??
(typeof payload.status === "string" ? payload.status : "published");
const enabled =
booleanOption(args.options.enabled) ??
(typeof payload.enabled === "boolean" ? payload.enabled : undefined);
const scenarios =
splitOption(args.options.scenarios) ??
(Array.isArray(payload.scenarios) ? (payload.scenarios as string[]) : ["audit"]);
const tags =
splitOption(args.options.tags) ??
(Array.isArray(payload.tags) ? (payload.tags as string[]) : undefined);
if (!title || !purpose || content === undefined) {
throw new Error(
"Usage: seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"
);
}
await runTool(
"seal_approval_document_create",
client,
corp,
{
title,
purpose,
content,
contentType,
status,
enabled,
scenarios,
tags
},
outputOptions(args.options)
);
return;
}
if (action === "update") {
const payload = jsonObject(args.json);
const documentId =
(maybeName && !maybeName.startsWith("-") ? maybeName : undefined) ??
stringOption(args.options.documentId) ??
stringOption(args.options["document-id"]) ??
stringOption(args.options.id) ??
(typeof payload.documentId === "string" ? payload.documentId : undefined);
const title = stringOption(args.options.title) ?? (typeof payload.title === "string" ? payload.title : undefined);
const purpose = stringOption(args.options.purpose) ?? (typeof payload.purpose === "string" ? payload.purpose : undefined);
const content = readContentInput(args, payload);
const contentType =
stringOption(args.options.type) ??
stringOption(args.options.contentType) ??
stringOption(args.options["content-type"]) ??
(typeof payload.contentType === "string" ? payload.contentType : undefined);
const status =
stringOption(args.options.status) ??
(typeof payload.status === "string" ? payload.status : undefined);
const enabled =
booleanOption(args.options.enabled) ??
(typeof payload.enabled === "boolean" ? payload.enabled : undefined);
const scenarios =
splitOption(args.options.scenarios) ??
(Array.isArray(payload.scenarios) ? (payload.scenarios as string[]) : undefined);
const tags =
splitOption(args.options.tags) ??
(Array.isArray(payload.tags) ? (payload.tags as string[]) : undefined);
const hasChanges =
title !== undefined ||
purpose !== undefined ||
content !== undefined ||
contentType !== undefined ||
status !== undefined ||
enabled !== undefined ||
scenarios !== undefined ||
tags !== undefined;
if (!documentId || !hasChanges) {
throw new Error(
"Usage: seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"
);
}
await runTool(
"seal_approval_document_update",
client,
corp,
{
documentId,
title,
purpose,
content,
contentType,
status,
enabled,
scenarios,
tags
},
outputOptions(args.options)
);
return;
}
if (action === "delete") {
const documentId =
(maybeName && !maybeName.startsWith("-") ? maybeName : undefined) ??
stringOption(args.options.documentId) ??
stringOption(args.options["document-id"]) ??
stringOption(args.options.id);
if (!documentId) {
throw new Error("Usage: seal-use documents delete <documentId> --yes [--corp <corpId>]");
}
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
throw confirmationRequired(
`Refusing to delete document '${documentId}' without --yes.`,
`seal-use documents delete ${documentId} --corp ${corp.id} --yes`
);
}
await runTool(
"seal_approval_delete_document",
client,
corp,
{ documentId },
outputOptions(args.options)
);
return;
}
throw new Error(`Unknown documents command: ${action}. Available: list, get, search, create, update, delete.`);
}
+146 -21
View File
@@ -1,3 +1,4 @@
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/rule-mapping.js";
@@ -10,6 +11,7 @@ import { runTool, runToolResult } from "../helpers.js";
import { confirmationRequired } from "../errors.js";
import {
booleanOption,
jsonObject,
numberOption,
parseRuleVersionSelector,
ruleVersionGetOptions,
@@ -25,6 +27,26 @@ import {
} from "../printer.js";
import type { ParsedArgs } from "../types.js";
function readDescriptionInput(args: ParsedArgs, payload: Record<string, unknown>): string | undefined {
const filePath =
stringOption(args.options.descriptionFile) ??
stringOption(args.options["description-file"]);
if (filePath) {
return readFileSync(filePath, "utf8").trim();
}
const direct = stringOption(args.options.description) ?? stringOption(args.options.desc);
if (direct !== undefined) return direct;
return typeof payload.description === "string" ? payload.description : undefined;
}
function resolveVersionOption(args: ParsedArgs, fallback?: string): string | undefined {
const explicit = stringOption(args.options.version);
if (explicit !== undefined) return explicit;
if (booleanOption(args.options.latest)) return "latest";
if ( fallback !== undefined && !fallback.startsWith("-") ) return fallback;
return undefined;
}
export async function handleRulesCommand(
action: string | undefined,
maybeName: string | undefined,
@@ -39,13 +61,15 @@ export async function handleRulesCommand(
}
if (action === "count") {
await runTool("seal_approval_rules_list", client!, corp, { countOnly: true }, outputOptions(args.options));
const version = resolveVersionOption(args);
await runTool("seal_approval_rules_list", client!, corp, { version, countOnly: true }, outputOptions(args.options));
return;
}
if (action === "list") {
const version = resolveVersionOption(args);
if (booleanOption(args.options.count)) {
await runTool("seal_approval_rules_list", client!, corp, { countOnly: true }, outputOptions(args.options));
await runTool("seal_approval_rules_list", client!, corp, { version, countOnly: true }, outputOptions(args.options));
return;
}
@@ -57,6 +81,7 @@ export async function handleRulesCommand(
client!,
corp,
{
version,
fields: RULE_SUMMARY_FIELDS,
limit,
offset
@@ -66,7 +91,7 @@ export async function handleRulesCommand(
return;
}
const result = await runToolResult("seal_approval_rules_list", client!, corp, { limit, offset });
const result = await runToolResult("seal_approval_rules_list", client!, corp, { version, limit, offset });
const output = outputOptions(args.options);
protectLargeRuleListOutput(result, output.allowFull === true || Boolean(output.outputFile));
printJson(result, output);
@@ -106,8 +131,8 @@ export async function handleRulesCommand(
}
if (action === "version") {
const version = maybeName ?? stringOption(args.options.version);
if (!version) throw new Error("Usage: seal-use rules version <versionId|versionNumber|latest>");
const version = resolveVersionOption(args, maybeName);
if (!version) throw new Error("Usage: seal-use rules version <versionNumber|latest>");
await runTool(
"seal_approval_rule_version_get",
client!,
@@ -118,11 +143,11 @@ export async function handleRulesCommand(
return;
}
if (action === "diff" || action === "diff-one" || action === "rule-diff") {
if (action === "diff") {
const from = stringOption(args.options.from) ?? maybeName;
const to = stringOption(args.options.to) ?? args.command[3];
if (!from || !to) {
throw new Error("Usage: seal-use rules diff <fromVersion> <toVersion> [--rule-id <stableRuleId>|--code <code>] [--full]");
throw new Error("Usage: seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--full]");
}
const singleSelector = args.command[4];
await runTool(
@@ -132,8 +157,8 @@ export async function handleRulesCommand(
{
from,
to,
ruleId: stringOption(args.options.ruleId) ?? stringOption(args.options["rule-id"]) ?? (action !== "diff" ? singleSelector : undefined),
code: stringOption(args.options.code),
ruleId: stringOption(args.options.ruleId) ?? stringOption(args.options["rule-id"]),
code: stringOption(args.options.code) ?? singleSelector,
includeUnchanged: booleanOption(args.options.includeUnchanged) ?? booleanOption(args.options["include-unchanged"]),
full: booleanOption(args.options.full),
format: stringOption(args.options.format)
@@ -144,16 +169,23 @@ export async function handleRulesCommand(
}
if (action === "get") {
const rawCode = stringOption(args.options.code) ?? (maybeName && !maybeName.startsWith("-") ? maybeName : undefined);
const code = rawCode ? (rawCode.startsWith("#") || rawCode.startsWith("rule-") ? rawCode : (rawCode.match(/^\d+$/) ? `#${rawCode.padStart(4, "0")}` : rawCode)) : undefined;
const target =
(maybeName && !maybeName.startsWith("-") ? maybeName : undefined) ??
stringOption(args.options.code) ??
stringOption(args.options.runtimeId) ??
stringOption(args.options["runtime-id"]) ??
stringOption(args.options.ruleId) ??
stringOption(args.options["rule-id"]);
if (!target) {
throw new Error("Usage: seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>] [--corp <corpId>]");
}
await runTool(
"seal_approval_rule_get",
client!,
corp,
{
...ruleVersionGetOptions(stringOption(args.options.version)),
code,
runtimeId: stringOption(args.options.runtimeId) ?? stringOption(args.options["runtime-id"]) ?? (maybeName?.startsWith("rule-") ? maybeName : undefined),
...ruleVersionGetOptions(resolveVersionOption(args)),
code: target,
recordId: stringOption(args.options.recordId) ?? stringOption(args.options["record-id"])
},
outputOptions(args.options)
@@ -161,9 +193,102 @@ export async function handleRulesCommand(
return;
}
if (action === "create") {
const payload = jsonObject(args.json);
const description = readDescriptionInput(args, payload);
const scope = stringOption(args.options.scope) ?? (typeof payload.scope === "string" ? payload.scope : undefined);
const strictness =
stringOption(args.options.strictness) ??
(typeof payload.strictness === "string" ? payload.strictness : "MUST_FOLLOW");
if (!description || !scope) {
throw new Error("Usage: seal-use rules create --description <text> --scope <scope> [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--description-file <path>] [--corp <corpId>]");
}
await runTool(
"seal_approval_rule_create",
client!,
corp,
{ description, scope, strictness },
outputOptions(args.options)
);
return;
}
if (action === "update") {
const payload = jsonObject(args.json);
const ruleId =
(maybeName && !maybeName.startsWith("-") ? maybeName : undefined) ??
stringOption(args.options.ruleId) ??
stringOption(args.options["rule-id"]) ??
stringOption(args.options.code) ??
(typeof payload.ruleId === "string" ? payload.ruleId : undefined);
const description = readDescriptionInput(args, payload);
const scope = stringOption(args.options.scope) ?? (typeof payload.scope === "string" ? payload.scope : undefined);
const strictness =
stringOption(args.options.strictness) ??
(typeof payload.strictness === "string" ? payload.strictness : undefined);
if (!ruleId || (description === undefined && scope === undefined && strictness === undefined)) {
throw new Error("Usage: seal-use rules update <code> [--description <text>|--description-file <path>] [--scope <scope>] [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--corp <corpId>]");
}
await runTool(
"seal_approval_rule_update",
client!,
corp,
{ ruleId, description, scope, strictness },
outputOptions(args.options)
);
return;
}
if (action === "delete") {
const ruleId =
(maybeName && !maybeName.startsWith("-") ? maybeName : undefined) ??
stringOption(args.options.ruleId) ??
stringOption(args.options["rule-id"]) ??
stringOption(args.options.code);
if (!ruleId) {
throw new Error("Usage: seal-use rules delete <code> --yes [--corp <corpId>]");
}
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
throw confirmationRequired(
`Refusing to delete rule '${ruleId}' without --yes.`,
`seal-use rules delete ${ruleId} --corp ${corp.id} --yes`
);
}
await runTool(
"seal_approval_rule_delete",
client!,
corp,
{ ruleId },
outputOptions(args.options)
);
return;
}
if (action === "publish") {
const payload = jsonObject(args.json);
const versionName =
(maybeName && !maybeName.startsWith("-") ? maybeName : undefined) ??
stringOption(args.options.versionName) ??
stringOption(args.options["version-name"]) ??
stringOption(args.options.name) ??
(typeof payload.versionName === "string" ? payload.versionName : undefined);
if (!versionName) {
throw new Error("Usage: seal-use rules publish <versionName> [--corp <corpId>]");
}
await runTool(
"seal_approval_rule_version_publish",
client!,
corp,
{ versionName },
outputOptions(args.options)
);
return;
}
if (action === "search") {
const keyword = maybeName ?? stringOption(args.options.query);
if (!keyword) throw new Error("Usage: seal-use rules search <keyword> [--version <versionId|versionNumber|latest>]");
if (!keyword) throw new Error("Usage: seal-use rules search <keyword> [--version <number|latest>] [--maxResults 20] [--corp <corpId>]");
await runTool(
"seal_approval_search",
client!,
@@ -177,7 +302,7 @@ export async function handleRulesCommand(
snippetOnly: booleanOption(args.options.snippetOnly) ?? booleanOption(args.options["snippet-only"]),
maxChars: numberOption(args.options.maxChars) ?? numberOption(args.options["max-chars"]),
fields: splitOption(args.options.fields),
...ruleVersionSearchOptions(stringOption(args.options.version))
...ruleVersionSearchOptions(resolveVersionOption(args))
},
outputOptions(args.options)
);
@@ -185,7 +310,7 @@ export async function handleRulesCommand(
}
if (action === "pull") {
const version = stringOption(args.options.version) ?? maybeName;
const version = resolveVersionOption(args, maybeName);
const out = stringOption(args.options.out) ?? stringOption(args.options.file) ?? stringOption(args.options.f);
await runTool(
"seal_approval_rules_pull",
@@ -249,9 +374,9 @@ export async function handleRulesCommand(
{
file: stringOption(args.options.file) ?? stringOption(args.options.f),
linter: stringOption(args.options.linter),
version: stringOption(args.options.version),
version: resolveVersionOption(args),
code: stringOption(args.options.code),
ruleId: stringOption(args.options.rule) ?? maybeName,
ruleId: stringOption(args.options.rule) ?? (maybeName && !maybeName.startsWith("-") ? maybeName : undefined),
minScore: numberOption(args.options.minScore) ?? numberOption(args.options["min-score"]),
level: stringOption(args.options.level),
summary: booleanOption(args.options.summary)
@@ -273,7 +398,7 @@ export async function handleRulesCommand(
}
if (action === "map") {
const versionSelector = stringOption(args.options.version) ?? maybeName;
const versionSelector = resolveVersionOption(args, maybeName);
const code = stringOption(args.options.code) ?? stringOption(args.options.rule);
const snapshot = loadRuleMappingSnapshot(corp.id, versionSelector);
if (!snapshot) {
@@ -300,5 +425,5 @@ export async function handleRulesCommand(
return;
}
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, clear, versions, version, diff, get, search, lint, linters, pull, push, map. Run 'seal-use help' for available commands.`);
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, get, search, create, update, delete, publish, versions, version, diff, lint, linters, pull, push, clear, map. Run 'seal-use help' for available commands.`);
}
-16
View File
@@ -1,16 +0,0 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { jsonObject } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleToolCommand(
action: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (!action) throw new Error("Usage: seal-use tool <toolName> [--json '{...}']");
await runTool(action, client, corp, jsonObject(args.json), outputOptions(args.options));
}
-6
View File
@@ -1,6 +0,0 @@
import { sealTools } from "../../domains/seal/tools.js";
import { printJson } from "../printer.js";
export function handleToolsListCommand() {
printJson(sealTools.map((tool) => ({ name: tool.name, description: tool.description })));
}
+84 -55
View File
@@ -253,18 +253,19 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
area: "rules",
title: "Approval rules management",
description: "Query, search, version, lint, import, and export approval audit rules.",
description: "Query, search, edit, publish, version, lint, import, and export approval audit rules. Read commands default to the current draft; pass --version latest (or --version <number>) to inspect published versions.",
commands: [
{
name: "count",
summary: "Count total rules in current enterprise",
usage: ["seal-use rules count [--corp <corpId>]"]
summary: "Count approval rules (defaults to current draft; pass --version latest for latest published version)",
usage: ["seal-use rules count [--version <number|latest>] [--corp <corpId>]"]
},
{
name: "list",
summary: "List approval rules with optional pagination and summary",
usage: ["seal-use rules list [--summary] [--count] [--limit 20] [--offset 0] [--output-file <path>] [--corp <corpId>]"],
summary: "List approval rules (defaults to current draft; pass --version latest for latest published version)",
usage: ["seal-use rules list [--version <number|latest>] [--summary] [--limit 20] [--offset 0] [--output-file <path>] [--corp <corpId>]"],
options: [
{ flag: "--version <number|latest>", description: "Read from a published version instead of current draft ('latest' for latest published version)" },
{ flag: "--summary", description: "Output compact summary fields (code, status, strictness, scope, updatedAt)" },
{ flag: "--limit <n>", description: "Number of rules to fetch (default: 20)" },
{ flag: "--offset <n>", description: "Offset index for pagination" },
@@ -273,9 +274,36 @@ export const HELP_REGISTRY: AreaHelp[] = [
]
},
{
name: "clear",
summary: "Clear all draft rules from enterprise",
usage: ["seal-use rules clear [--corp <corpId>] [--dry-run|--yes]"]
name: "get",
summary: "Get single rule by code (defaults to current draft; pass --version latest or --record-id for published snapshots)",
usage: [
"seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>] [--corp <corpId>]"
]
},
{
name: "search",
summary: "Search rules by keyword (defaults to current draft; pass --version latest for latest published version)",
usage: ["seal-use rules search <keyword> [--version <number|latest>] [--maxResults 20] [--corp <corpId>]"]
},
{
name: "create",
summary: "Create a new draft approval rule",
usage: ["seal-use rules create --description <text> --scope <scope> [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--description-file <path>] [--corp <corpId>]"]
},
{
name: "update",
summary: "Update a draft approval rule by code",
usage: ["seal-use rules update <code> [--description <text>|--description-file <path>] [--scope <scope>] [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--corp <corpId>]"]
},
{
name: "delete",
summary: "Delete a draft approval rule by code",
usage: ["seal-use rules delete <code> --yes [--corp <corpId>]"]
},
{
name: "publish",
summary: "Publish current draft rules as a new formal version",
usage: ["seal-use rules publish <versionName> [--corp <corpId>]"]
},
{
name: "versions",
@@ -284,45 +312,24 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "version",
summary: "Inspect a specific rule version",
usage: ["seal-use rules version <versionId|versionNumber|latest> [--corp <corpId>]"]
summary: "Inspect a specific published rule version",
usage: ["seal-use rules version <versionNumber|latest> [--corp <corpId>]"]
},
{
name: "diff",
summary: "Compare two published rule versions by persisted ID or code",
usage: ["seal-use rules diff <fromVersion> <toVersion> [--rule-id <stableRuleId>|--code <code>] [--include-unchanged] [--full] [--corp <corpId>]"],
summary: "Compare two published rule versions",
usage: ["seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--include-unchanged] [--full] [--corp <corpId>]"],
options: [
{ flag: "--rule-id <id>", description: "Compare only one stable rule ID" },
{ flag: "--code <code>", description: "Compare only one rule code when stable ID mapping is unavailable" },
{ flag: "--code <code>", description: "Compare only one rule code" },
{ flag: "--include-unchanged", description: "Include unchanged rules in the structured changes list" },
{ flag: "--full", description: "Expand an oversized diff; small diffs are returned in full by default" },
{ flag: "--format unified|json", description: "Return unified diff text together with structured metadata" }
],
description: "Uses locally persisted draft IDs when available and otherwise falls back to code. Output is truncated only when the total diff exceeds the safety limit; use --full to expand it."
},
{
name: "diff-one",
summary: "Inspect one rule change",
usage: ["seal-use rules diff-one <fromVersion> <toVersion> <ruleId> [--full] [--corp <corpId>]"],
description: "Single-rule alias for rules diff; use --code when the published snapshots have no stable ID."
},
{
name: "get",
summary: "Get single rule by rule code or record ID",
usage: [
"seal-use rules get <ruleCode> [--version <number|latest>] [--corp <corpId>]",
"seal-use rules get --record-id <recordId> --runtime-id rule-205 [--corp <corpId>]"
]
},
{
name: "search",
summary: "Search rules by keyword",
usage: ["seal-use rules search <keyword> [--version <versionId|versionNumber|latest>] [--maxResults 20] [--corp <corpId>]"]
},
{
name: "lint",
summary: "Lint rule text or rule file using builtin or custom linter",
usage: ["seal-use rules lint [--file <path>] [--linter <name|path>] [--version <id|num|latest>] [--code <code>] [--rule <ruleId>] [--min-score <score>] [--level all|error|warning] [--summary] [--corp <corpId>]"]
usage: ["seal-use rules lint [--file <path>] [--linter <name|path>] [--version <number|latest>] [--code <code>] [--min-score <score>] [--level all|error|warning] [--summary] [--corp <corpId>]"]
},
{
name: "linters",
@@ -332,17 +339,22 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
name: "pull",
summary: "Export rules to local JSON file",
usage: ["seal-use rules pull [--version <id|num|latest>] [--out <file>] [--corp <corpId>]"]
usage: ["seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]"]
},
{
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>]"]
usage: ["seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]"]
},
{
name: "clear",
summary: "Clear all draft rules from enterprise",
usage: ["seal-use rules clear [--dry-run|--yes] [--corp <corpId>]"]
},
{
name: "map",
summary: "Inspect locally synced production/test rule code mappings",
usage: ["seal-use rules map [--version <id|num|latest>] [--code <code>] [--corp <corpId>]"]
usage: ["seal-use rules map [--version <number|latest>] [--code <code>] [--corp <corpId>]"]
}
]
},
@@ -1038,26 +1050,43 @@ export const HELP_REGISTRY: AreaHelp[] = [
]
},
{
area: "tool",
title: "Direct low-level tool invocation",
description: "Execute individual Seal tools directly.",
commands: [
{
name: "",
summary: "Invoke a tool directly",
usage: ["seal-use tool <toolName> [--corp <corpId>] [--json '{\"key\":\"value\"}']"]
}
]
},
{
area: "tools",
title: "Available tools listing",
description: "List all executable domain tools.",
area: "documents",
title: "Approval knowledge documents",
description: "List, inspect, search, create, update, and delete approval knowledge articles and policy documents.",
commands: [
{
name: "list",
summary: "List all available domain tools",
usage: ["seal-use tools list"]
summary: "List approval knowledge documents",
usage: ["seal-use documents list [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]"]
},
{
name: "get",
summary: "Get approval knowledge document details by ID",
usage: ["seal-use documents get <documentId> [--corp <corpId>]"]
},
{
name: "search",
summary: "Search approval knowledge documents by keyword",
usage: ["seal-use documents search <keyword> [--maxResults 20] [--corp <corpId>]"]
},
{
name: "create",
summary: "Create a new approval knowledge document",
usage: [
"seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"
]
},
{
name: "update",
summary: "Update an approval knowledge document by ID",
usage: [
"seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"
]
},
{
name: "delete",
summary: "Delete an approval knowledge document by ID",
usage: ["seal-use documents delete <documentId> --yes [--corp <corpId>]"]
}
]
},
+10 -14
View File
@@ -53,6 +53,9 @@ describe("CLI read-only classification", () => {
["corps", "list"],
["corp", "list"],
["corp", "get", "corp-a"],
["documents", "list", "--corp", "corp-a"],
["documents", "get", "doc-1", "--corp", "corp-a"],
["documents", "search", "差旅", "--corp", "corp-a"],
["approval-runs", "get", "01a09dac-c688-767b-8eb4-37b945095585"],
["approval-runs", "list", "--corp", "corp-a"],
["deploy", "hosecloud", "status", "--corp", "corp-a"],
@@ -72,8 +75,15 @@ describe("CLI read-only classification", () => {
["corps", "switch", "corp-a"],
["corps", "extract-keys", "corp-a"],
["corps", "sync-test", "corp-a"],
["rules", "create"],
["rules", "update", "25"],
["rules", "delete", "25"],
["rules", "publish", "v1"],
["rules", "push"],
["rules", "clear"],
["documents", "create"],
["documents", "update", "doc-1"],
["documents", "delete", "doc-1"],
["simulation", "create", "--mode", "hosecloud"],
["deploy", "hosecloud", "sync", "sign-key"],
["deploy", "hosecloud", "configure"],
@@ -92,9 +102,6 @@ describe("CLI read-only classification", () => {
["auth", "keys"],
["analytics", "analyze", "record-1"],
["tool", "seal_approval_rule_create", "--json", "{}"],
["tool", "seal_webhook_delete", "--json", "{}"],
["tool", "seal_insight_record_analyze", "--json", "{}"],
["tool"],
["totally-unknown", "list"],
[]
]) {
@@ -102,17 +109,6 @@ describe("CLI read-only classification", () => {
}
});
test("routes `seal-use tool` through the tool registry's own classification", () => {
for (const command of [
["tool", "seal_approval_search", "--json", "{}"],
["tool", "seal_approval_rules_list", "--corp", "corp-a"],
["tool", "seal_whoami"],
["tool", "seal_approval_run_flow_get", "--json", '{"sn":"B26002352"}']
]) {
expect({ command, readOnly: isReadOnlyCliCommand(command) }).toEqual({ command, readOnly: true });
}
});
test("matches whole tokens, so a read prefix cannot smuggle a mutation", () => {
for (const command of [
["corps", "listing"],
+2 -10
View File
@@ -1,4 +1,3 @@
import { isReadOnlySealTool } from "../domains/seal/tools.js";
import { parseArgs } from "./parser.js";
/**
@@ -29,7 +28,8 @@ const AREA_ALIASES: Record<string, string> = {
*/
const READ_ONLY_COMMANDS: Record<string, string[]> = {
corps: ["list", "search", "get", "current"],
rules: ["count", "list", "versions", "version", "diff", "diff-one", "get", "search", "lint", "linters", "pull", "map"],
rules: ["count", "list", "versions", "version", "diff", "get", "search", "lint", "linters", "pull", "map"],
documents: ["list", "get", "search"],
webhook: ["ready", "status", "list", "get", "resource-pack export", "resource-pack preview"],
"approval-runs": [
"summary",
@@ -78,7 +78,6 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
// mutation despite reading like a query. See SEAL_MUTATING_TOOLS.
analytics: ["insight", "risks", "performance", "export"],
source: ["config"],
tools: ["list"],
skill: ["dump", "status"],
service: ["status", "logs"],
doctor: ["", "guide", "paths", "tenant", "auth"],
@@ -112,13 +111,6 @@ export function isReadOnlyCliCommand(argv: string[]): boolean {
if (actionTokens.length === 0 && TOP_LEVEL_READ_ONLY.has(area)) return true;
// `seal-use tool <name>` reaches the internal tool registry, which carries its own exhaustive
// read/write classification. Delegating to it keeps the two from drifting apart.
if (area === "tool") {
const toolName = actionTokens[0];
return toolName !== undefined && isReadOnlySealTool(toolName);
}
const allowed = READ_ONLY_COMMANDS[area];
if (!allowed) return false;
+8 -17
View File
@@ -16,6 +16,7 @@ import { handleContextCommand } from "./commands/context.js";
import { handleCorpsCommand } from "./commands/corps.js";
import { handleDeployCommand } from "./commands/deploy.js";
import { handleDoctorCommand } from "./commands/doctor.js";
import { handleDocumentsCommand } from "./commands/documents.js";
import { handleHttpCommand } from "./commands/http.js";
import { handleLlmCommand } from "./commands/llm.js";
import { handleMcpCommand, printMcpConfig } from "./commands/mcp.js";
@@ -29,8 +30,6 @@ import { handleSimulationCommand } from "./commands/simulation.js";
import { handleSkillCommand } from "./commands/skill.js";
import { handleSourceCommand } from "./commands/source.js";
import { handleTestCommand } from "./commands/test.js";
import { handleToolCommand } from "./commands/tool.js";
import { handleToolsListCommand } from "./commands/tools.js";
import { handleUpdateCommand, isNewerVersion } from "./commands/update.js";
import { isUpdateCacheExpired, loadUpdateCache, triggerBackgroundUpdateCheck } from "../core/update-cache.js";
import { handleUsersCommand } from "./commands/users.js";
@@ -74,10 +73,8 @@ export const KNOWN_AREAS = new Set([
"http",
"serve",
"update",
"tools",
"corps",
"corp",
"tool",
"source",
"auth",
"users",
@@ -89,6 +86,7 @@ export const KNOWN_AREAS = new Set([
"webhook",
"webhooks",
"context",
"documents",
"rules",
"approval-runs",
"analytics",
@@ -189,9 +187,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
if (
area === "version" ||
area === "v" ||
Boolean(args.options.version) ||
Boolean(args.options.v) ||
Boolean(args.options.V)
(!area && (Boolean(args.options.version) || Boolean(args.options.v) || Boolean(args.options.V)))
) {
const cache = loadUpdateCache();
const isUpgrade = cache?.latestVersion ? isNewerVersion(cache.latestVersion, VERSION_INFO.version) : false;
@@ -335,11 +331,6 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "tools" && action === "list") {
handleToolsListCommand();
return;
}
if (area === "corps" || area === "corp") {
if (action === "regression" || action === "test-regression") {
await handleTestCommand("regression", maybeName, args);
@@ -435,6 +426,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "documents") {
await handleDocumentsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "rules") {
await handleRulesCommand(action, maybeName, client, corp, args);
return;
@@ -465,10 +461,5 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "tool") {
await handleToolCommand(action, client, corp, args);
return;
}
throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
}
+14 -6
View File
@@ -83,20 +83,28 @@ export function loadRuleMappingSnapshot(
}
}
function stripLeadingZeros(val: string): string {
return val.replace(/^0+(?=\d)/, "");
}
export function filterRuleMapping(
mapping: RuleMappingItem[],
codeOrId?: string
): RuleMappingItem[] {
if (!codeOrId) return mapping;
const target = codeOrId.trim().toLowerCase();
const target = stripLeadingZeros(codeOrId.trim().toLowerCase().replace(/^#/, ""));
return mapping.filter((item) => {
const srcCode = String(item.sourceRuleCode).toLowerCase().replace(/^#/, "");
const tgtCode = String(item.targetRuleCode).toLowerCase().replace(/^#/, "");
const tgtShort = stripLeadingZeros(tgtCode.replace(/^rule-/, ""));
const srcShort = stripLeadingZeros(srcCode.replace(/^rule-/, ""));
return (
String(item.sourceRuleCode).toLowerCase() === target ||
String(item.targetRuleCode).toLowerCase() === target ||
srcCode === target ||
tgtCode === target ||
srcShort === target ||
tgtShort === target ||
item.sourceRuleId.toLowerCase() === target ||
item.targetRuleId.toLowerCase() === target ||
`#${item.sourceRuleCode}`.toLowerCase() === target ||
`#${item.targetRuleCode}`.toLowerCase() === target
item.targetRuleId.toLowerCase() === target
);
});
}
+8 -8
View File
@@ -46,7 +46,7 @@ describe("rules-local workspace", () => {
const parsed = parseLocalRulesContent(raw);
expect(parsed.rules.length).toBe(1);
expect(parsed.rules[0]!.description).toBe("打车必须备注起止地点");
expect(parsed.rules[0]!.code).toBe(1);
expect(parsed.rules[0]!.code).toBe(0);
});
test("rejects invalid format or empty description", () => {
@@ -79,15 +79,15 @@ describe("rules-local workspace", () => {
test("converts local rules to lint targets", () => {
const targets = localRulesToLintTargets([
{ code: 1, description: "规则一", name: "R1" },
{ code: "0002", description: "规则二" },
{ description: "规则三" }
{ code: 0, description: "规则零", name: "R0" },
{ code: "0001", description: "规则一" },
{ description: "规则二" }
]);
expect(targets[0]!.code).toBe("#0001");
expect(targets[0]!.name).toBe("R1");
expect(targets[1]!.code).toBe("#0002");
expect(targets[2]!.code).toBe("#0003");
expect(targets[0]!.code).toBe("0000");
expect(targets[0]!.name).toBe("R0");
expect(targets[1]!.code).toBe("0001");
expect(targets[2]!.code).toBe("0002");
});
});
+22 -9
View File
@@ -68,6 +68,15 @@ export function parseLocalRulesContent(rawText: string): {
throw new Error("本地规则文件格式错误: 顶层必须为规则数组或包含 'rules' 数组的对象");
}
function parseCodeNumber(value: unknown): number | undefined {
if (typeof value === "number" && Number.isInteger(value) && value >= 0) return value;
if (typeof value !== "string") return undefined;
const match = value.trim().match(/^(?:#|rule[-_:]?)?(\d+)$/i);
if (!match?.[1]) return undefined;
const num = Number(match[1]);
return Number.isInteger(num) && num >= 0 ? num : undefined;
}
function normalizeRuleItems(items: unknown[]): LocalRuleItem[] {
return items.map((item, idx) => {
if (!item || typeof item !== "object") {
@@ -79,10 +88,13 @@ function normalizeRuleItems(items: unknown[]): LocalRuleItem[] {
throw new Error(`第 ${idx + 1} 条规则缺少有效的 'description' (规则描述) 字段`);
}
const parsedCode = parseCodeNumber(r.code);
const code =
typeof r.code === "number" || typeof r.code === "string"
? r.code
: idx + 1;
parsedCode !== undefined
? parsedCode
: typeof r.code === "string" && r.code.trim()
? r.code.trim()
: idx;
return {
...r,
@@ -132,13 +144,14 @@ export function saveLocalRulesFile(
*/
export function localRulesToLintTargets(rules: LocalRuleItem[]): RuleLintTarget[] {
return rules.map((r, idx) => {
let codeStr: string | undefined;
if (typeof r.code === "number") {
codeStr = `#${String(r.code).padStart(4, "0")}`;
} else if (typeof r.code === "string") {
codeStr = r.code.startsWith("#") ? r.code : `#${r.code}`;
const parsedCode = parseCodeNumber(r.code);
let codeStr: string;
if (parsedCode !== undefined) {
codeStr = String(parsedCode).padStart(4, "0");
} else if (typeof r.code === "string" && r.code.trim()) {
codeStr = r.code.trim().replace(/^#/, "");
} else {
codeStr = `#${String(idx + 1).padStart(4, "0")}`;
codeStr = String(idx).padStart(4, "0");
}
return {
+35 -12
View File
@@ -92,6 +92,35 @@ export async function syncTestEnterprise(
};
if (options.dryRun || options.execute === false) {
const testSignatureSet = new Set(
testRules.rules.map((r) => JSON.stringify([r.description ?? "", r.scope ?? "", r.strictness ?? ""]))
);
const allSyncItems = prodRules.rules.map((rule, index) => {
const code = rule.code ?? index;
const sig = JSON.stringify([rule.description ?? "", rule.scope ?? "", rule.strictness ?? ""]);
const existingAtIndex = testRules.rules[index];
const isUnchanged =
(existingAtIndex &&
existingAtIndex.description === rule.description &&
existingAtIndex.scope === rule.scope &&
existingAtIndex.strictness === rule.strictness) ||
testSignatureSet.has(sig);
return {
index,
sourceRuleId: rule.id,
sourceRuleCode: code,
expectedTargetCode: `rule-${code}`,
description: rule.description,
scope: rule.scope,
strictness: rule.strictness,
unchanged: isUnchanged
};
});
const changedRules = allSyncItems
.filter((item) => !item.unchanged)
.map(({ unchanged, ...rest }) => rest);
const unchangedCount = allSyncItems.length - changedRules.length;
return {
dryRun: true as const,
source: {
@@ -118,15 +147,9 @@ export async function syncTestEnterprise(
targetExistingDraftRuleCount: testRules.rules.length,
toDeleteCount: testRules.rules.length,
toCreateCount: prodRules.rules.length,
rulesToSync: prodRules.rules.map((rule, index) => ({
index: index + 1,
sourceRuleId: rule.id,
sourceRuleCode: rule.code ?? index + 1,
expectedTargetCode: `rule-${index + 1}`,
description: rule.description,
scope: rule.scope,
strictness: rule.strictness
}))
unchangedCount,
changedCount: changedRules.length,
rulesToSync: changedRules
},
documentsPlan: {
sourceDocumentCount: prodDocs.length,
@@ -194,11 +217,11 @@ export async function syncTestEnterprise(
try { savePublishedRuleVersionSnapshot(testCorp.id, published.version, createdRules); } catch {}
const publishedRules = published.version.rules ?? [];
const ruleMapping = prodRules.rules.map((prodRule, index) => ({
index: index + 1,
index,
sourceRuleId: prodRule.id,
sourceRuleCode: prodRule.code ?? index + 1,
sourceRuleCode: prodRule.code ?? index,
targetRuleId: createdRules[index]?.id ?? "",
targetRuleCode: publishedRules[index]?.code ?? `rule-${index + 1}`,
targetRuleCode: publishedRules[index]?.code ?? `rule-${prodRule.code ?? index}`,
description: prodRule.description,
scope: prodRule.scope,
strictness: prodRule.strictness
+180 -5
View File
@@ -194,7 +194,7 @@ describe("sealTools", () => {
expect(result.rules).toEqual([
{
id: "rule-1",
code: "#0029",
code: "0029",
status: "active",
strictness: "MUST_FOLLOW",
scope: "travel"
@@ -590,8 +590,9 @@ describe("sealTools", () => {
expect(result.count).toBe(1);
expect(result.rules[0]).toMatchObject({
code: "0038",
runtimeRuleId: "rule-38",
ruleCode: "#0038",
ruleCode: "0038",
versionNumber: 16,
scope: "travel",
strictness: "MUST_FOLLOW",
@@ -847,17 +848,143 @@ describe("sealTools", () => {
const handler = tool!.handler as ToolHandler;
const result = await handler(
fakeRulesClient(),
{ versionNumber: 16, code: "#0044" },
{ versionNumber: 16, code: "44" },
fakeContext()
) as { ruleCode?: string; description?: string; versionNumber?: number };
) as { code?: number; ruleCode?: string; runtimeRuleId?: string; description?: string; versionNumber?: number };
expect(result).toMatchObject({
ruleCode: "#0044",
code: "0044",
ruleCode: "0044",
runtimeRuleId: "rule-44",
description: "Second published rule",
versionNumber: 16
});
});
test("approval rule get defaults to current draft and handles 0-based codes without +1 offset", async () => {
const tool = sealTools.find((item) => item.name === "seal_approval_rule_get");
expect(tool).toBeDefined();
const handler = tool!.handler as ToolHandler;
const client = fakeZeroBasedRulesClient();
// Draft lookup for code 0
const draftZero = await handler(client, { code: "0" }, fakeContext()) as Record<string, unknown>;
expect(draftZero).toMatchObject({
id: "uuid-0",
code: "0000",
ruleCode: "0000",
runtimeRuleId: "rule-0",
description: "Draft rule zero",
status: "active"
});
// Draft lookup for code 25 (sitting at array index 24 because code 12 was deleted)
const draft25 = await handler(client, { code: "25" }, fakeContext()) as Record<string, unknown>;
expect(draft25).toMatchObject({
id: "uuid-25",
code: "0025",
ruleCode: "0025",
runtimeRuleId: "rule-25",
description: "Draft rule twenty-five"
});
// Version lookup for code 0 and code 25 (never returns rule-24 when asking for 25)
const versionZero = await handler(client, { versionNumber: 9, code: "0000" }, fakeContext()) as Record<string, unknown>;
expect(versionZero).toMatchObject({
id: "uuid-0",
code: "0000",
ruleCode: "0000",
runtimeRuleId: "rule-0",
description: "Published rule zero",
versionNumber: 9
});
const version25 = await handler(client, { versionNumber: 9, code: "0025" }, fakeContext()) as Record<string, unknown>;
expect(version25).toMatchObject({
id: "uuid-25",
code: "0025",
ruleCode: "0025",
runtimeRuleId: "rule-25",
description: "Published rule twenty-five",
versionNumber: 9
});
});
test("approval run cited-rules extracts and merges result.rulesResult and result.hitRules", async () => {
const tool = sealTools.find((item) => item.name === "seal_approval_run_cited_rules_get");
expect(tool).toBeDefined();
const handler = tool!.handler as ToolHandler;
const mockClient = {
get: () => ({
json: async () => ({
data: {
id: "run-cited-1",
sourceDocumentSN: "BX20260928001",
ruleSetVersionNumber: 12,
result: {
hitRules: [
{
id: "rule-0",
description: "Rule zero description",
scope: "差旅报销单",
strictness: "MUST_FOLLOW"
},
{
id: "rule-25",
description: "Rule 25 description",
scope: "对公付款单",
strictness: "SHOULD_FOLLOW"
}
],
rulesResult: [
{
id: "rule-0",
ruleIntent: "Check hotel invoice",
appliedAnalysis: "Invoice matches",
checkResult: "PASS",
findings: []
},
{
id: "rule-25",
ruleIntent: "Check contract attachment",
appliedAnalysis: "Missing contract",
checkResult: "FAIL",
findings: ["未上传合同附件"]
}
]
}
}
})
})
} as unknown as KyInstance;
const res = await handler(mockClient, { recordId: "run-cited-1" }, fakeContext()) as {
count: number;
rules: Array<Record<string, unknown>>;
};
expect(res.count).toBe(2);
expect(res.rules[0]).toMatchObject({
code: "0000",
runtimeRuleId: "rule-0",
ruleCode: "0000",
description: "Rule zero description",
scope: "差旅报销单",
strictness: "MUST_FOLLOW",
checkResult: "PASS"
});
expect(res.rules[1]).toMatchObject({
code: "0025",
runtimeRuleId: "rule-25",
ruleCode: "0025",
description: "Rule 25 description",
scope: "对公付款单",
strictness: "SHOULD_FOLLOW",
checkResult: "FAIL",
findings: ["未上传合同附件"]
});
});
test("deploy hosecloud configure saves integration and rejects missing customApiUrl", async () => {
const tool = sealTools.find((item) => item.name === "seal_deploy_hosecloud_configure");
expect(tool).toBeDefined();
@@ -1269,3 +1396,51 @@ function fakeDeployClient(): KyInstance {
}
} as unknown as KyInstance;
}
function fakeZeroBasedRulesClient(): KyInstance {
// Simulate 0-based rules with a deleted rule gap (code 12 missing, so code 25 is at array index 24)
const draftRules = Array.from({ length: 26 }, (_, i) => i)
.filter((code) => code !== 12)
.map((code) => ({
id: `uuid-${code}`,
tenantId: "tenant-1",
code,
description: code === 0 ? "Draft rule zero" : code === 25 ? "Draft rule twenty-five" : `Draft rule ${code}`,
scope: "travel",
strictness: "MUST_FOLLOW",
status: "active",
createdAt: 1780898164536,
updatedAt: 1780898164536
}));
const versionRules = Array.from({ length: 26 }, (_, i) => i)
.filter((code) => code !== 12)
.map((code) => ({
code: `rule-${code}`,
description: code === 0 ? "Published rule zero" : code === 25 ? "Published rule twenty-five" : `Published rule ${code}`,
scope: "travel",
strictness: "MUST_FOLLOW"
}));
return {
get: (url: string) => ({
json: async () => ({
data: url === "api/v1/rule-set-versions"
? [
{
id: "version-9",
versionNumber: 9,
versionName: "v9",
publishedByName: "Tester",
rules: versionRules
}
]
: {
hasPendingDeletes: false,
rules: draftRules
}
})
})
} as unknown as KyInstance;
}
+2 -5
View File
@@ -682,9 +682,6 @@ export const approvalRunsTools = [
const projected = records.map((record) => pickApprovalRunCandidate(record, fields));
const nextRuleVersionNumber = records.find((record) => record.ruleSetVersionNumber !== undefined)?.ruleSetVersionNumber;
const nextRuleVersionSelector = nextRuleVersionNumber === undefined ? "latest" : String(nextRuleVersionNumber);
const nextRuleVersionPayload = nextRuleVersionNumber === undefined
? '"latestRuleVersion":true'
: `"ruleVersionNumber":${nextRuleVersionNumber}`;
return {
query,
@@ -698,8 +695,8 @@ export const approvalRunsTools = [
next: {
getSummary: `seal-use approval-runs get <recordId> --summary --corp ${context.corp.id}`,
getRuleVersion: `seal-use rules version ${nextRuleVersionSelector} --corp ${context.corp.id}`,
searchRuleVersion: `seal-use tool seal_approval_search --corp ${context.corp.id} --json '{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version",${nextRuleVersionPayload}}'`,
getVersionContext: `seal-use tool seal_approval_context_get --corp ${context.corp.id} --json '{${nextRuleVersionPayload}}'`
searchRuleVersion: `seal-use rules search <keyword> --version ${nextRuleVersionSelector} --corp ${context.corp.id}`,
getVersionContext: `seal-use context --ruleVersion ${nextRuleVersionSelector} --corp ${context.corp.id}`
},
...(params.includeBridge ? { bridge: summarizeRunBridge(records) } : {})
};
+143 -37
View File
@@ -95,7 +95,12 @@ export function projectApprovalRules(
return {
count,
hasPendingDeletes: data.hasPendingDeletes,
rules: fields ? rules.map((rule) => pickRuleFields(rule, fields)) : rules
rules: fields
? rules.map((rule) => pickRuleFields(rule, fields))
: rules.map((rule) => {
const codeNum = parseRuleCodeNumber(rule.code);
return codeNum !== undefined ? { ...rule, code: formatRuleCode(codeNum) } : rule;
})
};
}
@@ -104,15 +109,8 @@ export function pickRuleFields(rule: ApprovalRule, fields: readonly RuleField[])
for (const field of fields) {
if (rule[field] !== undefined) {
if (field === "code") {
const val = rule.code;
if (typeof val === "number") {
output.code = formatRuleCode(val) as never;
} else if (typeof val === "string") {
const digits = val.match(/\d+/)?.[0];
output.code = (digits ? formatRuleCode(Number(digits)) : val) as never;
} else {
output.code = val as never;
}
const codeNum = parseRuleCodeNumber(rule.code);
output.code = (codeNum !== undefined ? formatRuleCode(codeNum) : rule.code) as never;
} else {
output[field] = rule[field] as never;
}
@@ -597,6 +595,8 @@ export function summarizeApprovalRunDocument(record: ApprovalRun) {
export function extractCitedRules(record: ApprovalRun) {
const candidates: Array<[string, unknown]> = [
["result.rulesResult", getPath(record, "result.rulesResult")],
["result.hitRules", getPath(record, "result.hitRules")],
["result.citedRules", getPath(record, "result.citedRules")],
["result.matchedRules", getPath(record, "result.matchedRules")],
["result.ruleResults", getPath(record, "result.ruleResults")],
@@ -605,6 +605,7 @@ export function extractCitedRules(record: ApprovalRun) {
["pipelineData.matchedRules", getPath(record, "pipelineData.matchedRules")]
];
const rules: Array<Record<string, unknown>> = [];
const byIdentity = new Map<string, Record<string, unknown>>();
const seen = new Set<string>();
for (const [path, value] of candidates) {
@@ -616,19 +617,49 @@ export function extractCitedRules(record: ApprovalRun) {
items.forEach((item, index) => {
const object = asRecord(item);
if (!object) return;
const runtimeRuleId = stringFromUnknown(object.runtimeRuleId) ?? stringFromUnknown(object.runtimeId) ?? stringFromUnknown(object.id) ?? stringFromUnknown(object.ruleId);
const ruleCode = stringFromUnknown(object.ruleCode) ?? stringFromUnknown(object.code) ?? (runtimeRuleId ? runtimeRuleIdToCode(runtimeRuleId) : undefined);
const rawRuntimeId =
stringFromUnknown(object.runtimeRuleId) ??
stringFromUnknown(object.runtimeId) ??
stringFromUnknown(object.id) ??
stringFromUnknown(object.ruleId);
const rawCode = object.ruleCode ?? object.code;
const codeNum = parseRuleCodeNumber(rawCode ?? rawRuntimeId);
const runtimeRuleId =
rawRuntimeId ?? (codeNum !== undefined ? `rule-${codeNum}` : undefined);
const ruleCode =
(codeNum !== undefined ? formatRuleCode(codeNum) : undefined) ??
stringFromUnknown(object.ruleCode) ??
stringFromUnknown(object.code) ??
(runtimeRuleId ? runtimeRuleIdToCode(runtimeRuleId) : undefined);
const output = compactObject({
code: ruleCode,
runtimeRuleId,
ruleCode,
versionNumber: numberFromUnknown(object.versionNumber) ?? record.ruleSetVersionNumber,
description: stringFromUnknown(object.description),
scope: stringFromUnknown(object.scope),
strictness: stringFromUnknown(object.strictness),
ruleIntent: stringFromUnknown(object.ruleIntent),
appliedAnalysis: object.appliedAnalysis ?? object.analysis ?? object.reasoning,
checkResult: object.checkResult ?? object.result ?? object.decision,
findings: object.findings ?? object.riskPoints ?? object.evidence,
sourcePath: `${path}.${index}`
});
const identityKey = runtimeRuleId ?? ruleCode;
if (identityKey) {
const existing = byIdentity.get(identityKey);
if (existing) {
for (const [k, v] of Object.entries(output)) {
if (existing[k] === undefined && v !== undefined) {
existing[k] = v;
}
}
return;
}
byIdentity.set(identityKey, output);
rules.push(output);
return;
}
const key = JSON.stringify(output);
if (!seen.has(key)) {
seen.add(key);
@@ -838,30 +869,95 @@ export async function resolveRuleVersionForLookup(
return resolveRuleVersion(client, params);
}
export function findRuleInDraft(
rules: ApprovalRule[],
selector: { code?: string; runtimeId?: string; ruleId?: string }
) {
const rawTarget = selector.ruleId ?? selector.code ?? selector.runtimeId;
if (!rawTarget || !rawTarget.trim()) {
throw new Error("Usage: seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>]");
}
const trimmed = rawTarget.trim();
const targetCodeNum = parseRuleCodeNumber(trimmed);
const rule = rules.find((item) => {
if (item.id === trimmed) return true;
if (targetCodeNum !== undefined) {
const itemCodeNum = parseRuleCodeNumber(item.code);
if (itemCodeNum !== undefined && itemCodeNum === targetCodeNum) return true;
}
return false;
});
if (!rule) return undefined;
const codeNum = parseRuleCodeNumber(rule.code);
const formattedCode = codeNum !== undefined ? formatRuleCode(codeNum) : normalizeRuleCode(rule.code);
return compactObject({
id: rule.id,
code: formattedCode ?? rule.code,
ruleCode: formattedCode,
runtimeRuleId: codeNum !== undefined ? `rule-${codeNum}` : undefined,
description: rule.description,
scope: rule.scope,
strictness: rule.strictness,
status: rule.status,
createdAt: rule.createdAt,
updatedAt: rule.updatedAt
});
}
export function findRuleInVersion(
version: RuleSetVersion,
selector: { code?: string; runtimeId?: string }
selector: { code?: string; runtimeId?: string; ruleId?: string },
draftRules?: ApprovalRule[]
) {
const normalizedCode = normalizeRuleCode(selector.code);
const runtimeIndex = runtimeRuleIndex(selector.runtimeId);
const index = normalizedCode ? Number(normalizedCode.slice(1)) : runtimeIndex;
if (!index || index < 1) {
throw new Error("Pass --code '#0038' or --runtime-id rule-205");
const rawTarget = selector.ruleId ?? selector.code ?? selector.runtimeId;
if (!rawTarget || !rawTarget.trim()) {
throw new Error("Usage: seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>]");
}
const trimmed = rawTarget.trim();
const targetCodeNum = parseRuleCodeNumber(trimmed);
const normalizedTarget = normalizeRuleCode(trimmed);
const rule = version.rules.find((item, itemIndex) => {
const rule = version.rules.find((item) => {
const object = item as Record<string, unknown>;
const itemCode = normalizeRuleCode(stringFromUnknown(object.code) ?? stringFromUnknown(object.ruleCode));
return itemCode === normalizedCode || itemIndex + 1 === index;
const itemId = stringFromUnknown(object.id) ?? stringFromUnknown(object.ruleId) ?? stringFromUnknown(object.stableId);
if (itemId && itemId === trimmed) return true;
const rawItemCode = object.code ?? object.ruleCode ?? object.runtimeRuleId ?? object.runtimeId;
const itemCodeNum = parseRuleCodeNumber(rawItemCode);
if (targetCodeNum !== undefined && itemCodeNum !== undefined) {
return itemCodeNum === targetCodeNum;
}
const itemCode = normalizeRuleCode(rawItemCode);
return Boolean(itemCode && normalizedTarget && itemCode === normalizedTarget);
});
if (!rule) return undefined;
const object = rule as Record<string, unknown>;
const position = version.rules.indexOf(rule) + 1;
const rawItemCode = object.code ?? object.ruleCode ?? object.runtimeRuleId ?? object.runtimeId;
const codeNum = parseRuleCodeNumber(rawItemCode);
const matchedDraft = draftRules?.find((d) => {
if (codeNum !== undefined && parseRuleCodeNumber(d.code) === codeNum) return true;
return d.description === rule.description && d.scope === rule.scope && d.strictness === rule.strictness;
});
const resolvedId =
stringFromUnknown(object.id) ??
stringFromUnknown(object.ruleId) ??
stringFromUnknown(object.stableId) ??
matchedDraft?.id;
const formattedCode =
codeNum !== undefined
? formatRuleCode(codeNum)
: normalizeRuleCode(rawItemCode);
return compactObject({
runtimeRuleId: stringFromUnknown(object.runtimeRuleId) ?? `rule-${position}`,
ruleCode: normalizeRuleCode(stringFromUnknown(object.code) ?? stringFromUnknown(object.ruleCode)) ?? formatRuleCode(position),
id: resolvedId,
code: formattedCode ?? rawItemCode,
runtimeRuleId:
stringFromUnknown(object.runtimeRuleId) ??
(codeNum !== undefined ? `rule-${codeNum}` : stringFromUnknown(object.code)),
ruleCode: formattedCode,
versionId: version.id,
versionNumber: version.versionNumber,
versionName: version.versionName,
@@ -870,29 +966,39 @@ export function findRuleInVersion(
description: rule.description,
scope: rule.scope,
strictness: rule.strictness,
status: stringFromUnknown(object.status)
status: stringFromUnknown(object.status) ?? matchedDraft?.status
});
}
export function normalizeRuleCode(value?: string) {
if (!value) return undefined;
const digits = value.match(/\d+/)?.[0];
return digits ? formatRuleCode(Number(digits)) : value;
export function parseRuleCodeNumber(value: unknown): number | undefined {
if (typeof value === "number" && Number.isInteger(value) && value >= 0) {
return value;
}
if (typeof value !== "string") return undefined;
const trimmed = value.trim();
const match = trimmed.match(/^(?:#|rule[-_:]?)?(\d+)$/i);
if (!match?.[1]) return undefined;
const num = Number(match[1]);
return Number.isInteger(num) && num >= 0 ? num : undefined;
}
export function runtimeRuleIndex(value?: string) {
if (!value) return undefined;
const match = value.match(/(\d+)$/);
return match ? Number(match[1]) : undefined;
export function normalizeRuleCode(value?: unknown) {
const codeNum = parseRuleCodeNumber(value);
if (codeNum !== undefined) return formatRuleCode(codeNum);
return typeof value === "string" && value.trim() ? value.trim() : undefined;
}
export function runtimeRuleIndex(value?: unknown) {
return parseRuleCodeNumber(value);
}
export function runtimeRuleIdToCode(value: string) {
const index = runtimeRuleIndex(value);
return index ? formatRuleCode(index) : undefined;
const index = parseRuleCodeNumber(value);
return index !== undefined ? formatRuleCode(index) : undefined;
}
export function formatRuleCode(value: number) {
return `#${String(value).padStart(4, "0")}`;
return String(value).padStart(4, "0");
}
export function pickApprovalRunCandidate(record: ApprovalRun, fields: string[]) {
+123 -37
View File
@@ -100,7 +100,9 @@ const {
summarizeRunBridge,
summarizeRuleVersion,
resolveRuleVersionForLookup,
findRuleInDraft,
findRuleInVersion,
parseRuleCodeNumber,
normalizeRuleCode,
runtimeRuleIndex,
runtimeRuleIdToCode,
@@ -137,8 +139,9 @@ const {
export const rulesTools = [
{
name: "seal_approval_rules_list",
description: "列出 Seal 当前草稿审批规则;返回的 code 属于草稿编号体系,发布版本可能重新编码;支持 countOnly、fields、limit 以避免返回规则正文",
description: "列出 Seal 审批规则(默认当前草稿,传 version='latest' 或版本号则列出对应已发布版本);支持 countOnly、fields、limit",
parameters: z.object({
version: z.string().optional().describe("可选发布版本号或 'latest';不传则读取当前草稿"),
countOnly: z.boolean().optional().describe("只返回规则数量,不返回规则列表"),
fields: z.array(z.enum([
"id",
@@ -157,12 +160,33 @@ export const rulesTools = [
handler: async (
client: KyInstance,
params: {
version?: string;
countOnly?: boolean;
fields?: RuleField[];
limit?: number;
offset?: number;
}
) => {
if (params.version) {
const ver = await resolveRuleVersionSelector(client, params.version);
const mappedRules: ApprovalRule[] = (ver.rules ?? []).map((r) => ({
id: (r as ApprovalRule).id ?? String(r.code),
tenantId: (r as ApprovalRule).tenantId ?? "",
code: parseRuleCodeNumber(r.code) ?? (r.code as unknown as number),
description: r.description,
scope: r.scope,
strictness: r.strictness,
status: typeof r.status === "string" ? r.status : "published",
createdAt: (r as ApprovalRule).createdAt ?? ver.publishedAt ?? ver.createdAt ?? 0,
updatedAt: (r as ApprovalRule).updatedAt ?? ver.publishedAt ?? ver.createdAt ?? 0
}));
const projected = projectApprovalRules({ rules: mappedRules, hasPendingDeletes: false }, params);
return {
...projected,
versionNumber: ver.versionNumber,
versionName: ver.versionName ?? null
};
}
const data = await api.listApprovalRules(client);
return projectApprovalRules(data, params);
}
@@ -247,13 +271,17 @@ export const rulesTools = [
handler: async (
client: KyInstance,
params: { description: string; scope: string; strictness: string }
) => api.createApprovalRule(client, params)
) => {
const created = await api.createApprovalRule(client, params);
const codeNum = parseRuleCodeNumber(created?.code);
return codeNum !== undefined ? { ...created, code: formatRuleCode(codeNum) } : created;
}
},
{
name: "seal_approval_rule_update",
description: "更新 Seal 草稿审批规则",
parameters: z.object({
ruleId: z.string().describe("规则 ID"),
ruleId: z.string().describe("规则 ID 或规则编号 code"),
description: z.string().optional(),
scope: z.string().optional(),
strictness: z.enum(["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"]).optional()
@@ -262,20 +290,18 @@ export const rulesTools = [
client: KyInstance,
params: { ruleId: string; description?: string; scope?: string; strictness?: string }
) => {
let resolvedRuleId = params.ruleId;
if (resolvedRuleId && (resolvedRuleId.startsWith("#") || resolvedRuleId.startsWith("rule-") || resolvedRuleId.match(/^\d+$/))) {
let resolvedRuleId = params.ruleId.trim();
const targetCodeNum = parseRuleCodeNumber(resolvedRuleId);
if (targetCodeNum !== undefined) {
const draftData = await api.listApprovalRules(client).catch(() => undefined);
if (draftData?.rules) {
const normalizedInput = normalizeRuleCode(resolvedRuleId);
const runtimeIdx = runtimeRuleIndex(resolvedRuleId);
const targetIndex = normalizedInput ? Number(normalizedInput.slice(1)) : runtimeIdx;
const matched = draftData.rules.find((r, idx) => {
const code = normalizeRuleCode(stringFromUnknown((r as any).code) ?? stringFromUnknown((r as any).ruleCode));
return code === normalizedInput || (targetIndex !== undefined && idx + 1 === targetIndex);
});
if (matched) {
resolvedRuleId = matched.id;
const matched = draftData.rules.find(
(r) => r.id === resolvedRuleId || parseRuleCodeNumber(r.code) === targetCodeNum
);
if (!matched) {
throw new Error(`未在当前草稿中找到编号为 ${params.ruleId} 的规则`);
}
resolvedRuleId = matched.id;
}
}
const { ruleId, ...rest } = params;
@@ -286,7 +312,7 @@ export const rulesTools = [
const globalConfig = loadGlobalConfig();
if (globalConfig.lint?.enabled) {
const loaded = await loadRuleLinter(globalConfig.lint.activeLinter);
const lintResult = await lintSingleRule({ id: ruleId, description: params.description }, loaded);
const lintResult = await lintSingleRule({ id: resolvedRuleId, description: params.description }, loaded);
if (lintResult.issues.length > 0) {
console.error(`⚠️ [Linter 质检提醒] 规则质量评分: ${lintResult.score}/100 (发现 ${lintResult.issues.length} 处潜在风险):`);
for (const issue of lintResult.issues) {
@@ -302,18 +328,33 @@ export const rulesTools = [
}
}
return result;
const codeNum = parseRuleCodeNumber(result?.code);
return codeNum !== undefined ? { ...result, code: formatRuleCode(codeNum) } : result;
}
},
{
name: "seal_approval_rule_delete",
description: "删除 Seal 草稿审批规则",
parameters: z.object({
ruleId: z.string().describe("规则 ID")
ruleId: z.string().describe("规则 ID 或规则编号 code")
}),
handler: async (client: KyInstance, params: { ruleId: string }) => {
await api.deleteApprovalRule(client, params.ruleId);
return { success: true };
let resolvedRuleId = params.ruleId.trim();
const targetCodeNum = parseRuleCodeNumber(resolvedRuleId);
if (targetCodeNum !== undefined) {
const draftData = await api.listApprovalRules(client).catch(() => undefined);
if (draftData?.rules) {
const matched = draftData.rules.find(
(r) => r.id === resolvedRuleId || parseRuleCodeNumber(r.code) === targetCodeNum
);
if (!matched) {
throw new Error(`未在当前草稿中找到编号为 ${params.ruleId} 的规则`);
}
resolvedRuleId = matched.id;
}
}
await api.deleteApprovalRule(client, resolvedRuleId);
return { success: true, ruleId: resolvedRuleId };
}
},
{
@@ -422,14 +463,15 @@ export const rulesTools = [
},
{
name: "seal_approval_rule_get",
description: "按版本号/code/runtime-id/record-id 定位单条规则;code 只在选定的版本编号体系内有效,避免拉取整版规则快照",
description: "按规则编号 code(或规则 ID)获取单条规则详情;默认读取当前草稿(含规则 ID),指定 version 或 recordId 时读取对应发布版本快照",
parameters: z.object({
versionId: z.string().optional().describe("规则版本 ID"),
versionNumber: z.number().int().positive().optional().describe("规则版本号"),
latest: z.boolean().optional().describe("为 true 时取最新版本"),
code: z.string().optional().describe("规则展示编号,如 #0038;没有后端 code 时按版本内序号匹配"),
runtimeId: z.string().optional().describe("运行时规则 ID,如 rule-205;按版本内序号匹配"),
recordId: z.string().optional().describe("从运行记录推断 ruleSetVersionNumber")
latest: z.boolean().optional().describe("为 true 时取最新已发布版本"),
code: z.string().optional().describe("规则编号(如 0025)"),
runtimeId: z.string().optional().describe("规则编号兼容别名"),
ruleId: z.string().optional().describe("规则 ID 兼容别名"),
recordId: z.string().optional().describe("从审批运行记录推断所使用的已发布版本")
}),
handler: async (
client: KyInstance,
@@ -439,16 +481,45 @@ export const rulesTools = [
latest?: boolean;
code?: string;
runtimeId?: string;
ruleId?: string;
recordId?: string;
}
},
context: ToolContext
) => {
const version = await resolveRuleVersionForLookup(client, params);
const rule = findRuleInVersion(version, {
const selector = {
code: params.code,
runtimeId: params.runtimeId
runtimeId: params.runtimeId,
ruleId: params.ruleId
};
const explicitVersion = Boolean(
params.versionId || params.versionNumber || params.latest || params.recordId
);
const draftData = await api.listApprovalRules(client).catch(() => undefined);
if (!explicitVersion && draftData?.rules) {
const draftMatch = findRuleInDraft(draftData.rules, selector);
if (draftMatch) {
return draftMatch;
}
}
const rawVersion = await resolveRuleVersionForLookup(client, params).catch((err) => {
if (!explicitVersion && draftData?.rules) {
throw new Error(`Rule not found in current draft: ${params.code ?? params.runtimeId ?? params.ruleId ?? ""}`);
}
throw err;
});
const version = context?.corp?.id
? hydrateRuleVersionStableIds(context.corp.id, rawVersion)
: rawVersion;
const rule = findRuleInVersion(version, selector, draftData?.rules);
if (!rule) {
throw new Error(`Rule not found in version ${version.versionNumber}`);
throw new Error(
explicitVersion
? `Rule not found in version ${version.versionNumber}`
: `Rule not found in current draft or version ${version.versionNumber}`
);
}
return rule;
}
@@ -460,7 +531,7 @@ export const rulesTools = [
file: z.string().optional().describe("指定本地规则文件路径进行离线质检(支持 .json),0网络请求、不污染远端草稿"),
linter: z.string().optional().describe("指定使用的校验器名称或脚本路径(如 builtin、strict、./my-linter.ts)"),
version: z.string().optional().describe("指定要质检的历史发布版本号或 ID(如 16 或 latest),不传默认质检当前草稿"),
code: z.string().optional().describe("按规则展示编号过滤(如 #0038)"),
code: z.string().optional().describe("按规则编号过滤(如 25)"),
ruleId: z.string().optional().describe("按规则 ID 过滤"),
minScore: z.number().optional().describe("最低合格质量分阈值(0~100),低于该分值抛出错误以返回非零退出码"),
level: z.enum(["all", "error", "warning"]).default("all").describe("问题报告等级过滤"),
@@ -502,7 +573,7 @@ export const rulesTools = [
versionNumber = version.versionNumber;
targets = (version.rules ?? []).map((r, idx) => ({
id: (r as any).id ?? (r as any).runtimeId,
code: (r as any).code ?? `#${String(idx + 1).padStart(4, "0")}`,
code: normalizeRuleCode((r as any).code) ?? formatRuleCode(idx),
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: (r as any).scope,
@@ -512,7 +583,7 @@ export const rulesTools = [
const draftData = await api.listApprovalRules(client);
targets = (draftData.rules ?? []).map((r, idx) => ({
id: r.id,
code: (r as any).code ?? `#${String(idx + 1).padStart(4, "0")}`,
code: normalizeRuleCode((r as any).code) ?? formatRuleCode(idx),
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: r.scope,
@@ -521,12 +592,16 @@ export const rulesTools = [
}
if (params.code) {
const normalizedFilter = normalizeRuleCode(params.code);
targets = targets.filter(
(r) => r.code === params.code || r.code?.replace(/[#\s]/g, "") === params.code?.replace(/[#\s]/g, "")
(r) => normalizeRuleCode(r.code) === normalizedFilter
);
}
if (params.ruleId) {
targets = targets.filter((r) => r.id === params.ruleId || r.code === params.ruleId);
const normalizedRuleFilter = normalizeRuleCode(params.ruleId);
targets = targets.filter(
(r) => r.id === params.ruleId || (normalizedRuleFilter !== undefined && normalizeRuleCode(r.code) === normalizedRuleFilter)
);
}
const globalConfig = loadGlobalConfig();
@@ -584,7 +659,7 @@ export const rulesTools = [
versionNumber = targetVersion.versionNumber;
source = `version:${versionNumber}`;
rules = (targetVersion.rules ?? []).map((r, idx) => ({
code: (r as any).code ? Number(String((r as any).code).replace(/^#/, "")) || idx + 1 : idx + 1,
code: parseRuleCodeNumber((r as any).code) ?? idx,
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: (r as any).scope ?? "ALL",
@@ -594,7 +669,7 @@ export const rulesTools = [
const draftData = await api.listApprovalRules(client);
rules = (draftData.rules ?? []).map((r, idx) => ({
id: r.id,
code: r.code ?? idx + 1,
code: parseRuleCodeNumber(r.code) ?? idx,
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: r.scope ?? "ALL",
@@ -644,7 +719,18 @@ export const rulesTools = [
context: ToolContext
) => {
const filePath = params.file ?? "./rules.local.json";
const local = loadLocalRulesFile(filePath);
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;
+3
View File
@@ -377,6 +377,9 @@ export const simulationTools = [
const timeoutMs = parseDurationMs(params.timeout ?? "10m");
const pollIntervalMs = parseDurationMs(params.pollInterval ?? "2s");
const startedAt = Date.now();
console.error(
`⏳ [Simulation] 批次 ${params.batchId} 正在轮询等待结果(单据及附件解析预计耗时 1~3 分钟;若命令转入后台可等待完成通知,或随时执行 seal-use simulation status ${params.batchId} 查看进度)...`
);
while (true) {
const batch = await api.getSimulationBatch(client, params.batchId);
const status = (batch.status ?? "").toLowerCase();
+7 -8
View File
@@ -15,13 +15,12 @@ import {
describe("seal-use MCP server", () => {
test("tokenizes quoted JSON without invoking a shell", () => {
expect(tokenizeCommand(
`seal-use tool seal_approval_search --json '{"keywords":["差旅 发票"]}' --corp corp-a`
`seal-use rules search "差旅 发票" --corp corp-a`
)).toEqual([
"seal-use",
"tool",
"seal_approval_search",
"--json",
'{"keywords":["差旅 发票"]}',
"rules",
"search",
"差旅 发票",
"--corp",
"corp-a"
]);
@@ -125,14 +124,14 @@ describe("seal-use MCP server", () => {
for (const command of [
"seal-use corps mark corp-a --env production --confirm",
"seal-use rules push",
"seal-use rules create --description test --scope all",
"seal-use documents create --title t --purpose p --content c",
"seal-use simulation create --mode hosecloud",
"seal-use deploy hosecloud sync sign-key",
"seal-use users reset-password corp-a:u1",
"seal-use webhook replay",
"seal-use update",
"seal-use mcp",
"seal-use tool seal_approval_rule_create --json '{}'",
"seal-use tool seal_webhook_replay --json '{}'",
"seal-use totally-unknown-area list",
""
]) {
@@ -142,7 +141,7 @@ describe("seal-use MCP server", () => {
// Read-only commands must get past the policy; `version` is a top-level command with no
// registry row, and `corp` is an area alias the CLI dispatches as `corps`.
for (const command of ["seal-use version", "seal-use corps list", "seal-use corp list", "seal-use tool seal_approval_search --json '{}'"]) {
for (const command of ["seal-use version", "seal-use corps list", "seal-use corp list", "seal-use documents list --corp corp-a"]) {
const allowed = await callRead(command);
expect({ command, refusedByPolicy: allowed.text.includes("only runs read-only commands") }).toEqual({
command,