fix: address Codex PR review findings
This commit is contained in:
1 parent
0f164b6de5
commit
a7974abb08
44 files changed
+3317
-667
No files matched your search
@@ -9,6 +9,7 @@
|
||||
- `runner.ts`:`runCli` 分发入口。按注册表查命令;非常驻命令经 `runQueue` 串行化执行,避免并发写冲突。
|
||||
- `parser.ts`:严格参数解析器(`parseArgs` / `stringOption` / `booleanOption` / `outputOptions`);未知选项和缺值返回用法错误 `2`,相近拼写给出建议。同名参数按命令语境确定类型,例如 `bill --fields` 取值、`feetype --fields` 为布尔值,`workflow create -f` 取模板、`workflow tail -f` 为持续监听。
|
||||
- `printer.ts`:输出渲染(`printJson` / `printHelp` / `redactSensitiveText` 敏感信息脱敏)。
|
||||
完整 JSON 按值类型脱敏,保留 `keepItSecret` 等布尔业务标记和 null,凭据字符串及数值仍被遮蔽;紧凑 NDJSON 保持单行。普通诊断文本沿用 URL、Bearer 和键值脱敏。
|
||||
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
|
||||
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
|
||||
- `生产环境安全阻断 (Production Safeguard)`:对带副作用的敏感调试命令(如 `workflow test`),在正式生产企业 (`env === "prod"`) 执行时触发硬阻断,要求必须显式带上 `--force` 确认生产风险;自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
|
||||
|
||||
@@ -306,7 +306,8 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"options": [
|
||||
"--dry-run 只预览审批动作",
|
||||
"--yes/--confirm 确认执行审批动作",
|
||||
"--comment=<原因> 驳回或评论内容"
|
||||
"--comment=<原因> 驳回或评论内容",
|
||||
"trace 的 --no-invoice/--noInvoice/--basic 为兼容空操作;穿透诊断本身不补充加载发票详情"
|
||||
],
|
||||
"aliases": [
|
||||
"bills",
|
||||
@@ -350,6 +351,9 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"flow": {
|
||||
"summary": "审批流全域透视与穿透诊断",
|
||||
"usage": "hose-use flow <子命令> [单号|ID]",
|
||||
"options": [
|
||||
"get/trace 的 --no-invoice/--noInvoice/--basic 为兼容空操作;穿透诊断本身不补充加载发票详情"
|
||||
],
|
||||
"commands": {
|
||||
"get": "穿透诊断单据流转",
|
||||
"history": "查看审批流转时间线",
|
||||
|
||||
@@ -207,20 +207,23 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
|
||||
}
|
||||
|
||||
const client = await ctx.getClient();
|
||||
const skipInvoices = booleanOption(parsed.options, ["no-invoice", "noInvoice", "basic"]);
|
||||
const report = await traceBillFlowDetail(client, corpId, target, { skipInvoices });
|
||||
const legacyInvoiceOption = ["no-invoice", "noInvoice", "basic"].some((key) => Object.hasOwn(parsed.options, key));
|
||||
const compatibilityNotice = legacyInvoiceOption
|
||||
? "提示: --no-invoice/--noInvoice/--basic 仅为旧版兼容参数;穿透诊断不补充加载发票详情,传入这些参数不会改变结果。\n"
|
||||
: "";
|
||||
const report = await traceBillFlowDetail(client, corpId, target);
|
||||
|
||||
if (!report.found) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(report, runtime.outputOptions),
|
||||
stderr: "",
|
||||
stderr: compatibilityNotice,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到匹配 [${target}] 的单据或审批流实例\n 诊断提示: ${report.diagnostic.advice}\n`,
|
||||
stderr: `${compatibilityNotice}[NOT FOUND] 在企业 [${corp.name}] 下未找到匹配 [${target}] 的单据或审批流实例\n 诊断提示: ${report.diagnostic.advice}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -235,7 +238,7 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
stderr: compatibilityNotice,
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -294,7 +297,7 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
|
||||
|
||||
return {
|
||||
stdout: `${lines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
stderr: compatibilityNotice,
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -22,6 +22,7 @@ function printFlowHelp(): string {
|
||||
" --corp=<id> 指定操作企业 (默认激活企业)",
|
||||
" --json 以 JSON 结构化格式输出诊断数据",
|
||||
" --verbose 显示完整调试信息",
|
||||
" --no-invoice/--noInvoice/--basic 旧版兼容空操作;穿透诊断本身不补充加载发票详情",
|
||||
" -h, --help 显示帮助信息",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ export async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
: "📝 业务字段";
|
||||
return [
|
||||
entity.name,
|
||||
field.name,
|
||||
field.fieldKey ?? field.name,
|
||||
field.label,
|
||||
field.type,
|
||||
roleTag,
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { afterEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import * as services from "../../domains/platform/services.js";
|
||||
import * as billApi from "../../domains/bill/api.js";
|
||||
import * as cache from "../../core/cache/index.js";
|
||||
import * as session from "../../core/http/session-client.js";
|
||||
import * as helpers from "../helpers.js";
|
||||
import * as workflowShared from "./workflow/shared.js";
|
||||
import * as platformShared from "./platform/shared.js";
|
||||
import { parseArgs } from "../parser.js";
|
||||
import { runCli } from "../runner.js";
|
||||
import { commandFlags } from "../command-metadata.js";
|
||||
import { renderScopedHelp } from "../help.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import { handleNodeCommand } from "./workflow/node.js";
|
||||
import { handleLogs } from "./workflow/history.js";
|
||||
import { handleJob } from "./workflow/job.js";
|
||||
import { handleSchema } from "./platform/app-info.js";
|
||||
import { handleBillCommand } from "./bill/index.js";
|
||||
import { handleFlowCommand } from "./flow.js";
|
||||
|
||||
const runtime = {
|
||||
selectedCorp: { id: "fixture-corp", name: "离线测试企业", credentials: { corpId: "fixture-corp" } },
|
||||
jsonMode: true,
|
||||
} as CliRuntime;
|
||||
const spies: Array<{ mockRestore(): void }> = [];
|
||||
const directories: string[] = [];
|
||||
afterEach(async () => {
|
||||
for (const spy of spies.splice(0).reverse()) spy.mockRestore();
|
||||
await Promise.all(directories.splice(0).map((path) => rm(path, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
describe("review CLI compatibility regressions", () => {
|
||||
it("keeps real trace-shaped boolean flags valid through runner redaction", async () => {
|
||||
const raw = { id: "bill", state: "DRAFT", flowId: { id: "flow", state: "DRAFT", form: { code: "B-FIXTURE", keepItSecret: false, appSecurity: "fixture-credential" }, plan: { nodes: [] } } };
|
||||
spies.push(spyOn(helpers, "initCorpRuntime").mockReturnValue(runtime as any));
|
||||
spies.push(spyOn(session, "createSessionClient").mockResolvedValue({} as any));
|
||||
spies.push(spyOn(billApi, "getRawBillFlow").mockResolvedValue(raw));
|
||||
const result = await runCli(["bill", "trace", "B-FIXTURE", "--basic", "--json"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
const data = JSON.parse(result.stdout);
|
||||
expect(data.raw.flowId.form.keepItSecret).toBe(false);
|
||||
expect(data.raw.flowId.form.appSecurity).toBe("<redacted>");
|
||||
expect(result.stdout).not.toContain("fixture-credential");
|
||||
expect(result.stderr).toContain("旧版兼容参数");
|
||||
});
|
||||
|
||||
it("documents legacy trace flags without dropping them from the parser vocabulary", () => {
|
||||
for (const [area, action] of [["bill", "trace"], ["flow", "get"], ["trace", "get"]]) {
|
||||
const help = renderScopedHelp([area!, action!]);
|
||||
expect(help).toContain("兼容空操作");
|
||||
expect(help).toContain("不补充加载发票详情");
|
||||
const documented = help.split("支持选项:\n")[1]!.split("\n\n提示:")[0]!.trim().split("\n").map((line) => line.trim().match(/^--([^=[\s]+)/)?.[1]);
|
||||
expect(documented).toEqual(Object.keys(commandFlags(area, action)));
|
||||
for (const flag of ["no-invoice", "noInvoice", "basic"]) {
|
||||
expect(commandFlags(area, action)[flag]).toBe("boolean");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("restores edit --file as code while explicit mapping and map --file still work", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "hose-node-options-"));
|
||||
directories.push(dir);
|
||||
const codeFile = join(dir, "script.js");
|
||||
const mappingFile = join(dir, "mapping.json");
|
||||
const code = "// Keep exact bytes.\nreturn 7;\n";
|
||||
await writeFile(codeFile, code);
|
||||
await writeFile(mappingFile, JSON.stringify({ label: "mapped" }));
|
||||
const detail = { id: "wf", state: 0, tasks: [{ name: "action_js", type: "code-js2", label: "original", code: "return 0;" }] };
|
||||
spies.push(spyOn(workflowShared, "createWorkflowDetailClient").mockResolvedValue({ client: {} } as any));
|
||||
spies.push(spyOn(services, "getWorkflowDetail").mockResolvedValue(detail as any));
|
||||
const save = spyOn(services, "updateWorkflow").mockImplementation(async (_client, workflow) => workflow);
|
||||
spies.push(save);
|
||||
for (const flag of ["file", "code-file"]) {
|
||||
const result = await handleNodeCommand(parseArgs(["workflow", "node", "edit", "wf", "action_js", `--${flag}=${codeFile}`, "--dry-run"]), runtime);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout).changes.updatedFields.code).toContain(`${code.length} 字符`);
|
||||
}
|
||||
for (const [action, flag] of [["edit", "mapping-file"], ["edit", "mapping"], ["edit", "json-file"], ["map", "file"]]) {
|
||||
const result = await handleNodeCommand(parseArgs(["workflow", "node", action!, "wf", "action_js", `--${flag}=${mappingFile}`, "--dry-run"]), runtime);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout).changes.changedKeys).toContain("label");
|
||||
}
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
const result = await handleNodeCommand(parseArgs(["workflow", "node", "edit", "wf", "action_js", `--file=${codeFile}`, "--yes"]), runtime);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(save).toHaveBeenCalledTimes(1);
|
||||
expect(JSON.parse(result.stdout).editedTask.code).toBe(code);
|
||||
expect((save.mock.calls[0]?.[1]?.tasks?.[0] as any).code).toBe(code);
|
||||
});
|
||||
|
||||
for (const fallback of [false, true]) {
|
||||
it(`keeps legacy trace invoice flags as explicit no-ops (${fallback ? "search fallback" : "direct flow"})`, async () => {
|
||||
const target = fallback ? "流水中文" : "B-FIXTURE";
|
||||
const raw = { id: "bill", state: "DRAFT", flowId: { id: "flow", state: "DRAFT", form: { code: target, details: [{ feeTypeForm: { invoices: [{ invoiceId: "invoice" }] } }] }, plan: { nodes: [] } } };
|
||||
spies.push(spyOn(session, "createSessionClient").mockResolvedValue({} as any));
|
||||
spies.push(spyOn(billApi, "getRawBillFlow").mockImplementation(async (_client, _corp, query) => fallback && query !== "bill" ? undefined : raw));
|
||||
spies.push(spyOn(cache, "getGlobalCache").mockReturnValue({ withCache: async (_key: unknown, loader: () => Promise<unknown>) => loader() } as any));
|
||||
spies.push(spyOn(billApi, "listEntitySchemas").mockResolvedValue([]));
|
||||
const search = spyOn(billApi, "searchRawBills").mockResolvedValue({ items: [{ id: "bill", code: target, form: {} }], total: 1 } as any);
|
||||
spies.push(search);
|
||||
const invoice = spyOn(billApi, "getInvoiceValidationDetail").mockRejectedValue(new Error("must not supplement invoices"));
|
||||
spies.push(invoice);
|
||||
const baseline = await handleBillCommand(parseArgs(["bill", "trace", target]), runtime);
|
||||
expect(baseline.stderr).toBe("");
|
||||
expect(baseline.exitCode).toBe(0);
|
||||
for (const [area, action] of [["bill", "trace"], ["bill", "inspect"], ["flow", "get"], ["flow", "trace"], ["flow", "diagnose"]]) {
|
||||
for (const flag of ["no-invoice", "noInvoice", "basic"]) {
|
||||
for (const value of ["true", "false"]) {
|
||||
const parsed = parseArgs([area!, action!, target, `--${flag}=${value}`]);
|
||||
expect(parsed.options[flag]).toBe(value === "true");
|
||||
const result = await (area === "bill" ? handleBillCommand : handleFlowCommand)(parsed, runtime);
|
||||
expect(result.exitCode).toBe(baseline.exitCode);
|
||||
expect(JSON.parse(result.stdout)).toEqual(JSON.parse(baseline.stdout));
|
||||
expect(result.stderr).toContain("仅为旧版兼容参数");
|
||||
}
|
||||
}
|
||||
}
|
||||
const text = await handleBillCommand(parseArgs(["bill", "trace", target, "--basic"]), { ...runtime, jsonMode: false });
|
||||
expect(text.stdout).toContain("单据全域穿透诊断");
|
||||
expect(text.stderr).toContain("不会改变结果");
|
||||
expect(invoice).not.toHaveBeenCalled();
|
||||
if (fallback) expect(search).toHaveBeenCalled();
|
||||
else expect(search).not.toHaveBeenCalled();
|
||||
});
|
||||
}
|
||||
|
||||
it("preserves not-found trace output and status with compatibility notices", async () => {
|
||||
spies.push(spyOn(session, "createSessionClient").mockResolvedValue({} as any));
|
||||
spies.push(spyOn(billApi, "getRawBillFlow").mockResolvedValue(undefined));
|
||||
spies.push(spyOn(cache, "getGlobalCache").mockReturnValue({ withCache: async (_key: unknown, loader: () => Promise<unknown>) => loader() } as any));
|
||||
spies.push(spyOn(billApi, "listEntitySchemas").mockResolvedValue([]));
|
||||
spies.push(spyOn(billApi, "searchRawBills").mockResolvedValue({ items: [], total: 0 } as any));
|
||||
for (const jsonMode of [false, true]) {
|
||||
const result = await handleBillCommand(parseArgs(["bill", "trace", "missing", "--basic=false"]), { ...runtime, jsonMode });
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("旧版兼容参数");
|
||||
if (jsonMode) expect(JSON.parse(result.stdout).found).toBe(false);
|
||||
else expect(result.stderr).toContain("[NOT FOUND]");
|
||||
}
|
||||
});
|
||||
|
||||
it("shows actual physical schema keys, preserves JSON and falls back to name", async () => {
|
||||
const fields = [{ name: "alias_name", fieldKey: "E_REAL_KEY", label: "字段", type: "text" }, { name: "fallback_key", label: "旧字段", type: "text" }];
|
||||
spies.push(spyOn(platformShared, "resolveAppAndEntity").mockResolvedValue({ clients: {}, corpId: "corp", platform: { id: "app", name: "应用" }, entity: { id: "entity", name: "对象", fields } } as any));
|
||||
const args = ["platform", "schema", "app", "entity"];
|
||||
const text = await handleSchema(parseArgs(args), { ...runtime, jsonMode: false });
|
||||
expect(text.stdout).toContain("E_REAL_KEY");
|
||||
expect(text.stdout).toContain("fallback_key");
|
||||
expect(text.stdout).not.toContain("alias_name");
|
||||
const json = JSON.parse((await handleSchema(parseArgs(args), runtime)).stdout);
|
||||
expect(json.entities[0].fields).toEqual(fields);
|
||||
const filtered = JSON.parse((await handleSchema(parseArgs([...args, "--keyword=E_REAL_KEY"]), runtime)).stdout);
|
||||
expect(filtered.entities[0].fields).toEqual([fields[0]]);
|
||||
});
|
||||
|
||||
it("finds in-flight errors without expanding the existing terminal state filters", async () => {
|
||||
const jobs = [
|
||||
{ id: "running-boolean", status: "RUNNING", hasError: true },
|
||||
{ id: "started-string", status: "STARTED", hasError: "true" },
|
||||
{ id: "running-localized", status: "RUNNING", hasError: "存在" },
|
||||
{ id: "started-count", status: "STARTED", errorTaskCount: 1 },
|
||||
{ id: "running-normal", status: "RUNNING", hasError: false, errorTaskCount: 0 },
|
||||
{ id: "started-normal", status: "STARTED", hasError: "不存在" },
|
||||
{ id: "completed-normal", status: "COMPLETED", hasError: "false" },
|
||||
{ id: "completed-skip", status: "COMPLETED", errorTaskCount: 1 },
|
||||
{ id: "failed", status: "FAILED" },
|
||||
];
|
||||
const page = { executeCount: 9, successCount: 2, errorCount: 1, totalItems: 9, jobList: jobs };
|
||||
spies.push(spyOn(workflowShared, "createWorkflowDetailClient").mockResolvedValue({ client: {} } as any));
|
||||
const logs = spyOn(services, "listWorkflowLogs").mockResolvedValue(page as any);
|
||||
spies.push(logs, spyOn(services, "getWorkflowDetail").mockRejectedValue(new Error("offline unavailable")));
|
||||
const read = async (flags: string[]) => JSON.parse((await handleLogs(parseArgs(["workflow", "logs", "wf", ...flags]), runtime)).stdout);
|
||||
const errors = await read(["--has-error"]);
|
||||
const expected = ["running-boolean", "started-string", "running-localized", "started-count", "completed-skip", "failed"];
|
||||
expect(errors.jobList.map((j: any) => j.id)).toEqual(expected);
|
||||
expect(errors.totalItems).toBe(9);
|
||||
expect(errors.inProgressCount).toBe(6);
|
||||
expect((await read([])).jobList).toEqual(jobs);
|
||||
expect((await read(["--state=FAILED"])).jobList.map((j: any) => j.id)).toEqual(["completed-skip", "failed"]);
|
||||
expect((await read(["--state=COMPLETED"])).jobList.map((j: any) => j.id)).toEqual(["completed-normal"]);
|
||||
expect((await read(["--state=RUNNING"])).jobList).toEqual(jobs.slice(0, 6));
|
||||
expect((await read(["--state=RUNNING", "--has-error"])).jobList.map((j: any) => j.id)).toEqual(expected);
|
||||
expect(logs.mock.calls.at(-1)?.[2]?.state).toBe("RUNNING");
|
||||
const text = await handleLogs(parseArgs(["workflow", "logs", "wf"]), { ...runtime, jsonMode: false });
|
||||
expect(text.stdout.split("\n").find((line) => line.includes("running-boolean"))).toContain("⚠️ 包含错误");
|
||||
expect(text.stdout.split("\n").find((line) => line.includes("running-normal"))).toContain("⏳ 执行中");
|
||||
});
|
||||
|
||||
for (const state of [undefined, 0, 1, 2]) {
|
||||
it(`reports workflow state truthfully when detail state is ${state ?? "unavailable"}`, async () => {
|
||||
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue({} as any));
|
||||
spies.push(spyOn(services, "getJob").mockResolvedValue({ id: "job", pipelineId: "wf", status: "RUNNING" } as any));
|
||||
spies.push(spyOn(services, "getJobExecutionTree").mockResolvedValue([]));
|
||||
spies.push(spyOn(services, "getJobFailedExecutions").mockResolvedValue({ items: [] } as any));
|
||||
const detail = spyOn(services, "getWorkflowDetail");
|
||||
spies.push(detail);
|
||||
if (state === undefined) detail.mockRejectedValue(new Error("offline detail unavailable"));
|
||||
else detail.mockResolvedValue({ id: "wf", state, tasks: [{ name: "trigger", type: "clock" }] } as any);
|
||||
const expected = state === undefined ? "未知(无法读取工作流详情)" : state === 0 ? "⚪ 已停用" : state === 1 ? "🟢 启用中" : "未知";
|
||||
for (const mode of [[], ["--timeline"]]) {
|
||||
const parsed = parseArgs(["workflow", "job", "job", "--platform=p", ...mode]);
|
||||
const text = await handleJob(parsed, { ...runtime, jsonMode: false });
|
||||
expect(text.exitCode).toBe(0);
|
||||
expect(text.stdout).toContain(expected);
|
||||
if (state !== 0) expect(text.stdout).not.toContain("已停用");
|
||||
const json = JSON.parse((await handleJob(parsed, runtime)).stdout);
|
||||
if (state === undefined) {
|
||||
expect(json.workflow).toBeUndefined();
|
||||
expect(json.job.id).toBe("job");
|
||||
} else if (mode.length) expect(json.workflowState).toBe(expected);
|
||||
else expect(json.workflow.stateLabel).toBe(expected);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -39,18 +39,21 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
});
|
||||
const stateOption = stringOption(parsed.options, ["state"]);
|
||||
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
|
||||
const isJobError = (job: any): boolean => {
|
||||
const s = (job.status || "").toUpperCase();
|
||||
if (s === "STARTED" || s === "RUNNING") return false;
|
||||
const hasJobError = (job: any): boolean => {
|
||||
if (job.hasError === true || job.hasError === "存在" || job.hasError === "true") return true;
|
||||
if (typeof job.errorTaskCount === "number" && job.errorTaskCount > 0) return true;
|
||||
if (job.state === "FAILED" || job.status === "FAILED") return true;
|
||||
return false;
|
||||
};
|
||||
// Preserve the existing terminal-state filters while --has-error also sees in-flight errors.
|
||||
const isJobError = (job: any): boolean => {
|
||||
const s = (job.status || "").toUpperCase();
|
||||
return s !== "STARTED" && s !== "RUNNING" && hasJobError(job);
|
||||
};
|
||||
|
||||
let filteredJobList = rawResult.jobList;
|
||||
if (hasErrorFilter) {
|
||||
filteredJobList = filteredJobList.filter(isJobError);
|
||||
filteredJobList = filteredJobList.filter(hasJobError);
|
||||
} else if (stateOption) {
|
||||
const norm = stateOption.trim().toUpperCase();
|
||||
if (norm === "FAILED" || norm === "FAIL" || norm === "ERROR") {
|
||||
@@ -115,8 +118,8 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
|
||||
const formatErrorColumn = (job: any): string => {
|
||||
const s = (job.status || "").toUpperCase();
|
||||
if (hasJobError(job)) return "⚠️ 包含错误";
|
||||
if (s === "STARTED" || s === "RUNNING") return "⏳ 执行中";
|
||||
if (isJobError(job)) return "⚠️ 包含错误";
|
||||
return "正常";
|
||||
};
|
||||
|
||||
|
||||
@@ -404,6 +404,13 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
})),
|
||||
]);
|
||||
const workflowDetail = await getWorkflowDetail(client, job.pipelineId).catch(() => undefined);
|
||||
const workflowStateLabel = !workflowDetail
|
||||
? "未知(无法读取工作流详情)"
|
||||
: workflowDetail.state === 1
|
||||
? "🟢 启用中"
|
||||
: workflowDetail.state === 0
|
||||
? "⚪ 已停用"
|
||||
: "未知";
|
||||
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
|
||||
|
||||
const conditionDiagnoses = explainConditionBranches(tree);
|
||||
@@ -451,7 +458,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
jobId,
|
||||
pipelineId: job.pipelineId,
|
||||
workflowName: workflowDetail?.pipelineName || workflowDetail?.label,
|
||||
workflowState: workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||
workflowState: workflowStateLabel,
|
||||
jobStatus: job.state ?? job.status,
|
||||
totalTasks: timeline.length,
|
||||
executedTasks: tree.length,
|
||||
@@ -480,7 +487,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
"Job ID": job.id,
|
||||
"工作流 ID": job.pipelineId,
|
||||
...(workflowDetail ? { "工作流名称": workflowDetail.pipelineName || workflowDetail.label } : {}),
|
||||
"工作流状态": workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||
"工作流状态": workflowStateLabel,
|
||||
"Job 状态": job.state ?? job.status,
|
||||
"定义总步骤数": timeline.length,
|
||||
"已调度步骤数": tree.length,
|
||||
@@ -509,7 +516,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
id: workflowDetail.id,
|
||||
name: workflowDetail.pipelineName || workflowDetail.label,
|
||||
state: workflowDetail.state,
|
||||
stateLabel: workflowDetail.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||
stateLabel: workflowStateLabel,
|
||||
totalTasks: workflowDetail.tasks?.length ?? tree.length,
|
||||
}
|
||||
: undefined,
|
||||
@@ -571,7 +578,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
"Job ID": job.id,
|
||||
"工作流 ID (pipelineId)": job.pipelineId,
|
||||
...(workflowDetail ? { "工作流名称": workflowDetail.pipelineName || workflowDetail.label } : {}),
|
||||
"工作流状态": workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||
"工作流状态": workflowStateLabel,
|
||||
"Job 状态 (state)": formatJobStatusLabel(job.status, job.state),
|
||||
"开始时间": job.startTime || "-",
|
||||
"结束时间": job.endTime || "-",
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { parseArgs } from "../../parser.js";
|
||||
import { handleWorkflowEvalScript } from "./script.js";
|
||||
|
||||
test("MVEL CLI JSON returns the terminal expression and preserves failure exit codes", async () => {
|
||||
for (const [code, success] of [
|
||||
['Map result = new java.util.HashMap(); result.put("value", 7); result;', true],
|
||||
['new java.util.Date();', false],
|
||||
['if (true) { 7; }', false],
|
||||
] as const) {
|
||||
const result = await handleWorkflowEvalScript(parseArgs(["workflow", "eval-script", "--type", "code", "--code", code, "--json"]), { jsonMode: true } as any);
|
||||
const report = JSON.parse(result.stdout);
|
||||
expect(result.exitCode).toBe(success ? 0 : 1);
|
||||
expect(report.success).toBe(success);
|
||||
if (success) expect(report.returnValue).toEqual({ value: 7 });
|
||||
else expect(report.error.name).toBe("UnsupportedMvelSyntax");
|
||||
}
|
||||
});
|
||||
@@ -387,7 +387,7 @@ async function handleEditNode(
|
||||
}
|
||||
}
|
||||
|
||||
const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "file", "json-file"]);
|
||||
const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "json-file"]);
|
||||
if (mappingFile) {
|
||||
const fs = await import("fs/promises");
|
||||
const rawContent = await fs.readFile(mappingFile, "utf-8");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { listAllWorkflows } from "../../../domains/platform/services.js";
|
||||
import { flattenExecutionTree, listAllWorkflows } from "../../../domains/platform/services.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
@@ -71,7 +71,7 @@ export function extractCodeNodeSummaries(
|
||||
nodes: Array<any>,
|
||||
flattenExecutionTreeFn?: (nodes: any[]) => any[]
|
||||
): CodeNodeSummary[] {
|
||||
const flattened = flattenExecutionTreeFn ? flattenExecutionTreeFn(nodes) : nodes;
|
||||
const flattened = (flattenExecutionTreeFn ?? flattenExecutionTree)(nodes);
|
||||
const summaries: CodeNodeSummary[] = [];
|
||||
|
||||
for (const node of flattened) {
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { extractCodeNodeSummaries } from "./shared.js";
|
||||
import { flattenExecutionTree } from "../../../domains/platform/services.js";
|
||||
|
||||
test("test and job summaries retain nested execution containers and repeated loop executions", () => {
|
||||
const tree = [{ id: "loop", type: "every", children: [
|
||||
{ id: "iteration-1", type: "condition", tasks: [{ id: "a", name: "script", type: "code", output: { count: 3 } }] },
|
||||
{ id: "iteration-2", type: "condition", subTasks: [{ id: "b", name: "script", type: "code-js2", output: [1, 2] }] },
|
||||
{ id: "iteration-3", type: "condition", items: [{ id: "c", name: "script", type: "code", output: 7 }] },
|
||||
] }];
|
||||
const summaries = extractCodeNodeSummaries(tree);
|
||||
expect(summaries.map(item => item.id)).toEqual(["a", "b", "c"]);
|
||||
expect(summaries[0].rawOutput).toEqual({ count: 3 });
|
||||
expect(summaries).toEqual(extractCodeNodeSummaries(tree, flattenExecutionTree as any));
|
||||
});
|
||||
@@ -47,6 +47,21 @@ describe("cli/printer - 上下文防爆与敏感脱敏", () => {
|
||||
expect(redacted).toContain('"password": "<redacted>"');
|
||||
expect(redacted).toContain('"appSecurity": "<redacted>"');
|
||||
});
|
||||
|
||||
test("保留 JSON 中的业务布尔标记与空值,凭据仍脱敏", () => {
|
||||
const source = { keepItSecret: false, nested: { keepItSecret: true, secret: null }, password: "fixture", clientSecret: "fixture-client", appSecurity: 123 };
|
||||
const output = redactSensitiveText(JSON.stringify(source, null, 2));
|
||||
expect(JSON.parse(output)).toEqual({ keepItSecret: false, nested: { keepItSecret: true, secret: null }, password: "<redacted>", clientSecret: "<redacted>", appSecurity: "<redacted>" });
|
||||
expect(output).not.toContain("fixture");
|
||||
});
|
||||
|
||||
test("结构化脱敏保留单行 NDJSON 和字符串转义", () => {
|
||||
const source = { rows: [{ password: 'quoted "credential"', keepItSecret: false }], url: "https://example.test/?token=fixture-token&corpId=corp", description: "two\nlines" };
|
||||
const output = redactSensitiveText(JSON.stringify(source) + "\n");
|
||||
expect(output.split("\n")).toHaveLength(2);
|
||||
expect(JSON.parse(output)).toEqual({ rows: [{ password: "<redacted>", keepItSecret: false }], url: "https://example.test/?token=<redacted>&corpId=corp", description: "two\nlines" });
|
||||
expect(output).not.toContain("credential");
|
||||
});
|
||||
});
|
||||
|
||||
describe("protectLargeOutput 与 printJson 体积熔断保护", () => {
|
||||
|
||||
+27
-1
@@ -13,13 +13,39 @@ export function writeStdoutChunk(chunk: string): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
export function redactSensitiveText(value: string): string {
|
||||
function redactTextFragments(value: string): string {
|
||||
return value
|
||||
.replace(/([?&](?:accessToken|token|returnToken|security-token|x-amz-security-token|signature|x-amz-signature|ossaccesskeyid|x-amz-credential)=)[^&\s"']+/gi, "$1<redacted>")
|
||||
.replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1<redacted>")
|
||||
.replace(/((?:password|passwd|secret|appSecurity)["']?\s*[:=]\s*["']?)[^"',\s}]+/gi, "$1<redacted>");
|
||||
}
|
||||
|
||||
export function redactSensitiveText(value: string): string {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
const redactValue = (item: unknown, key = ""): unknown => {
|
||||
// Boolean/null flags such as keepItSecret are business metadata, not credentials.
|
||||
if (item === null || typeof item === "boolean") return item;
|
||||
if (/(?:password|passwd|secret|appSecurity)$/i.test(key)) return "<redacted>";
|
||||
if (typeof item === "string") return redactTextFragments(item);
|
||||
if (Array.isArray(item)) return item.map((child) => redactValue(child));
|
||||
if (typeof item === "object") {
|
||||
return Object.fromEntries(Object.entries(item).map(([name, child]) => [name, redactValue(child, name)]));
|
||||
}
|
||||
return item;
|
||||
};
|
||||
const leading = value.match(/^\s*/)?.[0] || "";
|
||||
const trailing = value.match(/\s*$/)?.[0] || "";
|
||||
// Keep compact NDJSON records on one line and ordinary CLI JSON readable.
|
||||
const multiline = value.trim().includes("\n");
|
||||
let json = JSON.stringify(redactValue(parsed), null, multiline || value.includes(": ") ? 2 : undefined);
|
||||
if (!multiline) json = json.replace(/\n\s*/g, " ");
|
||||
return leading + json + trailing;
|
||||
} catch {
|
||||
return redactTextFragments(value);
|
||||
}
|
||||
}
|
||||
|
||||
export function protectLargeOutput(result: unknown, options: OutputOptions = {}) {
|
||||
if (options.allowFull || options.outputFile) return;
|
||||
const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8");
|
||||
|
||||
Reference in new issue
Block a user