Add --dry-run mutation previews across remaining mutating commands

Close the AGENTS.md "Safety Guardrail & Mutation Preview" coverage gap:
every remote-mutating command now supports --dry-run returning
structured JSON with preview: true, without executing the mutation.

- Domain capabilities gain an optional dryRun param and preview
  handlers: sealUserCreate/ResetPassword/Delete/Activate/DelegationCreate,
  sealDelegationRevoke, sealApprovalRuleCreate/Update/Delete/
  VersionPublish, sealSimulationBatchClean, sealInsightRecordAnalyze.
  Previews reuse the shared mutationPreview() diff shape; reads (GET)
  are allowed to build the before/after, writes never fire.
- CLI wiring: users create/delegation/reset-password/delete, rules
  create/update/delete/publish, simulation delete, analytics analyze,
  auth link revoke pass dryRun; dry-run bypasses the --yes gate
  (webhook delete pattern); corps mark previews the local config tag
  change without writing it.
- Shared dryRunOption() helper in parser.ts; help registry documents
  --dry-run on all covered commands; cli-protocol.md §3 example list
  updated; cli.md and embedded skill regenerated.
- New src/cli/commands/dry-run-gates.test.ts pins the contract:
  preview JSON on stdout, zero mutating requests (GET-only where reads
  are needed), config untouched for local previews.

Local user-config writes (corps switch/rename, config mode/test-dir/
lint) stay outside this contract: they are reversible local edits with
no upstream effect.
This commit is contained in:
gitea committed 2026-10-24 22:08:37 +08:00
1 parent 245ec33d1a
commit ffb9820822
16 files changed
+515 -86

No files matched your search

