Close the AGENTS.md "Safety Guardrail & Mutation Preview" coverage gap: every remote-mutating command now supports --dry-run returning structured JSON with preview: true, without executing the mutation. - Domain capabilities gain an optional dryRun param and preview handlers: sealUserCreate/ResetPassword/Delete/Activate/DelegationCreate, sealDelegationRevoke, sealApprovalRuleCreate/Update/Delete/ VersionPublish, sealSimulationBatchClean, sealInsightRecordAnalyze. Previews reuse the shared mutationPreview() diff shape; reads (GET) are allowed to build the before/after, writes never fire. - CLI wiring: users create/delegation/reset-password/delete, rules create/update/delete/publish, simulation delete, analytics analyze, auth link revoke pass dryRun; dry-run bypasses the --yes gate (webhook delete pattern); corps mark previews the local config tag change without writing it. - Shared dryRunOption() helper in parser.ts; help registry documents --dry-run on all covered commands; cli-protocol.md §3 example list updated; cli.md and embedded skill regenerated. - New src/cli/commands/dry-run-gates.test.ts pins the contract: preview JSON on stdout, zero mutating requests (GET-only where reads are needed), config untouched for local previews. Local user-config writes (corps switch/rename, config mode/test-dir/ lint) stay outside this contract: they are reversible local edits with no upstream effect.
905 lines
37 KiB
TypeScript
905 lines
37 KiB
TypeScript
import { z } from "zod";
|
||
import type { KyInstance } from "ky";
|
||
import * as api from "../api.js";
|
||
import { createDocument, deleteDocument, documentCreateSchema, documentDeleteSchema, documentListSchema, documentUpdateSchema, listDocuments, updateDocument } from "../documents/service.js";
|
||
import { recodeRules, type RecodeOptions } from "../rules/recode.js";
|
||
import { executeRulePush } from "../rules/push.js";
|
||
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
||
import { loadGlobalConfig } from "../../../core/config/loader.js";
|
||
import { validationError } from "../../../core/errors.js";
|
||
import { redactSensitiveText } from "../../../core/redact.js";
|
||
import { searchApprovalContent } from "../search/service.js";
|
||
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rules/diff.js";
|
||
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rules/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
|
||
} from "../types.js";
|
||
import type {
|
||
CapabilityContext,
|
||
RuleField
|
||
} from "./helpers.js";
|
||
import * as helpers from "./helpers.js";
|
||
|
||
const {
|
||
projectApprovalRules,
|
||
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: "sealApprovalRulesRecode",
|
||
description: "重排草稿规则编号;首次返回预览与一次性确认码,第二次携带确认码才执行,不发布版本",
|
||
parameters: z.object({
|
||
dryRun: z.boolean().optional().describe("只预览,不签发确认码或执行重排"),
|
||
confirmCode: z.string().optional().describe("第一次运行返回的一次性确认码")
|
||
}),
|
||
handler: async (client: KyInstance, params: RecodeOptions, context: CapabilityContext) =>
|
||
recodeRules(client, context.corp, params)
|
||
},
|
||
{
|
||
name: "sealApprovalRulesList",
|
||
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: "sealApprovalRulesClear",
|
||
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;
|
||
const remaining = await api.listApprovalRules(client);
|
||
if (deleted > 0 && params.recode !== false) {
|
||
if (remaining.rules.length > 0) {
|
||
warnings.push("部分规则未删除,已跳过自动重排;如需重排剩余规则,请使用 rules recode 两阶段流程");
|
||
} else {
|
||
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 = recode ? await api.listApprovalRules(client) : remaining;
|
||
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: "sealApprovalRuleCreate",
|
||
description: "新建 Seal 草稿审批规则",
|
||
parameters: z.object({
|
||
description: z.string().describe("规则描述"),
|
||
scope: z.string().describe("适用场景"),
|
||
strictness: z.enum(["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"]).describe("严格程度"),
|
||
dryRun: z.boolean().optional().describe("仅预览将要创建的规则,不执行")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { description: string; scope: string; strictness: string; dryRun?: boolean },
|
||
context: CapabilityContext
|
||
) => {
|
||
if (params.dryRun) {
|
||
const { dryRun: _dryRun, ...payload } = params;
|
||
return {
|
||
...mutationPreview(context, "api/v1/rules", null, payload, 1),
|
||
dryRun: true,
|
||
mutation: "sealApprovalRuleCreate",
|
||
created: 0
|
||
};
|
||
}
|
||
const { dryRun: _dryRun, ...payload } = params;
|
||
const created = await api.createApprovalRule(client, payload);
|
||
const codeNum = parseRuleCodeNumber(created?.code);
|
||
return codeNum !== undefined ? { ...created, code: formatRuleCode(codeNum) } : created;
|
||
}
|
||
},
|
||
{
|
||
name: "sealApprovalRuleUpdate",
|
||
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 输出的北京时间字符串或毫秒时间戳);服务端草稿在该基准后被修改则拒绝更新"),
|
||
dryRun: z.boolean().optional().describe("仅预览将要更新的字段与变更 Diff,不执行写入")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
ruleId: string;
|
||
description?: string;
|
||
scope?: string;
|
||
strictness?: string;
|
||
ifUnchanged?: string | number;
|
||
dryRun?: boolean;
|
||
},
|
||
context: CapabilityContext
|
||
) => {
|
||
if (params.dryRun) {
|
||
const draftData = await api.listApprovalRules(client).catch(() => undefined);
|
||
const targetCodeNum = parseRuleCodeNumber(params.ruleId.trim());
|
||
const matched = draftData?.rules?.find(
|
||
(r) => r.id === params.ruleId.trim() || (targetCodeNum !== undefined && parseRuleCodeNumber(r.code) === targetCodeNum)
|
||
);
|
||
const { dryRun: _dryRun, ifUnchanged: _ifUnchanged, ruleId: _ruleId, ...changes } = params;
|
||
return {
|
||
...mutationPreview(
|
||
context,
|
||
"api/v1/rules",
|
||
matched ?? undefined,
|
||
matched ? { ...matched, ...changes } : changes,
|
||
1
|
||
),
|
||
dryRun: true,
|
||
mutation: "sealApprovalRuleUpdate",
|
||
ruleId: params.ruleId,
|
||
updated: 0
|
||
};
|
||
}
|
||
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: "sealApprovalRuleDelete",
|
||
description: "删除 Seal 草稿审批规则",
|
||
parameters: z.object({
|
||
ruleId: z.string().describe("规则 ID 或规则编号 code"),
|
||
dryRun: z.boolean().optional().describe("仅预览将被删除的规则,不执行删除")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { ruleId: string; dryRun?: boolean },
|
||
context: CapabilityContext
|
||
) => {
|
||
let resolvedRuleId = params.ruleId.trim();
|
||
const targetCodeNum = parseRuleCodeNumber(resolvedRuleId);
|
||
let matchedRule: ApprovalRule | undefined;
|
||
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;
|
||
matchedRule = matched;
|
||
}
|
||
}
|
||
if (params.dryRun) {
|
||
return {
|
||
...mutationPreview(context, "api/v1/rules", matchedRule ?? { id: resolvedRuleId }, null, 1),
|
||
dryRun: true,
|
||
mutation: "sealApprovalRuleDelete",
|
||
ruleId: resolvedRuleId,
|
||
deleted: 0
|
||
};
|
||
}
|
||
await api.deleteApprovalRule(client, resolvedRuleId);
|
||
return { success: true, ruleId: resolvedRuleId };
|
||
}
|
||
},
|
||
{
|
||
name: "sealApprovalRuleVersionsList",
|
||
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: "sealApprovalRuleVersionGet",
|
||
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: "sealApprovalRuleVersionDiff",
|
||
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: "sealApprovalRuleVersionPublish",
|
||
description: "发布 Seal 草稿审批规则为新版本",
|
||
parameters: z.object({
|
||
versionName: z.string().describe("版本名称"),
|
||
dryRun: z.boolean().optional().describe("仅预览将要发布的草稿规模,不执行发布")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { versionName: string; dryRun?: boolean },
|
||
context: CapabilityContext
|
||
) => {
|
||
const draft = await api.listApprovalRules(client).catch(() => undefined);
|
||
if (params.dryRun) {
|
||
return {
|
||
...mutationPreview(context, "api/v1/rules/versions", draft?.rules ?? [], { versionName: params.versionName }, draft?.rules?.length ?? 0),
|
||
dryRun: true,
|
||
mutation: "sealApprovalRuleVersionPublish",
|
||
versionName: params.versionName,
|
||
draftCount: draft?.rules?.length ?? 0,
|
||
published: false
|
||
};
|
||
}
|
||
const published = await api.publishApprovalRuleVersion(client, params.versionName);
|
||
if (draft) {
|
||
try { savePublishedRuleVersionSnapshot(context.corp.id, published.version, draft.rules); } catch {}
|
||
}
|
||
return published;
|
||
}
|
||
},
|
||
{
|
||
name: "sealApprovalRuleGet",
|
||
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: "sealApprovalRulesLint",
|
||
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: "sealApprovalRulesPull",
|
||
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: "sealApprovalRulesPush",
|
||
description: "将本地规则文件增量同步到远端草稿;支持持久化步骤恢复记录、状态核对(--status)与直接发布正式版本",
|
||
parameters: z.object({
|
||
file: z.string().optional().describe("要推送的本地规则文件路径,默认为 ./rules.local.json"),
|
||
dryRun: z.boolean().optional().describe("是否仅预览变更而不实际写入远端(默认 true,传 --yes 或 confirm: true 执行写入)"),
|
||
confirm: z.boolean().optional().describe("确认覆盖写入远端草稿"),
|
||
publish: z.boolean().optional().describe("写入草稿后是否直接发布为一个正式版本"),
|
||
versionName: z.string().optional().describe("发布版本的名称(仅在 publish=true 时有效)"),
|
||
statusOnly: z.boolean().optional().describe("仅查询最近一次 rules push 的持久化步骤记录并与远端草稿核对,不执行写入")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
file?: string;
|
||
dryRun?: boolean;
|
||
confirm?: boolean;
|
||
publish?: boolean;
|
||
versionName?: string;
|
||
statusOnly?: boolean;
|
||
},
|
||
context: CapabilityContext
|
||
) => executeRulePush(client, params, context)
|
||
},
|
||
{
|
||
name: "sealApprovalDocumentsList",
|
||
description: "列出 Seal 审批知识文档",
|
||
parameters: documentListSchema,
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: z.infer<typeof documentListSchema>
|
||
) => listDocuments(client, params)
|
||
},
|
||
{
|
||
name: "sealApprovalDocumentGet",
|
||
description: "获取 Seal 审批知识文档详情",
|
||
parameters: z.object({
|
||
documentId: z.string().describe("文档 ID")
|
||
}),
|
||
handler: async (client: KyInstance, params: { documentId: string }) =>
|
||
api.getApprovalDocument(client, params.documentId)
|
||
},
|
||
{
|
||
name: "sealApprovalDocumentCreate",
|
||
description: "新建 Seal 审批知识文档",
|
||
parameters: documentCreateSchema,
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: z.infer<typeof documentCreateSchema>,
|
||
context: CapabilityContext
|
||
) => createDocument(client, context.corp, params)
|
||
},
|
||
{
|
||
name: "sealApprovalDocumentUpdate",
|
||
description: "更新 Seal 审批知识文档",
|
||
parameters: documentUpdateSchema,
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: z.infer<typeof documentUpdateSchema>,
|
||
context: CapabilityContext
|
||
) => updateDocument(client, context.corp, params)
|
||
},
|
||
{
|
||
name: "sealApprovalDeleteDocument",
|
||
description: "删除 Seal 审批知识文档",
|
||
parameters: documentDeleteSchema,
|
||
handler: (client: KyInstance, params: z.infer<typeof documentDeleteSchema>, context: CapabilityContext) =>
|
||
deleteDocument(client, context.corp, params)
|
||
},
|
||
{
|
||
name: "sealApprovalSearch",
|
||
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: "sealApprovalContextGet",
|
||
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: "sealApprovalStylePreferencesGet",
|
||
description: "获取 Seal 审批风格偏好配置",
|
||
parameters: z.object({}),
|
||
handler: async (client: KyInstance, _params: unknown, context: CapabilityContext) =>
|
||
api.getApprovalStylePreferences(
|
||
client,
|
||
context.corp.seal.endpoints.approvalStylePreferences
|
||
)
|
||
},
|
||
{
|
||
name: "sealApprovalStylePreferencesUpdate",
|
||
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
|
||
)
|
||
}
|
||
];
|