From 8c7cb219a0f57eedca84b871fd6b73bd2d8dcee7 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 13 Oct 2026 02:24:41 +0000 Subject: [PATCH] Organize Seal modules and add guarded rule recoding --- .agents/rules/typescript-style.md | 5 + AGENTS.md | 2 + README.md | 6 +- skills/seal-use/SKILL.md | 10 +- skills/seal-use/references/cli.md | 2 + .../seal-use/references/rule-lightweight.md | 13 ++ src/cli/commands/analytics.ts | 2 +- src/cli/commands/approval-runs.ts | 4 +- src/cli/commands/corps-bind.test.ts | 12 +- src/cli/commands/corps/onboarding.ts | 2 +- src/cli/commands/corps/sync.ts | 6 +- src/cli/commands/deploy.ts | 2 +- src/cli/commands/rules-recode.test.ts | 103 ++++++++++ src/cli/commands/rules.ts | 14 +- src/cli/commands/source.ts | 2 +- src/cli/commands/webhook.ts | 4 +- src/cli/help.test.ts | 8 + src/cli/help.ts | 6 + src/cli/parser.ts | 4 +- src/domains/enterprise/onboarding.ts | 2 +- src/domains/hose/onboarding.ts | 2 +- src/domains/seal/api.ts | 22 +- .../{ => approval-runs}/attachments.test.ts | 2 +- .../seal/{ => approval-runs}/attachments.ts | 2 +- .../export.test.ts} | 4 +- .../export.ts} | 10 +- .../seal/capabilities/approval-runs.ts | 4 +- .../{ => capabilities}/capabilities.test.ts | 8 +- src/domains/seal/capabilities/deploy.ts | 2 +- src/domains/seal/capabilities/helpers.ts | 6 +- src/domains/seal/capabilities/index.ts | 1 + src/domains/seal/capabilities/insight.ts | 2 +- src/domains/seal/capabilities/rules.ts | 28 ++- src/domains/seal/capabilities/webhook.ts | 2 +- .../seal/{ => enterprise}/onboarding.ts | 12 +- src/domains/seal/{ => enterprise}/source.ts | 10 +- .../export.test.ts} | 4 +- .../{insight-export.ts => insight/export.ts} | 10 +- src/domains/seal/material-pack/export.ts | 2 +- .../push.test.ts} | 6 +- .../{outbound-push.ts => outbound/push.ts} | 10 +- src/domains/seal/regression/service.ts | 2 +- .../hose-outbound.test.ts} | 4 +- .../hose-outbound.ts} | 16 +- .../safety.test.ts} | 4 +- .../{replay-safety.ts => replay/safety.ts} | 4 +- .../webhook.test.ts} | 6 +- .../{webhook-replay.ts => replay/webhook.ts} | 16 +- .../{rule-diff.test.ts => rules/diff.test.ts} | 4 +- .../seal/{rule-diff.ts => rules/diff.ts} | 2 +- .../local.test.ts} | 4 +- .../seal/{rules-local.ts => rules/local.ts} | 2 +- .../mapping.test.ts} | 2 +- .../{rule-mapping.ts => rules/mapping.ts} | 4 +- src/domains/seal/rules/recode-tickets.test.ts | 74 +++++++ src/domains/seal/rules/recode-tickets.ts | 105 ++++++++++ src/domains/seal/rules/recode.test.ts | 192 ++++++++++++++++++ src/domains/seal/rules/recode.ts | 117 +++++++++++ .../version-snapshot.test.ts} | 4 +- .../version-snapshot.ts} | 6 +- .../service.test.ts} | 4 +- .../seal/{search.ts => search/service.ts} | 8 +- .../seal/{test-sync.ts => testing/sync.ts} | 17 +- src/probe.ts | 2 +- src/server.ts | 11 + 65 files changed, 837 insertions(+), 131 deletions(-) create mode 100644 src/cli/commands/rules-recode.test.ts rename src/domains/seal/{ => approval-runs}/attachments.test.ts (99%) rename src/domains/seal/{ => approval-runs}/attachments.ts (99%) rename src/domains/seal/{approval-runs-export.test.ts => approval-runs/export.test.ts} (99%) rename src/domains/seal/{approval-runs-export.ts => approval-runs/export.ts} (99%) rename src/domains/seal/{ => capabilities}/capabilities.test.ts (99%) rename src/domains/seal/{ => enterprise}/onboarding.ts (92%) rename src/domains/seal/{ => enterprise}/source.ts (72%) rename src/domains/seal/{insight-export.test.ts => insight/export.test.ts} (98%) rename src/domains/seal/{insight-export.ts => insight/export.ts} (97%) rename src/domains/seal/{outbound-push.test.ts => outbound/push.test.ts} (99%) rename src/domains/seal/{outbound-push.ts => outbound/push.ts} (97%) rename src/domains/seal/{hose-outbound-replay.test.ts => replay/hose-outbound.test.ts} (99%) rename src/domains/seal/{hose-outbound-replay.ts => replay/hose-outbound.ts} (96%) rename src/domains/seal/{replay-safety.test.ts => replay/safety.test.ts} (94%) rename src/domains/seal/{replay-safety.ts => replay/safety.ts} (89%) rename src/domains/seal/{webhook-replay.test.ts => replay/webhook.test.ts} (99%) rename src/domains/seal/{webhook-replay.ts => replay/webhook.ts} (97%) rename src/domains/seal/{rule-diff.test.ts => rules/diff.test.ts} (97%) rename src/domains/seal/{rule-diff.ts => rules/diff.ts} (99%) rename src/domains/seal/{rules-local.test.ts => rules/local.test.ts} (98%) rename src/domains/seal/{rules-local.ts => rules/local.ts} (98%) rename src/domains/seal/{rule-mapping.test.ts => rules/mapping.test.ts} (99%) rename src/domains/seal/{rule-mapping.ts => rules/mapping.ts} (97%) create mode 100644 src/domains/seal/rules/recode-tickets.test.ts create mode 100644 src/domains/seal/rules/recode-tickets.ts create mode 100644 src/domains/seal/rules/recode.test.ts create mode 100644 src/domains/seal/rules/recode.ts rename src/domains/seal/{rule-version-snapshot.test.ts => rules/version-snapshot.test.ts} (96%) rename src/domains/seal/{rule-version-snapshot.ts => rules/version-snapshot.ts} (96%) rename src/domains/seal/{search.test.ts => search/service.test.ts} (97%) rename src/domains/seal/{search.ts => search/service.ts} (98%) rename src/domains/seal/{test-sync.ts => testing/sync.ts} (97%) diff --git a/.agents/rules/typescript-style.md b/.agents/rules/typescript-style.md index e1f92d3..6c0873d 100644 --- a/.agents/rules/typescript-style.md +++ b/.agents/rules/typescript-style.md @@ -25,6 +25,11 @@ When modifying or adding TypeScript files in `src/`: 4. **Architecture**: - Prefer small, cohesive domain functions over large generic utility files. + - Place Seal business implementations and their colocated tests in the matching + feature directory under `src/domains/seal/`, for example `rules/recode.ts` + and `rules/recode.test.ts`. The domain root is reserved for `api.ts`, + `api.test.ts`, `types.ts`, and `capabilities.ts`; do not add business files + or old-path forwarding stubs there. See `AGENTS.md` for the feature layout. 5. **Frozen Utility Modules**: - `src/domains/seal/capabilities/helpers.ts` is FROZEN: no new exports. It is diff --git a/AGENTS.md b/AGENTS.md index 37d70fa..79f9eda 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,6 +6,8 @@ This is a Bun + TypeScript toolkit for the `seal-use` CLI and a local stdio MCP The repository doubles as a ZCode plugin: `.zcode-plugin/plugin.json` declares a skills-only plugin manifest and the agent skill lives under `skills/seal-use/`. The plugin ships no MCP surface; the local MCP runs from the CLI (`seal-use mcp`, or the `mcp-config` snippet for Cursor/Claude Desktop). The in-repo `.agents/skills/seal-use` symlink has been dropped; workspace and Codex skill loading use the global `~/.agents/skills/seal-use` copy installed by `seal-use skill install`. +Within `src/domains/seal/`, the root contains only shared protocol boundaries (`api.ts`, `api.test.ts`, `types.ts`) and the public capability export (`capabilities.ts`). Business implementations belong in their feature directories: `rules/`, `approval-runs/`, `insight/`, `replay/`, `outbound/`, `enterprise/`, `search/`, and `testing/`; existing `reports/`, `linter/`, `material-pack/`, `doctor/`, and `regression/` retain their own boundaries. Put new Seal implementations and their tests in the matching feature directory (for example `rules/recode.ts` and `rules/recode.test.ts`), rather than adding business files or legacy forwarding stubs to the domain root. The registry-wide tests live in `capabilities/capabilities.test.ts`. + Tests are colocated as `*.test.ts` files in `src/`. ## Build, Test, and Development Commands diff --git a/README.md b/README.md index a3dc772..bba0521 100644 --- a/README.md +++ b/README.md @@ -214,7 +214,7 @@ Most users do not need MCP. The public/shared path is the global `seal-use` CLI. ### One registry, two doors -All approval/logic lives once in the capability registry under `src/domains/seal/capabilities/` (`src/domains/seal/capabilities.ts` re-exports it). Two surfaces enter the same handlers, each with its own naming: +Shared approval behavior lives in the business modules under `src/domains/seal/`; the capability registry under `src/domains/seal/capabilities/` dispatches it (`src/domains/seal/capabilities.ts` re-exports the registry). Two surfaces enter the same handlers, each with its own naming: | Surface | Entry | Naming | | --- | --- | --- | @@ -240,6 +240,8 @@ Both run the same CLI dispatcher as the global binary, so `config` and `update` ## CLI-First Architecture +Seal implementations and their tests are grouped by feature: `src/domains/seal/rules/` owns local rule files, diffs, mappings, version snapshots, recoding and confirmation tickets; `approval-runs/` owns record export and attachments; `insight/` owns insight export; `replay/` owns Webhook/Hose replay and environment guards; `outbound/` owns downstream pushes; `enterprise/` owns Seal onboarding and identity resolution; `search/` owns cross-resource search; and `testing/` owns test-enterprise synchronization. Existing `reports/`, `linter/`, `material-pack/`, `doctor/` and `regression/` stay separate. Only shared API/types and the capability export remain at the domain root. + All Agent and automation capabilities are accessed through standard `seal-use ` CLI invocations (or through the `seal_use` / `seal_use_write` MCP tools passing the command string). Internal domain services output pure, parseable JSON on `stdout`, with human diagnostics and suggestions routed to `stderr`. Key CLI command groups: @@ -256,6 +258,8 @@ For rule list commands, prefer `seal-use rules count --corp ` or `seal-u For test tenants that need a clean slate before importing another rule set, use `seal-use rules clear --corp --dry-run` first, then `seal-use rules clear --corp --yes` to delete the current draft rules and verify the remaining count. +To compact draft rule numbers from `0000`, run `seal-use rules recode --corp `. The first call returns an impact preview and an enterprise/environment/draft-bound one-use credential (exit 10), without executing the recode. Inspect the preview, then run the returned `nextCommand` separately; the credential expires after five minutes, and `--yes` cannot bypass it. `--dry-run` only previews. The server determines ordering, and every rule can change number; the verified per-rule mapping is returned after execution. Recode does not publish a version; old rule numbers must be interpreted with their published version. Clearing and test synchronization reset numbering only after verifying an empty draft. + For approval run detail commands, prefer the same commands with explicit `--corp `—for example `seal-use approval-runs pick --corp --sn <单号> --latest` or `seal-use approval-runs get --corp --summary`—before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-use auth hose-link --corp --expire 7200`, which returns the unredacted `getProvisionalAuth` URL. ## Approval Run To Langfuse Bridge diff --git a/skills/seal-use/SKILL.md b/skills/seal-use/SKILL.md index 7ddb08a..a068225 100644 --- a/skills/seal-use/SKILL.md +++ b/skills/seal-use/SKILL.md @@ -63,6 +63,14 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr 生产规则变更遵循:生产改草稿 → 同步测试 → 模拟/回归验证 → 用户确认 → 生产发布。`sync-test`、`replay-test`、规则发布和清空等高风险操作优先 `--dry-run`,正式执行必须显式 `--yes` 或 `--confirm`。 +## 规则编号重排:两次调用 + +`seal-use rules recode --corp ` 将当前草稿编号从 `0000` 连续编排。具体顺序由服务端决定,新建草稿可能排在已有规则之前;所有规则均可能变号,不能把预览中的编号范围当作逐条映射。第一次只返回影响预览、6 位一次性凭证、到期时间和 `nextCommand`,`executed: false`,退出码为 10;尚未执行重排。核对目标企业和完整影响范围后,另一次调用返回的完整命令才执行;成功返回的 `changes` 是按稳定身份回读验证的真实编号映射。 + +凭证绑定企业、环境及草稿状态,5 分钟有效且只能使用一次;`--yes` / `--confirm` 不能替代凭证。`--dry-run` 只预览,不签发凭证。确认码尚未生效时停止连调,不把两阶段写成自动执行脚本;草稿变化或凭证失效时重新预览。执行失败或超时后先回读当前草稿,再决定是否重新申请,不能重用旧码或盲目重跑。 + +重排不发布版本。旧编号可能对应不同规则,查看历史记录需指定发布版本。具体预览与返回字段见 `references/rule-lightweight.md`。 + ## 业务术语契约 对外统一使用以下术语: @@ -93,7 +101,7 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr | 按单号、SN、record ID 查审批、结论、引用规则或直达链接 | `references/approval-run-lightweight.md` | 明确涉及附件/OCR/发票争议时,转读 `approval-attachment-trace.md` | | CLI 参数、退出码或命令语法 | `references/cli.md` | 只查业务流程时不要加载本文件 | | Webhook 资源包(ZIP/Excel 结构、附件校验、策略配置) | `references/webhook-resource-pack.md` | 只查命令语法时读 `cli.md`,不要加载本文件 | -| 规则数量、摘要列表、历史规则、制度文档(`documents`)或知识搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` | +| 规则数量、摘要列表、历史规则、编号重排、制度文档(`documents`)或知识搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` | | 规则质量评分、lint、发布前质检 | `references/rule-lint.md` | 不要把 lint 问题直接当成客诉根因 | | 客诉、截图/通知、预期业务行为,并要求诊断或修改规则 | `references/customer-feedback-rule-remediation.md` | 只有该流程明确要求附件追踪或测试发布时,才追加对应 reference | | Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` | diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index d1b0586..b44a61d 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -58,6 +58,7 @@ seal-use rules linters [--corp ] seal-use rules pull [--version ] [--out ] [--corp ] seal-use rules push [--file ] [--publish] [--version-name ] [--dry-run|--yes] [--corp ] seal-use rules clear [--dry-run|--yes] [--corp ] +seal-use rules recode [--dry-run] --corp seal-use rules map [--version ] [--code ] [--corp ] seal-use documents list [--scenarios ] [--limit 50] [--offset 0] [--corp ] seal-use documents get [--corp ] @@ -303,6 +304,7 @@ Approval rule maintenance: - `seal-use rules pull [--version ] [--out ] [--corp ]` - `seal-use rules push [--file ] [--publish] [--version-name ] [--dry-run|--yes] [--corp ]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Run `--dry-run` first; a local file exported with `rules pull` is preferred. - `seal-use rules clear [--dry-run|--yes] [--corp ]` +- `seal-use rules recode [--dry-run] --corp `: first returns an unexecuted numbering preview and a one-use credential (exit 10). Inspect the preview, then invoke the returned `nextCommand` separately. The credential is enterprise/environment/draft-bound, valid for five minutes, and cannot be replaced by `--yes`/`--confirm`. `--dry-run` only previews (exit 0). Recode does not publish; failed/uncertain executions require a draft read before another request. Do not script both phases into automatic consecutive execution. - `seal-use rules map [--version ] [--code ] [--corp ]` (reads local sync rule mapping snapshot) Rule identity and versioning (Draft by default vs. `--version latest`): diff --git a/skills/seal-use/references/rule-lightweight.md b/skills/seal-use/references/rule-lightweight.md index 04785ac..8b94411 100644 --- a/skills/seal-use/references/rule-lightweight.md +++ b/skills/seal-use/references/rule-lightweight.md @@ -92,6 +92,19 @@ Expected shape: } ``` +## Recode Draft Rule Numbers + +```bash +seal-use rules recode --corp +seal-use rules recode --dry-run --corp +``` + +The first command returns a preview, a six-character one-use confirmation code, `expiresAt`, and `nextCommand`, with `executed: false` and exit code 10. Inspect the enterprise and full impact scope, then invoke the returned command separately. Preview `changesDiff` shows the existing and resulting number ranges, not a per-rule mapping (`mappingAvailable: false`); every rule can change number. The code is bound to the enterprise, environment and exact draft state, expires in five minutes, and is consumed before the POST. Ordinary `--yes`/`--confirm` cannot bypass this flow. Do not combine both phases into an automatic script. + +`--dry-run` returns only the preview (exit 0) without issuing a code. A successful second call returns `executed: true`, the verified per-rule `changes` (`mappingAvailable: true`), and `nextCode`. Recode starts at `0000`, and the server determines ordering: new drafts may move before existing active rules. It does not publish. A not-yet-active code should not trigger immediate repeated calls. On expiry or draft changes request a fresh preview; on POST failure/timeout, read the current draft before requesting another code. A spent code is never reusable. + +Clearing rules and test synchronization reset the allocation counter only after verifying the draft is empty. If clear leaves any rules behind, it skips automatic recoding and reports a warning. + ## Output Discipline If a rule command would return many descriptions or more than about 20 rules, use `rules count`, `rules list --summary`, `rules search`, or `--output-file`. Use `--full` only for deliberate exports. diff --git a/src/cli/commands/analytics.ts b/src/cli/commands/analytics.ts index 5e6b3c4..e348bc8 100644 --- a/src/cli/commands/analytics.ts +++ b/src/cli/commands/analytics.ts @@ -1,6 +1,6 @@ import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; -import { exportInsightReportToExcel } from "../../domains/seal/insight-export.js"; +import { exportInsightReportToExcel } from "../../domains/seal/insight/export.js"; import { runCapability } from "../helpers.js"; import { booleanOption, numberOption, stringOption } from "../parser.js"; import { outputOptions, printJson } from "../printer.js"; diff --git a/src/cli/commands/approval-runs.ts b/src/cli/commands/approval-runs.ts index 7802853..b98852d 100644 --- a/src/cli/commands/approval-runs.ts +++ b/src/cli/commands/approval-runs.ts @@ -1,11 +1,11 @@ import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import * as api from "../../domains/seal/api.js"; -import { exportApprovalRunsToExcel, normalizeTimestamp } from "../../domains/seal/approval-runs-export.js"; +import { exportApprovalRunsToExcel, normalizeTimestamp } from "../../domains/seal/approval-runs/export.js"; import { downloadApprovalRunAttachments, extractApprovalRunAttachments -} from "../../domains/seal/attachments.js"; +} from "../../domains/seal/approval-runs/attachments.js"; import { runCapability, runCapabilityResult } from "../helpers.js"; import { booleanOption, numberOption, stringOption } from "../parser.js"; import { outputOptions, printJson } from "../printer.js"; diff --git a/src/cli/commands/corps-bind.test.ts b/src/cli/commands/corps-bind.test.ts index 7f68281..caf16b3 100644 --- a/src/cli/commands/corps-bind.test.ts +++ b/src/cli/commands/corps-bind.test.ts @@ -355,6 +355,10 @@ describe("corps sync-test", () => { expect(createdRules.length).toBe(2); expect((createdRules[0]!.body as any).description).toBe("Production Rule A"); expect((createdRules[1]!.body as any).description).toBe("Production Rule B"); + const resetIndex = requests.findIndex(r => r.path === "/api/v1/rules/batch-recode"); + const firstCreateIndex = requests.findIndex(r => r.method === "POST" && r.path === "/api/v1/rules"); + expect(resetIndex).toBeGreaterThanOrEqual(0); + expect(resetIndex).toBeLessThan(firstCreateIndex); const publishVersion = requests.find((r) => r.method === "POST" && r.path === "/api/v1/rule-set-versions/publish"); expect(publishVersion).toBeDefined(); @@ -909,6 +913,9 @@ describe("corps replay-test", () => { function mockSealSyncRequests(options: { onMutation?: (method: string, path: string, body?: unknown) => void; } = {}) { + let remainingTestRules = [ + { id: "test-rule-old", description: "Old test rule", scope: "global", strictness: "strict" } + ]; globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const requestUrl = typeof input === "string" ? input @@ -1071,9 +1078,7 @@ function mockSealSyncRequests(options: { } else { return jsonResponse({ data: { - rules: [ - { id: "test-rule-old", description: "Old test rule", scope: "global", strictness: "strict" } - ], + rules: remainingTestRules, hasPendingDeletes: false } }); @@ -1082,6 +1087,7 @@ function mockSealSyncRequests(options: { if (url.pathname.startsWith("/api/v1/rules/") && method === "DELETE") { options.onMutation?.("DELETE", url.pathname); + remainingTestRules = remainingTestRules.filter(rule => rule.id !== url.pathname.split("/").pop()); return jsonResponse({ data: { success: true } }); } diff --git a/src/cli/commands/corps/onboarding.ts b/src/cli/commands/corps/onboarding.ts index 58a969a..dfe50f9 100644 --- a/src/cli/commands/corps/onboarding.ts +++ b/src/cli/commands/corps/onboarding.ts @@ -1,6 +1,6 @@ import { maskHoseSecurity } from "../../../core/auth/hose.js"; import { scoreAssistLink } from "../../../core/auth/delegate.js"; -import { onboardSealBearer } from "../../../domains/seal/onboarding.js"; +import { onboardSealBearer } from "../../../domains/seal/enterprise/onboarding.js"; import { onboardAssistanceLink } from "../../../domains/enterprise/onboarding.js"; import { listHoseStaffs, diff --git a/src/cli/commands/corps/sync.ts b/src/cli/commands/corps/sync.ts index 71f298b..f397a79 100644 --- a/src/cli/commands/corps/sync.ts +++ b/src/cli/commands/corps/sync.ts @@ -1,14 +1,14 @@ import { createSealClient } from "../../../core/http/factory.js"; import type { CorpConfig } from "../../../core/config/types.js"; -import { syncTestEnterprise } from "../../../domains/seal/test-sync.js"; -import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../domains/seal/webhook-replay.js"; +import { syncTestEnterprise } from "../../../domains/seal/testing/sync.js"; +import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../domains/seal/replay/webhook.js"; import { selectCorp } from "../../helpers.js"; import { CliError, confirmationRequired, usageError } from "../../errors.js"; import { booleanOption, numberOption, stringOption } from "../../parser.js"; import { outputOptions, printJson } from "../../printer.js"; import type { ParsedArgs } from "../../types.js"; -export { buildTestHosecloudOutboundName } from "../../../domains/seal/test-sync.js"; +export { buildTestHosecloudOutboundName } from "../../../domains/seal/testing/sync.js"; export async function handleCorpSync( action: string | undefined, diff --git a/src/cli/commands/deploy.ts b/src/cli/commands/deploy.ts index ed45782..53f85aa 100644 --- a/src/cli/commands/deploy.ts +++ b/src/cli/commands/deploy.ts @@ -6,7 +6,7 @@ import { booleanOption, jsonObject, numberOption, stringOption } from "../parser import { outputOptions } from "../printer.js"; import type { ParsedArgs } from "../types.js"; import * as api from "../../domains/seal/api.js"; -import { listHoseIntegrations } from "../../domains/seal/outbound-push.js"; +import { listHoseIntegrations } from "../../domains/seal/outbound/push.js"; import { CliError } from "../errors.js"; export async function handleDeployCommand( diff --git a/src/cli/commands/rules-recode.test.ts b/src/cli/commands/rules-recode.test.ts new file mode 100644 index 0000000..6395b20 --- /dev/null +++ b/src/cli/commands/rules-recode.test.ts @@ -0,0 +1,103 @@ +import { expect, test } from "bun:test" +import { Client, InMemoryTransport } from "@modelcontextprotocol/client" +import { randomBytes } from "node:crypto" +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { createServer, SEAL_USE_MCP_TOOL_NAME, SEAL_USE_MCP_WRITE_TOOL_NAME } from "../../server.js" + +test("separate CLI processes share one-use tickets and MCP retains the first-phase JSON preview", async () => { + const dir = mkdtempSync(join(tmpdir(), "seal-recode-cli-")) + const corpId = `recode-${randomBytes(4).toString("hex")}` + let posts = 0 + const rules = [ + { id: "a", tenantId: "tenant", code: 0, description: "First", scope: "ALL", strictness: "MUST_FOLLOW", status: "ACTIVE" }, + { id: "b", tenantId: "tenant", code: 2, description: "Second", scope: "ALL", strictness: "MUST_FOLLOW", status: "ACTIVE" } + ] + const upstream = Bun.serve({ + hostname: "127.0.0.1", port: 0, + fetch(request) { + const path = new URL(request.url).pathname + if (path === "/api/v1/rules" && request.method === "GET") { + return Response.json({ data: { rules, hasPendingDeletes: false } }) + } + if (path === "/api/v1/auth/me") { + return Response.json({ data: { user: { id: "operator", tenantId: "tenant", name: "Operator" }, tenant: { id: "tenant", name: "Test" } } }) + } + if (path === "/api/v1/rules/batch-recode" && request.method === "POST") { + posts++ + rules.forEach((rule, index) => { rule.code = index }) + return Response.json({ data: { activeRules: 2, pendingDeleteRules: 0, nextCode: 2 } }) + } + return Response.json({ error: "Unexpected request" }, { status: 404 }) + } + }) + const enterprises = join(dir, "enterprises") + const store = join(dir, "tickets.sqlite") + mkdirSync(enterprises) + const url = `http://127.0.0.1:${upstream.port}` + writeFileSync(join(enterprises, "corp.json"), JSON.stringify({ + id: corpId, name: "CLI Test", environment: "test", + seal: { url }, source: { type: "seal", token: "test-token", sealUrl: url } + })) + writeFileSync(join(dir, "config.json"), JSON.stringify({ stateful: false })) + const env = { + SEAL_USE_ENTERPRISES_DIR: enterprises, + SEAL_USE_CONFIG_FILE: join(dir, "config.json"), + SEAL_USE_TOKEN_STORE: join(dir, "tokens.json"), + SEAL_USE_USAGE_FILE: join(dir, "usage.json"), + SEAL_USE_RECODE_STORE: store, + SEAL_DISABLE_BG_UPDATE: "1" + } + const previous = Object.fromEntries(Object.keys(env).map(key => [key, process.env[key]])) + const server = createServer({ enableCli: true }) + const client = new Client({ name: "recode-preview-test", version: "1.0.0" }) + const run = async (args: string[]) => { + const child = Bun.spawn([process.execPath, join(import.meta.dirname, "../../cli.ts"), "rules", "recode", "--corp", corpId, ...args], { + env: { ...process.env, ...env }, stdout: "pipe", stderr: "pipe" + }) + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited + ]) + return { stdout, stderr, exitCode } + } + try { + const dry = await run(["--dry-run"]) + expect(dry.exitCode).toBe(0) + expect(JSON.parse(dry.stdout).executed).toBe(false) + expect(existsSync(store)).toBe(false) + const first = await run(["--yes"]) + expect(first.exitCode).toBe(10) + const preview = JSON.parse(first.stdout) + expect(preview).toMatchObject({ phase: "confirmation_required", executed: false, impactCount: 2, mappingAvailable: false }) + expect(first.stderr).toContain(preview.nextCommand) + expect(posts).toBe(0) + await Bun.sleep(510) + const competed = await Promise.all([run(["--confirm-code", preview.confirmCode]), run(["--confirmCode", preview.confirmCode])]) + expect(competed.map(result => result.exitCode).sort()).toEqual([0, 10]) + const executed = JSON.parse(competed.find(result => result.exitCode === 0)!.stdout) + expect(executed).toMatchObject({ executed: true, nextCode: 2 }) + expect(executed.changes).toEqual([{ beforeCode: "0000", afterCode: "0000" }, { beforeCode: "0002", afterCode: "0001" }]) + expect(posts).toBe(1) + + for (const [key, value] of Object.entries(env)) process.env[key] = value + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair() + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]) + const denied = await client.callTool({ name: SEAL_USE_MCP_TOOL_NAME, arguments: { command: `rules recode --corp ${corpId}` } }) + expect(denied.isError).toBe(true) + const result = await client.callTool({ name: SEAL_USE_MCP_WRITE_TOOL_NAME, arguments: { command: `rules recode --corp ${corpId}` } }) + expect(result.isError).toBe(true) + const content = result.content as Array<{ type: "text"; text: string }> + expect(JSON.parse(content[0]!.text)).toMatchObject({ executed: false, phase: "confirmation_required" }) + expect(content[1]!.text).toContain("nextCommand") + expect(posts).toBe(1) + } finally { + await Promise.allSettled([client.close(), server.close()]) + upstream.stop(true) + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } + rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/src/cli/commands/rules.ts b/src/cli/commands/rules.ts index a157a2f..93d8387 100644 --- a/src/cli/commands/rules.ts +++ b/src/cli/commands/rules.ts @@ -1,7 +1,7 @@ import { readFileSync } from "node:fs"; import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; -import { filterRuleMapping, loadRuleMappingSnapshot } from "../../domains/seal/rule-mapping.js"; +import { filterRuleMapping, loadRuleMappingSnapshot } from "../../domains/seal/rules/mapping.js"; import { listAvailableLinters, PRIMARY_LINTERS_DIR, @@ -66,6 +66,18 @@ export async function handleRulesCommand( return; } + if (action === "recode") { + const result = await runCapabilityResult("sealApprovalRulesRecode", client!, corp, { + dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]), + confirmCode: stringOption(args.options.confirmCode) ?? stringOption(args.options["confirm-code"]) + }) as { phase: string; nextCommand?: string }; + printJson(result, outputOptions(args.options)); + if (result.phase === "confirmation_required") { + throw confirmationRequired("尚未执行规则重排。请核对预览后运行返回的 nextCommand。", result.nextCommand!); + } + return; + } + if (action === "list") { const version = resolveVersionOption(args); if (booleanOption(args.options.count)) { diff --git a/src/cli/commands/source.ts b/src/cli/commands/source.ts index 43cb64c..31dc354 100644 --- a/src/cli/commands/source.ts +++ b/src/cli/commands/source.ts @@ -1,5 +1,5 @@ import type { CorpConfig } from "../../core/config/types.js"; -import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js"; +import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/enterprise/source.js"; import { printJson } from "../printer.js"; export async function handleSourceCommand(action: string | undefined, corp: CorpConfig) { diff --git a/src/cli/commands/webhook.ts b/src/cli/commands/webhook.ts index 94059cf..4206e74 100644 --- a/src/cli/commands/webhook.ts +++ b/src/cli/commands/webhook.ts @@ -11,8 +11,8 @@ import { executeApprovalRunsReplay, resolveReplayCorpPair, type ReplayRecordsQuery -} from "../../domains/seal/webhook-replay.js"; -import { executeHoseOutboundReplay } from "../../domains/seal/hose-outbound-replay.js"; +} from "../../domains/seal/replay/webhook.js"; +import { executeHoseOutboundReplay } from "../../domains/seal/replay/hose-outbound.js"; import { checkWebhookReadiness, exportApprovalRunsToResourcePack, diff --git a/src/cli/help.test.ts b/src/cli/help.test.ts index d3380ce..95bb082 100644 --- a/src/cli/help.test.ts +++ b/src/cli/help.test.ts @@ -61,6 +61,14 @@ describe("extractHelpRequest", () => { }); describe("renderHelp", () => { + test("explains both recode phases without exposing internal activation timing", () => { + const help = renderHelp(["rules", "recode"]); + expect(help).toContain("一次性凭证"); + expect(help).toContain("另一次调用"); + expect(help).toContain("不执行重排"); + expect(help).not.toContain("500"); + expect(help).not.toContain("--confirm-code"); + }); test("renders global help when target is empty", () => { const help = renderHelp([]); expect(help).toContain("seal-use CLI"); diff --git a/src/cli/help.ts b/src/cli/help.ts index 1b89b8c..892ee13 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -351,6 +351,12 @@ export const HELP_REGISTRY: AreaHelp[] = [ summary: "Clear all draft rules from enterprise", usage: ["seal-use rules clear [--dry-run|--yes] [--corp ]"] }, + { + name: "recode", + summary: "Preview consecutive rule numbering, then execute with a one-use confirmation code", + usage: ["seal-use rules recode [--dry-run] --corp "], + description: "首次运行只返回影响预览、一次性凭证和 nextCommand,不执行重排;核对后另一次调用返回的命令才会生效。凭证绑定企业、环境和草稿,5 分钟有效且只能使用一次。--yes/--confirm 不能跳过该流程。--dry-run 只预览,不签发凭证。服务端决定编号顺序,所有规则均可能变号;逐条映射在执行后回读。重排不发布版本;查看旧编号需结合发布版本。" + }, { name: "map", summary: "Inspect locally synced production/test rule code mappings", diff --git a/src/cli/parser.ts b/src/cli/parser.ts index 4530901..7e1d69a 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -42,7 +42,7 @@ export const BOOLEAN_FLAGS = new Set([ export const VALUE_FLAGS = new Set([ "access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity", "base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes", - "channel", "chrome", "code", "concurrency", "content", "content-file", "content-hints", "content-type", "contentFile", + "channel", "chrome", "code", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date", "dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc", "description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix", @@ -90,7 +90,7 @@ export const KNOWN_FLAGS = new Set([ "app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto", "auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId", "bg-save", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome", - "code", "completed-only", "completedOnly", "concurrency", "confirm", "content", + "code", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc", "description", "description-file", diff --git a/src/domains/enterprise/onboarding.ts b/src/domains/enterprise/onboarding.ts index b026846..1e03425 100644 --- a/src/domains/enterprise/onboarding.ts +++ b/src/domains/enterprise/onboarding.ts @@ -6,7 +6,7 @@ import { } from "../../core/auth/delegate.js"; import { parseHoseAssistLink } from "../../core/auth/hose.js"; import { onboardHoseWebSession } from "../hose/onboarding.js"; -import { persistSealDelegateSession } from "../seal/onboarding.js"; +import { persistSealDelegateSession } from "../seal/enterprise/onboarding.js"; export type AssistanceLinkOnboardingInput = { name?: string; diff --git a/src/domains/hose/onboarding.ts b/src/domains/hose/onboarding.ts index 3310410..7545bd2 100644 --- a/src/domains/hose/onboarding.ts +++ b/src/domains/hose/onboarding.ts @@ -13,7 +13,7 @@ import { saveCorpConfig, type SavedCorpConfig } from "../../core/config/reposito import { normalizeBeijingIso } from "../../core/config/timestamps.js"; import type { CorpConfig } from "../../core/config/types.js"; import { getMe } from "../seal/api.js"; -import { resolveLiveSealEnterpriseConfig } from "../seal/source.js"; +import { resolveLiveSealEnterpriseConfig } from "../seal/enterprise/source.js"; export type HosePersistentInput = { id?: string; diff --git a/src/domains/seal/api.ts b/src/domains/seal/api.ts index d169380..9b530a2 100644 --- a/src/domains/seal/api.ts +++ b/src/domains/seal/api.ts @@ -10,6 +10,7 @@ import { CorpConfig } from "../../core/config/types.js"; import { ensureHoseOpenapiToken, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js"; import { createSealClientForUrl } from "../../core/http/factory.js"; import { redactSensitiveText } from "../../core/redact.js"; +import { safetyBlocked } from "../../core/errors.js"; import { resolveSealCustomHeaders } from "../../core/http/request-headers.js"; import { ApprovalDocumentListData, @@ -140,7 +141,13 @@ export async function deleteApprovalRule(client: KyInstance, ruleId: string): Pr } export async function recodeApprovalRules(client: KyInstance): Promise { - const response = await client.post("api/v1/rules/batch-recode", { throwHttpErrors: false }); + // Legacy clear/sync callers may reset an EMPTY draft's allocation counter. + // Renumbering existing rules must go through the ticketed recode capability. + const draft = await listApprovalRules(client); + if (draft.rules.length > 0) { + throw safetyBlocked("禁止隐式重排非空草稿,请使用 rules recode 的两阶段确认流程。"); + } + const response = await client.post("api/v1/rules/batch-recode", { throwHttpErrors: false, retry: 0 }); const body = await response.json().catch(() => ({})); return z.object({ ok: z.boolean(), @@ -153,6 +160,19 @@ export async function recodeApprovalRules(client: KyInstance): Promise }); } +/** Called only after the shared recode capability consumes its confirmation ticket. */ +export async function executeApprovalRulesRecode(client: KyInstance) { + const response = await client.post("api/v1/rules/batch-recode", { retry: 0 }); + const body = await response.json() as { data?: unknown }; + const result = z.object({ + activeRules: z.number().int().nonnegative(), + pendingDeleteRules: z.number().int().nonnegative(), + nextCode: z.number().int().nonnegative() + }).safeParse(body.data ?? body); + if (!result.success) throw new Error("规则重排接口返回了无效结果,请回读当前草稿确认状态。"); + return result.data; +} + export async function listApprovalRuleVersions(client: KyInstance): Promise { return unwrap(await client.get("api/v1/rule-set-versions"), z.array(RuleSetVersionSchema)); } diff --git a/src/domains/seal/attachments.test.ts b/src/domains/seal/approval-runs/attachments.test.ts similarity index 99% rename from src/domains/seal/attachments.test.ts rename to src/domains/seal/approval-runs/attachments.test.ts index 4b3961b..33e6f8b 100644 --- a/src/domains/seal/attachments.test.ts +++ b/src/domains/seal/approval-runs/attachments.test.ts @@ -9,7 +9,7 @@ import { sanitizeFileName, type FetchLike } from "./attachments.js"; -import type { ApprovalRun } from "./types.js"; +import type { ApprovalRun } from "../types.js"; describe("attachments domain", () => { let tmpDir: string; diff --git a/src/domains/seal/attachments.ts b/src/domains/seal/approval-runs/attachments.ts similarity index 99% rename from src/domains/seal/attachments.ts rename to src/domains/seal/approval-runs/attachments.ts index c0fbed3..4a08100 100644 --- a/src/domains/seal/attachments.ts +++ b/src/domains/seal/approval-runs/attachments.ts @@ -1,6 +1,6 @@ import fs from "node:fs"; import path from "node:path"; -import type { ApprovalRun } from "./types.js"; +import type { ApprovalRun } from "../types.js"; export interface ApprovalRunAttachment { path: string; diff --git a/src/domains/seal/approval-runs-export.test.ts b/src/domains/seal/approval-runs/export.test.ts similarity index 99% rename from src/domains/seal/approval-runs-export.test.ts rename to src/domains/seal/approval-runs/export.test.ts index 6ea9495..c98e1cb 100644 --- a/src/domains/seal/approval-runs-export.test.ts +++ b/src/domains/seal/approval-runs/export.test.ts @@ -14,8 +14,8 @@ import { resolveExportDateRange, resolveOutputFilePath, exportApprovalRunsToExcel -} from "./approval-runs-export.js"; -import type { CorpConfig } from "../../core/config/types.js"; +} from "./export.js"; +import type { CorpConfig } from "../../../core/config/types.js"; describe("approval-runs-export helpers", () => { test("normalizeTimestamp converts YYYY-MM-DD to Beijing time epoch string", () => { diff --git a/src/domains/seal/approval-runs-export.ts b/src/domains/seal/approval-runs/export.ts similarity index 99% rename from src/domains/seal/approval-runs-export.ts rename to src/domains/seal/approval-runs/export.ts index f292572..29e12fa 100644 --- a/src/domains/seal/approval-runs-export.ts +++ b/src/domains/seal/approval-runs/export.ts @@ -3,17 +3,17 @@ import { homedir } from "node:os"; import { dirname, extname, resolve } from "node:path"; import ExcelJS from "exceljs"; import type { KyInstance } from "ky"; -import { formatBeijingIso } from "../../core/config/timestamps.js"; -import type { CorpConfig } from "../../core/config/types.js"; -import * as api from "./api.js"; +import { formatBeijingIso } from "../../../core/config/timestamps.js"; +import type { CorpConfig } from "../../../core/config/types.js"; +import * as api from "../api.js"; import { alignApprovalRunsWithHoseFlow, createHoseOpenClient, getHoseOpenFlow, type HoseOpenStaffItem, type HoseRunAlignment -} from "../hose/index.js"; -import type { ApprovalRun, ApprovalRunListData } from "./types.js"; +} from "../../hose/index.js"; +import type { ApprovalRun, ApprovalRunListData } from "../types.js"; export interface ApprovalRunsExportOptions { limit?: number; diff --git a/src/domains/seal/capabilities/approval-runs.ts b/src/domains/seal/capabilities/approval-runs.ts index 0e265a4..a65a4e8 100644 --- a/src/domains/seal/capabilities/approval-runs.ts +++ b/src/domains/seal/capabilities/approval-runs.ts @@ -3,8 +3,8 @@ import type { KyInstance } from "ky"; import * as api from "../api.js"; import { ensureHoseCloseApiToken } from "../../../core/auth/hose.js"; import { formatBeijingIso } from "../../../core/config/timestamps.js"; -import { extractApprovalRunAttachments } from "../attachments.js"; -import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js"; +import { extractApprovalRunAttachments } from "../approval-runs/attachments.js"; +import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs/export.js"; import { alignApprovalRunsWithHoseFlow, createHoseOpenClient, diff --git a/src/domains/seal/capabilities.test.ts b/src/domains/seal/capabilities/capabilities.test.ts similarity index 99% rename from src/domains/seal/capabilities.test.ts rename to src/domains/seal/capabilities/capabilities.test.ts index 301e328..1bab8a8 100644 --- a/src/domains/seal/capabilities.test.ts +++ b/src/domains/seal/capabilities/capabilities.test.ts @@ -4,10 +4,10 @@ import { z } from "zod"; 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, findSealCapability, sealCapabilities } from "./capabilities.js"; +import { CorpConfig } from "../../../core/config/types.js"; +import { CliError } from "../../../core/errors.js"; +import { saveRuleMappingSnapshot } from "../rules/mapping.js"; +import { buildRulePushPlan, findSealCapability, sealCapabilities } from "../capabilities.js"; type CapabilityHandler = ( client: KyInstance, diff --git a/src/domains/seal/capabilities/deploy.ts b/src/domains/seal/capabilities/deploy.ts index bfae415..b4afe06 100644 --- a/src/domains/seal/capabilities/deploy.ts +++ b/src/domains/seal/capabilities/deploy.ts @@ -15,7 +15,7 @@ import { pushOutboundAndVerify, resolveCorporationId, selectHoseIntegration -} from "../outbound-push.js"; +} from "../outbound/push.js"; import type { CapabilityContext } from "./helpers.js"; diff --git a/src/domains/seal/capabilities/helpers.ts b/src/domains/seal/capabilities/helpers.ts index 7c7fd2e..914ba27 100644 --- a/src/domains/seal/capabilities/helpers.ts +++ b/src/domains/seal/capabilities/helpers.ts @@ -23,9 +23,9 @@ import type { SimulationBatch, WebhookIntegration } from "../types.js"; -import { extractApprovalRunAttachments } from "../attachments.js"; -import type { LocalRuleItem } from "../rules-local.js"; -import { loadRuleMappingSnapshot } from "../rule-mapping.js"; +import { extractApprovalRunAttachments } from "../approval-runs/attachments.js"; +import type { LocalRuleItem } from "../rules/local.js"; +import { loadRuleMappingSnapshot } from "../rules/mapping.js"; import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js"; export type CapabilityContext = { diff --git a/src/domains/seal/capabilities/index.ts b/src/domains/seal/capabilities/index.ts index 0bd7621..4f23878 100644 --- a/src/domains/seal/capabilities/index.ts +++ b/src/domains/seal/capabilities/index.ts @@ -129,6 +129,7 @@ export const SEAL_MUTATING_CAPABILITIES: ReadonlySet = new Set([ "sealApprovalRuleUpdate", "sealApprovalRuleVersionPublish", "sealApprovalRulesClear", + "sealApprovalRulesRecode", "sealApprovalRulesPush", "sealApprovalStylePreferencesUpdate", "sealDelegationCreate", diff --git a/src/domains/seal/capabilities/insight.ts b/src/domains/seal/capabilities/insight.ts index a742faa..6b672ec 100644 --- a/src/domains/seal/capabilities/insight.ts +++ b/src/domains/seal/capabilities/insight.ts @@ -1,7 +1,7 @@ import { z } from "zod"; import type { KyInstance } from "ky"; import * as api from "../api.js"; -import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js"; +import { exportInsightReportToExcel, type InsightExportOptions } from "../insight/export.js"; import type { CapabilityContext } from "./helpers.js"; diff --git a/src/domains/seal/capabilities/rules.ts b/src/domains/seal/capabilities/rules.ts index 7078c40..6a97e76 100644 --- a/src/domains/seal/capabilities/rules.ts +++ b/src/domains/seal/capabilities/rules.ts @@ -1,20 +1,21 @@ import { z } from "zod"; import type { KyInstance } from "ky"; import * as api from "../api.js"; +import { recodeRules, type RecodeOptions } from "../rules/recode.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 { 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"; +} from "../rules/local.js"; import { type ApprovalRule, type RuleSetVersion @@ -48,6 +49,16 @@ function attachCrossEnvRule(context: CapabilityContext, rule: Record + recodeRules(client, context.corp, params) + }, { name: "sealApprovalRulesList", description: "列出 Seal 审批规则(默认当前草稿,传 version='latest' 或版本号则列出对应已发布版本);支持 countOnly、fields、limit", @@ -144,8 +155,13 @@ export const rulesCapabilities = [ const warnings: string[] = []; let recode: unknown; + const remaining = await api.listApprovalRules(client); if (deleted > 0 && params.recode !== false) { - recode = await api.recodeApprovalRules(client); + if (remaining.rules.length > 0) { + warnings.push("部分规则未删除,已跳过自动重排;如需重排剩余规则,请使用 rules recode 两阶段流程"); + } else { + recode = await api.recodeApprovalRules(client); + } if ( recode && typeof recode === "object" && @@ -156,7 +172,7 @@ export const rulesCapabilities = [ } } - const after = await api.listApprovalRules(client); + const after = recode ? await api.listApprovalRules(client) : remaining; return { corpId: context.corp.id, corpName: context.corp.name, diff --git a/src/domains/seal/capabilities/webhook.ts b/src/domains/seal/capabilities/webhook.ts index 48fc466..4b4ebfd 100644 --- a/src/domains/seal/capabilities/webhook.ts +++ b/src/domains/seal/capabilities/webhook.ts @@ -6,7 +6,7 @@ import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from " import { resolveCorpConfig } from "../../../core/config/manager.js"; import { createSealClient } from "../../../core/http/factory.js"; import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js"; -import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js"; +import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../replay/webhook.js"; import { checkWebhookReadiness, previewMaterialPack, diff --git a/src/domains/seal/onboarding.ts b/src/domains/seal/enterprise/onboarding.ts similarity index 92% rename from src/domains/seal/onboarding.ts rename to src/domains/seal/enterprise/onboarding.ts index c61293b..c022f6c 100644 --- a/src/domains/seal/onboarding.ts +++ b/src/domains/seal/enterprise/onboarding.ts @@ -1,13 +1,13 @@ -import { saveCorpConfig, type SavedCorpConfig } from "../../core/config/repository.js"; -import { formatBeijingIso, normalizeBeijingIso } from "../../core/config/timestamps.js"; +import { saveCorpConfig, type SavedCorpConfig } from "../../../core/config/repository.js"; +import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js"; import { SealCookieMapSchema, SealHeaderMapSchema, type CorpConfig -} from "../../core/config/types.js"; -import { createSealClientForUrl } from "../../core/http/factory.js"; -import { resolveSealCustomHeaders } from "../../core/http/request-headers.js"; -import { getMe } from "./api.js"; +} from "../../../core/config/types.js"; +import { createSealClientForUrl } from "../../../core/http/factory.js"; +import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js"; +import { getMe } from "../api.js"; export type RemoteSealIdentity = { user: Record; diff --git a/src/domains/seal/source.ts b/src/domains/seal/enterprise/source.ts similarity index 72% rename from src/domains/seal/source.ts rename to src/domains/seal/enterprise/source.ts index cf93de1..4e12f2c 100644 --- a/src/domains/seal/source.ts +++ b/src/domains/seal/enterprise/source.ts @@ -1,8 +1,8 @@ -import { CorpConfig } from "../../core/config/types.js"; -import { createSealClient } from "../../core/http/factory.js"; -import { resolveSealEnterpriseConfig } from "../../core/auth/seal.js"; -import { SealEnterpriseConfig } from "../../core/auth/types.js"; -import { getMe } from "./api.js"; +import { CorpConfig } from "../../../core/config/types.js"; +import { createSealClient } from "../../../core/http/factory.js"; +import { resolveSealEnterpriseConfig } from "../../../core/auth/seal.js"; +import { SealEnterpriseConfig } from "../../../core/auth/types.js"; +import { getMe } from "../api.js"; export async function resolveLiveSealEnterpriseConfig( corp: CorpConfig diff --git a/src/domains/seal/insight-export.test.ts b/src/domains/seal/insight/export.test.ts similarity index 98% rename from src/domains/seal/insight-export.test.ts rename to src/domains/seal/insight/export.test.ts index a7087ba..fbb8a80 100644 --- a/src/domains/seal/insight-export.test.ts +++ b/src/domains/seal/insight/export.test.ts @@ -4,8 +4,8 @@ import { homedir } from "node:os"; import { join } from "node:path"; import ExcelJS from "exceljs"; import type { KyInstance } from "ky"; -import { type CorpConfig, CorpConfigSchema } from "../../core/config/types.js"; -import { exportInsightReportToExcel, resolveInsightOutputFilePath } from "./insight-export.js"; +import { type CorpConfig, CorpConfigSchema } from "../../../core/config/types.js"; +import { exportInsightReportToExcel, resolveInsightOutputFilePath } from "./export.js"; describe("insight-export domain", () => { test("resolveInsightOutputFilePath respects custom outputFile", () => { diff --git a/src/domains/seal/insight-export.ts b/src/domains/seal/insight/export.ts similarity index 97% rename from src/domains/seal/insight-export.ts rename to src/domains/seal/insight/export.ts index 831c4da..e0e2093 100644 --- a/src/domains/seal/insight-export.ts +++ b/src/domains/seal/insight/export.ts @@ -3,11 +3,11 @@ import { homedir } from "node:os"; import { dirname, resolve } from "node:path"; import ExcelJS from "exceljs"; import type { KyInstance } from "ky"; -import { formatBeijingIso } from "../../core/config/timestamps.js"; -import type { CorpConfig } from "../../core/config/types.js"; -import * as api from "./api.js"; -import { getBeijingDate, resolveExportDateRange } from "./approval-runs-export.js"; -import type { InsightPerformance } from "./types.js"; +import { formatBeijingIso } from "../../../core/config/timestamps.js"; +import type { CorpConfig } from "../../../core/config/types.js"; +import * as api from "../api.js"; +import { getBeijingDate, resolveExportDateRange } from "../approval-runs/export.js"; +import type { InsightPerformance } from "../types.js"; export interface InsightExportOptions { startDate?: string | number; diff --git a/src/domains/seal/material-pack/export.ts b/src/domains/seal/material-pack/export.ts index 18692fc..745d25e 100644 --- a/src/domains/seal/material-pack/export.ts +++ b/src/domains/seal/material-pack/export.ts @@ -7,7 +7,7 @@ import type { KyInstance } from "ky"; import { formatBeijingIso } from "../../../core/config/timestamps.js"; import type { CorpConfig } from "../../../core/config/types.js"; import * as api from "../api.js"; -import { extractApprovalRunAttachments, sanitizeFileName } from "../attachments.js"; +import { extractApprovalRunAttachments, sanitizeFileName } from "../approval-runs/attachments.js"; import type { ApprovalRun } from "../types.js"; import type { ResourcePackExportOptions, ResourcePackExportResult } from "./types.js"; diff --git a/src/domains/seal/outbound-push.test.ts b/src/domains/seal/outbound/push.test.ts similarity index 99% rename from src/domains/seal/outbound-push.test.ts rename to src/domains/seal/outbound/push.test.ts index ad9cdf8..edb878d 100644 --- a/src/domains/seal/outbound-push.test.ts +++ b/src/domains/seal/outbound/push.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from "bun:test"; import type { KyInstance } from "ky"; -import type { CorpConfig } from "../../core/config/types.js"; -import type { ApprovalIntegration, ApprovalStylePreferences } from "./types.js"; +import type { CorpConfig } from "../../../core/config/types.js"; +import type { ApprovalIntegration, ApprovalStylePreferences } from "../types.js"; import { assertAssistedIntegration, BLOCKING_NODE_ID, @@ -12,7 +12,7 @@ import { pushOutboundAndVerify, resolveCorporationId, selectHoseIntegration -} from "./outbound-push.js"; +} from "./push.js"; function corp(overrides: Partial = {}): CorpConfig { return { diff --git a/src/domains/seal/outbound-push.ts b/src/domains/seal/outbound/push.ts similarity index 97% rename from src/domains/seal/outbound-push.ts rename to src/domains/seal/outbound/push.ts index 46b21b3..a398f7e 100644 --- a/src/domains/seal/outbound-push.ts +++ b/src/domains/seal/outbound/push.ts @@ -1,15 +1,15 @@ import type { KyInstance } from "ky"; -import { confirmationRequired, safetyBlocked, validationError } from "../../core/errors.js"; -import type { CorpConfig } from "../../core/config/types.js"; -import * as api from "./api.js"; -import type { ApprovalIntegration, ApprovalRun, ApprovalStylePreferences } from "./types.js"; +import { confirmationRequired, safetyBlocked, validationError } from "../../../core/errors.js"; +import type { CorpConfig } from "../../../core/config/types.js"; +import * as api from "../api.js"; +import type { ApprovalIntegration, ApprovalRun, ApprovalStylePreferences } from "../types.js"; /** * Shared primitives for pushing a test/replay message into Seal's * `/api/hosecloud/outbound` gateway. Two callers need them and they must stay * in lockstep because they build the exact same wire payload: * - `capabilities/deploy.ts` → `sealDeployHosecloudTestOutbound` (single tenant) - * - `hose-outbound-replay.ts` → `webhook replay --channel hose-outbound` (cross tenant) + * - `replay/hose-outbound.ts` → `webhook replay --channel hose-outbound` (cross tenant) * * Anything that describes the outbound contract (payload shape, blocking nodeId, * integration selection, the assisted-only gate) lives here so a change to the diff --git a/src/domains/seal/regression/service.ts b/src/domains/seal/regression/service.ts index b913a9d..bbdb76a 100644 --- a/src/domains/seal/regression/service.ts +++ b/src/domains/seal/regression/service.ts @@ -9,7 +9,7 @@ import { ensureTestWebhookIntegration, pushWebhookDocument, transformApprovalRunToWebhookDocument -} from "../webhook-replay.js"; +} from "../replay/webhook.js"; export interface RegressionTestOptions { sourceCorp: CorpConfig; diff --git a/src/domains/seal/hose-outbound-replay.test.ts b/src/domains/seal/replay/hose-outbound.test.ts similarity index 99% rename from src/domains/seal/hose-outbound-replay.test.ts rename to src/domains/seal/replay/hose-outbound.test.ts index 71a4295..a75021b 100644 --- a/src/domains/seal/hose-outbound-replay.test.ts +++ b/src/domains/seal/replay/hose-outbound.test.ts @@ -3,8 +3,8 @@ import { selectMatchingOutboundLog, validateHoseOutboundReplaySafety, type HoseOutboundLogItem -} from "./hose-outbound-replay.js"; -import type { CorpConfig } from "../../core/config/types.js"; +} from "./hose-outbound.js"; +import type { CorpConfig } from "../../../core/config/types.js"; const mockLogs: HoseOutboundLogItem[] = [ { diff --git a/src/domains/seal/hose-outbound-replay.ts b/src/domains/seal/replay/hose-outbound.ts similarity index 96% rename from src/domains/seal/hose-outbound-replay.ts rename to src/domains/seal/replay/hose-outbound.ts index cd5ec67..f9742f8 100644 --- a/src/domains/seal/hose-outbound-replay.ts +++ b/src/domains/seal/replay/hose-outbound.ts @@ -1,8 +1,8 @@ import type { KyInstance } from "ky"; -import type { CorpConfig } from "../../core/config/types.js"; -import { safetyBlocked, validationError } from "../../core/errors.js"; -import { fetchHoseOutboundLogs, type HoseOutboundLogItem } from "../hose/close/outbound.js"; -import * as api from "./api.js"; +import type { CorpConfig } from "../../../core/config/types.js"; +import { safetyBlocked, validationError } from "../../../core/errors.js"; +import { fetchHoseOutboundLogs, type HoseOutboundLogItem } from "../../hose/close/outbound.js"; +import * as api from "../api.js"; import { assertAssistedIntegration, BLOCKING_NODE_ID, @@ -13,11 +13,11 @@ import { pushOutboundAndVerify, resolveCorporationId, selectHoseIntegration -} from "./outbound-push.js"; -import { assertNonProductionReplayTarget } from "./replay-safety.js"; -import type { ApprovalRun } from "./types.js"; +} from "../outbound/push.js"; +import { assertNonProductionReplayTarget } from "./safety.js"; +import type { ApprovalRun } from "../types.js"; -export type { HoseOutboundLogItem } from "../hose/close/outbound.js"; +export type { HoseOutboundLogItem } from "../../hose/close/outbound.js"; export interface HoseOutboundReplayOptions { sourceCorp: CorpConfig; diff --git a/src/domains/seal/replay-safety.test.ts b/src/domains/seal/replay/safety.test.ts similarity index 94% rename from src/domains/seal/replay-safety.test.ts rename to src/domains/seal/replay/safety.test.ts index 359e00b..54373fe 100644 --- a/src/domains/seal/replay-safety.test.ts +++ b/src/domains/seal/replay/safety.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; -import type { CorpConfig } from "../../core/config/types.js"; -import { assertNonProductionReplayTarget } from "./replay-safety.js"; +import type { CorpConfig } from "../../../core/config/types.js"; +import { assertNonProductionReplayTarget } from "./safety.js"; function corp(overrides: Partial = {}): CorpConfig { return { diff --git a/src/domains/seal/replay-safety.ts b/src/domains/seal/replay/safety.ts similarity index 89% rename from src/domains/seal/replay-safety.ts rename to src/domains/seal/replay/safety.ts index b612b05..dce92ce 100644 --- a/src/domains/seal/replay-safety.ts +++ b/src/domains/seal/replay/safety.ts @@ -1,5 +1,5 @@ -import { safetyBlocked } from "../../core/errors.js"; -import type { CorpConfig } from "../../core/config/types.js"; +import { safetyBlocked } from "../../../core/errors.js"; +import type { CorpConfig } from "../../../core/config/types.js"; /** * Shared environment guard for every replay channel: test traffic must never diff --git a/src/domains/seal/webhook-replay.test.ts b/src/domains/seal/replay/webhook.test.ts similarity index 99% rename from src/domains/seal/webhook-replay.test.ts rename to src/domains/seal/replay/webhook.test.ts index 6e0fe3b..7652221 100644 --- a/src/domains/seal/webhook-replay.test.ts +++ b/src/domains/seal/replay/webhook.test.ts @@ -9,9 +9,9 @@ import { ensureTestWebhookIntegration, executeApprovalRunsReplay, ALLOWED_WEBHOOK_FIELD_TYPES -} from "./webhook-replay.js"; -import type { ApprovalRun, WebhookIntegration } from "./types.js"; -import type { CorpConfig } from "../../core/config/types.js"; +} from "./webhook.js"; +import type { ApprovalRun, WebhookIntegration } from "../types.js"; +import type { CorpConfig } from "../../../core/config/types.js"; describe("webhook-replay domain", () => { const mockWebhookIntegration: WebhookIntegration = { diff --git a/src/domains/seal/webhook-replay.ts b/src/domains/seal/replay/webhook.ts similarity index 97% rename from src/domains/seal/webhook-replay.ts rename to src/domains/seal/replay/webhook.ts index 014e9df..cf7c019 100644 --- a/src/domains/seal/webhook-replay.ts +++ b/src/domains/seal/replay/webhook.ts @@ -1,12 +1,12 @@ import type { KyInstance } from "ky"; -import type { ApprovalRun, WebhookIntegration } from "./types.js"; -import type { MaterialField } from "./material-pack/types.js"; -import { webhookHeaders } from "./material-pack/signature.js"; -import { CliError, confirmationRequired, validationError } from "../../core/errors.js"; -import type { CorpConfig } from "../../core/config/types.js"; -import { resolveSealCustomHeaders } from "../../core/http/request-headers.js"; -import * as api from "./api.js"; -import { assertNonProductionReplayTarget } from "./replay-safety.js"; +import type { ApprovalRun, WebhookIntegration } from "../types.js"; +import type { MaterialField } from "../material-pack/types.js"; +import { webhookHeaders } from "../material-pack/signature.js"; +import { CliError, confirmationRequired, validationError } from "../../../core/errors.js"; +import type { CorpConfig } from "../../../core/config/types.js"; +import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js"; +import * as api from "../api.js"; +import { assertNonProductionReplayTarget } from "./safety.js"; export const ALLOWED_WEBHOOK_FIELD_TYPES = new Set([ "TEXT", diff --git a/src/domains/seal/rule-diff.test.ts b/src/domains/seal/rules/diff.test.ts similarity index 97% rename from src/domains/seal/rule-diff.test.ts rename to src/domains/seal/rules/diff.test.ts index 65bd44c..3728ec2 100644 --- a/src/domains/seal/rule-diff.test.ts +++ b/src/domains/seal/rules/diff.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; -import { diffRuleVersions, truncateRuleDiff } from "./rule-diff.js"; -import { PublishedRuleSnapshotSchema, RuleSetVersionSchema, type RuleSetVersion } from "./types.js"; +import { diffRuleVersions, truncateRuleDiff } from "./diff.js"; +import { PublishedRuleSnapshotSchema, RuleSetVersionSchema, type RuleSetVersion } from "../types.js"; function version(versionNumber: number, rules: Array>): RuleSetVersion { return { diff --git a/src/domains/seal/rule-diff.ts b/src/domains/seal/rules/diff.ts similarity index 99% rename from src/domains/seal/rule-diff.ts rename to src/domains/seal/rules/diff.ts index 24a1aec..522d1dd 100644 --- a/src/domains/seal/rule-diff.ts +++ b/src/domains/seal/rules/diff.ts @@ -1,4 +1,4 @@ -import type { RuleSetVersion } from "./types.js"; +import type { RuleSetVersion } from "../types.js"; export type RuleDiffStatus = "added" | "removed" | "modified" | "unchanged"; export type RuleDiffIdentityMode = "stable-id" | "code"; diff --git a/src/domains/seal/rules-local.test.ts b/src/domains/seal/rules/local.test.ts similarity index 98% rename from src/domains/seal/rules-local.test.ts rename to src/domains/seal/rules/local.test.ts index 8a5b799..b7041c7 100644 --- a/src/domains/seal/rules-local.test.ts +++ b/src/domains/seal/rules/local.test.ts @@ -7,8 +7,8 @@ import { loadLocalRulesFile, saveLocalRulesFile, localRulesToLintTargets -} from "./rules-local.js"; -import { findSealCapability } from "./capabilities.js"; +} from "./local.js"; +import { findSealCapability } from "../capabilities.js"; const tempDirs: string[] = []; diff --git a/src/domains/seal/rules-local.ts b/src/domains/seal/rules/local.ts similarity index 98% rename from src/domains/seal/rules-local.ts rename to src/domains/seal/rules/local.ts index 869d7ec..e29d2f3 100644 --- a/src/domains/seal/rules-local.ts +++ b/src/domains/seal/rules/local.ts @@ -1,6 +1,6 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs"; import { dirname, resolve } from "node:path"; -import type { RuleLintTarget } from "./linter/types.js"; +import type { RuleLintTarget } from "../linter/types.js"; export interface LocalRuleItem { id?: string; diff --git a/src/domains/seal/rule-mapping.test.ts b/src/domains/seal/rules/mapping.test.ts similarity index 99% rename from src/domains/seal/rule-mapping.test.ts rename to src/domains/seal/rules/mapping.test.ts index a8a87fd..3209f50 100644 --- a/src/domains/seal/rule-mapping.test.ts +++ b/src/domains/seal/rules/mapping.test.ts @@ -10,7 +10,7 @@ import { loadRuleMappingSnapshot, RuleMappingSnapshot, saveRuleMappingSnapshot -} from "./rule-mapping.js"; +} from "./mapping.js"; describe("rule-mapping", () => { let testDir: string; diff --git a/src/domains/seal/rule-mapping.ts b/src/domains/seal/rules/mapping.ts similarity index 97% rename from src/domains/seal/rule-mapping.ts rename to src/domains/seal/rules/mapping.ts index a3c19c1..115dbcd 100644 --- a/src/domains/seal/rule-mapping.ts +++ b/src/domains/seal/rules/mapping.ts @@ -1,7 +1,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { normalizeBeijingIso } from "../../core/config/timestamps.js"; -import { SEAL_STATE_DIR } from "../../core/paths.js"; +import { normalizeBeijingIso } from "../../../core/config/timestamps.js"; +import { SEAL_STATE_DIR } from "../../../core/paths.js"; export interface RuleMappingItem { index: number; diff --git a/src/domains/seal/rules/recode-tickets.test.ts b/src/domains/seal/rules/recode-tickets.test.ts new file mode 100644 index 0000000..c706449 --- /dev/null +++ b/src/domains/seal/rules/recode-tickets.test.ts @@ -0,0 +1,74 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { mkdtempSync, rmSync, statSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { RecodeTicketStore } from "./recode-tickets.js" + +const dirs: string[] = [] +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) +}) + +function storePath() { + const dir = mkdtempSync(join(tmpdir(), "seal-recode-tickets-")) + dirs.push(dir) + return join(dir, "tickets.sqlite") +} + +describe("recode confirmation tickets", () => { + test("enforces the private activation interval without spending an early ticket", () => { + let now = 1_000_000 + const store = new RecodeTicketStore(storePath(), () => now) + const ticket = store.issue("target", "draft") + expect(ticket.confirmCode).toMatch(/^[0-9A-F]{6}$/) + now += 499 + expect(() => store.consume(ticket.confirmCode, "target", "draft")).toThrow("尚未生效") + now += 1 + store.consume(ticket.confirmCode, "target", "draft") + expect(() => store.consume(ticket.confirmCode, "target", "draft")).toThrow("已使用") + }) + + test("persists across instances, binds target and draft, and protects file permissions", () => { + let now = 1_000_000 + const path = storePath() + const ticket = new RecodeTicketStore(path, () => now).issue("corp-a:staging:recode", "draft-a") + now += 500 + const second = new RecodeTicketStore(path, () => now) + expect(() => second.consume(ticket.confirmCode, "corp-b:staging:recode", "draft-a")).toThrow("企业或环境") + expect(() => second.consume(ticket.confirmCode, "corp-a:production:recode", "draft-a")).toThrow("企业或环境") + expect(() => second.consume(ticket.confirmCode, "corp-a:staging:recode", "draft-b")).toThrow("草稿规则已变化") + second.consume(ticket.confirmCode.toLowerCase(), "corp-a:staging:recode", "draft-a") + expect(statSync(path).mode & 0o777).toBe(0o600) + }) + + test("rejects expired, malformed, unknown and backward-clock tickets", () => { + let now = 1_000_000 + const store = new RecodeTicketStore(storePath(), () => now) + const ticket = store.issue("target", "draft") + now -= 1 + expect(() => store.consume(ticket.confirmCode, "target", "draft")).toThrow("已失效") + now = ticket.expiresAt + expect(() => store.consume(ticket.confirmCode, "target", "draft")).toThrow("已失效") + expect(() => store.consume("anything", "target", "draft")).toThrow("无效") + const unknown = ticket.confirmCode === "000000" ? "FFFFFF" : "000000" + expect(() => store.consume(unknown, "target", "draft")).toThrow("不存在") + }) + + test("only one competing process can consume the same ticket", async () => { + const path = storePath() + const ticket = new RecodeTicketStore(path, () => Date.now() - 1_000).issue("target", "draft") + const source = `import { RecodeTicketStore } from ${JSON.stringify(join(import.meta.dirname, "recode-tickets.ts"))}; + try { new RecodeTicketStore(${JSON.stringify(path)}).consume(${JSON.stringify(ticket.confirmCode)}, "target", "draft"); console.log("consumed") } + catch { console.log("blocked") }` + const children = Array.from({ length: 8 }, () => Bun.spawn([process.execPath, "-e", source], { stdout: "pipe", stderr: "pipe" })) + const outputs = await Promise.all(children.map(async child => { + const output = await new Response(child.stdout).text() + const errors = await new Response(child.stderr).text() + expect(await child.exited).toBe(0) + expect(errors).toBe("") + return output.trim() + })) + expect(outputs.filter(output => output === "consumed")).toHaveLength(1) + expect(outputs.filter(output => output === "blocked")).toHaveLength(7) + }) +}) diff --git a/src/domains/seal/rules/recode-tickets.ts b/src/domains/seal/rules/recode-tickets.ts new file mode 100644 index 0000000..0127a06 --- /dev/null +++ b/src/domains/seal/rules/recode-tickets.ts @@ -0,0 +1,105 @@ +import { Database } from "bun:sqlite" +import { createHash, randomBytes } from "node:crypto" +import { chmodSync, mkdirSync } from "node:fs" +import { dirname, join } from "node:path" +import { CliError, confirmationRequired } from "../../../core/errors.js" +import { SEAL_STATE_DIR } from "../../../core/paths.js" + +const MIN_CONFIRMATION_AGE_MS = 500 +const TICKET_TTL_MS = 5 * 60_000 + +type Ticket = { + target: string + fingerprint: string + issuedAt: number + expiresAt: number + consumedAt: number | null +} + +/** Local, cross-process confirmation state; no daemon or tenant credentials. */ +export class RecodeTicketStore { + constructor( + private readonly path = process.env.SEAL_USE_RECODE_STORE?.trim() || join(SEAL_STATE_DIR, "recode-tickets.sqlite"), + private readonly now: () => number = () => Date.now() + ) {} + + private open(): Database { + mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 }) + const db = new Database(this.path, { create: true, strict: true }) + try { + chmodSync(this.path, 0o600) + db.exec("PRAGMA busy_timeout = 5000") + db.exec(`CREATE TABLE IF NOT EXISTS recode_tickets ( + codeHash TEXT PRIMARY KEY, + target TEXT NOT NULL, + fingerprint TEXT NOT NULL, + issuedAt INTEGER NOT NULL, + expiresAt INTEGER NOT NULL, + consumedAt INTEGER + )`) + return db + } catch (error) { + db.close() + throw error + } + } + + issue(target: string, fingerprint: string): { confirmCode: string; expiresAt: number } { + const db = this.open() + try { + const issuedAt = this.now() + const expiresAt = issuedAt + TICKET_TTL_MS + // Keep spent hashes: a previously issued six-character code is never reissued. + for (let attempt = 0; attempt < 20; attempt++) { + const confirmCode = randomBytes(3).toString("hex").toUpperCase() + const inserted = db.query(`INSERT OR IGNORE INTO recode_tickets + (codeHash, target, fingerprint, issuedAt, expiresAt) VALUES (?, ?, ?, ?, ?)`) + .run(hashCode(confirmCode), target, fingerprint, issuedAt, expiresAt) + if (inserted.changes === 1) return { confirmCode, expiresAt } + } + throw new Error("无法生成规则重排确认码,请重新申请") + } finally { + db.close() + } + } + + consume(code: string, target: string, fingerprint: string): void { + const confirmCode = code.trim().toUpperCase() + const nextAction = "seal-use rules recode --corp " + if (!/^[0-9A-F]{6}$/.test(confirmCode)) { + throw confirmationRequired("规则重排确认码无效,请重新申请。", nextAction) + } + const db = this.open() + try { + // The write transaction covers validation AND consumption. Competing CLI + // processes cannot both authorize a POST using the same ticket. + db.transaction(() => { + const codeHash = hashCode(confirmCode) + const ticket = db.query("SELECT * FROM recode_tickets WHERE codeHash = ?").get(codeHash) + if (!ticket || ticket.consumedAt !== null) { + throw confirmationRequired("规则重排确认码不存在或已使用,请重新申请。", nextAction) + } + const now = this.now() + if (now < ticket.issuedAt || now >= ticket.expiresAt) { + throw confirmationRequired("规则重排确认码已失效,请重新申请。", nextAction) + } + if (ticket.target !== target) { + throw confirmationRequired("规则重排确认码不适用于当前企业或环境。", nextAction) + } + if (ticket.fingerprint !== fingerprint) { + throw confirmationRequired("草稿规则已变化,请重新预览并申请确认码。", nextAction) + } + if (now - ticket.issuedAt < MIN_CONFIRMATION_AGE_MS) { + throw new CliError("确认码尚未生效,请稍后使用第一次返回的 nextCommand 重试。", 10) + } + db.query("UPDATE recode_tickets SET consumedAt = ? WHERE codeHash = ?").run(now, codeHash) + }).immediate() + } finally { + db.close() + } + } +} + +function hashCode(code: string): string { + return createHash("sha256").update(code).digest("hex") +} diff --git a/src/domains/seal/rules/recode.test.ts b/src/domains/seal/rules/recode.test.ts new file mode 100644 index 0000000..ad37762 --- /dev/null +++ b/src/domains/seal/rules/recode.test.ts @@ -0,0 +1,192 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { mkdtempSync, rmSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import type { KyInstance } from "ky" +import type { CorpConfig } from "../../../core/config/types.js" +import { recodeRules } from "./recode.js" +import { recodeApprovalRules } from "../api.js" +import type { ApprovalRulesData } from "../types.js" +import { runCapabilityResult } from "../../../cli/helpers.js" +import { handleRulesCommand } from "../../../cli/commands/rules.js" +import { parseArgs } from "../../../cli/parser.js" + +const originalStore = process.env.SEAL_USE_RECODE_STORE +const dirs: string[] = [] +afterEach(() => { + if (originalStore === undefined) delete process.env.SEAL_USE_RECODE_STORE + else process.env.SEAL_USE_RECODE_STORE = originalStore + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) +}) + +function fixture() { + const dir = mkdtempSync(join(tmpdir(), "seal-rules-recode-")) + dirs.push(dir) + process.env.SEAL_USE_RECODE_STORE = join(dir, "tickets.sqlite") + const corp: CorpConfig = { + id: "recode-test", name: "Test Corp", environment: "test", auth: { refreshTtl: 300 }, + source: { type: "seal", token: "test-token", sealUrl: "https://staging.sealai.cc", expiresIn: 3600, staffId: "seal" }, + seal: { url: "https://staging.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } } + } + const state: ApprovalRulesData = { + hasPendingDeletes: true, + rules: [ + { id: "a", tenantId: "tenant-a", code: 0, description: "Keep invoice", scope: "ALL", strictness: "MUST_FOLLOW", status: "ACTIVE", updatedAt: 100 }, + { id: "b", tenantId: "tenant-a", code: 4, description: "Attach receipt", scope: "ALL", strictness: "SHOULD_FOLLOW", status: "DRAFT", updatedAt: 100 } + ] + } + const calls: string[] = [] + let tenantId = "tenant-a" + let origin = "https://staging.sealai.cc" + let failPost = false + let corruptReadback = false + let reorderOnServer = false + const client = { + get: async (url: string) => { + calls.push(`GET ${url}`) + const data = url === "api/v1/rules" ? structuredClone(state) : { + user: { id: "operator", tenantId, name: "Operator" }, tenant: { id: tenantId, name: "Tenant" } + } + const response = Response.json({ data }) + Object.defineProperty(response, "url", { value: `${origin}/${url}` }) + return response + }, + post: async (url: string, options: { retry?: number }) => { + calls.push(`POST ${url}`) + expect(options.retry).toBe(0) + if (failPost) throw new Error("upstream timeout") + const order = [...state.rules].sort((a, b) => Number(a.code) - Number(b.code)) + if (reorderOnServer) order.reverse() + order.forEach((rule, index) => { rule.code = index }) + if (corruptReadback) state.rules[0]!.description = "concurrent edit" + return Response.json({ data: { activeRules: state.rules.length, pendingDeleteRules: 1, nextCode: state.rules.length } }) + } + } as unknown as KyInstance + return { + client, corp, state, calls, + changeTenant: () => { tenantId = "tenant-b" }, + changeOrigin: () => { origin = "https://production.sealai.cc" }, + failPost: () => { failPost = true }, + corruptReadback: () => { corruptReadback = true }, + reorderOnServer: () => { reorderOnServer = true } + } +} + +async function ticket(f: ReturnType) { + const result = await recodeRules(f.client, f.corp, {}) + if (!("confirmCode" in result)) throw new Error("expected a confirmation ticket") + return result.confirmCode +} + +describe("two-phase rules recode", () => { + test("dry-run never issues a ticket, and yes/confirm cannot bypass the shared capability", async () => { + const f = fixture() + const preview = await recodeRules(f.client, f.corp, { dryRun: true }) + expect(preview).toMatchObject({ phase: "preview", executed: false, impactCount: 2, mappingAvailable: false }) + expect(preview.changesDiff).toEqual({ before: ["0000", "0004"], after: ["0000", "0001"] }) + expect(preview).not.toHaveProperty("confirmCode") + const first = await runCapabilityResult("sealApprovalRulesRecode", f.client, f.corp, { yes: true, confirm: true }) + expect(first).toMatchObject({ executed: false, phase: "confirmation_required" }) + expect(first).toHaveProperty("confirmCode") + expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0) + }) + + test("an early second call is rejected; a later call preserves identities and content", async () => { + const f = fixture() + const code = await ticket(f) + await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow("尚未生效") + expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0) + await Bun.sleep(510) + const result = await recodeRules(f.client, f.corp, { confirmCode: code }) + expect(result).toMatchObject({ executed: true, phase: "executed", nextCode: 2 }) + expect(result.changesDiff).toEqual({ before: ["0000", "0004"], after: ["0000", "0001"] }) + expect(f.state.rules.map(rule => rule.id)).toEqual(["a", "b"]) + await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow() + expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(1) + }) + + test("does not promise old-code order and reports a server-assigned permutation truthfully", async () => { + const f = fixture() + const code = await ticket(f) + f.reorderOnServer() + await Bun.sleep(510) + const result = await recodeRules(f.client, f.corp, { confirmCode: code }) + expect(result).toMatchObject({ executed: true, impactCount: 2, mappingAvailable: true }) + expect(result.changesDiff).toEqual({ before: ["0000", "0004"], after: ["0001", "0000"] }) + if (!("changes" in result)) throw new Error("expected verified changes") + expect(result.changes).toEqual([{ beforeCode: "0000", afterCode: "0001" }, { beforeCode: "0004", afterCode: "0000" }]) + }) + + test.each(["corp", "origin", "tenant", "content", "timestamp", "pendingDeletes"])("rejects a changed %s before any POST", async change => { + const f = fixture() + const code = await ticket(f) + if (change === "corp") f.corp.id = "another-corp" + if (change === "origin") f.changeOrigin() + if (change === "tenant") f.changeTenant() + if (change === "content") f.state.rules[0]!.description = "Changed" + if (change === "timestamp") f.state.rules[0]!.updatedAt = 101 + if (change === "pendingDeletes") f.state.hasPendingDeletes = false + await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow() + expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0) + }) + + test("a failed POST spends the ticket and is not retried", async () => { + const f = fixture() + const code = await ticket(f) + await Bun.sleep(510) + f.failPost() + await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow("upstream timeout") + await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow("已使用") + expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(1) + }) + + test("readback detects a concurrent content change after the POST", async () => { + const f = fixture() + const code = await ticket(f) + await Bun.sleep(510) + f.corruptReadback() + await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow("回读规则与预览不一致") + }) + + test("legacy auto-recode refuses a nonempty draft", async () => { + const f = fixture() + await expect(recodeApprovalRules(f.client)).rejects.toThrow("禁止隐式重排") + expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0) + }) + + test("partial clear reports remaining rules without silently recoding them", async () => { + const f = fixture() + const client = { + get: f.client.get, + post: f.client.post, + delete: async (url: string) => { + if (url.endsWith("/a")) throw new Error("delete failed") + f.state.rules = f.state.rules.filter(rule => rule.id !== "b") + return Response.json({}) + } + } as unknown as KyInstance + const result = await runCapabilityResult("sealApprovalRulesClear", client, f.corp, { dryRun: false }) + expect(result).toMatchObject({ deleted: 1, afterCount: 1 }) + expect((result as { warnings: string[] }).warnings[0]).toContain("跳过自动重排") + expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0) + expect(f.state.rules[0]!.code).toBe(0) + }) + + test("CLI prints the JSON preview before returning confirmation-required exit 10", async () => { + const f = fixture() + const lines: string[] = [] + const log = console.log + console.log = (...values: unknown[]) => { lines.push(values.map(String).join(" ")) } + try { + const args = parseArgs(["rules", "recode", "--corp", f.corp.id, "--yes"]) + await expect(handleRulesCommand("recode", undefined, f.client, f.corp, args)).rejects.toMatchObject({ exitCode: 10 }) + const preview = JSON.parse(lines.join("\n")) + expect(preview.executed).toBe(false) + expect(preview.nextCommand).toContain(`--confirm-code ${preview.confirmCode}`) + expect(preview).not.toHaveProperty("notBefore") + expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0) + } finally { + console.log = log + } + }) +}) diff --git a/src/domains/seal/rules/recode.ts b/src/domains/seal/rules/recode.ts new file mode 100644 index 0000000..98cf837 --- /dev/null +++ b/src/domains/seal/rules/recode.ts @@ -0,0 +1,117 @@ +import { createHash } from "node:crypto" +import type { KyInstance } from "ky" +import type { CorpConfig } from "../../../core/config/types.js" +import { formatBeijingIso } from "../../../core/config/timestamps.js" +import { validationError } from "../../../core/errors.js" +import * as api from "../api.js" +import { ApprovalRulesDataSchema, type ApprovalRule, type ApprovalRulesData } from "../types.js" +import { RecodeTicketStore } from "./recode-tickets.js" + +export type RecodeOptions = { dryRun?: boolean; confirmCode?: string } + +function codeNumber(rule: ApprovalRule): number { + const code = typeof rule.code === "number" + ? rule.code + : Number(rule.code?.replace(/^(?:#|rule[-_:]?)/i, "")) + if (!Number.isSafeInteger(code) || code < 0) { + throw validationError("当前草稿包含无效规则编号,无法安全预览重排。") + } + return code +} + +function orderedRules(data: ApprovalRulesData): ApprovalRule[] { + const rules = [...data.rules].sort((a, b) => codeNumber(a) - codeNumber(b)) + if (new Set(rules.map(rule => rule.id)).size !== rules.length || + new Set(rules.map(codeNumber)).size !== rules.length) { + throw validationError("当前草稿包含重复的规则身份或编号,无法安全重排。") + } + return rules +} + +function codeLabel(code: number): string { + return String(code).padStart(4, "0") +} + +function fingerprint(data: ApprovalRulesData): string { + return createHash("sha256").update(JSON.stringify({ + hasPendingDeletes: data.hasPendingDeletes, + rules: [...data.rules].sort((a, b) => a.id.localeCompare(b.id)) + })).digest("hex") +} + +function sameContent(before: ApprovalRule, after: ApprovalRule): boolean { + return before.description === after.description && before.scope === after.scope && + before.strictness === after.strictness && before.status === after.status && before.tenantId === after.tenantId +} + +export async function recodeRules(client: KyInstance, corp: CorpConfig, options: RecodeOptions) { + const response = await client.get("api/v1/rules") + const payload = await response.json() as { data?: unknown } + const before = ApprovalRulesDataSchema.parse(payload.data ?? payload) + const rules = orderedRules(before) + const baseUrl = response.url + ? response.url.replace(/\/api\/v1\/rules(?:\?.*)?$/, "") + : corp.seal.url ?? corp.source.sealUrl + if (!baseUrl) throw validationError("无法确定规则重排的目标环境。") + const targetUrl = `${baseUrl.replace(/\/+$/, "")}/api/v1/rules/batch-recode` + const beforeCodes = rules.map(rule => codeLabel(codeNumber(rule))) + const expectedCodes = rules.map((_, index) => codeLabel(index)) + const preview = { + preview: true, + executed: false, + corpName: corp.name, + targetUrl, + rulesCount: rules.length, + hasPendingDeletes: before.hasPendingDeletes, + // The API has no mapping-preview contract and can put new drafts before + // active rules. Report the full possible scope instead of guessing order. + impactCount: rules.length, + changesDiff: { before: beforeCodes, after: expectedCodes }, + mappingAvailable: false, + warning: "规则编号将从 0000 连续编排,所有规则均可能变号。具体顺序由服务端决定,逐条映射将在执行后回读;旧编号需结合发布版本查看。" + } + if (options.dryRun) return { ...preview, phase: "preview" as const } + + const me = await api.getMe(client) + const target = JSON.stringify(["rules-recode", corp.id, new URL(baseUrl).href, corp.environment, me.tenant.id]) + const tickets = new RecodeTicketStore() + const draftFingerprint = fingerprint(before) + if (options.confirmCode === undefined) { + const ticket = tickets.issue(target, draftFingerprint) + const quotedCorp = `'${corp.id.replace(/'/g, "'\\''")}'` + return { + ...preview, + phase: "confirmation_required" as const, + confirmCode: ticket.confirmCode, + expiresAt: formatBeijingIso(ticket.expiresAt), + nextCommand: `seal-use rules recode --corp ${quotedCorp} --confirm-code ${ticket.confirmCode}` + } + } + + tickets.consume(options.confirmCode, target, draftFingerprint) + // A failed/uncertain POST still spends the ticket. Never automatically resend it. + const result = await api.executeApprovalRulesRecode(client) + const after = await api.listApprovalRules(client) + const byId = new Map(after.rules.map(rule => [rule.id, rule])) + const actualCodes = after.rules.map(codeNumber).sort((a, b) => a - b) + if (after.rules.length !== rules.length || result.activeRules !== rules.length || result.nextCode !== rules.length || + actualCodes.some((code, index) => code !== index) || + rules.some(rule => { + const actual = byId.get(rule.id) + return !actual || !sameContent(rule, actual) + })) { + throw new Error("重排请求已发送,但回读规则与预览不一致。请先核对当前草稿,勿重复执行旧确认码。") + } + const changes = rules.map(rule => ({ beforeCode: codeLabel(codeNumber(rule)), afterCode: codeLabel(codeNumber(byId.get(rule.id)!)) })) + return { + ...preview, + preview: false, + executed: true, + phase: "executed" as const, + ...result, + impactCount: changes.filter(change => change.beforeCode !== change.afterCode).length, + mappingAvailable: true, + changesDiff: { before: beforeCodes, after: changes.map(change => change.afterCode) }, + changes + } +} diff --git a/src/domains/seal/rule-version-snapshot.test.ts b/src/domains/seal/rules/version-snapshot.test.ts similarity index 96% rename from src/domains/seal/rule-version-snapshot.test.ts rename to src/domains/seal/rules/version-snapshot.test.ts index bd8edd8..769dec4 100644 --- a/src/domains/seal/rule-version-snapshot.test.ts +++ b/src/domains/seal/rules/version-snapshot.test.ts @@ -6,8 +6,8 @@ import { hydrateRuleVersionStableIds, loadPublishedRuleVersionSnapshot, savePublishedRuleVersionSnapshot -} from "./rule-version-snapshot.js"; -import type { RuleSetVersion } from "./types.js"; +} from "./version-snapshot.js"; +import type { RuleSetVersion } from "../types.js"; const originalDir = process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR; let testDir = ""; diff --git a/src/domains/seal/rule-version-snapshot.ts b/src/domains/seal/rules/version-snapshot.ts similarity index 96% rename from src/domains/seal/rule-version-snapshot.ts rename to src/domains/seal/rules/version-snapshot.ts index 5544eb1..4204199 100644 --- a/src/domains/seal/rule-version-snapshot.ts +++ b/src/domains/seal/rules/version-snapshot.ts @@ -1,8 +1,8 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { formatBeijingIso } from "../../core/config/timestamps.js"; -import { SEAL_STATE_DIR } from "../../core/paths.js"; -import type { ApprovalRule, RuleSetVersion } from "./types.js"; +import { formatBeijingIso } from "../../../core/config/timestamps.js"; +import { SEAL_STATE_DIR } from "../../../core/paths.js"; +import type { ApprovalRule, RuleSetVersion } from "../types.js"; export const MAX_RETAINED_RULE_SNAPSHOTS = 20; diff --git a/src/domains/seal/search.test.ts b/src/domains/seal/search/service.test.ts similarity index 97% rename from src/domains/seal/search.test.ts rename to src/domains/seal/search/service.test.ts index b54e628..7e50943 100644 --- a/src/domains/seal/search.test.ts +++ b/src/domains/seal/search/service.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from "bun:test"; import { KyInstance } from "ky"; -import { CorpConfig } from "../../core/config/types.js"; -import { searchApprovalContent } from "./search.js"; +import { CorpConfig } from "../../../core/config/types.js"; +import { searchApprovalContent } from "./service.js"; function fakeSearchClient(): KyInstance { return { diff --git a/src/domains/seal/search.ts b/src/domains/seal/search/service.ts similarity index 98% rename from src/domains/seal/search.ts rename to src/domains/seal/search/service.ts index bac59bf..bbcee64 100644 --- a/src/domains/seal/search.ts +++ b/src/domains/seal/search/service.ts @@ -1,19 +1,19 @@ import { KyInstance } from "ky"; -import { formatBeijingIso } from "../../core/config/timestamps.js"; -import { CorpConfig } from "../../core/config/types.js"; +import { formatBeijingIso } from "../../../core/config/timestamps.js"; +import { CorpConfig } from "../../../core/config/types.js"; import { ApprovalDocument, ApprovalRule, ApprovalStylePreferences, RuleSetVersion -} from "./types.js"; +} from "../types.js"; import { getApprovalRuleVersion, getApprovalStylePreferences, listApprovalDocuments, listApprovalRuleVersions, listApprovalRules -} from "./api.js"; +} from "../api.js"; type MatchMode = "any" | "all"; type SearchArea = "rules" | "documents" | "preferences"; diff --git a/src/domains/seal/test-sync.ts b/src/domains/seal/testing/sync.ts similarity index 97% rename from src/domains/seal/test-sync.ts rename to src/domains/seal/testing/sync.ts index f0edaf1..8608866 100644 --- a/src/domains/seal/test-sync.ts +++ b/src/domains/seal/testing/sync.ts @@ -1,11 +1,11 @@ import { randomBytes } from "node:crypto"; import type { KyInstance } from "ky"; -import { createSealClient } from "../../core/http/factory.js"; -import { formatBeijingIso } from "../../core/config/timestamps.js"; -import type { CorpConfig } from "../../core/config/types.js"; -import * as api from "./api.js"; -import { computeNextSyncIteration, formatSyncVersionName, saveRuleMappingSnapshot } from "./rule-mapping.js"; -import { savePublishedRuleVersionSnapshot } from "./rule-version-snapshot.js"; +import { createSealClient } from "../../../core/http/factory.js"; +import { formatBeijingIso } from "../../../core/config/timestamps.js"; +import type { CorpConfig } from "../../../core/config/types.js"; +import * as api from "../api.js"; +import { computeNextSyncIteration, formatSyncVersionName, saveRuleMappingSnapshot } from "../rules/mapping.js"; +import { savePublishedRuleVersionSnapshot } from "../rules/version-snapshot.js"; export type TestSyncOptions = { versionName?: string; @@ -203,6 +203,9 @@ export async function syncTestEnterprise( createdDocs.push({ id: created.id, title: created.title }); } for (const rule of testRules.rules) await api.deleteApprovalRule(testClient, rule.id); + // Reset only after confirming the draft is empty, before allocating new codes. + const recodeResult = await api.recodeApprovalRules(testClient) as { ok: boolean; status: number }; + if (!recodeResult.ok) throw new Error(`Failed to recode test approval rules: HTTP ${recodeResult.status}`); const createdRules: any[] = []; for (const rule of prodRules.rules) { createdRules.push(await api.createApprovalRule(testClient, { @@ -211,8 +214,6 @@ export async function syncTestEnterprise( strictness: rule.strictness })); } - const recodeResult = await api.recodeApprovalRules(testClient) as { ok: boolean; status: number }; - if (!recodeResult.ok) throw new Error(`Failed to recode test approval rules: HTTP ${recodeResult.status}`); const hosecloudSync = await syncHosecloudIntegrationsToTest(prodCorp, testCorp, prodClient, testClient); const published = await api.publishApprovalRuleVersion(testClient, versionName); try { savePublishedRuleVersionSnapshot(testCorp.id, published.version, createdRules); } catch {} diff --git a/src/probe.ts b/src/probe.ts index faf57a7..8b7f6a8 100644 --- a/src/probe.ts +++ b/src/probe.ts @@ -2,7 +2,7 @@ import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig } from " import { resolveCorpConfig } from "./core/config/manager.js"; import { createSealClient } from "./core/http/factory.js"; import type { SealEnterpriseConfig } from "./core/auth/types.js"; -import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js"; +import { resolveLiveSealEnterpriseConfig } from "./domains/seal/enterprise/source.js"; import { getApprovalContext } from "./domains/seal/api.js"; import { printJson } from "./cli/printer.js"; diff --git a/src/server.ts b/src/server.ts index 6fa5d75..4d00703 100644 --- a/src/server.ts +++ b/src/server.ts @@ -172,6 +172,17 @@ export function startServer(): StdioServerHandle { export { tokenizeCommand }; function cliResult(result: { stdout: string; stderr: string; isError: boolean; exitCode: number }): CallToolResult { + // Confirmation-required commands can carry a structured, unexecuted preview. + // Preserve it for MCP consumers instead of returning only the next-step prose. + if (result.exitCode === 10 && result.stdout) { + return { + content: [ + { type: "text", text: result.stdout }, + ...(result.stderr ? [{ type: "text" as const, text: result.stderr }] : []) + ], + isError: true + }; + } const text = result.isError ? result.stderr || result.stdout : result.stdout; return { content: [