+1 -1
View File
@@ -46,7 +46,7 @@ When developing or refactoring CLI commands under `src/cli/`:
## 3. High-Risk Mutation & Preview Contract (`--dry-run`)
- All potentially destructive or state-mutating commands (e.g. `rules push`, `rules clear`, `corps sync-test`, `preference update`, `webhook create/update/delete`) **MUST** support `--dry-run`.
- All potentially destructive or state-mutating commands (e.g. `rules push/clear/create/update/delete/publish`, `corps sync-test`, `corps mark`, `preference update`, `users create/delete/reset-password/delegation`, `simulation delete`, `analytics analyze`, `auth link revoke`, `webhook create/update/delete`) **MUST** support `--dry-run`.
- **Preview Output**:
- When `--dry-run` is present, the command performs read-only discovery, simulates the mutation, and returns structured JSON with:
```json
+12 -12
View File
@@ -44,7 +44,7 @@ seal-use corps search <query> [--env <production|test>] [--strict]
seal-use corps get <corpId>
seal-use corps current [--corp <corpId>]
seal-use corps switch <corpId>
seal-use corps mark <corpId> --env <production|test> [--confirm]
seal-use corps mark <corpId> --env <production|test> [--dry-run] [--confirm]
seal-use corps rename <corpId> --name <newName>
seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]
@@ -63,10 +63,10 @@ seal-use rules count [--version <number|latest>] [--corp <corpId>]
seal-use rules list [--version <number|latest>] [--summary] [--limit 20] [--offset 0] [--output-file <path>] [--corp <corpId>]
seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>] [--corp <corpId>]
seal-use rules search <keyword> [--version <number|latest>] [--max-results 20] [--corp <corpId>]
seal-use rules create --description <text> --scope <scope> [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--description-file <path>] [--corp <corpId>]
seal-use rules update <code> [--description <text>|--description-file <path>] [--scope <scope>] [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--corp <corpId>]
seal-use rules delete <code> --yes [--corp <corpId>]
seal-use rules publish <versionName> [--corp <corpId>]
seal-use rules create --description <text> --scope <scope> [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--description-file <path>] [--dry-run] [--corp <corpId>]
seal-use rules update <code> [--description <text>|--description-file <path>] [--scope <scope>] [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--dry-run] [--corp <corpId>]
seal-use rules delete <code> [--dry-run] --yes [--corp <corpId>]
seal-use rules publish <versionName> [--dry-run] [--corp <corpId>]
seal-use rules versions [--corp <corpId>]
seal-use rules version <versionNumber|latest> [--corp <corpId>]
seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--include-unchanged] [--full] [--corp <corpId>]
@@ -134,7 +134,7 @@ seal-use simulation create --mode material_pack --package-ids <materialPackageId
seal-use simulation create --source-system weaver --request-ids "req-01,req-02" [--corp <corpId>]
seal-use simulation status <batchId> [--corp <corpId>]
seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] [--corp <corpId>]
seal-use simulation delete <batchId> --yes [--corp <corpId>]
seal-use simulation delete <batchId> [--dry-run] --yes [--corp <corpId>]
seal-use simulation specifications [--integration <sign-key>] [--corp <corpId>]
seal-use simulation approval-definitions [--corp <corpId>]
seal-use simulation list [--limit 50] [--all] [--query <text>] [--since <time>] [--until <time>] [--max-scan <n>] [--corp <corpId>]
@@ -170,17 +170,17 @@ seal-use auth check [--corp <corpId>]
seal-use auth link [--note <note>] [--expire <duration>] [--corp <corpId>]
seal-use auth link --from-link <url> [--note <note>] [--expire <duration>]
seal-use auth link list [--corp <corpId>]
seal-use auth link revoke <tokenId> [--corp <corpId>]
seal-use auth link revoke <tokenId> [--dry-run] [--corp <corpId>]
seal-use auth hose-link [--corp <corpId>] [--expire <duration>] [--force]
seal-use auth hose-openapi-token [--corp <corpId>] [--force]
seal-use auth hose-extract-keys <url> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]
seal-use auth hose-keys [--corp <corpId>] [--reveal]
seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]
seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--dry-run] [--corp <corpId>]
seal-use users search <keyword> [--corp <corpId>]
seal-use users delegation <userIdOrPhone|name> [--note <note>] [--expire <duration>] [--corp <corpId>]
seal-use users reset-password <userId> --yes [--corp <corpId>]
seal-use users delegation <userIdOrPhone|name> [--note <note>] [--expire <duration>] [--dry-run] [--corp <corpId>]
seal-use users reset-password <userId> [--dry-run] --yes [--corp <corpId>]
seal-use users get <userId> [--corp <corpId>]
seal-use users delete <userId> --yes [--corp <corpId>]
seal-use users delete <userId> [--dry-run] --yes [--corp <corpId>]
seal-use contacts departments [<departmentId>] [--corp <corpId>]
seal-use contacts children <departmentId> [--corp <corpId>]
seal-use contacts users <departmentId> [--corp <corpId>]
@@ -201,7 +201,7 @@ seal-use billing features [--corp <corpId>]
seal-use analytics insight [--start-date <ISO>] [--end-date <ISO>] [--limit <n>] [--corp <corpId>]
seal-use analytics risks <tagId> [--start-date <ISO>] [--end-date <ISO>] [--corp <corpId>]
seal-use analytics performance [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--corp <corpId>]
seal-use analytics analyze <recordId> [--corp <corpId>]
seal-use analytics analyze <recordId> [--dry-run] [--corp <corpId>]
seal-use analytics export [--downloads] [--out <file>] [--start-date <ISO>] [--end-date <ISO>] [--force] [--limit <n>] [--corp <corpId>]
seal-use context [--rule-version <versionId|versionNumber|latest>] [--document-limit 50] [--corp <corpId>]
seal-use source config [--corp <corpId>]
+3 -2
View File
@@ -3,7 +3,7 @@ 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 { runCapability } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { booleanOption, dryRunOption, numberOption, stringOption } from "../parser.js";
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
@@ -72,7 +72,8 @@ export async function handleAnalyticsCommand(
client,
corp,
{
recordId
recordId,
dryRun: dryRunOption(args)
},
outputOptions(args.options)
);
+9 -2
View File
@@ -15,6 +15,7 @@ import { createDelegation, getMe } from "../../domains/seal/api.js";
import { resolveHoseLinkIdentity, resolveSealLinkIdentity, summarizeSealLinkIdentity } from "../../domains/seal/enterprise/assist-identity.js";
import {
booleanOption,
dryRunOption,
parseDelegationExpireHours,
parseHoseExpireSeconds,
stringOption
@@ -99,8 +100,14 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
if (subAction === "revoke") {
const tokenId = args.command[3] ?? stringOption(args.options.tokenId) ?? stringOption(args.options.id);
if (!tokenId) throw usageError("Usage: seal-use auth link revoke <tokenId>");
await runCapability("sealDelegationRevoke", client, corp, { tokenId }, outputOptions(args.options));
if (!tokenId) throw usageError("Usage: seal-use auth link revoke <tokenId> [--dry-run]");
await runCapability(
"sealDelegationRevoke",
client,
corp,
{ tokenId, dryRun: dryRunOption(args) },
outputOptions(args.options)
);
return;
}
+15 -1
View File
@@ -13,7 +13,7 @@ import {
import type { CorpEnvironment } from "../../../core/config/types.js";
import { selectCorp } from "../../helpers.js";
import { confirmationRequired, usageError } from "../../../core/errors.js";
import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { booleanOption, dryRunOption, numberOption, stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
import { formatSafeSourceDetail, resolveCorpSealUrl } from "./shared.js";
@@ -167,6 +167,20 @@ export async function handleCorpOverview(
throw usageError("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");
}
const dryRun = dryRunOption(args);
if (dryRun) {
printJson({
preview: true,
dryRun: true,
mutation: "corps mark",
corpId: corp.id,
corpName: corp.name,
changesDiff: { before: corp.environment ?? undefined, after: targetEnv },
note: "环境标签影响同步与重放安全守卫;去掉 --dry-run 并加 --confirm 才会实际写入。"
});
return true;
}
const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true;
if (!confirmed) {
throw confirmationRequired(
+214
View File
@@ -0,0 +1,214 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runCli } from "../runner.js";
/**
* Mutation-preview (`--dry-run`) gates for commands that previously mutated
* without a preview path (AGENTS.md "Safety Guardrail & Mutation Preview").
* Every dry-run must return structured JSON with `preview: true` on stdout and
* never issue a mutating HTTP request — reads (GET) are allowed for building
* the before/after diff.
*/
const ORIGINAL_ENV = {
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
config: process.env.SEAL_USE_CONFIG_FILE,
tokenStore: process.env.SEAL_USE_TOKEN_STORE,
usageFile: process.env.SEAL_USE_USAGE_FILE
};
const ORIGINAL_FETCH = globalThis.fetch;
const tempDirs: string[] = [];
afterEach(() => {
restoreEnv("SEAL_USE_ENTERPRISES_DIR", ORIGINAL_ENV.enterprises);
restoreEnv("SEAL_USE_CONFIG_FILE", ORIGINAL_ENV.config);
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
restoreEnv("SEAL_USE_USAGE_FILE", ORIGINAL_ENV.usageFile);
globalThis.fetch = ORIGINAL_FETCH;
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
function setupMockEnv() {
const root = mkdtempSync(join(tmpdir(), "seal-use-dry-run-"));
const enterprises = join(root, "enterprises");
tempDirs.push(root);
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
process.env.SEAL_USE_USAGE_FILE = join(root, "usage.json");
mkdirSync(enterprises, { recursive: true });
writeFileSync(
join(enterprises, "dry-run-corp.json"),
JSON.stringify(
{
id: "dry-run-corp",
name: "Dry Run Corp",
environment: "test",
seal: {
url: "https://dry-run-corp.sealai.cc",
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: { type: "seal", token: "mock-token", sealUrl: "https://dry-run-corp.sealai.cc" }
},
null,
2
)
);
writeFileSync(
join(root, "config.json"),
JSON.stringify({ defaultCorpId: "dry-run-corp", stateful: true }, null, 2)
);
return { root, enterprises };
}
/** Records `METHOD url` per request and answers every call with a generic 200. */
function trackRequests() {
const requests: string[] = [];
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = typeof input === "string"
? input
: input instanceof URL
? input.toString()
: input.url;
const method = typeof input === "object" && "method" in input ? input.method : "GET";
requests.push(`${method} ${url}`);
return new Response(JSON.stringify({ data: {} }), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}) as typeof fetch;
return requests;
}
describe("mutation preview (--dry-run) gates", () => {
test("users create --dry-run previews without any network call", async () => {
setupMockEnv();
const requests = trackRequests();
const result = await runCli(["users", "create", "--name", "张三", "--phone", "13300001111", "--dry-run"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('"preview": true');
expect(result.stdout).toContain('"dryRun": true');
expect(requests).toEqual([]);
});
test("users delete --dry-run bypasses --yes and issues no mutating request", async () => {
setupMockEnv();
const requests = trackRequests();
const result = await runCli(["users", "delete", "user-123", "--dry-run"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('"preview": true');
expect(requests.every((entry) => entry.startsWith("GET "))).toBe(true);
});
test("rules create --dry-run previews the rule payload without any network call", async () => {
setupMockEnv();
const requests = trackRequests();
const result = await runCli([
"rules", "create", "--description", "测试规则", "--scope", "general", "--dry-run"
]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('"preview": true');
expect(result.stdout).toContain('"mutation": "sealApprovalRuleCreate"');
expect(requests).toEqual([]);
});
test("rules delete --dry-run bypasses --yes and issues no mutating request", async () => {
setupMockEnv();
const requests = trackRequests();
const result = await runCli(["rules", "delete", "0025", "--dry-run"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('"preview": true');
expect(result.stdout).toContain('"deleted": 0');
expect(requests.every((entry) => entry.startsWith("GET "))).toBe(true);
});
test("rules publish --dry-run previews draft scale without publishing", async () => {
setupMockEnv();
const requests = trackRequests();
const result = await runCli(["rules", "publish", "v-test", "--dry-run"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('"preview": true');
expect(result.stdout).toContain('"published": false');
expect(requests.every((entry) => entry.startsWith("GET "))).toBe(true);
});
test("simulation delete --dry-run bypasses --yes and issues no mutating request", async () => {
setupMockEnv();
const requests = trackRequests();
const result = await runCli(["simulation", "delete", "batch-42", "--dry-run"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('"preview": true');
expect(result.stdout).toContain('"cleaned": 0');
expect(requests.every((entry) => entry.startsWith("GET "))).toBe(true);
});
test("analytics analyze --dry-run previews without triggering server-side analysis", async () => {
setupMockEnv();
const requests = trackRequests();
const result = await runCli(["analytics", "analyze", "record-77", "--dry-run"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('"preview": true');
expect(result.stdout).toContain('"triggered": false');
expect(requests).toEqual([]);
});
test("auth link revoke --dry-run previews without revoking", async () => {
setupMockEnv();
const requests = trackRequests();
const result = await runCli(["auth", "link", "revoke", "token-1", "--dry-run"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('"preview": true');
expect(requests.every((entry) => entry.startsWith("GET "))).toBe(true);
});
test("corps mark --dry-run previews the tag change without writing config", async () => {
const { enterprises } = setupMockEnv();
trackRequests();
const result = await runCli(["corps", "mark", "dry-run-corp", "--env", "production", "--dry-run"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('"preview": true');
expect(result.stdout).toContain('"after": "production"');
const config = JSON.parse(readFileSync(join(enterprises, "dry-run-corp.json"), "utf8"));
expect(config.environment).toBe("test");
});
});
+9 -7
View File
@@ -12,6 +12,7 @@ import { runCapability, runCapabilityResult } from "../helpers.js";
import { confirmationRequired, validationError, usageError } from "../../core/errors.js";
import {
booleanOption,
dryRunOption,
jsonObject,
numberOption,
parseRuleVersionSelector,
@@ -220,7 +221,7 @@ export async function handleRulesCommand(
"sealApprovalRuleCreate",
client!,
corp,
{ description, scope, strictness },
{ description, scope, strictness, dryRun: dryRunOption(args) },
outputOptions(args.options)
);
return;
@@ -246,7 +247,7 @@ export async function handleRulesCommand(
"sealApprovalRuleUpdate",
client!,
corp,
{ ruleId, description, scope, strictness },
{ ruleId, description, scope, strictness, dryRun: dryRunOption(args) },
outputOptions(args.options)
);
return;
@@ -259,10 +260,11 @@ export async function handleRulesCommand(
stringOption(args.options["rule-id"]) ??
stringOption(args.options.code);
if (!ruleId) {
throw usageError("Usage: seal-use rules delete <code> --yes [--corp <corpId>]");
throw usageError("Usage: seal-use rules delete <code> [--dry-run] --yes [--corp <corpId>]");
}
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
const dryRun = dryRunOption(args);
if (!confirmed && !dryRun) {
throw confirmationRequired(
`Refusing to delete rule '${ruleId}' without --yes.`,
`seal-use rules delete ${ruleId} --corp ${corp.id} --yes`
@@ -272,7 +274,7 @@ export async function handleRulesCommand(
"sealApprovalRuleDelete",
client!,
corp,
{ ruleId },
{ ruleId, dryRun },
outputOptions(args.options)
);
return;
@@ -287,13 +289,13 @@ export async function handleRulesCommand(
stringOption(args.options.name) ??
(typeof payload.versionName === "string" ? payload.versionName : undefined);
if (!versionName) {
throw usageError("Usage: seal-use rules publish <versionName> [--corp <corpId>]");
throw usageError("Usage: seal-use rules publish <versionName> [--dry-run] [--corp <corpId>]");
}
await runCapability(
"sealApprovalRuleVersionPublish",
client!,
corp,
{ versionName },
{ versionName, dryRun: dryRunOption(args) },
outputOptions(args.options)
);
return;
+11 -3
View File
@@ -5,6 +5,7 @@ import { confirmationRequired, usageError, validationError } from "../../core/er
import { runCapability, runCapabilityResult } from "../helpers.js";
import {
booleanOption,
dryRunOption,
jsonObject,
numberOption,
splitOption,
@@ -172,15 +173,22 @@ export async function handleSimulationCommand(
if (action === "clean" || action === "delete") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw usageError("Usage: seal-use simulation delete <batchId> --yes");
if (!batchId) throw usageError("Usage: seal-use simulation delete <batchId> [--dry-run] --yes");
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
const dryRun = dryRunOption(args);
if (!confirmed && !dryRun) {
throw confirmationRequired(
`Refusing to delete simulation batch '${batchId}' without --yes.`,
`seal-use simulation delete ${batchId} --corp ${corp.id} --yes`
);
}
await runCapability("sealSimulationBatchClean", client, corp, { batchId }, outputOptions(args.options));
await runCapability(
"sealSimulationBatchClean",
client,
corp,
{ batchId, dryRun },
outputOptions(args.options)
);
return;
}
+18 -10
View File
@@ -2,7 +2,7 @@ import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { confirmationRequired, usageError } from "../../core/errors.js";
import { runCapability } from "../helpers.js";
import { booleanOption, parseDelegationExpireHours, stringOption } from "../parser.js";
import { booleanOption, dryRunOption, parseDelegationExpireHours, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
@@ -16,24 +16,31 @@ export async function handleUsersCommand(
if (action === "create") {
const name = stringOption(args.options.name) ?? maybeName;
const phone = stringOption(args.options.phone);
if (!name || !phone) throw usageError("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");
if (!name || !phone) throw usageError("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--dry-run]");
const deptId = stringOption(args.options.dept) ?? stringOption(args.options.departmentId);
const departmentIds = deptId ? [deptId] : undefined;
await runCapability("sealUserCreate", client, corp, { name, phone, departmentIds }, outputOptions(args.options));
await runCapability(
"sealUserCreate",
client,
corp,
{ name, phone, departmentIds, dryRun: dryRunOption(args) },
outputOptions(args.options)
);
return;
}
if (action === "reset-password") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw usageError("Usage: seal-use users reset-password <userId> --yes");
if (!userId) throw usageError("Usage: seal-use users reset-password <userId> [--dry-run] --yes");
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
const dryRun = dryRunOption(args);
if (!confirmed && !dryRun) {
throw confirmationRequired(
`Refusing to reset password of user '${userId}' without --yes.`,
`seal-use users reset-password ${userId} --corp ${corp.id} --yes`
);
}
await runCapability("sealUserResetPassword", client, corp, { userId }, outputOptions(args.options));
await runCapability("sealUserResetPassword", client, corp, { userId, dryRun }, outputOptions(args.options));
return;
}
@@ -52,15 +59,16 @@ export async function handleUsersCommand(
if (action === "delete") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw usageError("Usage: seal-use users delete <userId> --yes");
if (!userId) throw usageError("Usage: seal-use users delete <userId> [--dry-run] --yes");
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
const dryRun = dryRunOption(args);
if (!confirmed && !dryRun) {
throw confirmationRequired(
`Refusing to delete user '${userId}' without --yes.`,
`seal-use users delete ${userId} --corp ${corp.id} --yes`
);
}
await runCapability("sealUserDelete", client, corp, { userId }, outputOptions(args.options));
await runCapability("sealUserDelete", client, corp, { userId, dryRun }, outputOptions(args.options));
return;
}
@@ -81,7 +89,7 @@ export async function handleUsersCommand(
"sealUserDelegationCreate",
client,
corp,
{ userIdOrPhone, note, expiresInHours },
{ userIdOrPhone, note, expiresInHours, dryRun: dryRunOption(args) },
outputOptions(args.options)
);
return;
+15 -13
View File
@@ -80,9 +80,10 @@ export const HELP_REGISTRY: AreaHelp[] = [
name: "mark",
group: "企业配置",
summary: "Mark enterprise environment as production or test",
usage: ["seal-use corps mark <corpId> --env <production|test> [--confirm]"],
usage: ["seal-use corps mark <corpId> --env <production|test> [--dry-run] [--confirm]"],
options: [
{ flag: "--env <production|test>", description: "Target environment: 'production' or 'test' (required)" },
{ flag: "--dry-run", description: "Preview the environment tag change without writing local config" },
{ flag: "--confirm", description: "Confirm the environment update (required)" }
],
description: "Explicitly updates an enterprise's environment tag. Requires --confirm to prevent accidental changes."
@@ -289,22 +290,22 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
name: "create",
summary: "Create a new draft approval rule",
usage: ["seal-use rules create --description <text> --scope <scope> [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--description-file <path>] [--corp <corpId>]"]
usage: ["seal-use rules create --description <text> --scope <scope> [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--description-file <path>] [--dry-run] [--corp <corpId>]"]
},
{
name: "update",
summary: "Update a draft approval rule by code",
usage: ["seal-use rules update <code> [--description <text>|--description-file <path>] [--scope <scope>] [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--corp <corpId>]"]
usage: ["seal-use rules update <code> [--description <text>|--description-file <path>] [--scope <scope>] [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--dry-run] [--corp <corpId>]"]
},
{
name: "delete",
summary: "Delete a draft approval rule by code",
usage: ["seal-use rules delete <code> --yes [--corp <corpId>]"]
usage: ["seal-use rules delete <code> [--dry-run] --yes [--corp <corpId>]"]
},
{
name: "publish",
summary: "Publish current draft rules as a new formal version",
usage: ["seal-use rules publish <versionName> [--corp <corpId>]"]
usage: ["seal-use rules publish <versionName> [--dry-run] [--corp <corpId>]"]
},
{
name: "versions",
@@ -803,7 +804,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
name: "delete",
aliases: ["clean"],
summary: "Delete simulation batch records",
usage: ["seal-use simulation delete <batchId> --yes [--corp <corpId>]"]
usage: ["seal-use simulation delete <batchId> [--dry-run] --yes [--corp <corpId>]"]
},
{
name: "specifications",
@@ -1064,7 +1065,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
name: "link revoke",
summary: "【Seal 审核后台】撤销指定的 Seal 委托授权令牌",
usage: ["seal-use auth link revoke <tokenId> [--corp <corpId>]"]
usage: ["seal-use auth link revoke <tokenId> [--dry-run] [--corp <corpId>]"]
},
{
name: "hose-link",
@@ -1123,7 +1124,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
name: "create",
summary: "Create a new tenant user",
usage: ["seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]"]
usage: ["seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--dry-run] [--corp <corpId>]"]
},
{
name: "search",
@@ -1133,16 +1134,17 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
name: "delegation",
summary: "Create delegation token for a specific user",
usage: ["seal-use users delegation <userIdOrPhone|name> [--note <note>] [--expire <duration>] [--corp <corpId>]"],
usage: ["seal-use users delegation <userIdOrPhone|name> [--note <note>] [--expire <duration>] [--dry-run] [--corp <corpId>]"],
options: [
{ flag: "--note <note>", description: "委托授权备注说明" },
{ flag: "--expire, --expires-in <duration>", description: "委托授权有效期,推荐 '7d' 或 '24h'(最大 7 天,兼容秒数并自动向下取整)" }
{ flag: "--expire, --expires-in <duration>", description: "委托授权有效期,推荐 '7d' 或 '24h'(最大 7 天,兼容秒数并自动向下取整)" },
{ flag: "--dry-run", description: "Preview the delegation parameters without minting a token" }
]
},
{
name: "reset-password",
summary: "Reset user password",
usage: ["seal-use users reset-password <userId> --yes [--corp <corpId>]"]
usage: ["seal-use users reset-password <userId> [--dry-run] --yes [--corp <corpId>]"]
},
{
name: "get",
@@ -1152,7 +1154,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
name: "delete",
summary: "Delete user",
usage: ["seal-use users delete <userId> --yes [--corp <corpId>]"]
usage: ["seal-use users delete <userId> [--dry-run] --yes [--corp <corpId>]"]
}
]
},
@@ -1319,7 +1321,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
name: "analyze",
aliases: ["reanalyze"],
summary: "Trigger on-demand smart insight risk analysis for an approval record",
usage: ["seal-use analytics analyze <recordId> [--corp <corpId>]"]
usage: ["seal-use analytics analyze <recordId> [--dry-run] [--corp <corpId>]"]
},
{
name: "export",
+5
View File
@@ -368,6 +368,11 @@ export function webhookShowSecretOption(options: Record<string, string | boolean
);
}
/** Shared `--dry-run` read for mutation-preview gates (charter: one canonical spelling). */
export function dryRunOption(args: ParsedArgs): boolean | undefined {
return booleanOption(args.options["dry-run"]) ?? booleanOption(args.options.dryRun);
}
export function materialPackFilePolicyOptions(
options: Record<string, string | boolean>
): MaterialPackFilePolicyPatch | undefined {
@@ -43,7 +43,8 @@ describe("sealCapabilities", () => {
expect(Object.keys(schema.properties ?? {})).toEqual([
"description",
"scope",
"strictness"
"strictness",
"dryRun"
]);
expect(schema.required).toEqual(["description", "scope", "strictness"]);
});
+97 -21
View File
@@ -47,10 +47,28 @@ export const identityCapabilities = [
name: "sealDelegationRevoke",
description: "撤销/废除指定的 Seal 授权链接 (Delegation)",
parameters: z.object({
tokenId: z.string().describe("授权链接 ID (delegation record ID)")
tokenId: z.string().describe("授权链接 ID (delegation record ID)"),
dryRun: z.boolean().optional().describe("仅预览将被撤销的授权链接,不执行撤销")
}),
handler: async (client: KyInstance, params: { tokenId: string }) =>
api.revokeDelegation(client, params.tokenId)
handler: async (
client: KyInstance,
params: { tokenId: string; dryRun?: boolean }
) => {
if (params.dryRun) {
const target = await api
.listDelegations(client)
.then((items) => items.find((item) => item.id === params.tokenId))
.catch(() => undefined);
return {
preview: true,
dryRun: true,
mutation: "sealDelegationRevoke",
revoked: 0,
target: target ?? { id: params.tokenId }
};
}
return api.revokeDelegation(client, params.tokenId);
}
},
{
name: "sealUserCreate",
@@ -59,21 +77,42 @@ export const identityCapabilities = [
name: z.string().describe("用户姓名"),
phone: z.string().describe("手机号码 (例如 13300001111 或 +8613300001111)"),
permissions: z.array(z.string()).optional().describe("权限列表,默认为 []"),
departmentIds: z.array(z.string()).optional().describe("关联部门 ID 数组")
departmentIds: z.array(z.string()).optional().describe("关联部门 ID 数组"),
dryRun: z.boolean().optional().describe("仅预览将要创建的用户,不执行")
}),
handler: async (
client: KyInstance,
params: { name: string; phone: string; permissions?: string[]; departmentIds?: string[] }
) => api.createLocalUser(client, params)
params: { name: string; phone: string; permissions?: string[]; departmentIds?: string[]; dryRun?: boolean }
) => {
if (params.dryRun) {
const { dryRun: _dryRun, ...payload } = params;
return { preview: true, dryRun: true, mutation: "sealUserCreate", created: payload };
}
const { dryRun: _dryRun, ...payload } = params;
return api.createLocalUser(client, payload);
}
},
{
name: "sealUserResetPassword",
description: "重置指定 Seal 用户的默认/随机密码,并返回生成的新密码",
parameters: z.object({
userId: z.string().describe("用户 ID (_id)")
userId: z.string().describe("用户 ID (_id)"),
dryRun: z.boolean().optional().describe("仅预览将被重置密码的用户,不执行")
}),
handler: async (client: KyInstance, params: { userId: string }) =>
api.resetUserPassword(client, params.userId)
handler: async (client: KyInstance, params: { userId: string; dryRun?: boolean }) => {
if (params.dryRun) {
const before = await api.getUserDetail(client, params.userId).catch(() => undefined);
return {
preview: true,
dryRun: true,
mutation: "sealUserResetPassword",
reset: 0,
before,
wouldDo: "重置该用户密码并返回新的初始随机密码"
};
}
return api.resetUserPassword(client, params.userId);
}
},
{
name: "sealUserGet",
@@ -97,19 +136,43 @@ export const identityCapabilities = [
name: "sealUserDelete",
description: "删除指定 Seal 本地用户",
parameters: z.object({
userId: z.string().describe("用户 ID (_id)")
userId: z.string().describe("用户 ID (_id)"),
dryRun: z.boolean().optional().describe("仅预览将被删除的用户,不执行删除")
}),
handler: async (client: KyInstance, params: { userId: string }) =>
api.deleteLocalUser(client, params.userId)
handler: async (client: KyInstance, params: { userId: string; dryRun?: boolean }) => {
if (params.dryRun) {
const before = await api.getUserDetail(client, params.userId).catch(() => undefined);
return {
preview: true,
dryRun: true,
mutation: "sealUserDelete",
deleted: 0,
before
};
}
return api.deleteLocalUser(client, params.userId);
}
},
{
name: "sealUserActivate",
description: "启用/激活已离职的 Seal 用户账号",
parameters: z.object({
userId: z.string().describe("用户 ID (_id)")
userId: z.string().describe("用户 ID (_id)"),
dryRun: z.boolean().optional().describe("仅预览将被激活的用户,不执行")
}),
handler: async (client: KyInstance, params: { userId: string }) =>
api.activateLocalUser(client, params.userId)
handler: async (client: KyInstance, params: { userId: string; dryRun?: boolean }) => {
if (params.dryRun) {
const before = await api.getUserDetail(client, params.userId).catch(() => undefined);
return {
preview: true,
dryRun: true,
mutation: "sealUserActivate",
activated: 0,
before
};
}
return api.activateLocalUser(client, params.userId);
}
},
{
name: "sealUserDelegationCreate",
@@ -123,18 +186,31 @@ export const identityCapabilities = [
.min(1)
.max(168)
.optional()
.describe("授权链接有效期小时数(1~168 小时,即最大 7 天,默认 24 小时)")
.describe("授权链接有效期小时数(1~168 小时,即最大 7 天,默认 24 小时)"),
dryRun: z.boolean().optional().describe("仅预览将要签发的授权链接参数,不执行")
}),
handler: async (
client: KyInstance,
params: { userIdOrPhone: string; note?: string; expiresInHours?: number },
params: { userIdOrPhone: string; note?: string; expiresInHours?: number; dryRun?: boolean },
context: CapabilityContext
) =>
api.createDelegationForUser(
) => {
if (params.dryRun) {
const { dryRun: _dryRun, ...payload } = params;
return {
preview: true,
dryRun: true,
mutation: "sealUserDelegationCreate",
issued: false,
forUser: payload
};
}
const { dryRun: _dryRun, ...payload } = params;
return api.createDelegationForUser(
client,
params,
payload,
(token) => createSealClientForToken(context.corp, token),
context.corp
)
);
}
}
];
+16 -3
View File
@@ -53,12 +53,25 @@ export const insightCapabilities = [
name: "sealInsightRecordAnalyze",
description: "对指定的审批单运行记录按需触发智能洞察风险分析",
parameters: z.object({
recordId: z.string().describe("审批单运行记录 ID (recordId)")
recordId: z.string().describe("审批单运行记录 ID (recordId)"),
dryRun: z.boolean().optional().describe("仅预览将要触发的分析,不实际触发服务端分析")
}),
handler: async (
client: KyInstance,
params: { recordId: string }
) => api.analyzeInsightRecord(client, params.recordId)
params: { recordId: string; dryRun?: boolean }
) => {
if (params.dryRun) {
return {
preview: true,
dryRun: true,
mutation: "sealInsightRecordAnalyze",
recordId: params.recordId,
triggered: false,
wouldDo: "对该审批运行记录触发一次服务端智能洞察风险分析"
};
}
return api.analyzeInsightRecord(client, params.recordId);
}
},
{
name: "sealInsightExport",
+74 -8
View File
@@ -192,13 +192,25 @@ export const rulesCapabilities = [
parameters: z.object({
description: z.string().describe("规则描述"),
scope: z.string().describe("适用场景"),
strictness: z.enum(["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"]).describe("严格程度")
strictness: z.enum(["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"]).describe("严格程度"),
dryRun: z.boolean().optional().describe("仅预览将要创建的规则,不执行")
}),
handler: async (
client: KyInstance,
params: { description: string; scope: string; strictness: string }
params: { description: string; scope: string; strictness: string; dryRun?: boolean },
context: CapabilityContext
) => {
const created = await api.createApprovalRule(client, params);
if (params.dryRun) {
const { dryRun: _dryRun, ...payload } = params;
return {
...mutationPreview(context, "api/v1/rules", null, payload, 1),
dryRun: true,
mutation: "sealApprovalRuleCreate",
created: 0
};
}
const { dryRun: _dryRun, ...payload } = params;
const created = await api.createApprovalRule(client, payload);
const codeNum = parseRuleCodeNumber(created?.code);
return codeNum !== undefined ? { ...created, code: formatRuleCode(codeNum) } : created;
}
@@ -211,7 +223,8 @@ export const rulesCapabilities = [
description: z.string().optional(),
scope: z.string().optional(),
strictness: z.enum(["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"]).optional(),
ifUnchanged: z.union([z.string(), z.number()]).optional().describe("乐观并发预检基准:当前草稿的 updatedAt(rules get 输出的北京时间字符串或毫秒时间戳);服务端草稿在该基准后被修改则拒绝更新")
ifUnchanged: z.union([z.string(), z.number()]).optional().describe("乐观并发预检基准:当前草稿的 updatedAt(rules get 输出的北京时间字符串或毫秒时间戳);服务端草稿在该基准后被修改则拒绝更新"),
dryRun: z.boolean().optional().describe("仅预览将要更新的字段与变更 Diff,不执行写入")
}),
handler: async (
client: KyInstance,
@@ -221,9 +234,31 @@ export const rulesCapabilities = [
scope?: string;
strictness?: string;
ifUnchanged?: string | number;
dryRun?: boolean;
},
context: CapabilityContext
) => {
if (params.dryRun) {
const draftData = await api.listApprovalRules(client).catch(() => undefined);
const targetCodeNum = parseRuleCodeNumber(params.ruleId.trim());
const matched = draftData?.rules?.find(
(r) => r.id === params.ruleId.trim() || (targetCodeNum !== undefined && parseRuleCodeNumber(r.code) === targetCodeNum)
);
const { dryRun: _dryRun, ifUnchanged: _ifUnchanged, ruleId: _ruleId, ...changes } = params;
return {
...mutationPreview(
context,
"api/v1/rules",
matched ?? undefined,
matched ? { ...matched, ...changes } : changes,
1
),
dryRun: true,
mutation: "sealApprovalRuleUpdate",
ruleId: params.ruleId,
updated: 0
};
}
let resolvedRuleId = params.ruleId.trim();
const targetCodeNum = parseRuleCodeNumber(resolvedRuleId);
let draftRule: ApprovalRule | undefined;
@@ -292,11 +327,17 @@ export const rulesCapabilities = [
name: "sealApprovalRuleDelete",
description: "删除 Seal 草稿审批规则",
parameters: z.object({
ruleId: z.string().describe("规则 ID 或规则编号 code")
ruleId: z.string().describe("规则 ID 或规则编号 code"),
dryRun: z.boolean().optional().describe("仅预览将被删除的规则,不执行删除")
}),
handler: async (client: KyInstance, params: { ruleId: string }) => {
handler: async (
client: KyInstance,
params: { ruleId: string; dryRun?: boolean },
context: CapabilityContext
) => {
let resolvedRuleId = params.ruleId.trim();
const targetCodeNum = parseRuleCodeNumber(resolvedRuleId);
let matchedRule: ApprovalRule | undefined;
if (targetCodeNum !== undefined) {
const draftData = await api.listApprovalRules(client).catch(() => undefined);
if (draftData?.rules) {
@@ -307,8 +348,18 @@ export const rulesCapabilities = [
throw new Error(`未在当前草稿中找到编号为 ${params.ruleId} 的规则`);
}
resolvedRuleId = matched.id;
matchedRule = matched;
}
}
if (params.dryRun) {
return {
...mutationPreview(context, "api/v1/rules", matchedRule ?? { id: resolvedRuleId }, null, 1),
dryRun: true,
mutation: "sealApprovalRuleDelete",
ruleId: resolvedRuleId,
deleted: 0
};
}
await api.deleteApprovalRule(client, resolvedRuleId);
return { success: true, ruleId: resolvedRuleId };
}
@@ -406,10 +457,25 @@ export const rulesCapabilities = [
name: "sealApprovalRuleVersionPublish",
description: "发布 Seal 草稿审批规则为新版本",
parameters: z.object({
versionName: z.string().describe("版本名称")
versionName: z.string().describe("版本名称"),
dryRun: z.boolean().optional().describe("仅预览将要发布的草稿规模,不执行发布")
}),
handler: async (client: KyInstance, params: { versionName: string }, context: CapabilityContext) => {
handler: async (
client: KyInstance,
params: { versionName: string; dryRun?: boolean },
context: CapabilityContext
) => {
const draft = await api.listApprovalRules(client).catch(() => undefined);
if (params.dryRun) {
return {
...mutationPreview(context, "api/v1/rules/versions", draft?.rules ?? [], { versionName: params.versionName }, draft?.rules?.length ?? 0),
dryRun: true,
mutation: "sealApprovalRuleVersionPublish",
versionName: params.versionName,
draftCount: draft?.rules?.length ?? 0,
published: false
};
}
const published = await api.publishApprovalRuleVersion(client, params.versionName);
if (draft) {
try { savePublishedRuleVersionSnapshot(context.corp.id, published.version, draft.rules); } catch {}
+14 -2
View File
@@ -472,9 +472,21 @@ export const simulationCapabilities = [
name: "sealSimulationBatchClean",
description: "删除模拟测试批次产生的测试数据",
parameters: z.object({
batchId: z.string().describe("模拟批次 ID")
batchId: z.string().describe("模拟批次 ID"),
dryRun: z.boolean().optional().describe("仅预览批次当前状态与将被清理的数据,不执行删除")
}),
handler: async (client: KyInstance, params: { batchId: string }) => {
handler: async (client: KyInstance, params: { batchId: string; dryRun?: boolean }) => {
if (params.dryRun) {
const before = await api.getSimulationBatch(client, params.batchId).catch(() => undefined);
return {
preview: true,
dryRun: true,
mutation: "sealSimulationBatchClean",
batchId: params.batchId,
cleaned: 0,
before
};
}
const result = await api.cleanSimulationBatch(client, params.batchId);
return {
batchId: params.batchId,