Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a47a60f6e7 | ||
|
|
37874c0831 | ||
|
|
497e1c277c | ||
|
|
f2738ee4a3 | ||
|
|
951c8fc372 | ||
|
|
b94a43f8da |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.10.41",
|
||||
"version": "0.10.42",
|
||||
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.10.42] - 2026-09-30
|
||||
|
||||
### Added
|
||||
- Merge pull request #191 from yunyingk/codex/agent-feedback-hardening
|
||||
- Add one-shot run diagnosis and agent-feedback hardening
|
||||
- Merge pull request #190 from yunyingk/codex/rules-get-standard-timestamps
|
||||
- Standardize rules get and list timestamps to Beijing ISO format
|
||||
|
||||
|
||||
## [0.10.41] - 2026-09-30
|
||||
|
||||
### Added
|
||||
|
||||
Vendored
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "seal-use Wrapped API",
|
||||
"version": "0.10.41",
|
||||
"version": "0.10.42",
|
||||
"description": "HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter\n(`seal-use http`, or the `seal-use service start` daemon; default http://127.0.0.1:8787).\n\nThese endpoints describe the stable wrapped API for frontend developers and agents. They are\nnot the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,\nsource authentication, response compaction, and diagnostics-friendly fields.\n\nEvery operation declares `x-implementation-status`, so a caller can tell what the running\nadapter actually serves:\n\n- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`\n fails when an `implemented` operation has no matching route.\n- `planned` — contract-only, designed but not routed yet. Calling it returns 404.\n\nThe same capabilities are reachable through the CLI, and through the optional MCP server when\nit is enabled.\n\nAuthentication: none. The adapter answers every request with the enterprise credentials already\nstored on this machine, and never checks who is calling — so keep it on loopback (the default)\nand never expose the port to a network or an origin you do not control. The full trust model is\nin SECURITY.md, \"Trust model and documented limitations\".\n"
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: seal-use Wrapped API
|
||||
version: 0.10.41
|
||||
version: 0.10.42
|
||||
description: |
|
||||
HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter
|
||||
(`seal-use http`, or the `seal-use service start` daemon; default http://127.0.0.1:8787).
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.10.41",
|
||||
"version": "0.10.42",
|
||||
"private": true,
|
||||
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: seal-use
|
||||
description: "v0.10.41: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
description: "v0.10.42: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
metadata:
|
||||
version: 0.10.41
|
||||
short-description: Seal tenant and Hose approval automation (v0.10.41)
|
||||
version: 0.10.42
|
||||
short-description: Seal tenant and Hose approval automation (v0.10.42)
|
||||
---
|
||||
|
||||
# Seal Use
|
||||
@@ -100,3 +100,13 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
|
||||
| 已完成当前追踪后的相似坏案例对照 | `references/approval-bad-cases.md` | 不能作为首次诊断入口 |
|
||||
|
||||
冲突时遵循三条优先级:材料获取先于来源判断;来源判断先于 Hose 具体探测;审批事实追踪先于坏案例类比。跨阶段请求也要按阶段顺序读取,不能用后置 reference 替代前置 reference。
|
||||
|
||||
## 客诉/单据诊断一步聚合
|
||||
|
||||
客诉定界、单据排查优先一次调用完成,不要串行敲 4~5 个命令:
|
||||
|
||||
```bash
|
||||
seal-use approval-runs diagnose --sn <单号> --corp <corpId>
|
||||
```
|
||||
|
||||
一次返回单据摘要、AI 判定结果、引用规则、判定当时的规则版本快照(含被引规则的快照内容)与 Langfuse trace 指针;需要完整 result 原文加 `--full`,需要按 recordId 定位则直接传 `<recordId>`。只有诊断结果不够、需要更细颗粒时,再拆用 `pick` / `get --summary` / `cited-rules` / `rules version`。
|
||||
@@ -211,6 +211,26 @@ export async function handleApprovalRunsCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "diagnose") {
|
||||
const recordId = args.command[2];
|
||||
const sn = stringOption(args.options.sn) ?? stringOption(args.options["document-sn"]);
|
||||
if (!recordId && !sn) {
|
||||
throw new Error("Usage: seal-use approval-runs diagnose <recordId>|--sn <documentSN> [--full] [--corp <corpId>]");
|
||||
}
|
||||
await runTool(
|
||||
"seal_approval_run_diagnose",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
recordId,
|
||||
sn,
|
||||
full: booleanOption(args.options.full) === true
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "attachments") {
|
||||
const subAction = args.command[2];
|
||||
if (subAction === "download") {
|
||||
|
||||
@@ -39,11 +39,14 @@ export async function handleCorpSync(
|
||||
}
|
||||
if (!confirmed) {
|
||||
const preview = await syncTestEnterprise(prodCorp, testCorp, { versionName, execute: false }) as {
|
||||
rulesPlan: { sourceDraftRuleCount: number };
|
||||
documentsPlan: { sourceDocumentCount: number };
|
||||
rulesPlan: { sourceDraftRuleCount: number; targetExistingDraftRuleCount: number };
|
||||
documentsPlan: { sourceDocumentCount: number; toDeleteCount: number };
|
||||
};
|
||||
throw confirmationRequired(
|
||||
`Refusing to overwrite test enterprise '${testCorp.name}' (${testCorp.id}) with preferences, ${preview.rulesPlan.sourceDraftRuleCount} draft rules, and ${preview.documentsPlan.sourceDocumentCount} knowledge documents from production enterprise '${prodCorp.name}' (${prodCorp.id}) without --yes. This will replace test draft rules, synchronize knowledge documents, and publish a new version on the test enterprise.`,
|
||||
`Refusing to sync into test enterprise '${testCorp.name}' (${testCorp.id}) without --yes. ` +
|
||||
`This is DESTRUCTIVE for the test tenant: it will DELETE its ${preview.rulesPlan.targetExistingDraftRuleCount} existing draft rules and rebuild them from ${preview.rulesPlan.sourceDraftRuleCount} production draft rules, ` +
|
||||
`DELETE ${preview.documentsPlan.toDeleteCount} existing knowledge documents and re-import ${preview.documentsPlan.sourceDocumentCount} documents from production, overwrite test preferences, and publish a new rules version. ` +
|
||||
`Run with --dry-run first to review the exact documents that will be deleted.`,
|
||||
`seal-use corps sync-test ${prodCorp.id} --yes`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -521,6 +521,15 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
summary: "Inspect rules cited by AI in an approval decision",
|
||||
usage: ["seal-use approval-runs cited-rules <recordId> [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "diagnose",
|
||||
summary: "One-shot complaint/document diagnosis: document summary, AI decision, cited rules, rule version snapshot, and Langfuse trace pointer in a single call",
|
||||
usage: ["seal-use approval-runs diagnose <recordId>|--sn <documentSN> [--full] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--sn <documentSN>", description: "Target the run by Hose document SN instead of record ID" },
|
||||
{ flag: "--full", description: "Include the full raw AI result payload instead of the summary" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "document-summary",
|
||||
summary: "Inspect parsed source document summary",
|
||||
|
||||
@@ -44,6 +44,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
||||
"bridge",
|
||||
"get",
|
||||
"cited-rules",
|
||||
"diagnose",
|
||||
"document-summary",
|
||||
"attachments",
|
||||
"result",
|
||||
|
||||
@@ -124,7 +124,7 @@ describe("loadCorpConfigs", () => {
|
||||
expect(loadGlobalConfig()).toEqual({
|
||||
stateful: false,
|
||||
lint: {
|
||||
enabled: false,
|
||||
enabled: true,
|
||||
activeLinter: "builtin",
|
||||
minScore: 0
|
||||
}
|
||||
@@ -140,7 +140,7 @@ describe("loadCorpConfigs", () => {
|
||||
defaultCorpId: "corp-a",
|
||||
testEnterprisesDir: "/tmp/test-corps",
|
||||
lint: {
|
||||
enabled: false,
|
||||
enabled: true,
|
||||
activeLinter: "builtin",
|
||||
minScore: 0
|
||||
}
|
||||
@@ -151,7 +151,7 @@ describe("loadCorpConfigs", () => {
|
||||
defaultCorpId: "corp-a",
|
||||
testEnterprisesDir: "/tmp/test-corps",
|
||||
lint: {
|
||||
enabled: false,
|
||||
enabled: true,
|
||||
activeLinter: "builtin",
|
||||
minScore: 0
|
||||
}
|
||||
|
||||
@@ -203,7 +203,7 @@ describe("GlobalConfigSchema", () => {
|
||||
expect(GlobalConfigSchema.parse({})).toEqual({
|
||||
stateful: false,
|
||||
lint: {
|
||||
enabled: false,
|
||||
enabled: true,
|
||||
activeLinter: "builtin",
|
||||
minScore: 0
|
||||
}
|
||||
@@ -218,7 +218,7 @@ describe("GlobalConfigSchema", () => {
|
||||
stateful: true,
|
||||
defaultCorpId: "corp-a",
|
||||
lint: {
|
||||
enabled: false,
|
||||
enabled: true,
|
||||
activeLinter: "builtin",
|
||||
minScore: 0
|
||||
}
|
||||
|
||||
@@ -121,11 +121,11 @@ export const CorpConfigSchema = z.object({
|
||||
});
|
||||
|
||||
export const GlobalLintConfigSchema = z.object({
|
||||
enabled: z.boolean().default(false),
|
||||
enabled: z.boolean().default(true),
|
||||
activeLinter: z.string().default("builtin"),
|
||||
minScore: z.number().min(0).max(100).default(0)
|
||||
}).default({
|
||||
enabled: false,
|
||||
enabled: true,
|
||||
activeLinter: "builtin",
|
||||
minScore: 0
|
||||
});
|
||||
|
||||
@@ -96,12 +96,80 @@ describe("tenant-diagnose", () => {
|
||||
expect(result.rules.activeCount).toBe(1);
|
||||
expect(result.webhooks.hasReplayChannel).toBe(true);
|
||||
expect(result.summary.failedChecks).toBe(0);
|
||||
expect(result.corp.boundCorpId).toBe("prod-corp");
|
||||
expect(result.corp.boundCorpRole).toBe("prodParent");
|
||||
|
||||
const dashboard = formatTenantDoctorDashboard(result);
|
||||
expect(dashboard).toContain("HEALTHY");
|
||||
expect(dashboard).toContain("5000");
|
||||
});
|
||||
|
||||
test("reports an unknown quota instead of degrading after transient billing timeouts", async () => {
|
||||
const base = createMockClient({});
|
||||
let billingCalls = 0;
|
||||
const flakyClient = {
|
||||
get: async (url: string) => {
|
||||
if (url === "api/v1/billing/status") {
|
||||
billingCalls += 1;
|
||||
throw new Error("Request timed out after 15000ms");
|
||||
}
|
||||
return base.get(url);
|
||||
}
|
||||
} as any;
|
||||
|
||||
const testCorp: CorpConfig = {
|
||||
id: "test-corp",
|
||||
name: "园测企业",
|
||||
environment: "test",
|
||||
prodCorpId: "prod-corp",
|
||||
source: { type: "seal" },
|
||||
seal: { url: "https://test.sealai.cc" }
|
||||
} as any;
|
||||
|
||||
const result = await diagnoseTenantContract(flakyClient, testCorp);
|
||||
|
||||
expect(billingCalls).toBe(2);
|
||||
expect(result.verdict).toBe("HEALTHY");
|
||||
expect(result.quota.status).toBe("unknown");
|
||||
expect(result.summary.unknownChecks).toBe(1);
|
||||
const billingCheck = result.checks.find((check) => check.id === "billing_quota");
|
||||
expect(billingCheck?.status).toBe("unknown");
|
||||
|
||||
const dashboard = formatTenantDoctorDashboard(result);
|
||||
expect(dashboard).toContain("未知");
|
||||
});
|
||||
|
||||
test("recovers a transient billing timeout via the built-in retry", async () => {
|
||||
const base = createMockClient({});
|
||||
let billingCalls = 0;
|
||||
const flakyClient = {
|
||||
get: async (url: string) => {
|
||||
if (url === "api/v1/billing/status") {
|
||||
billingCalls += 1;
|
||||
if (billingCalls === 1) {
|
||||
throw new Error("fetch failed: socket hang up");
|
||||
}
|
||||
}
|
||||
return base.get(url);
|
||||
}
|
||||
} as any;
|
||||
|
||||
const testCorp: CorpConfig = {
|
||||
id: "test-corp",
|
||||
name: "重试恢复企业",
|
||||
environment: "test",
|
||||
prodCorpId: "prod-corp",
|
||||
source: { type: "seal" },
|
||||
seal: { url: "https://test.sealai.cc" }
|
||||
} as any;
|
||||
|
||||
const result = await diagnoseTenantContract(flakyClient, testCorp);
|
||||
|
||||
expect(billingCalls).toBe(2);
|
||||
expect(result.verdict).toBe("HEALTHY");
|
||||
expect(result.quota.status).toBe("sufficient");
|
||||
});
|
||||
|
||||
test("flags warning for low quota and unbound prod corp", async () => {
|
||||
const mockClient = createMockClient({
|
||||
billing: {
|
||||
@@ -128,6 +196,10 @@ describe("tenant-diagnose", () => {
|
||||
expect(result.quota.status).toBe("low");
|
||||
expect(result.rules.totalCount).toBe(0);
|
||||
expect(result.summary.warningChecks).toBeGreaterThan(0);
|
||||
// An unbound corp must not advertise a binding role.
|
||||
expect(result.corp.boundCorpId).toBeUndefined();
|
||||
expect(result.corp.boundCorpRole).toBeUndefined();
|
||||
expect(result.corp.boundCorpRoleDescription).toBeUndefined();
|
||||
});
|
||||
|
||||
test("flags fail when quota is exhausted or auth fails", async () => {
|
||||
|
||||
@@ -6,7 +6,8 @@ import * as api from "../api.js";
|
||||
export interface TenantHealthCheck {
|
||||
id: string;
|
||||
name: string;
|
||||
status: "pass" | "warn" | "fail";
|
||||
/** "unknown" means a transient probe failure (e.g. one-off timeout after a retry) — it must not degrade the verdict. */
|
||||
status: "pass" | "warn" | "fail" | "unknown";
|
||||
summary: string;
|
||||
details: Record<string, unknown>;
|
||||
recommendation?: string;
|
||||
@@ -30,6 +31,7 @@ export interface TenantDoctorDiagnosis {
|
||||
passedChecks: number;
|
||||
warningChecks: number;
|
||||
failedChecks: number;
|
||||
unknownChecks: number;
|
||||
};
|
||||
checks: TenantHealthCheck[];
|
||||
quota: {
|
||||
@@ -37,7 +39,7 @@ export interface TenantDoctorDiagnosis {
|
||||
balance: number;
|
||||
deductionAmount: number;
|
||||
estimatedRuns: number;
|
||||
status: "sufficient" | "low" | "exhausted";
|
||||
status: "sufficient" | "low" | "exhausted" | "unknown";
|
||||
};
|
||||
rules: {
|
||||
totalCount: number;
|
||||
@@ -59,13 +61,34 @@ export async function diagnoseTenantContract(
|
||||
const checks: TenantHealthCheck[] = [];
|
||||
const environment = corp.environment === "test" ? "test" : "production";
|
||||
const boundCorpId = environment === "test" ? corp.prodCorpId : corp.testCorpId;
|
||||
const boundCorpRole = environment === "test" ? "prodParent" : "testTarget";
|
||||
// Role labels only make sense for an existing binding; emitting them for an unbound corp reads as a phantom binding.
|
||||
const boundCorpRole = boundCorpId
|
||||
? environment === "test"
|
||||
? "prodParent" as const
|
||||
: "testTarget" as const
|
||||
: undefined;
|
||||
const boundCorpRoleDescription = boundCorpId
|
||||
? environment === "test"
|
||||
? "已绑定生产母企业 (上游配置与样本源)"
|
||||
: "已绑定测试靶场 (下游隔离演练环境)"
|
||||
: undefined;
|
||||
|
||||
// Transient network failures (timeouts, dropped sockets) get one retry before the check is
|
||||
// reported; if the retry also fails the check reports "unknown" instead of degrading the verdict.
|
||||
const isTransientNetworkError = (err: unknown): boolean => {
|
||||
const text = `${err instanceof Error ? err.name : ""} ${err instanceof Error ? err.message : String(err)}`.toLowerCase();
|
||||
return /timeout|timed out|abort|fetch failed|network|econn|etimedout|eai_again|socket/.test(text);
|
||||
};
|
||||
const probeWithRetry = async <T>(probe: () => Promise<T>): Promise<T> => {
|
||||
try {
|
||||
return await probe();
|
||||
} catch (err) {
|
||||
if (!isTransientNetworkError(err)) throw err;
|
||||
await new Promise((resolve) => setTimeout(resolve, 400));
|
||||
return probe();
|
||||
}
|
||||
};
|
||||
|
||||
// 1. Auth & Admin Probe
|
||||
let userDetail: any = null;
|
||||
let tenantDetail: any = null;
|
||||
@@ -125,7 +148,7 @@ export async function diagnoseTenantContract(
|
||||
balance: 0,
|
||||
deductionAmount: 120,
|
||||
estimatedRuns: 0,
|
||||
status: "exhausted" as "sufficient" | "low" | "exhausted"
|
||||
status: "exhausted" as "sufficient" | "low" | "exhausted" | "unknown"
|
||||
};
|
||||
|
||||
let ruleQuota = {
|
||||
@@ -134,7 +157,7 @@ export async function diagnoseTenantContract(
|
||||
};
|
||||
|
||||
try {
|
||||
const billing = await api.getBillingStatus(client);
|
||||
const billing = await probeWithRetry(() => api.getBillingStatus(client));
|
||||
const features = Array.isArray(billing.features) ? billing.features : [];
|
||||
|
||||
// Find AI Approval feature
|
||||
@@ -197,12 +220,19 @@ export async function diagnoseTenantContract(
|
||||
ruleQuota.remaining = typeof ruleFeat.remaining === "number" ? ruleFeat.remaining : 0;
|
||||
}
|
||||
} catch (err) {
|
||||
const transient = isTransientNetworkError(err);
|
||||
if (transient) {
|
||||
quotaInfo.status = "unknown";
|
||||
}
|
||||
checks.push({
|
||||
id: "billing_quota",
|
||||
name: "AI 审批额度余量",
|
||||
status: "warn",
|
||||
summary: `读取计费状态失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
details: { error: String(err) }
|
||||
status: transient ? "unknown" : "warn",
|
||||
summary: transient
|
||||
? "额度探测超时(已重试仍未达),额度未知——不判定为降级,其余检查不受影响"
|
||||
: `读取计费状态失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
details: { error: String(err), retried: transient },
|
||||
recommendation: transient ? `稍后重跑 seal-use doctor tenant --corp ${corp.id} 确认额度` : undefined
|
||||
});
|
||||
}
|
||||
|
||||
@@ -263,7 +293,7 @@ export async function diagnoseTenantContract(
|
||||
};
|
||||
|
||||
try {
|
||||
const integrations = await api.listWebhookIntegrations(client);
|
||||
const integrations = await probeWithRetry(() => api.listWebhookIntegrations(client));
|
||||
webhooksSummary.integrationCount = integrations.length;
|
||||
|
||||
const replayChannel = integrations.find(
|
||||
@@ -294,12 +324,16 @@ export async function diagnoseTenantContract(
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
const transient = isTransientNetworkError(err);
|
||||
checks.push({
|
||||
id: "webhook_integrations",
|
||||
name: "单据推送 Webhook 通道",
|
||||
status: "warn",
|
||||
summary: `检测 Webhook 通道失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
details: { error: String(err) }
|
||||
status: transient ? "unknown" : "warn",
|
||||
summary: transient
|
||||
? "检测 Webhook 通道超时(已重试仍未达),通道状态未知——不判定为降级"
|
||||
: `检测 Webhook 通道失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
details: { error: String(err), retried: transient },
|
||||
recommendation: transient ? `稍后重跑 seal-use doctor tenant --corp ${corp.id} 确认通道状态` : undefined
|
||||
});
|
||||
}
|
||||
|
||||
@@ -344,10 +378,11 @@ export async function diagnoseTenantContract(
|
||||
}
|
||||
}
|
||||
|
||||
// Compute overall verdict
|
||||
// Compute overall verdict; "unknown" checks (transient probe failures after retry) never degrade it.
|
||||
const failedChecks = checks.filter((c) => c.status === "fail").length;
|
||||
const warningChecks = checks.filter((c) => c.status === "warn").length;
|
||||
const passedChecks = checks.filter((c) => c.status === "pass").length;
|
||||
const unknownChecks = checks.filter((c) => c.status === "unknown").length;
|
||||
|
||||
let verdict: "HEALTHY" | "DEGRADED" | "BLOCKED" = "HEALTHY";
|
||||
if (failedChecks > 0) {
|
||||
@@ -373,7 +408,8 @@ export async function diagnoseTenantContract(
|
||||
totalChecks: checks.length,
|
||||
passedChecks,
|
||||
warningChecks,
|
||||
failedChecks
|
||||
failedChecks,
|
||||
unknownChecks
|
||||
},
|
||||
checks,
|
||||
quota: quotaInfo,
|
||||
@@ -400,8 +436,11 @@ export function formatTenantDoctorDashboard(diagnosis: TenantDoctorDiagnosis): s
|
||||
];
|
||||
|
||||
// Core metrics overview
|
||||
const quotaLine = quota.status === "unknown"
|
||||
? ` AI 审批余量: 未知(探测超时,不判定降级)`
|
||||
: ` AI 审批余量: ${quota.balance} 点 (可审约 ${quota.estimatedRuns} 笔)`;
|
||||
lines.push(
|
||||
` AI 审批余量: ${quota.balance} 点 (可审约 ${quota.estimatedRuns} 笔) | 规则数: ${rules.activeCount}/${rules.totalCount} | Webhook 通道: ${webhooks.integrationCount}`
|
||||
`${quotaLine} | 规则数: ${rules.activeCount}/${rules.totalCount} | Webhook 通道: ${webhooks.integrationCount}`
|
||||
);
|
||||
if (corp.boundCorpId) {
|
||||
lines.push(` 配对关系: ${corp.environment === "test" ? "来源生产母企业" : "绑定的测试靶场"} -> 「${corp.boundCorpId}」`);
|
||||
@@ -409,7 +448,7 @@ export function formatTenantDoctorDashboard(diagnosis: TenantDoctorDiagnosis): s
|
||||
lines.push(" " + "─".repeat(60));
|
||||
|
||||
for (const check of checks) {
|
||||
const icon = check.status === "pass" ? "✓" : check.status === "warn" ? "!" : "✗";
|
||||
const icon = check.status === "pass" ? "✓" : check.status === "warn" ? "!" : check.status === "unknown" ? "?" : "✗";
|
||||
lines.push(` [${icon}] ${check.name}: ${check.summary}`);
|
||||
if (check.recommendation) {
|
||||
lines.push(` 👉 建议: ${check.recommendation}`);
|
||||
|
||||
@@ -5,6 +5,8 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import { CliError } from "../../core/errors.js";
|
||||
import { saveRuleMappingSnapshot } from "./rule-mapping.js";
|
||||
import { buildRulePushPlan, findSealTool, sealTools } from "./tools.js";
|
||||
|
||||
type ToolHandler = (
|
||||
@@ -203,6 +205,139 @@ describe("sealTools", () => {
|
||||
expect(result.rules[0]).not.toHaveProperty("description");
|
||||
});
|
||||
|
||||
test("approval rules list renders timestamps in standard Beijing ISO format", async () => {
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_rules_list");
|
||||
expect(tool).toBeDefined();
|
||||
|
||||
const handler = tool!.handler as ToolHandler;
|
||||
|
||||
const full = await handler(fakeRulesClient(), {}, fakeContext()) as {
|
||||
rules: Array<Record<string, unknown>>;
|
||||
};
|
||||
expect(full.rules[0]?.createdAt).toBe("2026-06-08T13:56:04+08:00");
|
||||
expect(full.rules[0]?.updatedAt).toBe("2026-06-08T13:56:04+08:00");
|
||||
expect(full.rules[1]?.createdAt).toBe("2026-06-08T13:56:04+08:00");
|
||||
|
||||
const projected = await handler(
|
||||
fakeRulesClient(),
|
||||
{ fields: ["id", "createdAt"], limit: 1 },
|
||||
fakeContext()
|
||||
) as { rules: Array<Record<string, unknown>> };
|
||||
expect(projected.rules[0]).toEqual({
|
||||
id: "rule-1",
|
||||
createdAt: "2026-06-08T13:56:04+08:00"
|
||||
});
|
||||
});
|
||||
|
||||
test("approval rule get attaches crossEnv mapping when a sync-test snapshot exists", async () => {
|
||||
const mappingDir = mkdtempSync(join(tmpdir(), "seal-mapping-crossenv-"));
|
||||
process.env.SEAL_USE_MAPPINGS_DIR = mappingDir;
|
||||
try {
|
||||
saveRuleMappingSnapshot({
|
||||
syncedAt: "2026-09-30T10:00:00+08:00",
|
||||
source: { id: "prod-corp", name: "Prod Corp" },
|
||||
target: { id: "t-corp-1", name: "Test Corp", publishedVersionNumber: 3, rulesCount: 1 },
|
||||
versionMapping: {
|
||||
sourceProdVersionNumber: 22,
|
||||
sourceProdVersionName: "Prod v22 · #1",
|
||||
targetTestVersionNumber: 3,
|
||||
targetTestVersionName: "Test v3"
|
||||
},
|
||||
ruleMapping: [{
|
||||
index: 0,
|
||||
sourceRuleId: "rule-1",
|
||||
sourceRuleCode: 29,
|
||||
targetRuleId: "t-rule-1",
|
||||
targetRuleCode: "0002",
|
||||
description: "Must include full invoice detail",
|
||||
scope: "travel",
|
||||
strictness: "MUST_FOLLOW"
|
||||
}]
|
||||
});
|
||||
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_rule_get");
|
||||
expect(tool).toBeDefined();
|
||||
const handler = tool!.handler as ToolHandler;
|
||||
const context = { corp: { ...fakeContext().corp, testCorpId: "t-corp-1" } };
|
||||
|
||||
const draft = await handler(fakeRulesClient(), { code: "29" }, context) as Record<string, unknown>;
|
||||
expect(draft.crossEnv).toMatchObject({
|
||||
environment: "test",
|
||||
code: "0002",
|
||||
direction: "prodToTest",
|
||||
syncedAt: "2026-09-30T10:00:00+08:00"
|
||||
});
|
||||
} finally {
|
||||
delete process.env.SEAL_USE_MAPPINGS_DIR;
|
||||
rmSync(mappingDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("approval rule update without --if-unchanged leaves concurrency check absent", async () => {
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_rule_update");
|
||||
expect(tool).toBeDefined();
|
||||
const handler = tool!.handler as ToolHandler;
|
||||
const result = await handler(
|
||||
fakeRuleUpdateClient(1780898164536),
|
||||
{ ruleId: "29", description: "当单据金额超过 5000 元时必须提供发票原件与行程证明。" },
|
||||
fakeContext()
|
||||
) as Record<string, unknown>;
|
||||
expect(result).toMatchObject({ id: "rule-1", code: "0029" });
|
||||
});
|
||||
|
||||
test("approval rule update --if-unchanged rejects when the draft moved on (exit 13)", async () => {
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_rule_update");
|
||||
const handler = tool!.handler as ToolHandler;
|
||||
try {
|
||||
await handler(
|
||||
fakeRuleUpdateClient(1780898164536),
|
||||
{ ruleId: "29", description: "更新后的规则内容", ifUnchanged: "2026-06-08T13:56:03+08:00" },
|
||||
fakeContext()
|
||||
);
|
||||
expect.unreachable();
|
||||
} catch (err) {
|
||||
expect((err as CliError).exitCode).toBe(13);
|
||||
expect((err as Error).message).toContain("草稿并发冲突");
|
||||
}
|
||||
});
|
||||
|
||||
test("approval rule update --if-unchanged proceeds when the draft is unchanged", async () => {
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_rule_update");
|
||||
const handler = tool!.handler as ToolHandler;
|
||||
const result = await handler(
|
||||
fakeRuleUpdateClient(1780898164536),
|
||||
{ ruleId: "29", description: "当单据金额超过 5000 元时必须提供发票原件与行程证明。", ifUnchanged: "2026-06-08T13:56:04+08:00" },
|
||||
fakeContext()
|
||||
) as Record<string, unknown>;
|
||||
expect(result).toMatchObject({ id: "rule-1" });
|
||||
});
|
||||
|
||||
test("seal_approval_run_diagnose aggregates document, result, cited rules, and version snapshot", async () => {
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_run_diagnose");
|
||||
expect(tool).toBeDefined();
|
||||
const handler = tool!.handler as ToolHandler;
|
||||
|
||||
const byRecord = await handler(fakeDiagnoseClient(), { recordId: "run-1" }, fakeContext()) as Record<string, any>;
|
||||
expect(byRecord.recordId).toBe("run-1");
|
||||
expect(byRecord.documentSummary).toBeDefined();
|
||||
expect(byRecord.result).toMatchObject({ decision: "驳回" });
|
||||
expect(byRecord.citedRules.rules.length).toBeGreaterThan(0);
|
||||
expect(byRecord.ruleVersion?.version).toMatchObject({ versionNumber: 16 });
|
||||
expect(byRecord.ruleVersion?.citedSnapshots).toEqual([{
|
||||
code: "rule-38",
|
||||
description: "Rule 38 published snapshot",
|
||||
scope: "travel",
|
||||
strictness: "MUST_FOLLOW"
|
||||
}]);
|
||||
expect(byRecord.bridge).toBeDefined();
|
||||
expect(byRecord.next.url).toContain("approval-runs url run-1");
|
||||
|
||||
const bySn = await handler(fakeDiagnoseClient(), { sn: "B26001965" }, fakeContext()) as Record<string, any>;
|
||||
expect(bySn.recordId).toBe("run-1");
|
||||
|
||||
expect(handler(fakeDiagnoseClient(), {}, fakeContext())).rejects.toThrow("sn or recordId is required");
|
||||
});
|
||||
|
||||
test("approval rules clear can dry run without deleting", async () => {
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_rules_clear");
|
||||
expect(tool).toBeDefined();
|
||||
@@ -850,14 +985,15 @@ describe("sealTools", () => {
|
||||
fakeRulesClient(),
|
||||
{ versionNumber: 16, code: "44" },
|
||||
fakeContext()
|
||||
) as { code?: number; ruleCode?: string; runtimeRuleId?: string; description?: string; versionNumber?: number };
|
||||
) as { code?: number; ruleCode?: string; runtimeRuleId?: string; description?: string; versionNumber?: number; publishedAt?: string };
|
||||
|
||||
expect(result).toMatchObject({
|
||||
code: "0044",
|
||||
ruleCode: "0044",
|
||||
runtimeRuleId: "rule-44",
|
||||
description: "Second published rule",
|
||||
versionNumber: 16
|
||||
versionNumber: 16,
|
||||
publishedAt: "2026-06-08T13:56:04+08:00"
|
||||
});
|
||||
});
|
||||
|
||||
@@ -875,7 +1011,9 @@ describe("sealTools", () => {
|
||||
ruleCode: "0000",
|
||||
runtimeRuleId: "rule-0",
|
||||
description: "Draft rule zero",
|
||||
status: "active"
|
||||
status: "active",
|
||||
createdAt: "2026-06-08T13:56:04+08:00",
|
||||
updatedAt: "2026-06-08T13:56:04+08:00"
|
||||
});
|
||||
|
||||
// Draft lookup for code 25 (sitting at array index 24 because code 12 was deleted)
|
||||
@@ -1220,8 +1358,100 @@ function fakeApprovalRunsClient(requests: string[] = []): KyInstance {
|
||||
} as unknown as KyInstance;
|
||||
}
|
||||
|
||||
function fakeRulesClient(): KyInstance {
|
||||
function fakeRuleUpdateClient(draftUpdatedAt: number): KyInstance {
|
||||
const draftRule = {
|
||||
id: "rule-1",
|
||||
tenantId: "tenant-1",
|
||||
code: 29,
|
||||
description: "当单据金额超过 5000 元时必须提供发票原件。",
|
||||
scope: "travel",
|
||||
strictness: "MUST_FOLLOW",
|
||||
status: "active",
|
||||
createdAt: draftUpdatedAt,
|
||||
updatedAt: draftUpdatedAt
|
||||
};
|
||||
return {
|
||||
get: (url: string) => ({
|
||||
json: async () => ({
|
||||
data: url === "api/v1/rules"
|
||||
? { hasPendingDeletes: false, rules: [draftRule] }
|
||||
: draftRule
|
||||
})
|
||||
}),
|
||||
put: (_url: string, options?: { json?: { description?: string } }) => ({
|
||||
json: async () => ({
|
||||
data: {
|
||||
...draftRule,
|
||||
description: options?.json?.description ?? draftRule.description,
|
||||
updatedAt: draftUpdatedAt + 5000
|
||||
}
|
||||
})
|
||||
})
|
||||
} as unknown as KyInstance;
|
||||
}
|
||||
|
||||
function fakeDiagnoseClient(): KyInstance {
|
||||
const runDetail = {
|
||||
id: "run-1",
|
||||
status: "completed",
|
||||
taskMode: "assisted",
|
||||
sourceDocumentSN: "B26001965",
|
||||
sourceDocumentId: "doc-source-1",
|
||||
ruleSetVersionNumber: 16,
|
||||
document: {
|
||||
id: "normalized-doc-1",
|
||||
title: "差旅报销单",
|
||||
sourceDocumentSN: "B26001965",
|
||||
fields: [{ label: "金额", value: "100.00" }]
|
||||
},
|
||||
result: {
|
||||
decision: "驳回",
|
||||
summary: "费用存在风险",
|
||||
matchedRules: [{
|
||||
runtimeRuleId: "rule-38",
|
||||
ruleCode: "#0038",
|
||||
versionNumber: 16,
|
||||
scope: "travel",
|
||||
strictness: "MUST_FOLLOW",
|
||||
appliedAnalysis: "发票信息与报销说明不一致",
|
||||
checkResult: "failed"
|
||||
}]
|
||||
},
|
||||
sourceExtendData: { _langfuseTraceId: "trace-1" },
|
||||
createdAt: 1780898164536
|
||||
};
|
||||
return {
|
||||
get: (url: string) => ({
|
||||
json: async () => {
|
||||
if (url === "api/v1/approvals/run-1") {
|
||||
return { data: runDetail };
|
||||
}
|
||||
if (url.startsWith("api/v1/approvals")) {
|
||||
return { data: { total: 1, records: [{ id: "run-1", sourceDocumentSN: "B26001965" }] } };
|
||||
}
|
||||
if (url === "api/v1/rule-set-versions") {
|
||||
return {
|
||||
data: [{
|
||||
id: "version-16",
|
||||
versionNumber: 16,
|
||||
versionName: "v16",
|
||||
publishedByName: "Tester",
|
||||
rules: [{
|
||||
code: "rule-38",
|
||||
description: "Rule 38 published snapshot",
|
||||
scope: "travel",
|
||||
strictness: "MUST_FOLLOW"
|
||||
}]
|
||||
}]
|
||||
};
|
||||
}
|
||||
throw new Error(`Unhandled diagnose GET url: ${url}`);
|
||||
}
|
||||
})
|
||||
} as unknown as KyInstance;
|
||||
}
|
||||
|
||||
function fakeRulesClient(): KyInstance { return {
|
||||
get: (url: string) => ({
|
||||
json: async () => ({
|
||||
data: url === "api/v1/rule-set-versions"
|
||||
@@ -1231,6 +1461,7 @@ function fakeRulesClient(): KyInstance {
|
||||
versionNumber: 16,
|
||||
versionName: "v16",
|
||||
publishedByName: "Tester",
|
||||
publishedAt: 1780898164536,
|
||||
rules: [
|
||||
{
|
||||
code: "rule-29",
|
||||
|
||||
@@ -40,7 +40,9 @@ const {
|
||||
approvalRunAliases,
|
||||
extractHumanResult,
|
||||
matchesRunLookup,
|
||||
localDateKey
|
||||
localDateKey,
|
||||
resolveRuleVersion,
|
||||
summarizeRuleVersion
|
||||
} = helpers;
|
||||
|
||||
export const approvalRunsTools = [
|
||||
@@ -545,7 +547,9 @@ export const approvalRunsTools = [
|
||||
sourceDocumentId: record.sourceDocumentId,
|
||||
sourceSystem: record.sourceSystem,
|
||||
missing: {
|
||||
hoseDocumentUrl: !hoseDocumentUrl ? "sourceExtendData.hosecloudViewUrl is absent from the approval run detail." : undefined
|
||||
hoseDocumentUrl: !hoseDocumentUrl
|
||||
? `该审批运行未回写 hosecloudViewUrl,无法生成合思原单据直达链接;请到合思主系统以单据编号 ${record.sourceDocumentSN ?? record.sourceDocumentId ?? record.id} 检索原件,或检查该企业的 hosecloud 集成回写配置。`
|
||||
: undefined
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -614,6 +618,97 @@ export const approvalRunsTools = [
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_run_diagnose",
|
||||
description: "一键客诉/单据诊断:按单号 SN 或 recordId 一次聚合单据摘要、AI 判定结果、引用规则、当时的规则版本快照与 Langfuse trace 指针,替代串行调用 pick/get/cited-rules/rules version",
|
||||
parameters: z.object({
|
||||
sn: z.string().optional().describe("合思/易快报单号 (sourceDocumentSN);与 recordId 二选一"),
|
||||
recordId: z.string().optional().describe("Seal approval run record ID;与 sn 二选一"),
|
||||
full: z.boolean().optional().describe("为 true 时附带完整 AI result 原文(默认只带摘要)")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { sn?: string; recordId?: string; full?: boolean },
|
||||
context: ToolContext
|
||||
) => {
|
||||
if (!params.sn && !params.recordId) {
|
||||
throw new Error("sn or recordId is required for approval run diagnosis");
|
||||
}
|
||||
let detail: ApprovalRun;
|
||||
if (params.recordId) {
|
||||
detail = await api.getApprovalRun(client, params.recordId);
|
||||
} else {
|
||||
const { records } = await api.listApprovalRuns(client, {
|
||||
limit: 50,
|
||||
search: params.sn,
|
||||
sourceDocumentSN: params.sn
|
||||
});
|
||||
const matched = records.find((record) =>
|
||||
matchesRunLookup(record, { sourceDocumentSN: params.sn })
|
||||
);
|
||||
if (!matched) {
|
||||
throw new Error(`未找到单号为 ${params.sn} 的审批运行记录;可先用 seal-use approval-runs pick --sn ${params.sn} 确认单号`);
|
||||
}
|
||||
detail = await api.getApprovalRun(client, matched.id);
|
||||
}
|
||||
|
||||
const documentSummary = summarizeApprovalRunDocument(detail);
|
||||
const resultSummary = summarizeApprovalRunResult(detail);
|
||||
const citedRules = extractCitedRules(detail);
|
||||
|
||||
let ruleVersion: {
|
||||
version: ReturnType<typeof summarizeRuleVersion>;
|
||||
citedSnapshots: Array<Record<string, unknown>>;
|
||||
} | undefined;
|
||||
if (detail.ruleSetVersionNumber !== undefined) {
|
||||
try {
|
||||
const version = await resolveRuleVersion(client, { versionNumber: detail.ruleSetVersionNumber });
|
||||
const citedCodes = new Set(
|
||||
(Array.isArray(citedRules?.rules) ? citedRules.rules : [])
|
||||
.map((item) => item && typeof item === "object" ? item as Record<string, unknown> : undefined)
|
||||
.map((item) => item && helpers.parseRuleCodeNumber(item.ruleCode ?? item.code ?? item.runtimeRuleId))
|
||||
.filter((code): code is number => code !== undefined)
|
||||
);
|
||||
const citedSnapshots = (version.rules ?? [])
|
||||
.filter((snapshotRule) => {
|
||||
const object = snapshotRule as Record<string, unknown>;
|
||||
const codeNum = helpers.parseRuleCodeNumber(object.code ?? object.ruleCode ?? object.runtimeRuleId);
|
||||
return codeNum !== undefined && citedCodes.has(codeNum);
|
||||
})
|
||||
.map((snapshotRule) => {
|
||||
const object = snapshotRule as Record<string, unknown>;
|
||||
return {
|
||||
code: object.code ?? object.ruleCode,
|
||||
description: object.description,
|
||||
scope: object.scope,
|
||||
strictness: object.strictness
|
||||
};
|
||||
});
|
||||
ruleVersion = { version: summarizeRuleVersion(version), citedSnapshots };
|
||||
} catch {
|
||||
// 版本快照拉取失败不阻断诊断主流程
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
recordId: detail.id,
|
||||
sourceDocumentSN: detail.sourceDocumentSN,
|
||||
sourceDocumentId: detail.sourceDocumentId,
|
||||
status: detail.status,
|
||||
ruleSetVersionNumber: detail.ruleSetVersionNumber,
|
||||
documentSummary,
|
||||
result: params.full === true ? detail.result : resultSummary,
|
||||
citedRules,
|
||||
ruleVersion,
|
||||
bridge: summarizeRunBridge([detail]),
|
||||
next: {
|
||||
url: `seal-use approval-runs url ${detail.id} --corp ${context.corp.id}`,
|
||||
hoseDocument: `seal-use approval-runs url ${detail.id} --type hose-document --corp ${context.corp.id}`,
|
||||
replay: `seal-use approval-runs replay ${detail.id} --dry-run --corp ${context.corp.id}`
|
||||
}
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_run_langfuse_bridge_get",
|
||||
description: "从 Seal approval run 中抽取 Langfuse 定位信息;优先返回 _langfuseTraceId,没有时给出 hosecloud-{sourceDocumentSN} session 回退",
|
||||
|
||||
@@ -12,6 +12,8 @@ import type {
|
||||
} from "../types.js";
|
||||
import { extractApprovalRunAttachments } from "../attachments.js";
|
||||
import type { LocalRuleItem } from "../rules-local.js";
|
||||
import { loadRuleMappingSnapshot } from "../rule-mapping.js";
|
||||
import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js";
|
||||
|
||||
export type ToolContext = {
|
||||
corp: CorpConfig;
|
||||
@@ -73,6 +75,13 @@ export type ApprovalRunsSummaryOptions = {
|
||||
|
||||
export type RuleField = keyof ApprovalRule;
|
||||
|
||||
/** Render a rule timestamp in the standard Beijing ISO second precision instead of raw epoch millis. */
|
||||
function standardRuleTimestamp(value: unknown): string | undefined {
|
||||
if (typeof value === "number" && Number.isFinite(value) && value > 0) return formatBeijingIso(value);
|
||||
if (typeof value === "string" && value.trim()) return normalizeBeijingIso(value);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function projectApprovalRules(
|
||||
data: { rules: ApprovalRule[]; hasPendingDeletes: boolean },
|
||||
params: {
|
||||
@@ -98,7 +107,12 @@ export function projectApprovalRules(
|
||||
? rules.map((rule) => pickRuleFields(rule, fields))
|
||||
: rules.map((rule) => {
|
||||
const codeNum = parseRuleCodeNumber(rule.code);
|
||||
return codeNum !== undefined ? { ...rule, code: formatRuleCode(codeNum) } : rule;
|
||||
const withCode = codeNum !== undefined ? { ...rule, code: formatRuleCode(codeNum) } : rule;
|
||||
return {
|
||||
...withCode,
|
||||
createdAt: standardRuleTimestamp(rule.createdAt),
|
||||
updatedAt: standardRuleTimestamp(rule.updatedAt)
|
||||
};
|
||||
})
|
||||
};
|
||||
}
|
||||
@@ -110,6 +124,8 @@ export function pickRuleFields(rule: ApprovalRule, fields: readonly RuleField[])
|
||||
if (field === "code") {
|
||||
const codeNum = parseRuleCodeNumber(rule.code);
|
||||
output.code = (codeNum !== undefined ? formatRuleCode(codeNum) : rule.code) as never;
|
||||
} else if (field === "createdAt" || field === "updatedAt") {
|
||||
output[field] = standardRuleTimestamp(rule[field]) as never;
|
||||
} else {
|
||||
output[field] = rule[field] as never;
|
||||
}
|
||||
@@ -906,8 +922,8 @@ export function summarizeRuleVersion(version: RuleSetVersion) {
|
||||
publishedBy: version.publishedBy,
|
||||
publishedByName: version.publishedByName,
|
||||
rulesCount: version.rules.length,
|
||||
publishedAt: version.publishedAt,
|
||||
createdAt: version.createdAt
|
||||
publishedAt: standardRuleTimestamp(version.publishedAt),
|
||||
createdAt: standardRuleTimestamp(version.createdAt)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -957,8 +973,8 @@ export function findRuleInDraft(
|
||||
scope: rule.scope,
|
||||
strictness: rule.strictness,
|
||||
status: rule.status,
|
||||
createdAt: rule.createdAt,
|
||||
updatedAt: rule.updatedAt
|
||||
createdAt: standardRuleTimestamp(rule.createdAt),
|
||||
updatedAt: standardRuleTimestamp(rule.updatedAt)
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1017,7 +1033,7 @@ export function findRuleInVersion(
|
||||
versionId: version.id,
|
||||
versionNumber: version.versionNumber,
|
||||
versionName: version.versionName,
|
||||
publishedAt: version.publishedAt,
|
||||
publishedAt: standardRuleTimestamp(version.publishedAt),
|
||||
publishedByName: version.publishedByName,
|
||||
description: rule.description,
|
||||
scope: rule.scope,
|
||||
@@ -1026,6 +1042,49 @@ export function findRuleInVersion(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the cross-environment rule code from the latest sync-test mapping snapshot, when one
|
||||
* exists. Mapping snapshots are saved under the test (target) corp id, so a test corp reads its own
|
||||
* snapshot directly while a production corp reads the snapshot of its bound test tenant.
|
||||
*/
|
||||
export function resolveCrossEnvRuleMapping(
|
||||
corp: CorpConfig,
|
||||
rule: { code?: unknown; id?: unknown }
|
||||
): {
|
||||
environment: "production" | "test";
|
||||
code: string;
|
||||
direction: "prodToTest" | "testToProd";
|
||||
syncedAt: string;
|
||||
} | undefined {
|
||||
const codeNum = parseRuleCodeNumber(rule.code);
|
||||
const ruleId = stringFromUnknown(rule.id);
|
||||
if (codeNum === undefined && !ruleId) return undefined;
|
||||
const direction = corp.environment === "test" ? "testToProd" : "prodToTest";
|
||||
const snapshot = corp.environment === "test"
|
||||
? loadRuleMappingSnapshot(corp.id)
|
||||
: corp.testCorpId
|
||||
? loadRuleMappingSnapshot(corp.testCorpId)
|
||||
: null;
|
||||
if (!snapshot) return undefined;
|
||||
const item = snapshot.ruleMapping.find((mapping) => {
|
||||
if (direction === "prodToTest") {
|
||||
return (codeNum !== undefined && parseRuleCodeNumber(mapping.sourceRuleCode) === codeNum)
|
||||
|| (ruleId !== undefined && mapping.sourceRuleId === ruleId);
|
||||
}
|
||||
return (codeNum !== undefined && parseRuleCodeNumber(mapping.targetRuleCode) === codeNum)
|
||||
|| (ruleId !== undefined && mapping.targetRuleId === ruleId);
|
||||
});
|
||||
if (!item) return undefined;
|
||||
const crossCode = direction === "prodToTest" ? item.targetRuleCode : item.sourceRuleCode;
|
||||
const crossCodeNum = parseRuleCodeNumber(crossCode);
|
||||
return {
|
||||
environment: direction === "prodToTest" ? "test" : "production",
|
||||
code: crossCodeNum !== undefined ? formatRuleCode(crossCodeNum) : String(crossCode),
|
||||
direction,
|
||||
syncedAt: snapshot.syncedAt
|
||||
};
|
||||
}
|
||||
|
||||
export function parseRuleCodeNumber(value: unknown): number | undefined {
|
||||
if (typeof value === "number" && Number.isInteger(value) && value >= 0) {
|
||||
return value;
|
||||
|
||||
@@ -53,6 +53,7 @@ export const SEAL_READ_ONLY_TOOLS: ReadonlySet<string> = new Set([
|
||||
"seal_approval_rules_pull",
|
||||
"seal_approval_run_attachments_get",
|
||||
"seal_approval_run_cited_rules_get",
|
||||
"seal_approval_run_diagnose",
|
||||
"seal_approval_run_document_summary_get",
|
||||
"seal_approval_run_flow_get",
|
||||
"seal_approval_run_get",
|
||||
|
||||
@@ -3,6 +3,7 @@ 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";
|
||||
@@ -37,9 +38,15 @@ const {
|
||||
normalizeRuleCode,
|
||||
formatRuleCode,
|
||||
resolveRuleVersion,
|
||||
resolveRuleVersionSelector
|
||||
resolveRuleVersionSelector,
|
||||
resolveCrossEnvRuleMapping
|
||||
} = helpers;
|
||||
|
||||
function attachCrossEnvRule(context: ToolContext, rule: Record<string, unknown>) {
|
||||
const crossEnv = resolveCrossEnvRuleMapping(context.corp, rule);
|
||||
return crossEnv ? { ...rule, crossEnv } : rule;
|
||||
}
|
||||
|
||||
export const rulesTools = [
|
||||
{
|
||||
name: "seal_approval_rules_list",
|
||||
@@ -183,47 +190,77 @@ export const rulesTools = [
|
||||
},
|
||||
{
|
||||
name: "seal_approval_rule_update",
|
||||
description: "更新 Seal 草稿审批规则",
|
||||
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()
|
||||
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 }
|
||||
params: {
|
||||
ruleId: string;
|
||||
description?: string;
|
||||
scope?: string;
|
||||
strictness?: string;
|
||||
ifUnchanged?: string | number;
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
let resolvedRuleId = params.ruleId.trim();
|
||||
const targetCodeNum = parseRuleCodeNumber(resolvedRuleId);
|
||||
if (targetCodeNum !== undefined) {
|
||||
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 || parseRuleCodeNumber(r.code) === targetCodeNum
|
||||
(r) => r.id === resolvedRuleId || (targetCodeNum !== undefined && parseRuleCodeNumber(r.code) === targetCodeNum)
|
||||
);
|
||||
if (!matched) {
|
||||
throw new Error(`未在当前草稿中找到编号为 ${params.ruleId} 的规则`);
|
||||
}
|
||||
resolvedRuleId = matched.id;
|
||||
draftRule = matched;
|
||||
}
|
||||
}
|
||||
const { ruleId: _ruleId, ...rest } = params;
|
||||
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);
|
||||
|
||||
if (params.description) {
|
||||
const finalDescription = result?.description ?? params.description;
|
||||
if (finalDescription && loadGlobalConfig().lint?.enabled !== false) {
|
||||
try {
|
||||
const globalConfig = loadGlobalConfig();
|
||||
if (globalConfig.lint?.enabled) {
|
||||
const loaded = await loadRuleLinter(globalConfig.lint.activeLinter);
|
||||
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) {
|
||||
console.error(` • [${issue.level.toUpperCase()}] ${issue.message}${issue.snippet ? ` ("${issue.snippet}")` : ""}`);
|
||||
if (issue.suggestion) {
|
||||
console.error(` 👉 建议: ${issue.suggestion}`);
|
||||
}
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -404,7 +441,7 @@ export const rulesTools = [
|
||||
if (!explicitVersion && draftData?.rules) {
|
||||
const draftMatch = findRuleInDraft(draftData.rules, selector);
|
||||
if (draftMatch) {
|
||||
return draftMatch;
|
||||
return attachCrossEnvRule(context, draftMatch);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -425,7 +462,7 @@ export const rulesTools = [
|
||||
: `Rule not found in current draft or version ${version.versionNumber}`
|
||||
);
|
||||
}
|
||||
return rule;
|
||||
return attachCrossEnvRule(context, rule);
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user