968 lines
39 KiB
TypeScript
968 lines
39 KiB
TypeScript
import { z } from "zod";
|
||
import type { KyInstance } from "ky";
|
||
import * as api from "../api.js";
|
||
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
||
import { loadGlobalConfig } from "../../../core/config/loader.js";
|
||
import { validationError } from "../../../core/errors.js";
|
||
import { redactSensitiveText } from "../../../core/redact.js";
|
||
import { searchApprovalContent } from "../search.js";
|
||
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
|
||
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
|
||
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
|
||
import {
|
||
loadLocalRulesFile,
|
||
saveLocalRulesFile,
|
||
localRulesToLintTargets,
|
||
type LocalRuleItem
|
||
} from "../rules-local.js";
|
||
import {
|
||
type ApprovalRule,
|
||
type RuleSetVersion
|
||
} from "../types.js";
|
||
import type {
|
||
CapabilityContext,
|
||
RuleField
|
||
} from "./helpers.js";
|
||
import * as helpers from "./helpers.js";
|
||
|
||
const {
|
||
projectApprovalRules,
|
||
buildRulePushPlan,
|
||
normalizeRuleStrictness,
|
||
mutationPreview,
|
||
summarizeRuleVersion,
|
||
resolveRuleVersionForLookup,
|
||
findRuleInDraft,
|
||
findRuleInVersion,
|
||
parseRuleCodeNumber,
|
||
normalizeRuleCode,
|
||
formatRuleCode,
|
||
resolveRuleVersion,
|
||
resolveRuleVersionSelector,
|
||
resolveCrossEnvRuleMapping
|
||
} = helpers;
|
||
|
||
function attachCrossEnvRule(context: CapabilityContext, rule: Record<string, unknown>) {
|
||
const crossEnv = resolveCrossEnvRuleMapping(context.corp, rule);
|
||
return crossEnv ? { ...rule, crossEnv } : rule;
|
||
}
|
||
|
||
export const rulesCapabilities = [
|
||
{
|
||
name: "seal_approval_rules_list",
|
||
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",
|
||
"code",
|
||
"tenantId",
|
||
"status",
|
||
"strictness",
|
||
"scope",
|
||
"createdAt",
|
||
"updatedAt",
|
||
"description"
|
||
])).optional().describe("只返回指定字段;不传则返回完整规则"),
|
||
limit: z.number().int().nonnegative().optional().describe("最多返回多少条规则;0 可配合 fields 或 countOnly 只取数量"),
|
||
offset: z.number().int().nonnegative().optional().describe("跳过前多少条规则")
|
||
}),
|
||
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);
|
||
}
|
||
},
|
||
{
|
||
name: "seal_approval_rules_clear",
|
||
description: "清空 Seal 当前草稿审批规则;用于测试环境导入规则前重置草稿规则集",
|
||
parameters: z.object({
|
||
dryRun: z.boolean().optional().describe("只预览将删除的规则数量,不执行删除"),
|
||
recode: z.boolean().optional().describe("删除后尝试重新编排规则编号;失败会作为 warning 返回")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { dryRun?: boolean; recode?: boolean },
|
||
context: CapabilityContext
|
||
) => {
|
||
const before = await api.listApprovalRules(client);
|
||
if (params.dryRun) {
|
||
return {
|
||
...mutationPreview(context, "api/v1/rules", before.rules, [], before.rules.length),
|
||
corpId: context.corp.id,
|
||
corpName: context.corp.name,
|
||
dryRun: true,
|
||
beforeCount: before.rules.length,
|
||
deleted: 0,
|
||
afterCount: before.rules.length,
|
||
hasPendingDeletes: before.hasPendingDeletes
|
||
};
|
||
}
|
||
|
||
const failed: Array<{ ruleId: string; error: string }> = [];
|
||
let deleted = 0;
|
||
for (const rule of before.rules) {
|
||
try {
|
||
await api.deleteApprovalRule(client, rule.id);
|
||
deleted += 1;
|
||
} catch (error) {
|
||
failed.push({
|
||
ruleId: rule.id,
|
||
error: redactSensitiveText(error instanceof Error ? error.message : String(error))
|
||
});
|
||
}
|
||
}
|
||
|
||
const warnings: string[] = [];
|
||
let recode: unknown;
|
||
if (deleted > 0 && params.recode !== false) {
|
||
recode = await api.recodeApprovalRules(client);
|
||
if (
|
||
recode &&
|
||
typeof recode === "object" &&
|
||
"ok" in recode &&
|
||
recode.ok !== true
|
||
) {
|
||
warnings.push("batch-recode did not complete; current rules were still deleted");
|
||
}
|
||
}
|
||
|
||
const after = await api.listApprovalRules(client);
|
||
return {
|
||
corpId: context.corp.id,
|
||
corpName: context.corp.name,
|
||
dryRun: false,
|
||
beforeCount: before.rules.length,
|
||
deleted,
|
||
failed,
|
||
afterCount: after.rules.length,
|
||
hasPendingDeletes: after.hasPendingDeletes,
|
||
warnings,
|
||
recode
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "seal_approval_rule_create",
|
||
description: "新建 Seal 草稿审批规则",
|
||
parameters: z.object({
|
||
description: z.string().describe("规则描述"),
|
||
scope: z.string().describe("适用场景"),
|
||
strictness: z.enum(["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"]).describe("严格程度")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { description: string; scope: string; strictness: string }
|
||
) => {
|
||
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 草稿审批规则;支持 --if-unchanged 乐观并发预检(草稿在基准后被他人修改则拒绝)",
|
||
parameters: z.object({
|
||
ruleId: z.string().describe("规则 ID 或规则编号 code"),
|
||
description: z.string().optional(),
|
||
scope: z.string().optional(),
|
||
strictness: z.enum(["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"]).optional(),
|
||
ifUnchanged: z.union([z.string(), z.number()]).optional().describe("乐观并发预检基准:当前草稿的 updatedAt(rules get 输出的北京时间字符串或毫秒时间戳);服务端草稿在该基准后被修改则拒绝更新")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
ruleId: string;
|
||
description?: string;
|
||
scope?: string;
|
||
strictness?: string;
|
||
ifUnchanged?: string | number;
|
||
},
|
||
context: CapabilityContext
|
||
) => {
|
||
let resolvedRuleId = params.ruleId.trim();
|
||
const targetCodeNum = parseRuleCodeNumber(resolvedRuleId);
|
||
let draftRule: ApprovalRule | undefined;
|
||
if (targetCodeNum !== undefined || params.ifUnchanged !== undefined) {
|
||
const draftData = await api.listApprovalRules(client).catch(() => undefined);
|
||
if (draftData?.rules) {
|
||
const matched = draftData.rules.find(
|
||
(r) => r.id === resolvedRuleId || (targetCodeNum !== undefined && parseRuleCodeNumber(r.code) === targetCodeNum)
|
||
);
|
||
if (!matched) {
|
||
throw new Error(`未在当前草稿中找到编号为 ${params.ruleId} 的规则`);
|
||
}
|
||
resolvedRuleId = matched.id;
|
||
draftRule = matched;
|
||
}
|
||
}
|
||
if (params.ifUnchanged !== undefined) {
|
||
const expectedMs = typeof params.ifUnchanged === "number"
|
||
? params.ifUnchanged
|
||
: Date.parse(params.ifUnchanged);
|
||
const serverMs = typeof draftRule?.updatedAt === "number"
|
||
? draftRule.updatedAt
|
||
: draftRule?.updatedAt !== undefined
|
||
? Date.parse(String(draftRule.updatedAt))
|
||
: NaN;
|
||
const expectedSec = Number.isFinite(expectedMs) ? Math.floor(expectedMs / 1000) : undefined;
|
||
const serverSec = Number.isFinite(serverMs) ? Math.floor(serverMs / 1000) : undefined;
|
||
if (expectedSec === undefined || serverSec === undefined || expectedSec !== serverSec) {
|
||
throw validationError(
|
||
`草稿并发冲突:规则 ${params.ruleId} 的草稿在预检基准之后已被修改(服务端 updatedAt ${serverMs !== undefined && Number.isFinite(serverMs) ? formatBeijingIso(serverMs) : "未知"},预检基准 ${params.ifUnchanged})。`,
|
||
`seal-use rules get ${params.ruleId} --corp ${context.corp.id} 重新读取最新草稿并核对后重试`
|
||
);
|
||
}
|
||
}
|
||
const { ruleId: _ruleId, ifUnchanged: _ifUnchanged, ...rest } = params;
|
||
const result = await api.updateApprovalRule(client, resolvedRuleId, rest);
|
||
|
||
const finalDescription = result?.description ?? params.description;
|
||
if (finalDescription && loadGlobalConfig().lint?.enabled !== false) {
|
||
try {
|
||
const globalConfig = loadGlobalConfig();
|
||
const loaded = await loadRuleLinter(globalConfig.lint.activeLinter);
|
||
const lintResult = await lintSingleRule(
|
||
{ id: resolvedRuleId, description: finalDescription, scope: result?.scope ?? params.scope },
|
||
loaded
|
||
);
|
||
if (lintResult.issues.length > 0) {
|
||
console.error(`⚠️ [Linter 质检提醒] 规则质量评分: ${lintResult.score}/100 (发现 ${lintResult.issues.length} 处潜在风险):`);
|
||
for (const issue of lintResult.issues) {
|
||
console.error(` • [${issue.level.toUpperCase()}] ${issue.message}${issue.snippet ? ` ("${issue.snippet}")` : ""}`);
|
||
if (issue.suggestion) {
|
||
console.error(` 👉 建议: ${issue.suggestion}`);
|
||
}
|
||
}
|
||
}
|
||
} catch {
|
||
// 容错降级:质检异常绝不阻断规则更新
|
||
}
|
||
}
|
||
|
||
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 或规则编号 code")
|
||
}),
|
||
handler: async (client: KyInstance, params: { ruleId: string }) => {
|
||
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 };
|
||
}
|
||
},
|
||
{
|
||
name: "seal_approval_rule_versions_list",
|
||
description: "列出 Seal 已发布审批规则版本摘要,不展开每个版本的规则快照",
|
||
parameters: z.object({}),
|
||
handler: async (client: KyInstance) => {
|
||
const versions = await api.listApprovalRuleVersions(client);
|
||
return {
|
||
count: versions.length,
|
||
latest: versions[0] ? summarizeRuleVersion(versions[0]) : undefined,
|
||
versions: versions.map(summarizeRuleVersion)
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "seal_approval_rule_version_get",
|
||
description: "获取指定 Seal 已发布审批规则版本详情,包含该版本的规则快照",
|
||
parameters: z.object({
|
||
versionId: z.string().optional().describe("规则版本 ID"),
|
||
versionNumber: z.number().int().positive().optional().describe("规则版本号"),
|
||
latest: z.boolean().optional().describe("为 true 时获取最新版本")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { versionId?: string; versionNumber?: number; latest?: boolean }
|
||
) => {
|
||
if (params.versionId) return api.getApprovalRuleVersion(client, params.versionId);
|
||
|
||
const versions = await api.listApprovalRuleVersions(client);
|
||
const version = params.versionNumber
|
||
? versions.find((item) => item.versionNumber === params.versionNumber)
|
||
: versions[0];
|
||
|
||
if (!version) {
|
||
throw new Error(params.versionNumber
|
||
? `Rule version not found: ${params.versionNumber}`
|
||
: "No rule versions found");
|
||
}
|
||
|
||
return version;
|
||
}
|
||
},
|
||
{
|
||
name: "seal_approval_rule_version_diff",
|
||
description: "对比两个已发布审批规则版本;优先使用本地持久化稳定 ID,没有时回退到 code",
|
||
parameters: z.object({
|
||
from: z.string().min(1).describe("起始规则版本号、版本 ID 或 latest"),
|
||
to: z.string().min(1).describe("目标规则版本号、版本 ID 或 latest"),
|
||
ruleId: z.string().optional().describe("只对比指定稳定规则 ID"),
|
||
code: z.string().optional().describe("只对比指定规则 code"),
|
||
includeUnchanged: z.boolean().optional().describe("是否返回未变化规则,默认 false"),
|
||
full: z.boolean().optional().describe("超过默认 diff 上限时返回完整内容"),
|
||
format: z.enum(["unified", "json"]).default("unified").describe("输出格式;unified 将 diff 文本放入 unifiedDiff 字段")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
from: string;
|
||
to: string;
|
||
ruleId?: string;
|
||
code?: string;
|
||
includeUnchanged?: boolean;
|
||
full?: boolean;
|
||
format?: "unified" | "json";
|
||
},
|
||
context: CapabilityContext
|
||
) => {
|
||
const fromVersion = hydrateRuleVersionStableIds(context.corp.id, await resolveRuleVersionSelector(client, params.from));
|
||
const toVersion = hydrateRuleVersionStableIds(context.corp.id, await resolveRuleVersionSelector(client, params.to));
|
||
let result = diffRuleVersions(fromVersion, toVersion, {
|
||
includeUnchanged: params.includeUnchanged
|
||
});
|
||
if (!params.ruleId && !params.code) return { ...truncateRuleDiff(result, 20_000, params.full === true), format: params.format ?? "unified" };
|
||
|
||
const changes = result.changes.filter((change) => {
|
||
if (params.ruleId && change.ruleId === params.ruleId) return true;
|
||
if (!params.code) return false;
|
||
return normalizedRuleCode(params.code) === normalizedRuleCode(change.before?.code ?? change.before?.ruleCode ?? change.after?.code ?? change.after?.ruleCode ?? change.ruleId);
|
||
});
|
||
const counts = { added: 0, removed: 0, modified: 0, unchanged: 0 };
|
||
for (const change of changes) counts[change.status] += 1;
|
||
result = {
|
||
...result,
|
||
counts,
|
||
changes,
|
||
unifiedDiff: changes.map((change) => change.diff).filter(Boolean).join("\n")
|
||
};
|
||
return { ...truncateRuleDiff(result, 20_000, params.full === true), format: params.format ?? "unified" };
|
||
}
|
||
},
|
||
{
|
||
name: "seal_approval_rule_version_publish",
|
||
description: "发布 Seal 草稿审批规则为新版本",
|
||
parameters: z.object({
|
||
versionName: z.string().describe("版本名称")
|
||
}),
|
||
handler: async (client: KyInstance, params: { versionName: string }, context: CapabilityContext) => {
|
||
const draft = await api.listApprovalRules(client).catch(() => undefined);
|
||
const published = await api.publishApprovalRuleVersion(client, params.versionName);
|
||
if (draft) {
|
||
try { savePublishedRuleVersionSnapshot(context.corp.id, published.version, draft.rules); } catch {}
|
||
}
|
||
return published;
|
||
}
|
||
},
|
||
{
|
||
name: "seal_approval_rule_get",
|
||
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("规则编号(如 0025)"),
|
||
runtimeId: z.string().optional().describe("规则编号兼容别名"),
|
||
ruleId: z.string().optional().describe("规则 ID 兼容别名"),
|
||
recordId: z.string().optional().describe("从审批运行记录推断所使用的已发布版本")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
versionId?: string;
|
||
versionNumber?: number;
|
||
latest?: boolean;
|
||
code?: string;
|
||
runtimeId?: string;
|
||
ruleId?: string;
|
||
recordId?: string;
|
||
},
|
||
context: CapabilityContext
|
||
) => {
|
||
const selector = {
|
||
code: params.code,
|
||
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 attachCrossEnvRule(context, 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(
|
||
explicitVersion
|
||
? `Rule not found in version ${version.versionNumber}`
|
||
: `Rule not found in current draft or version ${version.versionNumber}`
|
||
);
|
||
}
|
||
return attachCrossEnvRule(context, rule);
|
||
}
|
||
},
|
||
{
|
||
name: "seal_approval_rules_lint",
|
||
description: "对 Seal 本地规则文件、草稿审批规则或指定发布版本规则进行质量与可执行性检查(模糊词、悬空例外检测)",
|
||
parameters: z.object({
|
||
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("按规则编号过滤(如 25)"),
|
||
ruleId: z.string().optional().describe("按规则 ID 过滤"),
|
||
minScore: z.number().optional().describe("最低合格质量分阈值(0~100),低于该分值抛出错误以返回非零退出码"),
|
||
level: z.enum(["all", "error", "warning"]).default("all").describe("问题报告等级过滤"),
|
||
summary: z.boolean().optional().describe("为 true 时仅返回存在瑕疵/扣分的规则")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
file?: string;
|
||
linter?: string;
|
||
version?: string;
|
||
code?: string;
|
||
ruleId?: string;
|
||
minScore?: number;
|
||
level?: "all" | "error" | "warning";
|
||
summary?: boolean;
|
||
},
|
||
context: CapabilityContext
|
||
) => {
|
||
let targets: RuleLintTarget[] = [];
|
||
let versionNumber: number | undefined;
|
||
|
||
if (params.file) {
|
||
const local = loadLocalRulesFile(params.file);
|
||
targets = localRulesToLintTargets(local.rules);
|
||
versionNumber = local.meta.versionNumber;
|
||
} else if (params.version) {
|
||
const versions = await api.listApprovalRuleVersions(client);
|
||
const versionNumberParsed = Number(params.version);
|
||
const version = isNaN(versionNumberParsed)
|
||
? params.version === "latest"
|
||
? versions[0]
|
||
: versions.find((v) => v.id === params.version)
|
||
: versions.find((v) => v.versionNumber === versionNumberParsed);
|
||
|
||
if (!version) {
|
||
throw new Error(`未找到指定的规则版本: ${params.version}`);
|
||
}
|
||
versionNumber = version.versionNumber;
|
||
targets = (version.rules ?? []).map((r, idx) => ({
|
||
id: (r as any).id ?? (r as any).runtimeId,
|
||
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,
|
||
strictness: (r as any).strictness
|
||
}));
|
||
} else {
|
||
const draftData = await api.listApprovalRules(client);
|
||
targets = (draftData.rules ?? []).map((r, idx) => ({
|
||
id: r.id,
|
||
code: normalizeRuleCode((r as any).code) ?? formatRuleCode(idx),
|
||
name: (r as any).name ?? (r as any).title,
|
||
description: r.description ?? "",
|
||
scope: r.scope,
|
||
strictness: r.strictness
|
||
}));
|
||
}
|
||
|
||
if (params.code) {
|
||
const normalizedFilter = normalizeRuleCode(params.code);
|
||
targets = targets.filter(
|
||
(r) => normalizeRuleCode(r.code) === normalizedFilter
|
||
);
|
||
}
|
||
if (params.ruleId) {
|
||
const normalizedRuleFilter = normalizeRuleCode(params.ruleId);
|
||
targets = targets.filter(
|
||
(r) => r.id === params.ruleId || (normalizedRuleFilter !== undefined && normalizeRuleCode(r.code) === normalizedRuleFilter)
|
||
);
|
||
}
|
||
|
||
const globalConfig = loadGlobalConfig();
|
||
const linterNameOrPath = params.linter ?? globalConfig.lint?.activeLinter ?? "builtin";
|
||
const loadedLinter = await loadRuleLinter(linterNameOrPath);
|
||
|
||
const batchResult = await lintRuleBatch(
|
||
targets,
|
||
loadedLinter,
|
||
{ corpId: context?.corp?.id, versionNumber, allRules: targets },
|
||
{ minScore: params.minScore, level: params.level, summary: params.summary }
|
||
);
|
||
|
||
if (params.minScore && batchResult.overallScore < params.minScore) {
|
||
throw new Error(
|
||
`[Linter 质量门禁未通过] 综合评分 ${batchResult.overallScore} 低于要求的最低分 ${params.minScore} 分 (共发现 ${batchResult.issueCount} 条问题规则)。`
|
||
);
|
||
}
|
||
|
||
return batchResult;
|
||
}
|
||
},
|
||
{
|
||
name: "seal_approval_rules_pull",
|
||
description: "从 Seal 远端拉取草稿或指定版本规则,保存至本地规则文件(支持离线编辑与本地 Lint,绝不污染远端草稿)",
|
||
parameters: z.object({
|
||
version: z.string().optional().describe("指定拉取的历史发布版本号或 ID(如 16 或 latest),不传默认拉取当前草稿规则"),
|
||
out: z.string().optional().describe("保存的目标本地文件路径,默认为 ./rules.local.json")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
version?: string;
|
||
out?: string;
|
||
},
|
||
context: CapabilityContext
|
||
) => {
|
||
const outPath = params.out ?? "./rules.local.json";
|
||
let rules: LocalRuleItem[] = [];
|
||
let source = "draft";
|
||
let versionNumber: number | undefined;
|
||
|
||
if (params.version) {
|
||
const versions = await api.listApprovalRuleVersions(client);
|
||
const versionNumberParsed = Number(params.version);
|
||
const targetVersion = isNaN(versionNumberParsed)
|
||
? params.version === "latest"
|
||
? versions[0]
|
||
: versions.find((v) => v.id === params.version)
|
||
: versions.find((v) => v.versionNumber === versionNumberParsed);
|
||
|
||
if (!targetVersion) {
|
||
throw new Error(`未找到指定的规则版本: ${params.version}`);
|
||
}
|
||
versionNumber = targetVersion.versionNumber;
|
||
source = `version:${versionNumber}`;
|
||
rules = (targetVersion.rules ?? []).map((r, idx) => ({
|
||
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",
|
||
strictness: (r as any).strictness ?? "MUST_FOLLOW"
|
||
}));
|
||
} else {
|
||
const draftData = await api.listApprovalRules(client);
|
||
rules = (draftData.rules ?? []).map((r, idx) => ({
|
||
id: r.id,
|
||
code: parseRuleCodeNumber(r.code) ?? idx,
|
||
name: (r as any).name ?? (r as any).title,
|
||
description: r.description ?? "",
|
||
scope: r.scope ?? "ALL",
|
||
strictness: r.strictness ?? "MUST_FOLLOW",
|
||
status: r.status
|
||
}));
|
||
}
|
||
|
||
const savedPath = saveLocalRulesFile(outPath, {
|
||
corpId: context.corp.id,
|
||
source,
|
||
versionNumber,
|
||
exportedAt: formatBeijingIso(),
|
||
rulesCount: rules.length,
|
||
rules
|
||
});
|
||
|
||
return {
|
||
saved: true,
|
||
path: savedPath,
|
||
rulesCount: rules.length,
|
||
corpId: context.corp.id,
|
||
source,
|
||
versionNumber
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "seal_approval_rules_push",
|
||
description: "将本地规则文件增量同步到远端草稿;按规则 ID 更新/删除并保留未变更规则,支持直接发布为正式版本",
|
||
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 时有效)")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
file?: string;
|
||
dryRun?: boolean;
|
||
confirm?: boolean;
|
||
publish?: boolean;
|
||
versionName?: string;
|
||
},
|
||
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
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "seal_approval_documents_list",
|
||
description: "列出 Seal 审批知识文档",
|
||
parameters: z.object({
|
||
scenarios: z.array(z.string()).optional().describe("场景过滤"),
|
||
offset: z.number().int().nonnegative().optional(),
|
||
limit: z.number().int().positive().optional()
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { scenarios?: string[]; offset?: number; limit?: number }
|
||
) => api.listApprovalDocuments(client, params)
|
||
},
|
||
{
|
||
name: "seal_approval_document_get",
|
||
description: "获取 Seal 审批知识文档详情",
|
||
parameters: z.object({
|
||
documentId: z.string().describe("文档 ID")
|
||
}),
|
||
handler: async (client: KyInstance, params: { documentId: string }) =>
|
||
api.getApprovalDocument(client, params.documentId)
|
||
},
|
||
{
|
||
name: "seal_approval_document_create",
|
||
description: "新建 Seal 审批知识文档",
|
||
parameters: z.object({
|
||
title: z.string(),
|
||
purpose: z.string(),
|
||
content: z.string().describe("正文,通常为 Markdown"),
|
||
contentType: z.string().optional(),
|
||
status: z.string().optional(),
|
||
enabled: z.boolean().optional(),
|
||
scenarios: z.array(z.string()).optional(),
|
||
tags: z.array(z.string()).optional()
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
title: string;
|
||
purpose: string;
|
||
content: string;
|
||
contentType?: string;
|
||
status?: string;
|
||
enabled?: boolean;
|
||
scenarios?: string[];
|
||
tags?: string[];
|
||
}
|
||
) => api.createApprovalDocument(client, params)
|
||
},
|
||
{
|
||
name: "seal_approval_document_update",
|
||
description: "更新 Seal 审批知识文档",
|
||
parameters: z.object({
|
||
documentId: z.string(),
|
||
title: z.string().optional(),
|
||
purpose: z.string().optional(),
|
||
content: z.string().optional(),
|
||
contentType: z.string().optional(),
|
||
status: z.string().optional(),
|
||
enabled: z.boolean().optional(),
|
||
scenarios: z.array(z.string()).optional(),
|
||
tags: z.array(z.string()).optional()
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
documentId: string;
|
||
title?: string;
|
||
purpose?: string;
|
||
content?: string;
|
||
contentType?: string;
|
||
status?: string;
|
||
enabled?: boolean;
|
||
scenarios?: string[];
|
||
tags?: string[];
|
||
}
|
||
) => {
|
||
const { documentId, ...rest } = params;
|
||
return api.updateApprovalDocument(client, documentId, rest);
|
||
}
|
||
},
|
||
{
|
||
name: "seal_approval_delete_document",
|
||
description: "删除 Seal 审批知识文档",
|
||
parameters: z.object({
|
||
documentId: z.string().describe("知识文档 ID")
|
||
}),
|
||
handler: (client: KyInstance, params: { documentId: string }) =>
|
||
api.deleteApprovalDocument(client, params.documentId)
|
||
},
|
||
{
|
||
name: "seal_approval_search",
|
||
description: "按关键词组检索 Seal 审批规则、审批文档和审批偏好配置,返回命中位置、字段、行号和前后三行上下文",
|
||
parameters: z.object({
|
||
keywords: z.array(z.string()).min(1).describe("关键词组"),
|
||
matchMode: z.enum(["any", "all"]).optional().describe("any 命中任一关键词,all 要求同一行命中全部关键词"),
|
||
areas: z.array(z.enum(["rules", "documents", "preferences"])).optional().describe("检索范围"),
|
||
caseSensitive: z.boolean().optional().describe("是否大小写敏感"),
|
||
contextLines: z.number().int().nonnegative().optional().describe("返回命中行前后几行,默认 3"),
|
||
documentLimit: z.number().int().positive().optional().describe("缓存刷新时最多拉取文档数,默认 100"),
|
||
maxResults: z.number().int().positive().optional().describe("最多返回命中数,默认 50"),
|
||
refresh: z.boolean().optional().describe("是否跳过 5 分钟内存缓存并强制刷新"),
|
||
ruleVersionScope: z.enum(["current", "all", "version"]).optional().describe("规则检索范围,默认 current;all 会检索所有已发布历史版本"),
|
||
ruleVersionId: z.string().optional().describe("ruleVersionScope=version 时指定版本 ID"),
|
||
ruleVersionNumber: z.number().int().positive().optional().describe("ruleVersionScope=version 时指定版本号"),
|
||
latestRuleVersion: z.boolean().optional().describe("ruleVersionScope=version 时取最新已发布版本"),
|
||
snippetOnly: z.boolean().optional().describe("只返回命中行,不返回前后文"),
|
||
maxChars: z.number().int().positive().optional().describe("每个文本片段最多返回字符数"),
|
||
fields: z.array(z.string()).optional().describe("只搜索指定字段,如 history.description、description、scope")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
keywords: string[];
|
||
matchMode?: "any" | "all";
|
||
areas?: Array<"rules" | "documents" | "preferences">;
|
||
caseSensitive?: boolean;
|
||
contextLines?: number;
|
||
documentLimit?: number;
|
||
maxResults?: number;
|
||
refresh?: boolean;
|
||
ruleVersionScope?: "current" | "all" | "version";
|
||
ruleVersionId?: string;
|
||
ruleVersionNumber?: number;
|
||
latestRuleVersion?: boolean;
|
||
snippetOnly?: boolean;
|
||
maxChars?: number;
|
||
fields?: string[];
|
||
},
|
||
context: CapabilityContext
|
||
) => searchApprovalContent(client, context.corp, params)
|
||
},
|
||
{
|
||
name: "seal_approval_context_get",
|
||
description: "聚合获取 Seal 现有审批规则、审批文档和审批风格偏好",
|
||
parameters: z.object({
|
||
documentLimit: z.number().int().positive().optional().describe("最多返回的审批文档数量"),
|
||
ruleVersionId: z.string().optional().describe("指定已发布规则版本 ID;指定后 rules 返回该版本快照"),
|
||
ruleVersionNumber: z.number().int().positive().optional().describe("指定已发布规则版本号;指定后 rules 返回该版本快照"),
|
||
latestRuleVersion: z.boolean().optional().describe("为 true 时 rules 返回最新已发布版本快照")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
documentLimit?: number;
|
||
ruleVersionId?: string;
|
||
ruleVersionNumber?: number;
|
||
latestRuleVersion?: boolean;
|
||
},
|
||
context: CapabilityContext
|
||
) => {
|
||
const currentContext = await api.getApprovalContext(client, {
|
||
documentLimit: params.documentLimit,
|
||
stylePreferencesEndpoint: context.corp.seal.endpoints.approvalStylePreferences
|
||
});
|
||
|
||
if (!params.ruleVersionId && !params.ruleVersionNumber && !params.latestRuleVersion) {
|
||
return currentContext;
|
||
}
|
||
|
||
const version = await resolveRuleVersion(client, params);
|
||
return {
|
||
...currentContext,
|
||
rules: {
|
||
version: summarizeRuleVersion(version),
|
||
rules: version.rules
|
||
}
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "seal_approval_style_preferences_get",
|
||
description: "获取 Seal 审批风格偏好配置",
|
||
parameters: z.object({}),
|
||
handler: async (client: KyInstance, _params: unknown, context: CapabilityContext) =>
|
||
api.getApprovalStylePreferences(
|
||
client,
|
||
context.corp.seal.endpoints.approvalStylePreferences
|
||
)
|
||
},
|
||
{
|
||
name: "seal_approval_style_preferences_update",
|
||
description: "更新 Seal 审批风格偏好配置",
|
||
parameters: z.object({
|
||
tone: z.string().optional(),
|
||
language: z.string().optional(),
|
||
detailLevel: z.string().optional(),
|
||
outputFormat: z.string().optional(),
|
||
examples: z.array(z.string()).optional(),
|
||
prohibitedPhrases: z.array(z.string()).optional(),
|
||
customInstructions: z.string().optional()
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: Record<string, unknown>,
|
||
context: CapabilityContext
|
||
) =>
|
||
api.updateApprovalStylePreferences(
|
||
client,
|
||
params,
|
||
context.corp.seal.endpoints.approvalStylePreferences
|
||
)
|
||
}
|
||
];
|