fix(cli): 统一生产环境确认协议与预览行为

- 新增 src/cli/production.ts:--allow-prod 为唯一生产覆盖参数,
  --allow-production / --force 仅作兼容别名;JSON 阻断统一为
  PROD_OVERRIDE_REQUIRED,并携带 nextAction 与 details.operation
- workflow test 与 workflow nodes grant 统一提示文案、错误结构与
  nextAction 生成;workflow test 的 JSON 阻断不再返回空 stdout
- 预览 --dry-run 始终放行,实际执行才要求覆盖参数;nodes grant
  参数校验前置,缺少节点类型时不再先报生产阻断
- 两个命令的成功结果统一携带 productionOverride / productionWarning
- corps tag 将企业从 prod 降级为 test/demo 时输出显著警告
- 同步 CLI 帮助、CLI/workflow README 与 Skill;补充对应单测

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
giteaandClaude committed 2026-11-18 16:44:57 +08:00
1 parent 038aca10fb
commit 5be2bd5432
16 files changed
+575 -127

No files matched your search

+1 -1
View File
@@ -14,7 +14,7 @@
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
带结构化元数据的 `EkbError.details` 会保留在 JSON 错误中,例如工作流主保存已完成但元数据刷新失败时的 `remoteSaved` 和服务端版本;普通错误输出不变。
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
- `生产环境安全阻断 (Production Safeguard)`:对带副作用的敏感命令,在正式生产企业 (`env === "prod"`) 执行时触发硬阻断。`workflow test` 需显式带 `--force` 确认生产风险;`workflow nodes grant` 需显式带 `--allow-prod`,并继续遵守 `--dry-run`/`--yes` 两阶段确认。自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
- `生产环境确认 (Production Safeguard)`:`src/cli/production.ts` 统一策略。正式生产企业 (`env === "prod"`) 执行敏感命令时,只要求显式追加 `--allow-prod` 表明操作者已知晓目标为生产企业,不禁止功能;`--force` 保留为兼容别名。预览 (`--dry-run`) 始终放行,不要求覆盖参数;实际执行仍遵守 `--dry-run`/`--yes` 两阶段确认。阻断统一返回文本提示或 JSON 错误 `PROD_OVERRIDE_REQUIRED`(含 `nextAction` 与 `details.operation`)。自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
- `helpers.ts`:横切运行时助手(`initCorpRuntime` / `requireSelectedCorp` / `getSessionClientForRuntime`)。
- `service.ts`:常驻守护进程管理(安装/启停/状态)。
- `help.ts`:帮助文本组织。
+19
View File
@@ -159,6 +159,25 @@ describe("CLI - corps environment attributes & filtering", () => {
expect(res.stdout).toContain("[DRY-RUN]");
expect(res.stdout).toContain("设置企业环境属性");
expect(res.stdout).toContain("newEnv: test");
expect(res.stdout).toContain("将不再触发生产环境确认");
});
it("corps tag dry-run from production to demo includes the same downgrade warning", async () => {
const runtime = createMockRuntime();
const res = await handleCorpsCommand(
{
area: "corps",
action: "tag",
args: ["corp_prod"],
options: { demo: true, "dry-run": true },
raw: ["corps", "tag", "corp_prod", "--demo", "--dry-run"],
},
runtime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("将不再触发生产环境确认");
expect(res.stdout).toContain("newEnv: demo");
});
it("corps current displays environment attribute label", async () => {
+12 -2
View File
@@ -6,6 +6,12 @@ import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mu
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveTargetCorpByArgOrContext } from "./shared.js";
/** 生产降级为测试/演示会关闭该企业的生产确认门禁,必须显著提示。 */
function productionDowngradeWarning(currentEnv: CorpEnv, targetEnv: CorpEnv): string | undefined {
if (currentEnv !== "prod" || targetEnv === "prod") return undefined;
return "该企业原为正式生产环境;改为测试/演示后,workflow test 与 workflow nodes grant 将不再触发生产环境确认。";
}
export async function handleTagCorp(
parsed: CliParsedArgs,
runtime: CliRuntime
@@ -154,12 +160,15 @@ export async function handleTagCorp(
};
}
const currentEnv = getCorpEnv(targetCorp);
const downgradeWarning = productionDowngradeWarning(currentEnv, targetEnv);
const changes = {
corpId: targetCorp.id,
name: targetCorp.name,
currentEnv: targetCorp.env,
currentEnv,
newEnv: targetEnv,
newIsTest: targetEnv !== "prod",
...(downgradeWarning ? { warning: downgradeWarning } : {}),
};
if (isDryRun(parsed, runtime)) {
@@ -192,6 +201,7 @@ export async function handleTagCorp(
env: updatedCorp.env,
isTest: updatedCorp.isTest,
configFile: filePath,
...(downgradeWarning ? { warning: downgradeWarning } : {}),
},
runtime.outputOptions
),
@@ -209,7 +219,7 @@ export async function handleTagCorp(
});
return {
stdout: `[SUCCESS] 企业环境属性设置成功:\n\n${summary}\n`,
stdout: `${downgradeWarning ? `⚠️ ${downgradeWarning}\n\n` : ""}[SUCCESS] 企业环境属性设置成功:\n\n${summary}\n`,
stderr: "",
exitCode: 0,
};
+48 -1
View File
@@ -106,11 +106,58 @@ describe("workflow debug mutation and result contract", () => {
} as any;
const blocked = await handleWorkflowTest(args({ yes: true }), prodRuntime);
expect(blocked.exitCode).toBe(1);
expect(blocked.stderr).toContain("生产环境安全阻断");
expect(blocked.stderr).toContain("生产环境确认");
expect(run).not.toHaveBeenCalled();
const allowed = await handleWorkflowTest(args({ yes: true, force: true }), prodRuntime);
expect(allowed.exitCode).toBe(0);
expect(run).toHaveBeenCalledTimes(1);
});
it("reports a structured production confirmation error in JSON mode", async () => {
const { client, run } = setup();
const prodRuntime = {
selectedCorp: { id: "prod-corp", name: "生产正式企业", env: "prod", isTest: false },
jsonMode: true,
} as any;
const blocked = await handleWorkflowTest(args({ yes: true }), prodRuntime);
expect(blocked.exitCode).toBe(1);
expect(blocked.stderr).toBe("");
const payload = JSON.parse(blocked.stdout);
expect(payload.code).toBe("PROD_OVERRIDE_REQUIRED");
expect(payload.details.operation).toBe("workflow.test");
expect(payload.nextAction).toContain("--allow-prod");
expect(client).not.toHaveBeenCalled();
expect(run).not.toHaveBeenCalled();
});
it("allows production dry-run without the override and teaches --allow-prod", async () => {
const { client, run } = setup();
const prodRuntime = {
selectedCorp: { id: "prod-corp", name: "生产正式企业", env: "prod", isTest: false },
jsonMode: true,
} as any;
const preview = await handleWorkflowTest(args({ "dry-run": true }), prodRuntime);
expect(preview.exitCode).toBe(0);
const payload = JSON.parse(preview.stdout);
expect(payload.dryRun).toBe(true);
expect(payload.changes.productionOverride).toBe(false);
expect(payload.nextAction).toContain("--allow-prod");
expect(client).not.toHaveBeenCalled();
expect(run).not.toHaveBeenCalled();
});
it("marks production execution results when --allow-prod is used", async () => {
const { run } = setup();
const prodRuntime = {
selectedCorp: { id: "prod-corp", name: "生产正式企业", env: "prod", isTest: false },
jsonMode: true,
} as any;
const result = await handleWorkflowTest(args({ yes: true, "allow-prod": true }), prodRuntime);
expect(result.exitCode).toBe(0);
const payload = JSON.parse(result.stdout);
expect(payload.productionOverride).toBe(true);
expect(payload.productionWarning).toContain("正式生产企业");
expect(run).toHaveBeenCalledTimes(1);
});
});
@@ -26,7 +26,7 @@ test("production corp is blocked before any grant request or confirmation", asyn
);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("生产环境安全阻断");
expect(result.stderr).toContain("生产环境确认");
expect(result.stderr).toContain("--allow-prod");
expect(grant).not.toHaveBeenCalled();
} finally {
@@ -45,8 +45,48 @@ test("env-unmarked corp is conservatively treated as production", async () => {
);
expect(result.exitCode).toBe(1);
const parsed = JSON.parse(result.stdout);
expect(parsed.code).toBe("PROD_GRANT_BLOCKED");
expect(parsed.code).toBe("PROD_OVERRIDE_REQUIRED");
expect(parsed.nextAction).toContain("--allow-prod");
expect(parsed.details.operation).toBe("workflow.nodes.grant");
expect(grant).not.toHaveBeenCalled();
} finally {
grant.mockRestore();
}
});
test("production dry-run is allowed without --allow-prod and teaches the override", async () => {
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
success: true, saved: ["code"], skipped: [], rawMessage: "ok", isTest: false,
});
try {
const result = await handleWorkflowCommand(
parseArgs(["workflow", "nodes", "grant", "code", "--dry-run"]),
prodRuntime()
);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("productionOverride: false");
expect(result.stdout).toContain("实际执行需追加 --allow-prod");
expect(result.stdout).toContain("--allow-prod");
expect(grant).not.toHaveBeenCalled();
} finally {
grant.mockRestore();
}
});
test("missing node types is reported before the production confirmation", async () => {
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
success: true, saved: [], skipped: [], rawMessage: "ok", isTest: false,
});
try {
const result = await handleWorkflowCommand(
parseArgs(["workflow", "nodes", "grant", "--yes"]),
prodRuntime()
);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("请指定要开通的节点类型");
expect(result.stderr).not.toContain("生产环境确认");
expect(grant).not.toHaveBeenCalled();
} finally {
grant.mockRestore();
@@ -65,7 +105,7 @@ test("--allow-prod dry-run previews the production grant without writing", async
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("productionOverride: true");
expect(result.stdout).toContain("生产环境逃生口已启用");
expect(result.stdout).toContain("生产环境覆盖已启用");
expect(result.stdout).toContain("--allow-prod --yes");
expect(grant).not.toHaveBeenCalled();
} finally {
@@ -101,7 +141,7 @@ test("--allow-prod --yes executes the production grant and marks the result", as
);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("生产环境逃生口已启用");
expect(result.stdout).toContain("生产环境覆盖已启用");
expect(result.stdout).toContain("灰度节点开通结果");
expect(grant).toHaveBeenCalledTimes(1);
} finally {
@@ -109,6 +149,24 @@ test("--allow-prod --yes executes the production grant and marks the result", as
}
});
test("--force remains a compatible production override alias", async () => {
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
success: true, saved: ["code"], skipped: [], rawMessage: "ok", isTest: false,
});
try {
const result = await handleWorkflowCommand(
parseArgs(["workflow", "nodes", "grant", "code", "--force", "--yes"]),
prodRuntime()
);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("生产环境覆盖已启用");
expect(grant).toHaveBeenCalledTimes(1);
} finally {
grant.mockRestore();
}
});
test("--allow-prod --yes JSON result exposes productionOverride", async () => {
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
success: true, saved: ["code"], skipped: [], rawMessage: "新开通的节点:code", isTest: false,
+50 -54
View File
@@ -3,7 +3,8 @@ import { GRAY_NODES_CATALOG, normalizeGrayNodes } from "../../../domains/platfor
import { isCorpProd } from "../../../core/config/types.js";
import { booleanOption, stringOption } from "../../parser.js";
import { printJson, printTable, printKeyValue } from "../../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import { buildConfirmedCommand, isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import { hasProductionOverride, productionGuard, productionOverrideMeta } from "../../production.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { createPiperClientForCorp } from "../../helpers.js";
@@ -113,40 +114,6 @@ export async function handleGrantNodes(
runtime: CliRuntime
): Promise<CliResult> {
const corp = runtime.selectedCorp!;
const isProd = isCorpProd(corp);
const allowProd = booleanOption(parsed.options, ["allow-prod", "allow-production"]);
const prodNextAction = "hose-use workflow nodes grant <type...> --allow-prod --yes";
// 生产环境默认硬拦截:灰度节点开通属于不可逆企业级写操作。
// 逃生口必须显式追加 --allow-prod,且仍受 --dry-run / --yes 两阶段确认约束。
if (isProd && !allowProd) {
return {
stdout: runtime.jsonMode
? printJson({
error: true,
code: "PROD_GRANT_BLOCKED",
message: "对正式生产企业开通灰度节点需显式追加 --allow-prod",
exitCode: 1,
nextAction: prodNextAction,
}) + "\n"
: "",
stderr: runtime.jsonMode
? ""
: [
"🛑 生产环境安全阻断 (Production Safeguard):",
`当前工作企业 [${corp.name || corp.id}] 被判定为【正式生产环境】。`,
"灰度节点开通是不可逆的企业级写操作,默认禁止对生产企业执行。",
"",
"如确需在生产环境开通,必须显式追加 --allow-prod 承担风险,并先预览再执行:",
" hose-use workflow nodes grant <type...> --allow-prod --dry-run",
` ${prodNextAction}`,
"",
"若企业环境标记有误,请检查 ~/.config/hose-use/enterprises/ 下的 env / isTest 字段。",
].join("\n") + "\n",
exitCode: 1,
};
}
const rawNodes = parsed.args.slice(1);
const optionNodes = stringOption(parsed.options, ["nodes", "node", "type", "types"]);
const collected: string[] = [];
@@ -170,27 +137,51 @@ export async function handleGrantNodes(
};
}
const isProd = isCorpProd(corp);
const allowProd = hasProductionOverride(parsed);
const isTest = booleanOption(parsed.options, ["is-test"]);
const confirmNextAction = buildConfirmedCommand(parsed);
const prodNextAction = buildConfirmedCommand(parsed, ["--allow-prod"]);
// 预览不产生写操作,始终放行;生产环境只在 nextAction 中补上覆盖参数。
if (isDryRun(parsed, runtime)) {
return mutationPreview(
parsed,
runtime,
"开通企业工作流灰度节点",
corp.corpId || corp.credentials.corpId || corp.id,
{
nodes: normalizeGrayNodes(targetNodes),
isTest,
attachedOptions: GRANT_ATTACHED_OPTIONS,
adminPasswordRequired: Boolean(process.env.HOSE_ADMIN_PASSWORD),
...(isProd
? {
productionOverride: allowProd,
productionWarning: allowProd
? "生产环境覆盖已启用:实际执行会变更正式生产企业,请再次核对企业与节点类型。"
: "当前为正式生产企业:实际执行需追加 --allow-prod 确认。",
}
: {}),
},
{ extraArgs: isProd && !allowProd ? ["--allow-prod"] : [] }
);
}
const blocked = productionGuard(parsed, runtime, {
operation: "开通企业工作流灰度节点",
operationCode: "workflow.nodes.grant",
risk: "灰度节点开通是不可逆的企业级写操作,会改变正式生产企业的可用节点能力。",
nextAction: prodNextAction,
});
if (blocked) return blocked;
requireMutationConfirmation(
parsed,
runtime,
"开通企业工作流灰度节点",
isProd ? prodNextAction : "hose-use workflow nodes grant <type...> --yes"
isProd ? prodNextAction : confirmNextAction
);
const isTest = booleanOption(parsed.options, ["is-test"]);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "开通企业工作流灰度节点", corp.corpId || corp.credentials.corpId || corp.id, {
nodes: normalizeGrayNodes(targetNodes),
isTest,
attachedOptions: GRANT_ATTACHED_OPTIONS,
adminPasswordRequired: Boolean(process.env.HOSE_ADMIN_PASSWORD),
...(isProd
? {
productionOverride: true,
productionWarning: "生产环境逃生口已启用:实际执行会变更正式生产企业,请再次核对企业与节点类型。",
}
: {}),
});
}
const password = stringOption(parsed.options, ["password", "pwd", "admin-key"]);
@@ -200,9 +191,14 @@ export async function handleGrantNodes(
isTest,
});
const overrideMeta = productionOverrideMeta(
parsed,
runtime,
"生产环境覆盖已启用 (--allow-prod):本次对正式生产企业执行了灰度节点开通。"
);
if (runtime.jsonMode) {
return {
stdout: printJson(isProd ? { ...result, productionOverride: true } : result, runtime.outputOptions),
stdout: printJson({ ...result, ...overrideMeta }, runtime.outputOptions),
stderr: "",
exitCode: result.success ? 0 : 1,
};
@@ -212,8 +208,8 @@ export async function handleGrantNodes(
}
const lines = [
...(isProd
? ["⚠️ 生产环境逃生口已启用 (--allow-prod):本次对正式生产企业执行了灰度节点开通。", ""]
...(overrideMeta.productionOverride
? [`⚠️ ${overrideMeta.productionWarning}`, ""]
: []),
`====== 灰度节点开通结果 [${corp.name}] ======`,
printKeyValue({
+3 -3
View File
@@ -88,15 +88,15 @@ export async function handleNodeCommand(
"",
"子命令 (企业灰度节点级别):",
" nodes [list] [--all] 列出当前企业已开通的节点字典 (别名: probe, catalog)",
" nodes grant <type...> [--is-test] [--allow-prod] 为当前企业开通灰度节点(生产环境需显式 --allow-prod)",
" nodes grant <type...> [--is-test] [--allow-prod] 为当前企业开通灰度节点(生产企业执行需显式 --allow-prod)",
"",
"示例:",
" hose-use workflow nodes",
" hose-use workflow nodes --all",
" hose-use workflow nodes grant code-js2",
" hose-use workflow nodes grant code-js2 --is-test # 仅用于工作流位于测试 Piper 的企业",
" hose-use workflow nodes grant code-js2 --allow-prod --dry-run # 生产企业:先预览",
" hose-use workflow nodes grant code-js2 --allow-prod --yes # 生产企业:确认执行",
" hose-use workflow nodes grant code-js2 --dry-run # 生产企业:预览(无需覆盖参数)",
" hose-use workflow nodes grant code-js2 --allow-prod --yes # 生产企业:确认执行(--force 兼容)",
" hose-use workflow node list 896398895352487950",
].join("\n") + "\n",
exitCode: 1,
+49 -43
View File
@@ -12,7 +12,8 @@ import { stringOption, booleanOption, numberOption } from "../../parser.js";
import { printJson, printTable, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { createWorkflowDetailClient, extractCodeNodeSummaries, formatCodeNodeSummariesCard } from "./shared.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import { buildConfirmedCommand, isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import { hasProductionOverride, productionGuard, productionOverrideMeta } from "../../production.js";
export async function handleWorkflowTest(
parsed: CliParsedArgs,
@@ -47,7 +48,7 @@ export async function handleWorkflowTest(
"通用选项:",
" --timeout=<ms> 设置轮询超时时间 (默认 15000ms)",
" --auto-publish 是否自动发布测试快照 (默认 false)",
" --force, -f 允许在正式生产环境 (env: prod) 下执行调试",
" --allow-prod 确认在正式生产环境 (env: prod) 下执行调试(--force 为兼容别名)",
" --dry-run 只预览,不发起调试",
" --yes/--confirm 确认执行真实工作流节点",
"",
@@ -63,36 +64,50 @@ export async function handleWorkflowTest(
const filePath = stringOption(parsed.options, ["file", "path"]);
const isEmpty = booleanOption(parsed.options, ["empty", "none"]);
const sampleOption = stringOption(parsed.options, ["sample", "sample-id", "sampleId"]);
const forceProd = booleanOption(parsed.options, ["force", "f", "allow-prod", "allow-production"]);
const allowProd = hasProductionOverride(parsed);
const isProductionCorp = Boolean(runtime.selectedCorp && isCorpProd(runtime.selectedCorp));
const warnings = ["调试会在真实环境执行工作流节点,可能改变业务数据、发送通知并生成快照;auto-publish 还可能发布流程。"];
if (isProductionCorp) {
warnings.push(`⚠️ 当前企业 [${runtime.selectedCorp?.name || runtime.selectedCorp?.id}] 为正式生产环境 (env: prod)!正式执行时需显式追加 --force 参数。`);
warnings.push(`⚠️ 当前企业 [${runtime.selectedCorp?.name || runtime.selectedCorp?.id}] 为正式生产环境 (env: prod)!正式执行时需显式追加 --allow-prod。`);
}
const nextActionCmd = isProductionCorp
? `hose-use workflow test ${pipelineId} --yes --force`
: `hose-use workflow test ${pipelineId} --yes`;
const nextActionCmd = buildConfirmedCommand(parsed, isProductionCorp ? ["--allow-prod"] : []);
const confirmExecution = () => requireMutationConfirmation(parsed, runtime, "执行工作流调试", nextActionCmd);
if (isDryRun(parsed, runtime)) {
const previewResult = mutationPreview(parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, rawBody, filePath, empty: isEmpty, autoPublish, timeoutMs, warnings });
if (isProductionCorp) {
if (runtime.jsonMode) {
try {
const parsedJson = JSON.parse(previewResult.stdout);
if (parsedJson.nextAction && !parsedJson.nextAction.includes("--force")) {
parsedJson.nextAction = `${parsedJson.nextAction} --force`;
previewResult.stdout = `${JSON.stringify(parsedJson, null, 2)}\n`;
}
} catch {
// ignore
}
} else {
previewResult.stdout = previewResult.stdout.replace(/--yes/g, "--yes --force");
}
}
return previewResult;
return mutationPreview(
parsed,
runtime,
"执行工作流调试",
pipelineId,
{
flowCodeOrId,
rawBody,
filePath,
empty: isEmpty,
autoPublish,
timeoutMs,
warnings,
...(isProductionCorp
? {
productionOverride: allowProd,
productionWarning: allowProd
? "生产环境覆盖已启用:实际执行会在正式生产企业产生真实业务变更。"
: "当前为正式生产企业:实际执行需追加 --allow-prod 确认。",
}
: {}),
},
{ extraArgs: isProductionCorp && !allowProd ? ["--allow-prod"] : [] }
);
}
// 生产确认只要求“用户明确知道在操作生产企业”,不做功能禁止;预览已在上面放行。
const blocked = productionGuard(parsed, runtime, {
operation: "执行工作流调试",
operationCode: "workflow.test",
risk: "调试会真实执行工作流节点,可能产生单据流转、第三方调用、通知与快照发布等不可逆业务变更。",
nextAction: nextActionCmd,
});
if (blocked) return blocked;
if (flowCodeOrId || rawBody || filePath || isEmpty) confirmExecution();
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
@@ -390,24 +405,6 @@ export async function handleWorkflowTest(
// 3. 执行端到端调试测试
confirmExecution();
if (isProductionCorp && !forceProd) {
return {
stdout: "",
stderr: [
`🛑 生产环境安全阻断 (Production Safeguard):`,
`当前工作企业 [${runtime.selectedCorp?.name || runtime.selectedCorp?.id}] 被标记为【🏭 正式生产环境】(env: prod)!`,
`在正式生产企业执行工作流调试可能产生不可逆的单据流转、第三方系统调用与真实业务变更。`,
``,
`如确需在生产环境进行带副作用的真实调试,必须显式附加 --force 参数确认生产风险:`,
` hose-use workflow test ${pipelineId} ${parsed.raw.filter((a) => !["--yes", "-y", "--dry-run"].includes(a)).slice(2).join(" ")} --yes --force`,
``,
`建议切换至测试企业进行调试:`,
` hose-use corps switch <测试企业ID>`,
].join("\n") + "\n",
exitCode: 1,
};
}
const execution = await runWorkflowDebugTest(client, pipelineId, {
flowCodeOrId: targetId,
data: customPayload,
@@ -417,7 +414,16 @@ export async function handleWorkflowTest(
autoPublish,
timeoutMs,
});
const report = { ...execution, productionEnabled: detail ? isEnabled : null, warnings };
const report = {
...execution,
productionEnabled: detail ? isEnabled : null,
warnings,
...productionOverrideMeta(
parsed,
runtime,
"生产环境覆盖已启用 (--allow-prod):本次调试在正式生产企业真实执行。"
),
};
const exitCode = report.outcome === "completed" ? 0 : 1;
if (runtime.jsonMode) {
+1 -1
View File
@@ -51,7 +51,7 @@ const SUB_ACTION_HELP: Record<string, SubActionHelp> = {
"--sample=<1|2|3> 直接选用服务器最近接收的数据样本发起测试",
"--timeout=<ms> 轮询超时时间 (毫秒,默认 15000)",
"--auto-publish 调试通过后是否自动发布测试快照 (默认 false)",
"--force, -f 生产环境安全放行 (正式企业 env: prod 调试必须加)",
"--allow-prod 确认在正式生产企业 (env: prod) 执行调试(--force 为兼容别名)",
"--dry-run 只预览测试配置,不发起调用",
"--yes/--confirm 确认执行真实调试",
],
+22 -9
View File
@@ -45,21 +45,34 @@ export function requireMutationConfirmation(
throw new MutationConfirmationRequired(operation, nextAction);
}
/**
* 基于当前原始参数构造「确认执行」命令,并补齐缺失的附加参数。
* 所有命令的 nextAction 都走这里,避免各自拼接造成格式漂移。
*/
export function buildConfirmedCommand(parsed: CliParsedArgs, extraArgs: string[] = []): string {
const strip = new Set([
"--dry-run", "--dryRun", "--dryrun",
"--yes", "-y", "--confirm", "--force-write", "--forceWrite",
]);
const args = (parsed.raw ?? []).filter((arg) => !strip.has(arg));
const isAiPro = args[0] === "hose-aipro" || args[0] === "aipro";
const cleanArgs =
args[0] === "hose-aipro" || args[0] === "hose-use" || args[0] === "aipro"
? args.slice(1)
: args;
const extra = extraArgs.filter((arg) => arg && !cleanArgs.includes(arg));
return `${isAiPro ? "hose-aipro" : "hose-use"} ${[...cleanArgs, ...extra].join(" ")} --yes`;
}
export function mutationPreview(
parsed: CliParsedArgs,
runtime: CliRuntime,
operation: string,
target: string,
changes: Record<string, unknown>
changes: Record<string, unknown>,
options: { extraArgs?: string[] } = {}
): CliResult {
const confirmedArgs = parsed.raw.filter((arg) => !["--dry-run", "--dryRun", "--dryrun"].includes(arg));
const isAiPro = confirmedArgs[0] === "hose-aipro" || confirmedArgs[0] === "aipro";
const binaryPrefix = isAiPro ? "hose-aipro" : "hose-use";
const cleanArgs =
confirmedArgs[0] === "hose-aipro" || confirmedArgs[0] === "hose-use" || confirmedArgs[0] === "aipro"
? confirmedArgs.slice(1)
: confirmedArgs;
const nextAction = `${binaryPrefix} ${cleanArgs.join(" ")} --yes`;
const nextAction = buildConfirmedCommand(parsed, options.extraArgs);
const payload = {
dryRun: true,
operation,
+91
View File
@@ -0,0 +1,91 @@
import { isCorpProd } from "../core/config/types.js";
import { booleanOption } from "./parser.js";
import { printJson } from "./printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "./types.js";
/**
* 生产环境确认策略(CLI 统一入口)。
*
* 约定:
* - `--allow-prod` 是唯一的显式生产覆盖参数;`--allow-production` 与历史 `--force` 仅作兼容别名。
* - 覆盖参数只负责让用户明确知道“当前在操作正式生产企业”,不替代 `--dry-run` / `--yes` 两阶段确认。
* - 预览(`--dry-run`)永远放行,不要求覆盖参数;预览的 nextAction 会自动补上覆盖参数。
* - 所有命令的阻断提示与 JSON 错误使用同一结构与同一个错误码 `PROD_OVERRIDE_REQUIRED`。
*/
export const PRODUCTION_OVERRIDE_FLAGS = ["allow-prod", "allow-production", "force"] as const;
export function hasProductionOverride(parsed: CliParsedArgs): boolean {
return booleanOption(parsed.options, [...PRODUCTION_OVERRIDE_FLAGS]);
}
export interface ProductionGuardOptions {
/** 人类可读动作名,如「执行工作流调试」 */
operation: string;
/** 机器可读动作标识,如 `workflow.test` */
operationCode: string;
/** 一行风险说明 */
risk: string;
/** 补齐覆盖参数后的完整恢复命令 */
nextAction: string;
}
/**
* 正式生产企业且未显式追加覆盖参数时,返回统一的阻断结果;否则返回 null。
*/
export function productionGuard(
parsed: CliParsedArgs,
runtime: CliRuntime,
options: ProductionGuardOptions
): CliResult | null {
const corp = runtime.selectedCorp;
if (!corp || !isCorpProd(corp) || hasProductionOverride(parsed)) return null;
const corpId = corp.corpId || corp.id;
const message = `当前企业 [${corp.name || corp.id}] 为正式生产环境,${options.operation}需显式追加 --allow-prod 确认`;
const text = [
"🛑 生产环境确认 (Production Safeguard):",
`当前工作企业 [${corp.name || corp.id}] 被判定为【🏭 正式生产环境】。`,
options.risk,
"",
"确认继续请显式追加 --allow-prod(--force 为兼容别名),并继续遵守 --dry-run / --yes 两阶段确认:",
` ${options.nextAction}`,
"",
"如企业环境标记有误,可使用: hose-use corps tag <企业ID> --test",
].join("\n") + "\n";
return {
stdout: runtime.jsonMode
? printJson(
{
error: true,
code: "PROD_OVERRIDE_REQUIRED",
message,
exitCode: 1,
nextAction: options.nextAction,
details: {
corpId,
corpName: corp.name || corp.id,
env: "prod",
operation: options.operationCode,
},
},
runtime.outputOptions
) + "\n"
: "",
stderr: runtime.jsonMode ? "" : text,
exitCode: 1,
};
}
/**
* 生产覆盖生效时的统一结果标记;非生产或未覆盖返回空对象。
*/
export function productionOverrideMeta(
parsed: CliParsedArgs,
runtime: CliRuntime,
warning: string
): { productionOverride?: true; productionWarning?: string } {
const corp = runtime.selectedCorp;
if (!corp || !isCorpProd(corp) || !hasProductionOverride(parsed)) return {};
return { productionOverride: true, productionWarning: warning };
}
@@ -103,7 +103,7 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
- 执行 `hose-use workflow nodes` 查看当前租户已开通的节点字典;
- 执行 `hose-use workflow nodes --all` 查看当前企业与官方全量 108 个灰度节点清单的开通状态对照;
- 执行 `hose-use workflow nodes grant <type...>` 申请开通灰度节点(内置管理员密码预留设计:未配置环境变量 `HOSE_ADMIN_PASSWORD` 时为免密便捷模式;配置后强制要求 `--password` 授权)。
- 正式生产企业默认被硬拦截;确需在生产环境开通时,必须显式追加 `--allow-prod`,并继续遵守 `--dry-run` → `--yes` 两阶段确认。`--is-test` 只切换 Piper 域名,不构成生产授权。
- 正式生产企业执行开通前需显式追加 `--allow-prod` 表明已知晓目标环境(`--force` 为兼容别名),并继续遵守 `--dry-run` → `--yes` 两阶段确认;`--dry-run` 预览不要求覆盖参数。`--is-test` 只切换 Piper 域名,不构成生产授权。
## 静态分析器:诊断边界显式化(硬门禁 vs 软建议)
@@ -161,7 +161,7 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `
节点卡片标题保存在 `displayName`,用 `--display-name` 修改;`--label` 是节点类型标题,服务端保存时可能按节点类型重新生成,不能可靠地用于重命名已有节点。设计器前端把节点标题限制为 20 个字符;后端本身不校验该长度(实测 21 字仍可保存),本地 CLI 按前端上限强制校验,超过 20 个 Unicode 字符会在写入前抛出 `ValidationError`。条件/内置节点类型的 `desc` 也由平台按配置重新生成,自定义 `--desc` 可能不会持久化。
灰度开通遵循统一写操作门禁:`--dry-run` 仅返回归一化节点清单且不调用网关;实际开通需要 `--yes/--confirm`。生产企业额外要求显式 `--allow-prod`。管理员密码用于额外授权,不能替代写操作确认。
灰度开通遵循统一写操作门禁:`--dry-run` 仅返回归一化节点清单且不调用网关;实际开通需要 `--yes/--confirm`。生产企业额外要求显式 `--allow-prod`(预览不要求)。管理员密码用于额外授权,不能替代写操作确认。
节点定位约定:CLI 的字符串编号(如 `3`、`2.1`)始终对应列表展示的层级编号;SDK 传入数字 `3` 时表示深度优先遍历的第 3 个节点。节点名称仍可直接用于定位,两个编号体系不再在一次查找中竞争。