Merge pull request #109 from yunyingk/fix/recent-pr-stability
fix: stabilize auth identity, record operations, and workflow diagnostics
This commit is contained in:
36 files changed
+1066
-340
No files matched your search
@@ -3,6 +3,7 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname } from "node:path";
|
||||
import { runCli } from "./cli/runner.js";
|
||||
import { writeStdoutChunk } from "./cli/printer.js";
|
||||
|
||||
process.stdout.on("error", (err: any) => {
|
||||
if (err?.code === "EPIPE") process.exit(0);
|
||||
@@ -26,6 +27,7 @@ const result = isAiPro
|
||||
: await runCli(process.argv.slice(2), {
|
||||
appRoot,
|
||||
entryFile,
|
||||
writeStdout: writeStdoutChunk,
|
||||
});
|
||||
|
||||
try {
|
||||
|
||||
@@ -20,3 +20,7 @@
|
||||
|
||||
- handler 统一签名 `(parsed, runtime, options) => Promise<CliResult>`。
|
||||
- 命令文件内部不重复做异常体系,只抛/透传 `EkbError` 子类。
|
||||
|
||||
## 嵌入调用与流式输出
|
||||
|
||||
`runCli` 默认通过 `CliResult` 返回结果,不直接写进进程 stdout。终端入口可显式传入 `CliRunOptions.writeStdout` 异步回调;处理器必须等待回调完成,保证慢管道有背压。MCP / HTTP 不提供该回调,流式记录应使用 `--output-file`,否则返回用法错误。普通命令的返回结构保持不变。
|
||||
@@ -267,7 +267,7 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
|
||||
` 阶段判定 : ${report.diagnostic.stageLabel}`,
|
||||
` 当前驻留节点: ${report.currentNode?.name || "-"}${report.currentNode?.id ? ` (${report.currentNode.id})` : ""}`,
|
||||
` 待办处理人: ${approverNames || "(当前无待办审批人)"}`,
|
||||
` 是否可审批: ${report.diagnostic.canApprove ? "✅ 是 (支持执行同意/驳回)" : "❌ 否 (当前不可审批)"}`,
|
||||
` 是否可审批: ${report.diagnostic.canApprove === null ? "未知(需核对当前身份的实际待办与权限)" : report.diagnostic.canApprove ? "✅ 是 (支持执行同意/驳回)" : "❌ 否 (当前不可审批)"}`,
|
||||
` 诊断结论 : ${report.diagnostic.summary}`,
|
||||
` 排障建议 : ${report.diagnostic.advice}`,
|
||||
];
|
||||
|
||||
@@ -346,11 +346,18 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
||||
|
||||
it("supports dynamic staff switching via corps link [corp] --staff=<id>", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async () =>
|
||||
new Response(JSON.stringify({ items: [] }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
})) as unknown as typeof fetch;
|
||||
const corp = structuredClone(mockCorps[0]);
|
||||
Object.assign(corp.credentials, { appKey: "staff-switch-key", appSecurity: "staff-switch-security" });
|
||||
const dynamicRuntime = { ...searchRuntime, selectedCorp: corp, corpContext: { ...searchRuntime.corpContext, resolve: () => corp } } as CliRuntime;
|
||||
globalThis.fetch = (async (input: string | URL | Request) => {
|
||||
const url = input instanceof Request ? input.url : String(input);
|
||||
const body = url.includes("getAccessToken")
|
||||
? { value: { accessToken: "openapi-staff-switch", corporationId: "alphaPhysicalId", expireTime: Date.now() + 7200000 } }
|
||||
: url.includes("getProvisionalAuth")
|
||||
? { value: { message: "https://app.ekuaibao.com/web/thirdparty.html?accessToken=token-new-staff&ekbCorpId=alphaPhysicalId" } }
|
||||
: { items: [] };
|
||||
return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } });
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
const res = await handleCorpsCommand(
|
||||
@@ -361,7 +368,7 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
||||
options: { staff: "alphaPhysicalId:NEW_ADMIN_STAFF" },
|
||||
raw: ["corps", "link", "corpAlpha", "--staff=alphaPhysicalId:NEW_ADMIN_STAFF"],
|
||||
},
|
||||
searchRuntime
|
||||
dynamicRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
@@ -370,7 +377,7 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
||||
expect(res.stdout).toContain("动态换签");
|
||||
|
||||
// --json 模式验证
|
||||
const jsonRuntime = { ...searchRuntime, jsonMode: true };
|
||||
const jsonRuntime = { ...dynamicRuntime, jsonMode: true };
|
||||
const jsonRes = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
@@ -385,6 +392,8 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
||||
const parsed = JSON.parse(jsonRes.stdout);
|
||||
expect(parsed.dynamicStaff).toBe(true);
|
||||
expect(parsed.staffId).toBe("alphaPhysicalId:NEW_ADMIN_STAFF");
|
||||
expect(corp.credentials.accessToken).toBe("token-alpha");
|
||||
expect(corp.credentials.staffId).toBe("STAFF_001");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
|
||||
@@ -219,7 +219,7 @@ describe("CLI - flow & trace 全域透视与穿透诊断命令族", () => {
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("单据全域穿透诊断 [BX-999]");
|
||||
expect(res.stdout).toContain("总监审批");
|
||||
expect(res.stdout).toContain("是否可审批: ✅ 是");
|
||||
expect(res.stdout).toContain("是否可审批: 未知");
|
||||
});
|
||||
|
||||
it("未找到单据时返回 exitCode 1 与排障建议", async () => {
|
||||
|
||||
@@ -487,7 +487,6 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
|
||||
const streamedLines: string[] = [];
|
||||
const writeSpy = spyOn(process.stdout, "write").mockImplementation((str: any) => {
|
||||
streamedLines.push(String(str));
|
||||
return true;
|
||||
});
|
||||
spies.push(writeSpy);
|
||||
@@ -500,11 +499,12 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
options: { ndjson: true },
|
||||
raw: ["platform", "records", "platform-1", "entity-1", "--ndjson"],
|
||||
},
|
||||
dummyRuntime
|
||||
{ ...dummyRuntime, writeStdout: async (chunk) => { streamedLines.push(chunk); } }
|
||||
);
|
||||
|
||||
expect(streamRes.exitCode).toBe(0);
|
||||
expect(streamedLines.length).toBe(2);
|
||||
expect(writeSpy).not.toHaveBeenCalled();
|
||||
|
||||
const row1 = JSON.parse(streamedLines[0].trim());
|
||||
expect(row1.id).toBe("r-1");
|
||||
@@ -513,5 +513,17 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
expect(row1.active).toBe(true);
|
||||
expect(row1.fields["自定义字段"]).toBe("测试值");
|
||||
});
|
||||
|
||||
it("rejects malformed batch predicates before fetching all records or calling the writer", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
const fetch = spyOn(services, "fetchAllEntityRecords").mockResolvedValue({ data: [], total: 0 } as any);
|
||||
const write = spyOn(services, "batchSafeEditRecords").mockResolvedValue([]);
|
||||
spies.push(fetch, write);
|
||||
await expect(handlePlatformCommand({ area: "platform", action: "batch-edit", args: ["platform-1", "entity-1"], options: { where: "序号 in [1]", set: "active=true", yes: true }, raw: [] }, dummyRuntime)).rejects.toThrow("不支持的筛选条件");
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(write).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
buildSafeRecordEditPayload,
|
||||
editRecord,
|
||||
fetchAllEntityRecords,
|
||||
filterRecordsByPredicate,
|
||||
compileRecordPredicate,
|
||||
getRecordDetail,
|
||||
parseSetClause,
|
||||
recomputeRecordLedger,
|
||||
@@ -146,6 +146,7 @@ async function handleBatchEdit(
|
||||
const idsOpt = stringOption(parsed.options, ["ids", "id"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]);
|
||||
const whereClause = stringOption(parsed.options, ["where"]);
|
||||
const predicate = whereClause ? compileRecordPredicate(whereClause, resolved.entity) : undefined;
|
||||
const setClause = stringOption(parsed.options, ["set"]);
|
||||
const dataStr = stringOption(parsed.options, ["data", "form", "d"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "f"]);
|
||||
@@ -237,9 +238,7 @@ async function handleBatchEdit(
|
||||
{ filterBy }
|
||||
);
|
||||
let records = page.data;
|
||||
if (whereClause) {
|
||||
records = filterRecordsByPredicate(records, whereClause, resolved.entity);
|
||||
}
|
||||
if (predicate) records = records.filter(predicate);
|
||||
recordIds = records
|
||||
.map((r) => {
|
||||
const dl =
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
buildKeywordFilter,
|
||||
calculateEntityRecordStats,
|
||||
fetchAllEntityRecords,
|
||||
filterRecordsByPredicate,
|
||||
compileRecordPredicate,
|
||||
iterateAllEntityRecords,
|
||||
normalizeDatalinkRecord,
|
||||
parseExpectClause,
|
||||
@@ -14,11 +14,17 @@ import {
|
||||
} from "../../../domains/datalink/services.js";
|
||||
import type { LedgerContinuityReport } from "../../../domains/datalink/types.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import { printJson, printTable, printKeyValue, redactSensitiveText } from "../../printer.js";
|
||||
import { usageError } from "../../errors.js";
|
||||
import { open } from "node:fs/promises";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { cell, resolveAppAndEntity, splitFields } from "./shared.js";
|
||||
|
||||
export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const isStream = booleanOption(parsed.options, ["ndjson", "stream"], false);
|
||||
if (isStream && !runtime.outputOptions?.outputFile && !runtime.writeStdout) {
|
||||
throw usageError("当前调用入口不支持直接 NDJSON 流,请使用 --output-file <path> 保存,或在终端运行该命令。");
|
||||
}
|
||||
const isStatsSubcommand = parsed.args[0] === "stats" || parsed.action === "stats";
|
||||
const appIndex = parsed.args[0] === "stats" ? 1 : 0;
|
||||
const entityIndex = parsed.args[0] === "stats" ? 2 : 1;
|
||||
@@ -28,9 +34,9 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
|
||||
const whereClause = stringOption(parsed.options, ["where"]);
|
||||
const predicate = whereClause ? compileRecordPredicate(whereClause, resolved.entity) : undefined;
|
||||
const sumOption = stringOption(parsed.options, ["sum", "aggregate"]);
|
||||
const isProfileStats = isStatsSubcommand || booleanOption(parsed.options, ["stats", "profile"], false);
|
||||
const isStream = booleanOption(parsed.options, ["ndjson", "stream"], false);
|
||||
const isRaw = booleanOption(parsed.options, ["raw"], false);
|
||||
const isFlat = booleanOption(parsed.options, ["flat", "normalize", "normalized"], false);
|
||||
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
@@ -44,33 +50,41 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
// 1. 高性能流式下发模式 (--ndjson / --stream,内存开销 O(pageSize),专为海量数据外部脚本管道设计)
|
||||
if (isStream) {
|
||||
let streamCount = 0;
|
||||
const maxLimit = isAll ? Infinity : count;
|
||||
let bytes = 0;
|
||||
const maxLimit = isAll ? Infinity : count ?? 20;
|
||||
const outputFile = runtime.outputOptions?.outputFile;
|
||||
const file = outputFile ? await open(outputFile, "w", 0o600) : undefined;
|
||||
|
||||
for await (const rawRecord of iterateAllEntityRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity.id,
|
||||
{ filterBy, pageSize }
|
||||
)) {
|
||||
if (whereClause) {
|
||||
const matched = filterRecordsByPredicate([rawRecord], whereClause, resolved.entity);
|
||||
if (matched.length === 0) continue;
|
||||
try {
|
||||
if (maxLimit > 0) {
|
||||
for await (const rawRecord of iterateAllEntityRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity.id,
|
||||
{ filterBy, pageSize }
|
||||
)) {
|
||||
if (predicate && !predicate(rawRecord)) continue;
|
||||
|
||||
let outputRecord: Record<string, unknown> = isRaw
|
||||
? (rawRecord as Record<string, unknown>)
|
||||
: (normalizeDatalinkRecord(rawRecord, resolved.entity) as unknown as Record<string, unknown>);
|
||||
|
||||
if (fields.length) {
|
||||
outputRecord = selectRecordFields(outputRecord, fields, resolved.entity.fields);
|
||||
}
|
||||
|
||||
const chunk = redactSensitiveText(JSON.stringify(outputRecord)) + "\n";
|
||||
if (file) await file.writeFile(chunk);
|
||||
else await runtime.writeStdout!(chunk);
|
||||
bytes += Buffer.byteLength(chunk);
|
||||
streamCount++;
|
||||
if (maxLimit !== undefined && streamCount >= maxLimit) break;
|
||||
}
|
||||
}
|
||||
|
||||
let outputRecord: Record<string, unknown> = isRaw
|
||||
? (rawRecord as Record<string, unknown>)
|
||||
: (normalizeDatalinkRecord(rawRecord, resolved.entity) as unknown as Record<string, unknown>);
|
||||
|
||||
if (fields.length) {
|
||||
outputRecord = selectRecordFields(outputRecord, fields, resolved.entity.fields);
|
||||
}
|
||||
|
||||
process.stdout.write(JSON.stringify(outputRecord) + "\n");
|
||||
streamCount++;
|
||||
if (maxLimit !== undefined && streamCount >= maxLimit) break;
|
||||
} finally {
|
||||
await file?.close();
|
||||
}
|
||||
|
||||
return { stdout: "", stderr: "", exitCode: 0 };
|
||||
return { stdout: outputFile ? printJson({ outputFile, bytes, records: streamCount }) : "", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// 2. 宏观画像与统计模式 (--stats 或 platform records stats <应用> <对象>)
|
||||
@@ -82,9 +96,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
{ filterBy, pageSize }
|
||||
);
|
||||
let records = page.data;
|
||||
if (whereClause) {
|
||||
records = filterRecordsByPredicate(records, whereClause, resolved.entity);
|
||||
}
|
||||
if (predicate) records = records.filter(predicate);
|
||||
const stats = calculateEntityRecordStats(records, resolved.entity, page.total);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
@@ -118,9 +130,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
: await searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
|
||||
let data = page.data;
|
||||
if (whereClause) {
|
||||
data = filterRecordsByPredicate(data, whereClause, resolved.entity);
|
||||
}
|
||||
if (predicate) data = data.filter(predicate);
|
||||
|
||||
// 3. 数学聚合核算模式 (--sum="租赁费用,日折旧费")
|
||||
if (sumOption) {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { afterEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import { handleWorkflowTest } from "./workflow/test.js";
|
||||
import * as shared from "./workflow/shared.js";
|
||||
import * as services from "../../domains/platform/services.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../types.js";
|
||||
import type { WorkflowTestReport } from "../../domains/platform/types.js";
|
||||
|
||||
const runtime = { selectedCorp: { id: "mock-corp" }, jsonMode: true } as CliRuntime;
|
||||
const args = (options: Record<string, string | boolean> = {}): CliParsedArgs => ({ area: "workflow", action: "test", args: ["pipe"], options: { flow: "ID01-record", ...options }, raw: ["workflow", "test", "pipe", "--flow=ID01-record"] });
|
||||
const completed: WorkflowTestReport = { jobId: "job", pipelineId: "pipe", status: "COMPLETED", outcome: "completed", timedOut: false, diagnosticsComplete: true, diagnosticsErrors: [], runType: "DEBUG", targetEntityId: "record", executionTree: [], failedExecutions: [], conditionDiagnoses: [] };
|
||||
|
||||
describe("workflow debug mutation and result contract", () => {
|
||||
const spies: Array<{ mockRestore(): void }> = [];
|
||||
afterEach(() => { while (spies.length) spies.pop()!.mockRestore(); });
|
||||
function setup(report = completed) {
|
||||
const client = spyOn(shared, "createWorkflowDetailClient").mockResolvedValue({ client: {} } as any);
|
||||
const detail = spyOn(services, "getWorkflowDetail").mockResolvedValue({ state: 1 } as any);
|
||||
const run = spyOn(services, "runWorkflowDebugTest").mockResolvedValue(report);
|
||||
spies.push(client, detail, run);
|
||||
return { client, detail, run };
|
||||
}
|
||||
it("dry-run with auto-publish does not create clients or start a job even if --yes is also set", async () => {
|
||||
const { client, run } = setup();
|
||||
const result = await handleWorkflowTest(args({ "dry-run": true, "auto-publish": true, yes: true }), runtime);
|
||||
const preview = JSON.parse(result.stdout);
|
||||
expect(preview.dryRun).toBe(true);
|
||||
expect(preview.changes.autoPublish).toBe(true);
|
||||
expect(preview.changes.warnings).not.toHaveLength(0);
|
||||
expect(client).not.toHaveBeenCalled();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
it("requires explicit mutation confirmation before creating clients", async () => {
|
||||
const { client, run } = setup();
|
||||
await expect(handleWorkflowTest(args(), runtime)).rejects.toThrow("请先使用 --dry-run");
|
||||
expect(client).not.toHaveBeenCalled();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
for (const [triggerType, options] of [
|
||||
["clock", {}],
|
||||
["webhook", { body: '{"event":"test"}' }],
|
||||
["webhook", { empty: true }],
|
||||
["webhook", { file: "/unused-in-dry-run.json" }],
|
||||
["ekuaibao-datalink-create-trigger", { record: "ID01-record" }],
|
||||
] as Array<[string, Record<string, string | boolean>]>) {
|
||||
it(`previews ${triggerType} without creating clients (${Object.keys(options).join(",")})`, async () => {
|
||||
const { client, run } = setup();
|
||||
const result = await handleWorkflowTest({ ...args(), options: { ...options, "dry-run": true, yes: true } }, runtime);
|
||||
expect(JSON.parse(result.stdout).dryRun).toBe(true);
|
||||
expect(client).not.toHaveBeenCalled();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
}
|
||||
it("requires confirmation for a schedule trigger without --flow", async () => {
|
||||
const { detail, run } = setup();
|
||||
detail.mockResolvedValue({ state: 1, tasks: [{ type: "clock" }] } as any);
|
||||
await expect(handleWorkflowTest({ ...args(), options: {} }, runtime)).rejects.toThrow("请先使用 --dry-run");
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
it("keeps confirmed schedule and webhook trigger routing", async () => {
|
||||
const { detail, run } = setup();
|
||||
detail.mockResolvedValue({ state: 1, tasks: [{ type: "clock" }] } as any);
|
||||
const scheduled = await handleWorkflowTest({ ...args(), options: { yes: true } }, runtime);
|
||||
expect(scheduled.exitCode).toBe(0);
|
||||
expect(run.mock.calls[0]?.[2]?.triggerCategory).toBe("SCHEDULE");
|
||||
expect(run.mock.calls[0]?.[2]?.flowCodeOrId).toBe("");
|
||||
detail.mockResolvedValue({ state: 1, tasks: [{ type: "webhook" }] } as any);
|
||||
const webhook = await handleWorkflowTest({ ...args(), options: { body: '{"event":"test"}', yes: true } }, runtime);
|
||||
expect(webhook.exitCode).toBe(0);
|
||||
expect(run.mock.calls[1]?.[2]?.data).toEqual({ event: "test" });
|
||||
expect(run.mock.calls[1]?.[2]?.triggerCategory).toBe("WEBHOOK");
|
||||
});
|
||||
it("allows confirmed enabled-workflow debug with machine-readable risk information", async () => {
|
||||
const { run } = setup();
|
||||
const result = await handleWorkflowTest(args({ yes: true }), runtime);
|
||||
expect(result.exitCode).toBe(0);
|
||||
const report = JSON.parse(result.stdout);
|
||||
expect(report.productionEnabled).toBe(true);
|
||||
expect(report.warnings).not.toHaveLength(0);
|
||||
expect(run).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("retains an unknown production state in the result when the status check fails", async () => {
|
||||
const { detail } = setup();
|
||||
detail.mockRejectedValue(new Error("status unavailable"));
|
||||
const result = await handleWorkflowTest(args({ yes: true }), runtime);
|
||||
const report = JSON.parse(result.stdout);
|
||||
expect(report.productionEnabled).toBeNull();
|
||||
expect(report.warnings.join(" ")).toContain("启用状态未知");
|
||||
});
|
||||
for (const jsonMode of [true, false]) {
|
||||
it(`returns a failing exit code for failed and incomplete runs (json=${jsonMode})`, async () => {
|
||||
setup({ ...completed, status: "FAILED", outcome: "failed" });
|
||||
const result = await handleWorkflowTest(args({ yes: true }), { ...runtime, jsonMode });
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stdout).toContain("FAILED");
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -588,6 +588,7 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
return { json: async () => ({ code: 200, data: null }) };
|
||||
},
|
||||
get: (url: string) => {
|
||||
if (url.includes("/level/failed")) return { json: async () => ({ code: 200, data: [] }) };
|
||||
if (url.includes("execution")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
@@ -665,7 +666,7 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
area: "workflow",
|
||||
action: "test",
|
||||
args: ["wf_test_1"],
|
||||
options: { flow: "ZJ-20261015-001387", platformId: "p1" },
|
||||
options: { flow: "ZJ-20261015-001387", platformId: "p1", yes: true },
|
||||
raw: ["workflow", "test", "wf_test_1", "--flow=ZJ-20261015-001387", "--platform-id=p1"],
|
||||
},
|
||||
mockRuntime
|
||||
@@ -681,6 +682,7 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
it("allows workflow test when pipeline is enabled in production with full security prompt", async () => {
|
||||
const mockClient = {
|
||||
get: (url: string) => {
|
||||
if (url.includes("/level/failed")) return { json: async () => ({ code: 200, data: [] }) };
|
||||
if (url.includes("api/easo/pipelines/")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
@@ -740,7 +742,7 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
area: "workflow",
|
||||
action: "test",
|
||||
args: ["wf_prod_1"],
|
||||
options: { flow: "ZJ-20261015-001387", platformId: "p1" },
|
||||
options: { flow: "ZJ-20261015-001387", platformId: "p1", yes: true },
|
||||
raw: ["workflow", "test", "wf_prod_1", "--flow=ZJ-20261015-001387", "--platform-id=p1"],
|
||||
},
|
||||
mockRuntime
|
||||
@@ -755,6 +757,7 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
it("handles workflow test for clock trigger without requiring --flow", async () => {
|
||||
const mockClient = {
|
||||
get: (url: string) => {
|
||||
if (url.includes("/level/failed")) return { json: async () => ({ code: 200, data: [] }) };
|
||||
if (url.includes("api/easo/pipelines/")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
@@ -818,7 +821,7 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
area: "workflow",
|
||||
action: "test",
|
||||
args: ["wf_clock_1"],
|
||||
options: { platformId: "p1" },
|
||||
options: { platformId: "p1", yes: true },
|
||||
raw: ["workflow", "test", "wf_clock_1", "--platform-id=p1"],
|
||||
},
|
||||
mockRuntime
|
||||
@@ -833,6 +836,7 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
it("handles workflow test for webhook trigger requiring body or empty", async () => {
|
||||
const mockClient = {
|
||||
get: (url: string) => {
|
||||
if (url.includes("/level/failed")) return { json: async () => ({ code: 200, data: [] }) };
|
||||
if (url.includes("api/easo/pipelines/")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
@@ -911,7 +915,7 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
area: "workflow",
|
||||
action: "test",
|
||||
args: ["wf_webhook_1"],
|
||||
options: { body: '{"code":"XM-001"}', platformId: "p1" },
|
||||
options: { body: '{"code":"XM-001"}', platformId: "p1", yes: true },
|
||||
raw: ["workflow", "test", "wf_webhook_1", '--body={"code":"XM-001"}', "--platform-id=p1"],
|
||||
},
|
||||
mockRuntime
|
||||
@@ -924,6 +928,7 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
it("handles workflow test for datalink trigger displaying dynamic fields", async () => {
|
||||
const mockClient = {
|
||||
get: (url: string) => {
|
||||
if (url.includes("/level/failed")) return { json: async () => ({ code: 200, data: [] }) };
|
||||
if (url.includes("api/easo/pipelines/")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
|
||||
@@ -149,7 +149,7 @@ export async function handleWorkflowDiffJob(
|
||||
} else {
|
||||
const divergedNodes = diff.nodes.filter((n) => n.diverged);
|
||||
const nodeRows = divergedNodes.map((n) => [
|
||||
n.taskName,
|
||||
n.currentLoopPath ? `${n.taskName} [loop ${n.currentLoopPath}]` : n.taskName,
|
||||
n.displayName || "-",
|
||||
n.type || "-",
|
||||
n.statusA || "(未执行)",
|
||||
|
||||
@@ -487,7 +487,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
if (diag.rules.length > 0) {
|
||||
outLines.push(" • 规则比对明细:");
|
||||
for (const r of diag.rules) {
|
||||
const statusIcon = r.matched ? "✅" : "❌";
|
||||
const statusIcon = r.matched === null ? "?" : r.matched ? "✅" : "❌";
|
||||
const missTag = r.isMissing ? " [⚠️ 属性缺失]" : "";
|
||||
outLines.push(` ${statusIcon} ${r.leftLabel} ${r.operatorLabel} ${JSON.stringify(r.expectedValue)}${missTag}`);
|
||||
outLines.push(` ↳ ${r.detail}`);
|
||||
|
||||
@@ -10,6 +10,7 @@ import { stringOption, booleanOption, numberOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
|
||||
export async function handleWorkflowTest(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -25,12 +26,14 @@ export async function handleWorkflowTest(
|
||||
"不同触发器的调试参数分支:",
|
||||
" 1. 单据触发 (flowForm): --flow=<单号|ID> 指定单据",
|
||||
" 2. 台账触发 (dataLink): --record=<记录ID|编码> 指定业务对象数据",
|
||||
" 3. 定时触发 (clock): 直接执行,无需任何参数",
|
||||
" 3. 定时触发 (clock): 无需业务参数,使用 --yes 确认执行",
|
||||
" 4. 外部调用 (webhook): --body='{...}' 或 --file=<path.json> 传入事件请求体",
|
||||
"",
|
||||
"通用选项:",
|
||||
" --timeout=<ms> 设置轮询超时时间 (默认 15000ms)",
|
||||
" --auto-publish 是否自动发布测试快照 (默认 false)",
|
||||
" --dry-run 只预览,不发起调试",
|
||||
" --yes/--confirm 确认执行真实工作流节点",
|
||||
"",
|
||||
"别名: hose-use workflow debug <pipelineId>",
|
||||
].join("\n") + "\n",
|
||||
@@ -38,16 +41,26 @@ export async function handleWorkflowTest(
|
||||
};
|
||||
}
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const flowCodeOrId = stringOption(parsed.options, ["flow", "record", "code", "flow-code", "flowCode", "bill", "entity", "id"]);
|
||||
const autoPublish = booleanOption(parsed.options, ["auto-publish", "autoPublish", "publish"]);
|
||||
const timeoutMs = numberOption(parsed.options, ["timeout", "timeout-ms", "timeoutMs"]) || 15000;
|
||||
const timeoutMs = numberOption(parsed.options, ["timeout", "timeout-ms", "timeoutMs"]) ?? 15000;
|
||||
const rawBody = stringOption(parsed.options, ["body", "data", "payload"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "path"]);
|
||||
const isEmpty = booleanOption(parsed.options, ["empty", "none"]);
|
||||
|
||||
const warnings = ["调试会在真实环境执行工作流节点,可能改变业务数据、发送通知并生成快照;auto-publish 还可能发布流程。"];
|
||||
const confirmExecution = () => requireMutationConfirmation(parsed, runtime, "执行工作流调试", `hose-use workflow test ${pipelineId} --yes`);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, rawBody, filePath, empty: isEmpty, autoPublish, timeoutMs, warnings });
|
||||
}
|
||||
if (flowCodeOrId || rawBody || filePath || isEmpty) confirmExecution();
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
|
||||
// 1. 获取工作流详情与触发器元数据
|
||||
const detail = await getWorkflowDetail(client, pipelineId).catch(() => null);
|
||||
const detail = await getWorkflowDetail(client, pipelineId).catch(() => {
|
||||
warnings.push("未能读取工作流状态,启用状态未知。");
|
||||
return null;
|
||||
});
|
||||
const isEnabled = detail?.state === 1 || (detail as any)?.active === true;
|
||||
const triggerNode = detail?.tasks?.[0];
|
||||
const triggerType = triggerNode?.type || "unknown";
|
||||
@@ -124,7 +137,7 @@ export async function handleWorkflowTest(
|
||||
const source = await getWorkflowDebugSource(client, pipelineId, { page: 1, pageSize: 5 });
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(source, runtime.outputOptions),
|
||||
stdout: printJson({ ...source, productionEnabled: detail ? isEnabled : null, warnings }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -187,7 +200,7 @@ export async function handleWorkflowTest(
|
||||
const source = await getWorkflowDebugSource(client, pipelineId, { page: 1, pageSize: 5 });
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(source, runtime.outputOptions),
|
||||
stdout: printJson({ ...source, productionEnabled: detail ? isEnabled : null, warnings }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -226,7 +239,8 @@ export async function handleWorkflowTest(
|
||||
}
|
||||
|
||||
// 3. 执行端到端调试测试
|
||||
const report = await runWorkflowDebugTest(client, pipelineId, {
|
||||
confirmExecution();
|
||||
const execution = await runWorkflowDebugTest(client, pipelineId, {
|
||||
flowCodeOrId: targetId,
|
||||
data: customPayload,
|
||||
triggerCategory: category,
|
||||
@@ -235,12 +249,14 @@ export async function handleWorkflowTest(
|
||||
autoPublish,
|
||||
timeoutMs,
|
||||
});
|
||||
const report = { ...execution, productionEnabled: detail ? isEnabled : null, warnings };
|
||||
const exitCode = report.outcome === "completed" ? 0 : 1;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(report, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
exitCode,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -279,6 +295,9 @@ export async function handleWorkflowTest(
|
||||
"生成 Job ID": report.jobId,
|
||||
"测试目标对象": targetDescription,
|
||||
"执行结果状态": report.status,
|
||||
"测试结果": report.outcome,
|
||||
"是否超时": String(report.timedOut),
|
||||
"诊断完整": String(report.diagnosticsComplete),
|
||||
"运行模式": report.runType,
|
||||
"总耗时(ms)": String(report.durationTime ?? "-"),
|
||||
"节点执行总数": report.executionTree.length,
|
||||
@@ -294,6 +313,9 @@ export async function handleWorkflowTest(
|
||||
: "暂无顶层节点执行记录",
|
||||
];
|
||||
|
||||
outLines.push(...warnings.map(warning => `⚠️ ${warning}`));
|
||||
outLines.push(...report.diagnosticsErrors.map(error => `诊断读取失败 [${error.source}]: ${error.message}`));
|
||||
|
||||
if (report.conditionDiagnoses.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push("── 💡 条件分支跳过诊断 (为什么没有走内部子任务?) ──");
|
||||
@@ -304,7 +326,7 @@ export async function handleWorkflowTest(
|
||||
if (diag.rules.length > 0) {
|
||||
outLines.push(" • 规则比对明细:");
|
||||
for (const r of diag.rules) {
|
||||
const statusIcon = r.matched ? "✅" : "❌";
|
||||
const statusIcon = r.matched === null ? "?" : r.matched ? "✅" : "❌";
|
||||
const missTag = r.isMissing ? " [⚠️ 属性缺失]" : "";
|
||||
outLines.push(` ${statusIcon} ${r.leftLabel} ${r.operatorLabel} ${JSON.stringify(r.expectedValue)}${missTag}`);
|
||||
outLines.push(` ↳ ${r.detail}`);
|
||||
@@ -316,6 +338,6 @@ export async function handleWorkflowTest(
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: report.status === "FAILED" ? 1 : 0,
|
||||
exitCode,
|
||||
};
|
||||
}
|
||||
@@ -6,6 +6,13 @@ import { renderScopedHelp } from "./help.js";
|
||||
|
||||
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
|
||||
|
||||
/** Await the write callback so a slow terminal or pipe applies backpressure. */
|
||||
export function writeStdoutChunk(chunk: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
process.stdout.write(chunk, error => error ? reject(error) : resolve());
|
||||
});
|
||||
}
|
||||
|
||||
export function redactSensitiveText(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>")
|
||||
|
||||
@@ -136,6 +136,7 @@ async function dispatchCli(
|
||||
entryFile: options.entryFile,
|
||||
launcher: options.launcher,
|
||||
});
|
||||
runtime.writeStdout = options.writeStdout;
|
||||
|
||||
try {
|
||||
if (!parsed.area) {
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { InMemoryTransport } from "@modelcontextprotocol/server";
|
||||
import { runCli } from "./runner.js";
|
||||
import { createServer, HOSE_CLI_TOOL_NAME } from "../server.js";
|
||||
import { startHttpServer } from "../http/server.js";
|
||||
import * as helpers from "./helpers.js";
|
||||
import * as shared from "./commands/platform/shared.js";
|
||||
import * as records from "../domains/datalink/services.js";
|
||||
|
||||
describe("NDJSON output destinations across CLI, MCP and HTTP", () => {
|
||||
const spies: Array<{ mockRestore(): void }> = [];
|
||||
let directory: string;
|
||||
let produced: number;
|
||||
let directWrite: ReturnType<typeof spyOn>;
|
||||
const command = ["platform", "records", "app", "entity", "--ndjson", "--raw"];
|
||||
beforeEach(() => {
|
||||
directory = mkdtempSync(join(tmpdir(), "hose-stream-test-"));
|
||||
produced = 0;
|
||||
spies.push(spyOn(helpers, "initCorpRuntime").mockImplementation(options => ({ selectedCorp: { id: "mock-corp" }, jsonMode: options?.jsonMode, outputOptions: options?.outputOptions }) as any));
|
||||
spies.push(spyOn(shared, "resolveAppAndEntity").mockResolvedValue({ clients: { ekbClient: {} }, corpId: "mock-corp", platform: { id: "app" }, entity: { id: "entity", fields: [] } } as any));
|
||||
spies.push(spyOn(records, "iterateAllEntityRecords").mockImplementation(async function* () {
|
||||
produced++; yield { id: "r1", secret: "mock-secret" };
|
||||
produced++; yield { id: "r2", active: true };
|
||||
}));
|
||||
directWrite = spyOn(process.stdout, "write").mockImplementation(() => true);
|
||||
spies.push(directWrite);
|
||||
});
|
||||
afterEach(() => {
|
||||
while (spies.length) spies.pop()!.mockRestore();
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("waits for the terminal destination before producing the next record", async () => {
|
||||
let started!: () => void, release!: () => void;
|
||||
const firstWrite = new Promise<void>(resolve => { started = resolve; });
|
||||
const blocked = new Promise<void>(resolve => { release = resolve; });
|
||||
const chunks: string[] = [];
|
||||
const running = runCli(command, { writeStdout: async chunk => {
|
||||
chunks.push(chunk);
|
||||
if (chunks.length === 1) { started(); await blocked; }
|
||||
} });
|
||||
await firstWrite;
|
||||
expect(produced).toBe(1);
|
||||
release();
|
||||
const result = await running;
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(chunks).toHaveLength(2);
|
||||
expect(chunks[0]).not.toContain("mock-secret");
|
||||
expect(JSON.parse(chunks[0]).secret).toBe("<redacted>");
|
||||
expect(directWrite).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("writes actual NDJSON to output-file and returns a compact summary", async () => {
|
||||
const outputFile = join(directory, "records.ndjson");
|
||||
const result = await runCli([...command, "-o", outputFile]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
const summary = JSON.parse(result.stdout);
|
||||
const contents = readFileSync(outputFile, "utf8");
|
||||
expect(summary.outputFile).toBe(outputFile);
|
||||
expect(summary.records).toBe(2);
|
||||
expect(summary.bytes).toBe(Buffer.byteLength(contents));
|
||||
expect(contents.trim().split("\n").map(line => JSON.parse(line).id)).toEqual(["r1", "r2"]);
|
||||
expect(contents).not.toContain("mock-secret");
|
||||
expect(directWrite).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects embedded streaming without a destination before fetching records", async () => {
|
||||
const result = await runCli([...command, "--json"]);
|
||||
expect(result.exitCode).toBe(2);
|
||||
expect(result.stdout).toContain("output-file");
|
||||
expect(produced).toBe(0);
|
||||
expect(directWrite).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns a proper MCP error rather than emitting record bytes on process stdout", async () => {
|
||||
const server = createServer({ enabled: true });
|
||||
const client = new Client({ name: "stream-test", version: "1" });
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
|
||||
const result = await client.callTool({ name: HOSE_CLI_TOOL_NAME, arguments: { command: command.join(" ") } });
|
||||
expect(result.isError).toBe(true);
|
||||
expect(JSON.stringify(result.content)).toContain("output-file");
|
||||
expect(produced).toBe(0);
|
||||
expect(directWrite).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
|
||||
it("returns an HTTP error response instead of a successful empty result", async () => {
|
||||
const server = await startHttpServer({ host: "127.0.0.1", port: 0, silent: true });
|
||||
try {
|
||||
const address = server.address() as { port: number };
|
||||
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
||||
if (process.env.HOSE_HTTP_TOKEN) headers.Authorization = `Bearer ${process.env.HOSE_HTTP_TOKEN.trim()}`;
|
||||
const response = await fetch(`http://127.0.0.1:${address.port}/api/cli`, { method: "POST", headers, body: JSON.stringify({ command: command.join(" ") }) });
|
||||
expect(response.status).toBe(400);
|
||||
const result = await response.json() as { exitCode: number; stderr: string };
|
||||
expect(result.exitCode).toBe(2);
|
||||
expect(result.stderr).toContain("output-file");
|
||||
expect(produced).toBe(0);
|
||||
expect(directWrite).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,8 @@ export interface CliParsedArgs {
|
||||
}
|
||||
|
||||
export interface CliRunOptions {
|
||||
/** Only terminal entrypoints supply a protocol-safe streaming destination. */
|
||||
writeStdout?: (chunk: string) => Promise<void>;
|
||||
appRoot?: string;
|
||||
entryFile?: string;
|
||||
launcher?: {
|
||||
@@ -33,6 +35,7 @@ export interface OutputOptions {
|
||||
}
|
||||
|
||||
export interface CliRuntime {
|
||||
writeStdout?: (chunk: string) => Promise<void>;
|
||||
corpContext: CorpContext;
|
||||
selectedCorp: CorpConfig | null;
|
||||
jsonMode: boolean;
|
||||
|
||||
@@ -46,3 +46,9 @@ src/core/
|
||||
- 业务域如果需要缓存,统一使用 `core/cache/` 提供的多级缓存门面
|
||||
- 业务域如果需要持久化数据,统一接入 `core/db/` 并注册版本迁移
|
||||
|
||||
|
||||
## 员工换签与默认会话
|
||||
|
||||
- `getCorpProvisionalAuthLink` 显式指定 `staffId` 时需要已配置的 OpenAPI 密钥;旧员工的 Session Token 不会伪装成目标员工。
|
||||
- 临时换签只返回独立链接,不修改默认身份、Token 或缓存。只有 `persistStaff=true` 才把目标身份、Token、有效期和员工名称一起持久化;同一身份的普通续期保持原行为。
|
||||
- 校验签发身份与目标一致,并在保存成功后更新内存配置;失败时不留下半更新的内存身份。
|
||||
@@ -0,0 +1,80 @@
|
||||
import { afterEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import { getCorpProvisionalAuthLink } from "./openapi-onboard.js";
|
||||
import * as openapi from "./openapi-v1.js";
|
||||
import * as loader from "../config/loader.js";
|
||||
import * as links from "./link-import.js";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
|
||||
describe("provisional link identity isolation", () => {
|
||||
const spies: Array<{ mockRestore(): void }> = [];
|
||||
afterEach(() => { while (spies.length) spies.pop()!.mockRestore(); });
|
||||
function setup(uid = "corp:B") {
|
||||
const corp: CorpConfig = {
|
||||
id: "corp", name: "Mock", source: "openapi", baseUrl: "https://example.test",
|
||||
staffId: "corp:A", staffName: "A", session: { staffName: "A" },
|
||||
credentials: { accessToken: "token-A", corpId: "corp", staffId: "corp:A", appKey: "key", appSecurity: "security" },
|
||||
};
|
||||
const token = spyOn(openapi, "fetchHoseOpenApiAccessToken").mockResolvedValue("openapi");
|
||||
const sign = spyOn(openapi, "fetchHoseProvisionalAuth").mockResolvedValue({ uid, token: "token-B", url: "https://example.test/link", expiresIn: 7200, expiresAt: Date.now() + 7200000 });
|
||||
const save = spyOn(loader, "saveCorpConfig").mockReturnValue("/mock/corp.json");
|
||||
const invalidate = spyOn(links, "invalidateCorpSubdomainTokenCaches").mockImplementation(() => {});
|
||||
spies.push(token, sign, save, invalidate);
|
||||
return { corp, save, sign, invalidate };
|
||||
}
|
||||
|
||||
it("does not mutate or save the default identity for a temporary staff link", async () => {
|
||||
const { corp, save, invalidate } = setup();
|
||||
const before = structuredClone(corp);
|
||||
const result = await getCorpProvisionalAuthLink(corp, { staffId: "corp:B", staffName: "B" });
|
||||
expect(result.staffId).toBe("corp:B");
|
||||
expect(result.staffName).toBe("B");
|
||||
expect(corp).toEqual(before);
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
expect(invalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("persists token and normalized identity together and clears the old staff name", async () => {
|
||||
const { corp, save } = setup();
|
||||
const result = await getCorpProvisionalAuthLink(corp, { staffId: "B", persistStaff: true });
|
||||
expect(result.staffName).toBeUndefined();
|
||||
expect(corp.credentials.accessToken).toBe("token-B");
|
||||
expect(corp.credentials.staffId).toBe("corp:B");
|
||||
expect(corp.staffId).toBe("corp:B");
|
||||
expect(corp.staffName).toBeUndefined();
|
||||
expect(corp.session?.staffName).toBeUndefined();
|
||||
expect(save.mock.calls[0]?.[0].credentials.staffId).toBe("corp:B");
|
||||
});
|
||||
|
||||
it("keeps ordinary renewal of the same staff working", async () => {
|
||||
const { corp, save } = setup("corp:A");
|
||||
await getCorpProvisionalAuthLink(corp);
|
||||
expect(corp.credentials.accessToken).toBe("token-B");
|
||||
expect(corp.credentials.staffId).toBe("corp:A");
|
||||
expect(save).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not partly mutate memory when saving fails", async () => {
|
||||
const { corp, save } = setup();
|
||||
const before = structuredClone(corp);
|
||||
save.mockImplementation(() => { throw new Error("disk unavailable"); });
|
||||
await expect(getCorpProvisionalAuthLink(corp, { staffId: "corp:B", persistStaff: true })).rejects.toThrow("disk unavailable");
|
||||
expect(corp).toEqual(before);
|
||||
});
|
||||
|
||||
it("rejects a mismatched signing identity before persisting", async () => {
|
||||
const { corp, save } = setup("corp:C");
|
||||
const before = structuredClone(corp);
|
||||
await expect(getCorpProvisionalAuthLink(corp, { staffId: "corp:B", persistStaff: true })).rejects.toThrow("身份与目标员工不一致");
|
||||
expect(corp).toEqual(before);
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not disguise an existing session as another staff without OpenAPI keys", async () => {
|
||||
const { corp, sign, save } = setup();
|
||||
delete corp.credentials.appKey;
|
||||
delete corp.credentials.appSecurity;
|
||||
await expect(getCorpProvisionalAuthLink(corp, { staffId: "corp:B" })).rejects.toThrow("需要已配置的 OpenAPI");
|
||||
expect(sign).not.toHaveBeenCalled();
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -424,6 +424,10 @@ export async function getCorpProvisionalAuthLink(
|
||||
const targetStaffId = options.staffId || corp.staffId || corp.credentials.staffId;
|
||||
const targetStaffName = options.staffName || (options.staffId ? undefined : corp.staffName || corp.session?.staffName);
|
||||
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
|
||||
const syncLocalSession = options.syncLocalSession !== false && (!options.staffId || options.persistStaff === true);
|
||||
if (options.staffId && !hasOpenApiPersistentCredentials(corp)) {
|
||||
throw new AuthenticationError("切换员工签发链接需要已配置的 OpenAPI 持久化密钥,现有会话不能代表其他员工。");
|
||||
}
|
||||
|
||||
// 1. 若尚未配置 appKey/appSecurity,先确保会话有效并尝试自动提权提取密钥
|
||||
if (!hasOpenApiPersistentCredentials(corp)) {
|
||||
@@ -455,21 +459,26 @@ export async function getCorpProvisionalAuthLink(
|
||||
pageType,
|
||||
});
|
||||
|
||||
if (options.syncLocalSession !== false) {
|
||||
corp.credentials.accessToken = provisional.token;
|
||||
if (!corp.auth) corp.auth = { refreshTtl: 300 };
|
||||
corp.auth.expiresAt = provisional.expiresAt;
|
||||
if (corp.session) {
|
||||
corp.session.expTime = provisional.expiresAt;
|
||||
const normalizedStaffId = targetStaffId.includes(":") ? targetStaffId : `${corpId}:${targetStaffId}`;
|
||||
if (provisional.uid !== normalizedStaffId) {
|
||||
throw new AuthenticationError("免密链接签发身份与目标员工不一致,未更新本地会话。");
|
||||
}
|
||||
if (syncLocalSession) {
|
||||
const updated = structuredClone(corp);
|
||||
updated.credentials.accessToken = provisional.token;
|
||||
if (!updated.auth) updated.auth = { refreshTtl: 300 };
|
||||
updated.auth.expiresAt = provisional.expiresAt;
|
||||
if (updated.session) {
|
||||
updated.session.expTime = provisional.expiresAt;
|
||||
}
|
||||
if (options.persistStaff && options.staffId) {
|
||||
corp.staffId = options.staffId;
|
||||
corp.credentials.staffId = options.staffId;
|
||||
if (options.staffName) {
|
||||
corp.staffName = options.staffName;
|
||||
}
|
||||
updated.staffId = normalizedStaffId;
|
||||
updated.credentials.staffId = normalizedStaffId;
|
||||
updated.staffName = options.staffName;
|
||||
if (updated.session) updated.session.staffName = options.staffName;
|
||||
}
|
||||
saveCorpConfig(corp, options.enterprisesDir);
|
||||
saveCorpConfig(updated, options.enterprisesDir);
|
||||
Object.assign(corp, updated);
|
||||
invalidateCorpSubdomainTokenCaches(corp);
|
||||
}
|
||||
|
||||
@@ -477,7 +486,7 @@ export async function getCorpProvisionalAuthLink(
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
staffId: provisional.uid || targetStaffId,
|
||||
staffName: targetStaffName || corp.staffName || corp.session?.staffName || undefined,
|
||||
staffName: targetStaffName ?? undefined,
|
||||
url: provisional.url,
|
||||
token: provisional.token,
|
||||
expiresIn: provisional.expiresIn,
|
||||
@@ -504,7 +513,7 @@ export async function getCorpProvisionalAuthLink(
|
||||
);
|
||||
}
|
||||
|
||||
if (explicitDuration !== undefined && options.syncLocalSession !== false) {
|
||||
if (explicitDuration !== undefined && syncLocalSession) {
|
||||
if (!corp.auth) corp.auth = { refreshTtl: 300 };
|
||||
corp.auth.expiresAt = expMs;
|
||||
if (corp.session) {
|
||||
|
||||
@@ -45,7 +45,7 @@ src/domains/bill/
|
||||
- 跨 `backlogs/search`、`flows/my`、`flows/approved`、`carbonCopy/search` 与 `backlogs/id` 多通道穿透检索单据流程实例;
|
||||
- 智能提取单据金额、提报人、提报时间、归属部门、当前驻留节点与待办审批人列表;
|
||||
- 内置待办根因诊断引擎,智能判定流转阶段(`DRAFT`、`APPROVING`、`PAYING`、`PAID`、`REJECTED`):
|
||||
- 识别“待出纳支付/打款”节点(如 `PAYING` 或节点名包含“打款/出纳/支付”),精准提示不可审批及自动化工作流调用报错 400(无待办审批事项)的根本原因与排障建议;
|
||||
- 按实际流程状态(如 `PAYING`)和节点类型判断支付阶段,显示名称不参与阶段判定;流程状态优先于 backlog 状态。缺少当前身份的实际待办证据时,`diagnostic.canApprove` 为 `null`,CLI 显示“未知”,节点配置中的审批人不构成权限保证;
|
||||
- 结构化还原流转时间线轨迹(Timeline),自动标记 Ebot 智能审批与自动跳过节点。
|
||||
|
||||
CLI 入口为 `hose-use bill approve|reject|transfer|add-node|comment <单号|ID>`,以及 `hose-use flow [get|trace] <单号|ID>` / `hose-use bill trace <单号|ID>`。所有会改变状态的动作都要求 `--yes`(交互终端未提供时会拒绝执行);转交和加签的 `--approver-id` 支持完整员工 ID、工号或唯一姓名匹配,驳回强制要求 `--comment`。
|
||||
@@ -772,7 +772,7 @@ describe("Bill Domain", () => {
|
||||
expect(report.pendingApprovers).toHaveLength(1);
|
||||
expect(report.pendingApprovers[0].name).toBe("李主管");
|
||||
expect(report.diagnostic.stage).toBe("APPROVING");
|
||||
expect(report.diagnostic.canApprove).toBe(true);
|
||||
expect(report.diagnostic.canApprove).toBeNull();
|
||||
expect(report.diagnostic.summary).toContain("待办审批人: 李主管");
|
||||
expect(report.timeline).toHaveLength(1);
|
||||
expect(report.timeline[0].action).toBe("SUBMIT");
|
||||
@@ -824,6 +824,17 @@ describe("Bill Domain", () => {
|
||||
expect(report.timeline[0].automatic).toBe(true);
|
||||
});
|
||||
|
||||
for (const nodeName of ["出纳审批", "支付复核", "普通审批"]) {
|
||||
it(`uses actual state instead of the display name: ${nodeName}`, async () => {
|
||||
const raw = { id: "backlog", state: "APPROVING", nodeName, flowId: { id: "flow", state: "APPROVING", form: {}, plan: { nextNodeId: "node", nodes: [{ id: "node", name: nodeName, type: "APPROVAL", approverId: "staff" }] } } };
|
||||
const client = { post: async () => new Response(JSON.stringify({ value: raw })) } as any;
|
||||
const result = await traceBillFlowDetail(client, "corp", "ID01-record");
|
||||
expect(result.diagnostic.stage).toBe("APPROVING");
|
||||
expect(result.diagnostic.canApprove).toBeNull();
|
||||
expect(result.diagnostic.advice).toContain("实际待办");
|
||||
});
|
||||
}
|
||||
|
||||
it("单据不存在时返回友好未找到诊断报告", async () => {
|
||||
const client = {
|
||||
post: async () => new Response(JSON.stringify({ items: [] })),
|
||||
|
||||
+10
-10
@@ -964,14 +964,14 @@ export async function getBillFlow(
|
||||
|
||||
function resolveFlowStage(
|
||||
rawState: string,
|
||||
nodeName?: string
|
||||
nodeType?: string
|
||||
): "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN" {
|
||||
const s = rawState.toUpperCase();
|
||||
const n = (nodeName || "").toLowerCase();
|
||||
const n = (nodeType || "").toUpperCase();
|
||||
|
||||
if (s.includes("REJECT") || s === "TERMINATED") return "REJECTED";
|
||||
if (s === "PAID" || s === "COMPLETED" || s === "PROCESSED") return "PAID";
|
||||
if (s.includes("PAY") || n.includes("打款") || n.includes("出纳") || n.includes("支付")) return "PAYING";
|
||||
if (s.includes("PAY") || ["PAYMENT", "PAY", "CASHIER"].includes(n)) return "PAYING";
|
||||
if (s.includes("APPROV") || s === "PENDING" || s === "SENDING") return "APPROVING";
|
||||
if (s.includes("DRAFT")) return "DRAFT";
|
||||
return "UNKNOWN";
|
||||
@@ -983,7 +983,7 @@ function buildDiagnosticReport(
|
||||
currentNodeName?: string,
|
||||
pendingApprovers: { id?: string; name?: string; code?: string }[] = []
|
||||
): {
|
||||
canApprove: boolean;
|
||||
canApprove: boolean | null;
|
||||
stage: "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN";
|
||||
stageLabel: string;
|
||||
summary: string;
|
||||
@@ -998,15 +998,15 @@ function buildDiagnosticReport(
|
||||
stage,
|
||||
stageLabel: "待支付 / 出纳打款",
|
||||
summary: `单据已通过全部分级审批流转,当前停留在【${currentNodeName || "出纳打款"}】环节`,
|
||||
advice: "该单据当前无待办审批任务,若调用自动审批接口必报 400(无待办审批事项)。出纳打款后单据即闭环;若属于自动化打款流水,请检查工作流触发器是否误推了待支付单据,建议增加条件【审批状态 等于 APPROVING】进行拦截。",
|
||||
advice: "流程处于支付环节。请先核对实际待办与操作权限;无待办时调用审批接口可能返回 400。若工作流误触发支付阶段单据,请核对触发条件与流程状态。",
|
||||
};
|
||||
case "APPROVING":
|
||||
return {
|
||||
canApprove: true,
|
||||
canApprove: null,
|
||||
stage,
|
||||
stageLabel: "审批中 (待办审批)",
|
||||
summary: `单据当前停留在【${currentNodeName || "审批"}】节点${approverNames ? `,待办审批人: ${approverNames}` : ""}`,
|
||||
advice: "单据处于正常待办审批状态,当前待办人员或工作流自动化可正常执行同意 (agree) 或驳回 (reject) 操作。",
|
||||
advice: "单据处于审批阶段;所列人员来自当前节点配置。执行同意或驳回前,仍需核对当前身份的实际待办与审批权限。",
|
||||
};
|
||||
case "REJECTED":
|
||||
return {
|
||||
@@ -1034,7 +1034,7 @@ function buildDiagnosticReport(
|
||||
};
|
||||
default:
|
||||
return {
|
||||
canApprove: false,
|
||||
canApprove: null,
|
||||
stage,
|
||||
stageLabel: rawState || "未知状态",
|
||||
summary: `单据当前处于状态: ${rawState || "未知"}`,
|
||||
@@ -1125,7 +1125,7 @@ export async function traceBillFlowDetail(
|
||||
const submitDate = typeof form.submitDate === "number" ? new Date(form.submitDate).toLocaleString("zh-CN", { hour12: false }) : undefined;
|
||||
|
||||
// 状态提取
|
||||
const rawState = String(rawFlow.state || flow.state || form.state || "").toUpperCase();
|
||||
const rawState = String(flow.state || rawFlow.state || form.state || "").toUpperCase();
|
||||
const stateLabel = translateBillFlowState(rawState);
|
||||
|
||||
// 当前驻留节点提取
|
||||
@@ -1163,7 +1163,7 @@ export async function traceBillFlowDetail(
|
||||
}
|
||||
|
||||
// 诊断规则引擎
|
||||
const stage = resolveFlowStage(rawState, currentNode?.name);
|
||||
const stage = resolveFlowStage(rawState, currentNode?.type);
|
||||
const diagnostic = buildDiagnosticReport(stage, rawState, currentNode?.name, pendingApprovers);
|
||||
|
||||
// 流转时间线
|
||||
|
||||
@@ -329,7 +329,8 @@ export interface BillFlowTraceDiagnostic {
|
||||
currentNode?: { id?: string; name?: string; type?: string };
|
||||
pendingApprovers: { id?: string; name?: string; code?: string }[];
|
||||
diagnostic: {
|
||||
canApprove: boolean;
|
||||
/** null means the current identity's actual approval task was not verified. */
|
||||
canApprove: boolean | null;
|
||||
stage: "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN";
|
||||
stageLabel: string;
|
||||
summary: string;
|
||||
|
||||
@@ -45,10 +45,14 @@ hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
||||
也可以使用 `datalink` / `data-link` 作为同义命令域。
|
||||
|
||||
- `records --ndjson`(或 `--stream`):针对万级~十万级海量记录,采用 AsyncGenerator 分页流式生成,逐行向 `stdout` 发射 NDJSON。内存恒定为 $O(\text{pageSize})$,严防大报文撑爆内存或终端,无缝对接下游 `jq`、Python 处理流水线。
|
||||
- 终端入口提供显式输出回调并等待写入完成以响应背压;`--ndjson -o <path>` 写入真正的 NDJSON 文件,返回文件路径、字节数和记录数摘要。
|
||||
- MCP / HTTP 默认不提供终端输出通道;未指定文件时拒绝直接流式输出,避免污染协议 stdout 或返回空的成功响应。输出逐行执行统一脱敏。
|
||||
- `records --stats`(或 `records stats <应用> <对象>` / `records profile`):宏观结构与特征聚类画像。输出总记录数、启用/停用分布及占比、唯一标题数与重名分布、编码生成规则聚类(自动提取 `${groupIndex}-${formCode}-month-${idx}` 等动态模板分布)、最早与最新维护时间,毫秒级洞察数据特征。
|
||||
- `records --flat`:自动剥离底层动态物理前缀(如 `E_<entityId>_`),提取关联引用对象的名称/编码,将复杂元数据规整为 `{ id, code, name, active, createTime, updateTime, fields }` 干净对象。
|
||||
- `records --sum="字段1,字段2" [--group-by="分组字段"]`:台账数学聚合核算,自动解析纯数值、金额对象(`{ standard: 100 }`)与货币符号字符串(`¥12,500.00`),输出样本数、总合计(SUM)、均值(AVG)、最小值(MIN)、最大值(MAX)以及指定字段的分组小计。
|
||||
- `records --where="条件"`:支持在客户端按字段中文标签或物理名做声明式组合过滤(支持 `==`, `!=`, `>`, `<`, `>=`, `<=`, `in (...)`, 以及 `&&` 联合条件)。
|
||||
- 条件在分页和写入前完整编译校验;无效语法、未知字段和歧义字段报 `ValidationError`,空结果也不会掩盖语法错误。字符串中的逗号和 `&&` 可用引号保护。
|
||||
- 归一化记录的 `fields` 支持按中文标签或原字段名选择,可组合 `--flat --fields` 或 `--ndjson --fields`。
|
||||
- `audit --check-continuous="序号字段"`:台账连续性体检,精准识别期数序号序列中的断层缺失(MISSING)与重号重复(DUPLICATE)。
|
||||
- `audit --expect="字段 ~= 期望值 [+- 容差]"`:基线数值离群诊断,自动识别并列出偏离基准值的异常记录明细与差额。
|
||||
- `record update <应用> <业务对象> [--where="条件"] --set="字段=值" [--dry-run] [--yes]`:声明式原地批量修改,支持中文字段标签解析与智能类型转换,通过 `--dry-run` 预览拟更新记录与合并后字段,追加 `--yes` 真正执行。
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
batchSafeEditRecords,
|
||||
buildKeywordFilter,
|
||||
calculateEntityRecordStats,
|
||||
compileRecordPredicate,
|
||||
fetchAllEntityRecords,
|
||||
filterRecordsByPredicate,
|
||||
iterateAllEntityRecords,
|
||||
@@ -26,6 +27,37 @@ import {
|
||||
selectRecordFields,
|
||||
} from "./services.js";
|
||||
|
||||
describe("record predicate and normalized projection regressions", () => {
|
||||
const entity = { id: "ent", name: "台账", fields: [
|
||||
{ name: "E_ent_seq", label: "序号", type: "number" },
|
||||
{ name: "E_ent_rent", label: "租金", type: "number" },
|
||||
{ name: "E_ent_note", label: "备注", type: "text" },
|
||||
{ name: "E_ent_name", label: "名称", type: "text" },
|
||||
] } as any;
|
||||
const records = [
|
||||
{ dataLink: { id: "r1", E_ent_seq: 1, E_ent_rent: 100, E_ent_note: "A,B && C", E_ent_name: "Name" } },
|
||||
{ dataLink: { id: "r2", E_ent_seq: 2, E_ent_rent: 200, E_ent_note: null } },
|
||||
];
|
||||
|
||||
for (const clause of ["序号 in [1]", "序号 == 1 &&", "不存在 != 1", "序号 === 1", "序号 in ()", "序号 > 1 || 序号 < 3", "备注 == 'broken", "序号 == 1&&garbage"]) {
|
||||
test(`rejects invalid predicate even with no records: ${clause}`, () => {
|
||||
expect(() => filterRecordsByPredicate([], clause, entity)).toThrow();
|
||||
});
|
||||
}
|
||||
test("validates unknown and ambiguous fields before evaluating records", () => {
|
||||
expect(() => compileRecordPredicate("租 == 1", { ...entity, fields: [...entity.fields, { name: "other", label: "租期", type: "number" }] })).toThrow("歧义");
|
||||
});
|
||||
test("honors quotes, commas and conjunctions inside values", () => {
|
||||
expect(filterRecordsByPredicate(records, "备注 in ('A,B && C','other')&&序号>=1", entity)).toEqual([records[0]]);
|
||||
expect(filterRecordsByPredicate(records, "备注 == null", entity)).toEqual([records[1]]);
|
||||
expect(filterRecordsByPredicate(records, "序号 in (1,2) && 租金 < 150", entity)).toEqual([records[0]]);
|
||||
});
|
||||
test("selects normalized business fields and system name by label or original field name", () => {
|
||||
const normalized = normalizeDatalinkRecord(records[0], entity);
|
||||
expect(selectRecordFields(normalized as any, ["租金", "E_ent_seq", "名称", "id"], entity.fields)).toEqual({ 租金: 100, 序号: 1, 名称: "Name", id: "r1" });
|
||||
});
|
||||
});
|
||||
|
||||
const platform = {
|
||||
id: "platform-1",
|
||||
name: "业务应用",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "./api.js";
|
||||
import { ValidationError } from "../../core/errors.js";
|
||||
import type {
|
||||
DatalinkEntity,
|
||||
DatalinkField,
|
||||
@@ -118,12 +119,22 @@ export function selectRecordFields(
|
||||
? (record.dataLink as Record<string, unknown>)
|
||||
: record;
|
||||
const selected: Record<string, unknown> = {};
|
||||
const normalizedFields = record.fields && typeof record.fields === "object" && !Array.isArray(record.fields)
|
||||
? record.fields as Record<string, unknown>
|
||||
: undefined;
|
||||
for (const selector of fields) {
|
||||
const definition = definitions.find(
|
||||
(field) => field.name === selector || field.label === selector
|
||||
);
|
||||
const sourceName = definition?.name ?? selector;
|
||||
if (sourceName in dataLink) selected[definition?.label || selector] = dataLink[sourceName];
|
||||
const label = definition?.label || selector;
|
||||
if (sourceName in dataLink) selected[label] = dataLink[sourceName];
|
||||
else if (normalizedFields && label in normalizedFields) selected[label] = normalizedFields[label];
|
||||
else if (normalizedFields && sourceName in normalizedFields) selected[label] = normalizedFields[sourceName];
|
||||
else if (normalizedFields) {
|
||||
const systemName = sourceName.replace(/^E_.+_/, "");
|
||||
if (["name", "code"].includes(systemName) && systemName in record) selected[label] = record[systemName];
|
||||
}
|
||||
}
|
||||
return record.dataLink && typeof record.dataLink === "object"
|
||||
? { ...record, dataLink: selected }
|
||||
@@ -1152,76 +1163,103 @@ export function auditLedgerContinuityAndBaseline(
|
||||
/**
|
||||
* 客户端声明式筛选器(支持 ==, !=, >, >=, <, <=, in (...) 以及 && 组合)
|
||||
*/
|
||||
function splitPredicateParts(source: string, separator: string): string[] {
|
||||
const parts: string[] = [];
|
||||
let quote = "", depth = 0, start = 0;
|
||||
for (let i = 0; i < source.length; i++) {
|
||||
const char = source[i];
|
||||
if (quote) {
|
||||
if (char === "\\") i++;
|
||||
else if (char === quote) quote = "";
|
||||
continue;
|
||||
}
|
||||
if (char === "'" || char === '"') quote = char;
|
||||
else if (char === "(") depth++;
|
||||
else if (char === ")") {
|
||||
if (--depth < 0) throw new ValidationError("筛选条件括号不匹配");
|
||||
} else if (depth === 0 && source.startsWith(separator, i)) {
|
||||
parts.push(source.slice(start, i).trim());
|
||||
start = i + separator.length;
|
||||
i += separator.length - 1;
|
||||
}
|
||||
}
|
||||
if (quote || depth !== 0) throw new ValidationError("筛选条件引号或括号不匹配");
|
||||
parts.push(source.slice(start).trim());
|
||||
if (parts.some(part => !part)) throw new ValidationError("筛选条件或列表值不能为空");
|
||||
return parts;
|
||||
}
|
||||
|
||||
function predicateLiteral(raw: string): string | number | boolean | null {
|
||||
if (/^(["']).*\1$/s.test(raw)) {
|
||||
const value = raw.slice(1, -1);
|
||||
if (raw[0] === '"') {
|
||||
try { return JSON.parse(raw); } catch { throw new ValidationError(`筛选值不是有效字符串: ${raw}`); }
|
||||
}
|
||||
if (/(?<!\\)'/.test(value)) throw new ValidationError(`筛选值引号不匹配: ${raw}`);
|
||||
return value.replace(/\\(['\\])/g, "$1");
|
||||
}
|
||||
if (raw === "null") return null;
|
||||
if (raw === "true" || raw === "false") return raw === "true";
|
||||
if (/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(raw) && Number.isFinite(Number(raw))) return Number(raw);
|
||||
if (/^[\p{L}\p{N}_:.$/-]+$/u.test(raw)) return raw;
|
||||
throw new ValidationError(`不支持的筛选值: ${raw};文本中的空格或符号请使用引号`);
|
||||
}
|
||||
|
||||
function predicateField(entity: DatalinkEntity, query: string): DatalinkField | string {
|
||||
const key = query.trim().toLowerCase();
|
||||
const candidates = entity.fields.filter(f =>
|
||||
f.name.toLowerCase() === key || f.label?.toLowerCase() === key ||
|
||||
f.name.toLowerCase() === `e_${entity.id.replace(/^\$/, "").toLowerCase()}_${key}`
|
||||
);
|
||||
if (!candidates.length && ["id", "recordId", "active", "name", "code", "createTime", "updateTime", "entityId"].includes(query)) return query;
|
||||
const matches = candidates.length ? candidates : entity.fields.filter(f => f.label?.toLowerCase().includes(key));
|
||||
if (matches.length > 1) throw new ValidationError(`筛选字段存在歧义: ${query},请使用完整字段名`);
|
||||
if (matches.length === 1) return matches[0];
|
||||
if (["id", "recordId", "active", "name", "code", "createTime", "updateTime", "entityId"].includes(query)) return query;
|
||||
throw new ValidationError(`未知筛选字段: ${query}`);
|
||||
}
|
||||
|
||||
/** 先完整校验语法和字段,再生成可复用的筛选器,空结果集也不能掩盖错误。 */
|
||||
export function compileRecordPredicate(whereClause: string, entity: DatalinkEntity): (record: DatalinkRecord) => boolean {
|
||||
const conditions = splitPredicateParts(whereClause, "&&").map(cond => {
|
||||
// 1. in 操作符: field in (v1, v2, v3)
|
||||
const inMatch = cond.match(/^(.+?)\s+in\s*\((.*)\)$/i);
|
||||
// 2. 比较操作符: ==, !=, >=, <=, >, <, =
|
||||
const compMatch = inMatch ? null : cond.match(/^(.+?)\s*(==|!=|>=|<=|>|<|=)\s*(.+)$/s);
|
||||
if (!inMatch && !compMatch) throw new ValidationError(`不支持的筛选条件: ${cond}`);
|
||||
const field = predicateField(entity, (inMatch ?? compMatch)![1].trim());
|
||||
const op = inMatch ? "in" : compMatch![2];
|
||||
const targets = inMatch
|
||||
? splitPredicateParts(inMatch[2], ",").map(predicateLiteral)
|
||||
: [predicateLiteral(compMatch![3].trim())];
|
||||
return (record: DatalinkRecord) => {
|
||||
const actual = extractRecordFieldValue(record, field);
|
||||
const equal = (target: string | number | boolean | null): boolean => {
|
||||
if (target === null) return actual === null || actual === undefined;
|
||||
if (typeof target === "number") return extractNumericFieldValue(record, field) === target;
|
||||
return actual !== null && actual !== undefined && String(actual) === String(target);
|
||||
};
|
||||
if (op === "in") return targets.some(equal);
|
||||
// 字符串/布尔比较
|
||||
if (op === "=" || op === "==") return equal(targets[0]);
|
||||
if (op === "!=") return !equal(targets[0]);
|
||||
// 数值比较
|
||||
const value = extractNumericFieldValue(record, field);
|
||||
const target = targets[0];
|
||||
if (value === null || typeof target !== "number") return false;
|
||||
return op === ">" ? value > target : op === ">=" ? value >= target : op === "<" ? value < target : value <= target;
|
||||
};
|
||||
});
|
||||
return record => conditions.every(condition => condition(record));
|
||||
}
|
||||
|
||||
export function filterRecordsByPredicate(
|
||||
records: DatalinkRecord[],
|
||||
whereClause: string,
|
||||
entity: DatalinkEntity
|
||||
): DatalinkRecord[] {
|
||||
if (!whereClause || !whereClause.trim()) return records;
|
||||
|
||||
const conditions = whereClause
|
||||
.split(/\s+&&\s+/)
|
||||
.map((c) => c.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
return records.filter((r) => {
|
||||
return conditions.every((cond) => {
|
||||
// 1. in 操作符: field in (v1, v2, v3)
|
||||
const inMatch = cond.match(/^(.+?)\s+in\s*\((.+?)\)$/i);
|
||||
if (inMatch) {
|
||||
const fieldKey = inMatch[1].trim();
|
||||
const rawValues = inMatch[2]
|
||||
.split(",")
|
||||
.map((v) => v.trim().replace(/^['"]|['"]$/g, ""));
|
||||
const actualVal = String(extractRecordFieldValue(r, resolveEntityField(entity, fieldKey) ?? fieldKey) ?? "");
|
||||
return rawValues.some((v) => v === actualVal);
|
||||
}
|
||||
|
||||
// 2. 比较操作符: ==, !=, >=, <=, >, <, =
|
||||
const compMatch = cond.match(/^(.+?)\s*(==|!=|>=|<=|>|<|=)\s*(.+)$/);
|
||||
if (compMatch) {
|
||||
const fieldKey = compMatch[1].trim();
|
||||
const op = compMatch[2];
|
||||
const rawTarget = compMatch[3].trim().replace(/^['"]|['"]$/g, "");
|
||||
const actualRaw = extractRecordFieldValue(r, resolveEntityField(entity, fieldKey) ?? fieldKey);
|
||||
|
||||
// 数值比较
|
||||
const actualNum = extractNumericFieldValue(r, resolveEntityField(entity, fieldKey) ?? fieldKey);
|
||||
const targetNum = Number(rawTarget);
|
||||
if (actualNum !== null && !Number.isNaN(targetNum)) {
|
||||
switch (op) {
|
||||
case "==":
|
||||
case "=":
|
||||
return actualNum === targetNum;
|
||||
case "!=":
|
||||
return actualNum !== targetNum;
|
||||
case ">":
|
||||
return actualNum > targetNum;
|
||||
case ">=":
|
||||
return actualNum >= targetNum;
|
||||
case "<":
|
||||
return actualNum < targetNum;
|
||||
case "<=":
|
||||
return actualNum <= targetNum;
|
||||
}
|
||||
}
|
||||
|
||||
// 字符串/布尔比较
|
||||
const actualStr = String(actualRaw ?? "");
|
||||
switch (op) {
|
||||
case "==":
|
||||
case "=":
|
||||
return actualStr === rawTarget;
|
||||
case "!=":
|
||||
return actualStr !== rawTarget;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
});
|
||||
return records.filter(compileRecordPredicate(whereClause, entity));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -22,8 +22,8 @@ hose-use workflow logs <pipelineId> [--has-error] [--state=FAILED]
|
||||
hose-use workflow job <jobId> [--failed] [--node=<name|id>] [--verbose]
|
||||
hose-use workflow diff <snapshotId1> <snapshotId2> [--pipelineId=<id>]
|
||||
hose-use workflow diff-job <jobId1> <jobId2> [--json]
|
||||
hose-use workflow test <pipelineId> [--flow=<单号>] [--record=<ID>] [--body='{...}']
|
||||
hose-use workflow debug <pipelineId> --flow=<单号>
|
||||
hose-use workflow test <pipelineId> [--flow=<单号>] [--record=<ID>] [--body='{...}'] [--dry-run|--yes]
|
||||
hose-use workflow debug <pipelineId> --flow=<单号> --yes
|
||||
```
|
||||
|
||||
## 触发器分类与调测路径分支 (Path Branching)
|
||||
@@ -32,7 +32,7 @@ hose-use workflow debug <pipelineId> --flow=<单号>
|
||||
|
||||
| 触发器分类 (`category`) | 常见触发器类型 (`type`) | 调测协议与入参 | CLI 命令与交互行为 |
|
||||
|---|---|---|---|
|
||||
| **`SCHEDULE`** (定时调度) | `clock` | 服务端无 `debugSource`,`inputs: { id: "" }` | **自动模拟触发**:无需 `--flow`,直接秒级派发并抓取执行树 |
|
||||
| **`SCHEDULE`** (定时调度) | `clock` | 服务端无 `debugSource`,`inputs: { id: "" }` | **自动模拟触发**:无需 `--flow`,经 `--yes` 确认后派发并抓取执行树 |
|
||||
| **`WEBHOOK`** (外部集成) | `webhook`, `hab-trigger-task` | 服务端无 `debugSource`,`inputs: { data: { ... } }` | **Payload 注入**:支持 `--body='{...}'` / `--file=event.json` / `--empty` |
|
||||
| **`DATALINK`** (业务对象台账) | `ekuaibao-datalink-*-trigger` | 服务端返回 `fields` 动态列定义与台账记录 | **动态列展示**:按实体结构动态打表,支持 `--record=<ID>` 或 `--flow=<编码>` |
|
||||
| **`FLOW_FORM`** (单据流转) | `ekuaibao-flowform-trigger`, `ekuaibao-ebot-trigger` | 服务端返回单据列表与表单定义 | **单据列表与筛选**:支持 `--flow=<单号>`,未提供时拉取候选单据表供挑选 |
|
||||
@@ -58,3 +58,13 @@ hose-use workflow debug <pipelineId> --flow=<单号>
|
||||
完整接口说明、认证链路、MCP tool 列表见:
|
||||
|
||||
[docs/modules/platform.md](../../../docs/modules/platform.md)
|
||||
|
||||
## 调试与诊断结果契约
|
||||
|
||||
- 调试属于写操作:`--dry-run` 仅展示目标、发布选项和风险,不创建客户端或发起 Job;实际执行需要 `--yes` / `--confirm`。启用中的工作流仍可在确认后直接调试。
|
||||
- JSON 和预览均包含风险信息。执行结果提供 `productionEnabled`(状态未知时为 `null`)和 `warnings`。
|
||||
- `outcome` 为 `completed`、`failed`、`timed_out` 或 `incomplete`;只有完整成功才返回退出码 `0`。超时不取消已经发起的 Job,保留 `jobId` 以供 `workflow job` 续查。
|
||||
- `timedOut`、`diagnosticsComplete`、`diagnosticsErrors` 区分执行超时、读取失败与没有失败节点;权限错误不再被当成空的成功结果。
|
||||
- 条件解释支持已声明的比较操作符、嵌套 AND/OR 和循环上下文;缺少证据、不支持的值类型或执行尚未结束时,`evaluation` / `matched` 为 `null`,不据此声称分支判定为 False。
|
||||
- `diff-job` 按父任务路径、循环路径及重复次数配对实例;JSON 节点包含 `instanceKey` / `currentLoopPath`,输出变化也计入差异。
|
||||
- `execution-context.ts` 是条件解释和 Job diff 共用的纯执行实例索引,不负责请求或 CLI 输出。
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { WorkflowTaskExecution } from "./types.js";
|
||||
|
||||
export interface ExecutionContext {
|
||||
node: WorkflowTaskExecution;
|
||||
key: string;
|
||||
scope: string[];
|
||||
loopPath: string;
|
||||
}
|
||||
|
||||
/** Index real executions by parent task path, loop context and repeated occurrence. */
|
||||
export function indexExecutionContexts(tree: WorkflowTaskExecution[]): ExecutionContext[] {
|
||||
const result: ExecutionContext[] = [];
|
||||
const entries = new Map<string, { node: WorkflowTaskExecution; parentId?: string }>();
|
||||
const occurrences = new Map<string, number>();
|
||||
function collect(node: WorkflowTaskExecution, parentId?: string) {
|
||||
if (!node || !node.id || entries.has(node.id)) return;
|
||||
entries.set(node.id, { node, parentId: String(node.parentId || parentId || "") || undefined });
|
||||
for (const key of ["children", "subTasks", "items", "tasks"]) {
|
||||
const children = node[key];
|
||||
if (Array.isArray(children)) for (const child of children) collect(child, node.id);
|
||||
}
|
||||
}
|
||||
for (const node of tree) collect(node);
|
||||
const scopes = new Map<string, { parts: string[]; loopPath: string }>();
|
||||
function scopeOf(id: string, visited = new Set<string>()): { parts: string[]; loopPath: string } {
|
||||
const cached = scopes.get(id);
|
||||
if (cached) return cached;
|
||||
const entry = entries.get(id);
|
||||
if (!entry || visited.has(id)) return { parts: [JSON.stringify(["unresolved-parent", id])], loopPath: "" };
|
||||
visited.add(id);
|
||||
const parent = entry.parentId ? scopeOf(entry.parentId, visited) : { parts: [], loopPath: "" };
|
||||
const loopPath = String(entry.node.currentLoopPath ?? parent.loopPath);
|
||||
const scope = { parts: [...parent.parts, JSON.stringify([entry.node.name || entry.node.type || "unnamed", loopPath])], loopPath };
|
||||
scopes.set(id, scope);
|
||||
return scope;
|
||||
}
|
||||
for (const { node } of entries.values()) {
|
||||
const { parts, loopPath } = scopeOf(node.id);
|
||||
const base = JSON.stringify(parts);
|
||||
const occurrence = occurrences.get(base) ?? 0;
|
||||
occurrences.set(base, occurrence + 1);
|
||||
result.push({ node, key: `${base}#${occurrence}`, scope: parts.slice(0, -1), loopPath });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { diffWorkflowJobs } from "./services.js";
|
||||
import type { WorkflowJobDetail, WorkflowTaskExecution } from "./types.js";
|
||||
|
||||
const job = { id: "job", status: "COMPLETED" } as WorkflowJobDetail;
|
||||
const node = (id: string, loop: string, status = "COMPLETED", value = 1): WorkflowTaskExecution => ({ id, name: "edit", type: "code", status, currentLoopPath: loop, inputs: { value } });
|
||||
|
||||
describe("workflow diff execution identities", () => {
|
||||
it("compares every loop instance rather than only the first task name", () => {
|
||||
const result = diffWorkflowJobs(job, [node("a0", "0"), node("a1", "1", "FAILED", 2)], job, [node("b0", "0"), node("b1", "1", "COMPLETED", 3)]);
|
||||
expect(result.nodes).toHaveLength(2);
|
||||
expect(result.summary.divergedNodesCount).toBe(1);
|
||||
expect(result.summary.statusDiffCount).toBe(1);
|
||||
expect(result.nodes.find(n => n.diverged)?.currentLoopPath).toBe("1");
|
||||
});
|
||||
it("preserves repeated attempts and identifies missing instances", () => {
|
||||
const result = diffWorkflowJobs(job, [node("a0", "0"), node("a1", "0", "FAILED")], job, [node("b0", "0")]);
|
||||
expect(result.nodes).toHaveLength(2);
|
||||
expect(result.summary.divergedNodesCount).toBe(1);
|
||||
});
|
||||
it("uses the parent task path when repeated names occur in different branches", () => {
|
||||
const tree = (prefix: string, value: number): WorkflowTaskExecution[] => [
|
||||
{ id: prefix + "left", name: "left", type: "condition", status: "COMPLETED", children: [node(prefix + "a", "0")] },
|
||||
{ id: prefix + "right", name: "right", type: "condition", status: "COMPLETED", children: [node(prefix + "b", "0", "COMPLETED", value)] },
|
||||
];
|
||||
const result = diffWorkflowJobs(job, tree("a", 1), job, tree("b", 2));
|
||||
expect(result.nodes).toHaveLength(4);
|
||||
expect(result.summary.divergedNodesCount).toBe(1);
|
||||
});
|
||||
it("counts output-only changes, including the singular output wire format", () => {
|
||||
const result = diffWorkflowJobs(job, [{ ...node("a", "0"), output: { value: 1 } }], job, [{ ...node("b", "0"), output: { value: 2 } }]);
|
||||
expect(result.summary.divergedNodesCount).toBe(1);
|
||||
expect(result.nodes[0]?.outputsDiff).toEqual([{ field: "value", from: 1, to: 2 }]);
|
||||
});
|
||||
it("resolves flat parentId relationships even when siblings change order", () => {
|
||||
const tree = (prefix: string, reversed: boolean): WorkflowTaskExecution[] => {
|
||||
const children = [
|
||||
{ ...node(prefix + "childA", "0", "COMPLETED", 1), parentId: prefix + "left" },
|
||||
{ ...node(prefix + "childB", "0", "COMPLETED", 2), parentId: prefix + "right" },
|
||||
];
|
||||
return [...(reversed ? children.reverse() : children), { id: prefix + "left", name: "left", type: "condition", status: "COMPLETED" }, { id: prefix + "right", name: "right", type: "condition", status: "COMPLETED" }];
|
||||
};
|
||||
const result = diffWorkflowJobs(job, tree("a", false), job, tree("b", true));
|
||||
expect(result.summary.divergedNodesCount).toBe(0);
|
||||
expect(result.nodes).toHaveLength(4);
|
||||
});
|
||||
it("does not discard scalar output changes", () => {
|
||||
const result = diffWorkflowJobs(job, [{ ...node("a", "0"), output: 1 }], job, [{ ...node("b", "0"), output: 2 }]);
|
||||
expect(result.summary.divergedNodesCount).toBe(1);
|
||||
expect(result.nodes[0]?.outputsDiff).toEqual([{ field: "$value", from: 1, to: 2 }]);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,9 @@
|
||||
import { KyInstance } from "ky";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import * as api from "./api.js";
|
||||
import { ValidationError } from "../../core/errors.js";
|
||||
import { explainConditionBranches } from "./workflow-branch.js";
|
||||
import { indexExecutionContexts } from "./execution-context.js";
|
||||
import {
|
||||
Platform,
|
||||
WorkflowSummary,
|
||||
@@ -547,23 +549,22 @@ export function diffWorkflowJobs(
|
||||
jobB: WorkflowJobDetail,
|
||||
treeB: WorkflowTaskExecution[]
|
||||
): WorkflowJobDiff {
|
||||
const flatA = flattenExecutionTree(treeA);
|
||||
const flatB = flattenExecutionTree(treeB);
|
||||
|
||||
const allNames = Array.from(
|
||||
new Set([
|
||||
...flatA.map((n) => n.name).filter(Boolean),
|
||||
...flatB.map((n) => n.name).filter(Boolean),
|
||||
])
|
||||
) as string[];
|
||||
const flatA = indexExecutionContexts(treeA);
|
||||
const flatB = indexExecutionContexts(treeB);
|
||||
const byKeyA = new Map(flatA.map(context => [context.key, context]));
|
||||
const byKeyB = new Map(flatB.map(context => [context.key, context]));
|
||||
const allKeys = new Set([...byKeyA.keys(), ...byKeyB.keys()]);
|
||||
|
||||
const nodes: NodeExecutionDiff[] = [];
|
||||
let divergedNodesCount = 0;
|
||||
let statusDiffCount = 0;
|
||||
|
||||
for (const name of allNames) {
|
||||
const nodeA = flatA.find((n) => n.name === name);
|
||||
const nodeB = flatB.find((n) => n.name === name);
|
||||
for (const key of allKeys) {
|
||||
const contextA = byKeyA.get(key);
|
||||
const contextB = byKeyB.get(key);
|
||||
const nodeA = contextA?.node;
|
||||
const nodeB = contextB?.node;
|
||||
const name = nodeB?.name || nodeA?.name || nodeB?.type || nodeA?.type || "unnamed";
|
||||
|
||||
const statusA = nodeA?.status;
|
||||
const statusB = nodeB?.status;
|
||||
@@ -572,8 +573,9 @@ export function diffWorkflowJobs(
|
||||
|
||||
// 比较 inputs
|
||||
const inputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = [];
|
||||
const inA = (nodeA?.inputs as Record<string, unknown>) || {};
|
||||
const inB = (nodeB?.inputs as Record<string, unknown>) || {};
|
||||
const payloadFields = (value: unknown): Record<string, unknown> => value === undefined ? {} : value !== null && typeof value === "object" ? value as Record<string, unknown> : { $value: value };
|
||||
const inA = payloadFields(nodeA?.inputs);
|
||||
const inB = payloadFields(nodeB?.inputs);
|
||||
const inputKeys = Array.from(new Set([...Object.keys(inA), ...Object.keys(inB)]));
|
||||
for (const k of inputKeys) {
|
||||
if (JSON.stringify(inA[k]) !== JSON.stringify(inB[k])) {
|
||||
@@ -583,8 +585,8 @@ export function diffWorkflowJobs(
|
||||
|
||||
// 比较 outputs
|
||||
const outputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = [];
|
||||
const outA = (nodeA?.outputs as Record<string, unknown>) || {};
|
||||
const outB = (nodeB?.outputs as Record<string, unknown>) || {};
|
||||
const outA = payloadFields(nodeA?.outputs ?? nodeA?.output);
|
||||
const outB = payloadFields(nodeB?.outputs ?? nodeB?.output);
|
||||
const outputKeys = Array.from(new Set([...Object.keys(outA), ...Object.keys(outB)]));
|
||||
for (const k of outputKeys) {
|
||||
if (JSON.stringify(outA[k]) !== JSON.stringify(outB[k])) {
|
||||
@@ -596,13 +598,15 @@ export function diffWorkflowJobs(
|
||||
!nodeA ||
|
||||
!nodeB ||
|
||||
isStatusDiff ||
|
||||
Boolean(nodeB.error && !nodeA.error) ||
|
||||
inputsDiff.length > 0;
|
||||
JSON.stringify(nodeA.error) !== JSON.stringify(nodeB.error) ||
|
||||
inputsDiff.length > 0 || outputsDiff.length > 0;
|
||||
|
||||
if (isDiverged) divergedNodesCount++;
|
||||
|
||||
nodes.push({
|
||||
taskName: name,
|
||||
instanceKey: key,
|
||||
currentLoopPath: contextB?.loopPath || contextA?.loopPath || undefined,
|
||||
displayName: (nodeB?.displayName || nodeA?.displayName || nodeB?.label || nodeA?.label) ?? undefined,
|
||||
type: nodeB?.type || nodeA?.type,
|
||||
statusA,
|
||||
@@ -668,6 +672,9 @@ export async function runWorkflowDebugTest(
|
||||
pollIntervalMs?: number;
|
||||
} = {}
|
||||
): Promise<import("./types.js").WorkflowTestReport> {
|
||||
if (!Number.isFinite(options.timeoutMs ?? 15000) || (options.timeoutMs ?? 15000) < 0 || !Number.isFinite(options.pollIntervalMs ?? 500) || (options.pollIntervalMs ?? 500) <= 0) {
|
||||
throw new ValidationError("timeoutMs 必须为非负数,pollIntervalMs 必须为正数");
|
||||
}
|
||||
let targetEntityId = options.flowCodeOrId ?? "";
|
||||
const code = options.flowCodeOrId;
|
||||
const isDirectCode = !code || code.includes("-") || code.startsWith("ID01");
|
||||
@@ -698,47 +705,65 @@ export async function runWorkflowDebugTest(
|
||||
const timeoutMs = options.timeoutMs ?? 15000;
|
||||
const pollIntervalMs = options.pollIntervalMs ?? 500;
|
||||
const start = Date.now();
|
||||
|
||||
let finalJob: import("./types.js").WorkflowJobDetail | undefined;
|
||||
const diagnosticsErrors: Array<{ source: string; message: string }> = [];
|
||||
const recordError = (source: string, error: unknown) => diagnosticsErrors.push({ source, message: error instanceof Error ? error.message : String(error) });
|
||||
const terminal = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]);
|
||||
const jobState = (job?: WorkflowJobDetail) => String(job?.status || job?.state || "UNKNOWN").toUpperCase();
|
||||
let finalJob: WorkflowJobDetail | undefined;
|
||||
let pollingFailed = false;
|
||||
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
try {
|
||||
const job = await api.getJob(client, jobId);
|
||||
const state = (job.status || (job as any).state || "").toUpperCase();
|
||||
if (state === "COMPLETED" || state === "FAILED" || state === "STOP") {
|
||||
finalJob = job;
|
||||
finalJob = job;
|
||||
if (terminal.has(jobState(job))) break;
|
||||
} catch (error) {
|
||||
// 任务刚创建可能存在短延时,继续轮询
|
||||
const status = (error as { status?: number; response?: { status?: number } } | null)?.status
|
||||
?? (error as { response?: { status?: number } } | null)?.response?.status;
|
||||
if (status !== 404) {
|
||||
recordError("job", error);
|
||||
pollingFailed = true;
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
// 任务刚创建可能存在短延时,继续轮询
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
||||
await new Promise((resolve) => setTimeout(resolve, Math.min(pollIntervalMs, Math.max(0, timeoutMs - (Date.now() - start)))));
|
||||
}
|
||||
|
||||
if (!finalJob) {
|
||||
finalJob = await api.getJob(client, jobId);
|
||||
if (!finalJob && !pollingFailed) {
|
||||
try { finalJob = await api.getJob(client, jobId); }
|
||||
catch (error) { recordError("job", error); pollingFailed = true; }
|
||||
}
|
||||
|
||||
const [tree, failedPage] = await Promise.all([
|
||||
api.getJobExecutionTree(client, jobId).catch(() => []),
|
||||
api.getJobFailedExecutions(client, jobId).catch(() => ({
|
||||
number: 1,
|
||||
size: 100,
|
||||
totalPages: 0,
|
||||
totalItems: 0,
|
||||
items: [],
|
||||
})),
|
||||
const timedOut = !pollingFailed && !terminal.has(jobState(finalJob));
|
||||
const [treeResult, failuresResult] = await Promise.allSettled([
|
||||
api.getJobExecutionTree(client, jobId),
|
||||
api.getJobFailedExecutions(client, jobId),
|
||||
]);
|
||||
const tree = treeResult.status === "fulfilled" ? treeResult.value : [];
|
||||
const failedItems = failuresResult.status === "fulfilled" ? failuresResult.value.items : [];
|
||||
if (treeResult.status === "rejected") recordError("executionTree", treeResult.reason);
|
||||
if (failuresResult.status === "rejected") recordError("failedExecutions", failuresResult.reason);
|
||||
|
||||
const rawFailed = extractFailureExecutions(tree, failedPage.items);
|
||||
const rawFailed = extractFailureExecutions(tree, failedItems);
|
||||
const diagnosticsComplete = diagnosticsErrors.length === 0;
|
||||
const status = jobState(finalJob);
|
||||
const hasExecutionError = rawFailed.length > 0 || finalJob?.hasError === true || Number(finalJob?.errorTaskCount ?? 0) > 0;
|
||||
let outcome: import("./types.js").WorkflowTestReport["outcome"] = "incomplete";
|
||||
if (timedOut) outcome = "timed_out";
|
||||
else if (terminal.has(status) && (status !== "COMPLETED" || hasExecutionError)) outcome = "failed";
|
||||
else if (status === "COMPLETED" && diagnosticsComplete) outcome = "completed";
|
||||
const conditionDiagnoses = explainConditionBranches(tree);
|
||||
|
||||
return {
|
||||
jobId,
|
||||
pipelineId,
|
||||
status: finalJob.status || (finalJob as any).state || "UNKNOWN",
|
||||
runType: finalJob.runType || "DEBUG",
|
||||
durationTime: typeof (finalJob as any).durationTime === "number" ? (finalJob as any).durationTime : undefined,
|
||||
status,
|
||||
outcome,
|
||||
timedOut,
|
||||
diagnosticsComplete,
|
||||
diagnosticsErrors,
|
||||
runType: finalJob?.runType || "DEBUG",
|
||||
durationTime: typeof finalJob?.durationTime === "number" ? finalJob.durationTime : undefined,
|
||||
targetEntityId,
|
||||
triggerCategory: options.triggerCategory,
|
||||
triggerType: options.triggerType,
|
||||
|
||||
@@ -555,6 +555,8 @@ export interface WorkflowSnapshotDiff {
|
||||
|
||||
export interface NodeExecutionDiff {
|
||||
taskName: string;
|
||||
instanceKey?: string;
|
||||
currentLoopPath?: string;
|
||||
displayName?: string;
|
||||
type?: string;
|
||||
statusA?: string;
|
||||
@@ -631,6 +633,10 @@ export interface WorkflowTestReport {
|
||||
jobId: string;
|
||||
pipelineId: string;
|
||||
status: string;
|
||||
outcome: "completed" | "failed" | "timed_out" | "incomplete";
|
||||
timedOut: boolean;
|
||||
diagnosticsComplete: boolean;
|
||||
diagnosticsErrors: Array<{ source: string; message: string }>;
|
||||
runType: string;
|
||||
durationTime?: number;
|
||||
targetEntityId: string;
|
||||
|
||||
@@ -3,6 +3,63 @@ import { explainConditionBranches } from "./workflow-branch.js";
|
||||
import type { WorkflowTaskExecution } from "./types.js";
|
||||
|
||||
describe("Workflow Condition Branch Diagnosis", () => {
|
||||
const choose = (property = "value") => `@{choose('${JSON.stringify({ key: "source", properties: [{ key: property }] })}')}`;
|
||||
const branch = (filter: any, status = "COMPLETED"): WorkflowTaskExecution => ({ id: "condition", name: "condition", type: "condition", status, tasks: [{ name: "child", type: "http" }], combineFilters: filter });
|
||||
const diagnose = (actual: unknown, compare: string, expected: unknown) => explainConditionBranches([
|
||||
{ id: "source", name: "source", type: "code", status: "COMPLETED", output: { value: actual } },
|
||||
branch({ filters: [{ key: choose(), compare, value: expected }], condition: "AND" }),
|
||||
])[0];
|
||||
|
||||
for (const [operator, actual, expected, matched] of [
|
||||
["gt", 10, 5, true], ["gte", 5, 5, true], ["lt", 1, 5, true], ["lte", 5, 5, true],
|
||||
["in", "A", ["A", "B"], true], ["not_in", "C", ["A", "B"], true],
|
||||
["include", ["A"], "AB", false], ["not_include", ["A"], "AB", true],
|
||||
["empty", false, null, false], ["empty", 0, null, false], ["empty", [], null, true],
|
||||
["not_empty", 0, null, true], ["unsupported", 1, 1, null], ["gt", "text", 1, null],
|
||||
["eq", null, null, true], ["eq", { amount: 10 }, 10, null],
|
||||
] as const) {
|
||||
it(`evaluates ${operator} without inventing a result (${JSON.stringify(actual)})`, () => {
|
||||
expect(diagnose(actual, operator, expected)?.rules[0]?.matched).toBe(matched);
|
||||
});
|
||||
}
|
||||
|
||||
it("keeps all expected reference IDs rather than only the first", () => {
|
||||
const tag = (key: string) => `@{value('${JSON.stringify({ key, label: key })}')}`;
|
||||
expect(diagnose(["A", "B"], "eq", [tag("A"), tag("B")])?.rules[0]?.matched).toBe(true);
|
||||
});
|
||||
it("evaluates nested OR / AND groups and does not infer False from an incomplete execution tree", () => {
|
||||
const result = explainConditionBranches([
|
||||
{ id: "source", name: "source", type: "code", status: "COMPLETED", output: { value: 10 } },
|
||||
branch({ condition: "OR", filters: [{ filters: [{ key: choose(), compare: "eq", value: 1 }] }, { filters: [{ key: choose(), compare: "gt", value: 5 }] }] }),
|
||||
])[0];
|
||||
expect(result?.evaluation).toBe(true);
|
||||
expect(result?.hasSkippedTasks).toBe(false);
|
||||
expect(result?.summary).toContain("执行树是否完整");
|
||||
});
|
||||
it("does not claim skipped tasks for a still-running condition or absent upstream evidence", () => {
|
||||
const running = explainConditionBranches([branch({ filters: [{ key: choose(), compare: "eq", value: 1 }] }, "RUNNING")])[0];
|
||||
expect(running?.evaluation).toBeNull();
|
||||
expect(running?.rules[0]?.matched).toBeNull();
|
||||
expect(running?.hasSkippedTasks).toBe(false);
|
||||
expect(running?.summary).toContain("无法确定");
|
||||
});
|
||||
it("resolves nested branches against the matching loop instance", () => {
|
||||
const tree = [1, 10].map((value, index) => ({ id: `loop-${index}`, name: "loop", type: "every", status: "COMPLETED", currentLoopPath: String(index), children: [
|
||||
{ id: `source-${index}`, name: "source", type: "code", status: "COMPLETED", output: { value } },
|
||||
{ ...branch({ filters: [{ key: choose(), compare: "gt", value: 5 }] }), id: `condition-${index}` },
|
||||
] }));
|
||||
const result = explainConditionBranches(tree);
|
||||
expect(result.map(item => item.rules[0]?.actualValue)).toEqual([1, 10]);
|
||||
expect(result.map(item => item.evaluation)).toEqual([false, true]);
|
||||
});
|
||||
it("recognizes an executed child by parentId even if the flat response order differs", () => {
|
||||
const condition = branch({ filters: [] });
|
||||
const result = explainConditionBranches([
|
||||
{ id: "child", name: "child", parentId: condition.id, type: "http", status: "COMPLETED" },
|
||||
condition,
|
||||
]);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
it("diagnoses missing upstream property when property is absent from outputs", () => {
|
||||
const tree: WorkflowTaskExecution[] = [
|
||||
{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { WorkflowTaskExecution } from "./types.js";
|
||||
import { indexExecutionContexts } from "./execution-context.js";
|
||||
|
||||
export interface ConditionRuleExplanation {
|
||||
leftLabel: string;
|
||||
@@ -9,7 +10,7 @@ export interface ConditionRuleExplanation {
|
||||
expectedValue: any;
|
||||
actualValue: any;
|
||||
isMissing: boolean;
|
||||
matched: boolean;
|
||||
matched: boolean | null;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
@@ -18,6 +19,7 @@ export interface ConditionBranchExplanation {
|
||||
conditionNodeName: string;
|
||||
conditionNodeLabel: string;
|
||||
hasSkippedTasks: boolean;
|
||||
evaluation: boolean | null;
|
||||
skippedTaskNames: string[];
|
||||
rules: ConditionRuleExplanation[];
|
||||
summary: string;
|
||||
@@ -52,7 +54,7 @@ function parseChooseTag(tag: string): {
|
||||
try {
|
||||
const parsed = JSON.parse(match[1]);
|
||||
const upstreamNode = parsed.key || "";
|
||||
const upstreamProp = parsed.properties?.[0]?.key || "";
|
||||
const upstreamProp = (parsed.properties ?? []).map((property: { key?: string }) => property.key).filter(Boolean).join(".");
|
||||
const label = parsed.label || `${upstreamNode}.${upstreamProp}`;
|
||||
return { upstreamNode, upstreamProp, label };
|
||||
} catch {
|
||||
@@ -84,42 +86,58 @@ function parseValueTag(val: any): any {
|
||||
/**
|
||||
* 比较两个值是否匹配
|
||||
*/
|
||||
function evaluateRule(actual: any, expected: any, compare: string): boolean {
|
||||
if (actual === undefined || actual === null) {
|
||||
if (compare === "empty") return true;
|
||||
if (compare === "not_empty") return false;
|
||||
return false;
|
||||
function cleanRuleValue(value: any): any {
|
||||
if (Array.isArray(value)) return value.map(cleanRuleValue);
|
||||
if (typeof value === "string") {
|
||||
const match = value.match(/@\{value\('(.*)'\)\}/);
|
||||
if (match) {
|
||||
try { const parsed = JSON.parse(match[1]); return parsed.key ?? parsed.value; }
|
||||
catch { return value; }
|
||||
}
|
||||
}
|
||||
const actualStr = String(actual);
|
||||
const expectedStr = typeof expected === "string" ? expected : JSON.stringify(expected);
|
||||
if (value && typeof value === "object" && "id" in value) return value.id;
|
||||
return value;
|
||||
}
|
||||
|
||||
function evaluateRule(actual: any, expected: any, compare: string): boolean | null {
|
||||
const empty = actual === undefined || actual === null || actual === "" || (Array.isArray(actual) && actual.length === 0);
|
||||
if (compare === "empty") return empty;
|
||||
if (compare === "not_empty") return !empty;
|
||||
if (!Object.hasOwn(OP_MAP, compare)) return null;
|
||||
if (actual === undefined) return false;
|
||||
actual = cleanRuleValue(actual);
|
||||
expected = cleanRuleValue(expected);
|
||||
if (actual === null) return compare === "eq" ? expected === null : compare === "neq" ? expected !== null : false;
|
||||
if ([actual, expected].some(value => value !== null && typeof value === "object" && !Array.isArray(value))) return null;
|
||||
const equal = (a: any, b: any): boolean => {
|
||||
if (Array.isArray(a) && !Array.isArray(b)) return a.length === 1 && equal(a[0], b);
|
||||
if (!Array.isArray(a) && Array.isArray(b)) return b.length === 1 && equal(a, b[0]);
|
||||
return typeof a === "object" || typeof b === "object" ? JSON.stringify(a) === JSON.stringify(b) : String(a) === String(b);
|
||||
};
|
||||
switch (compare) {
|
||||
case "eq":
|
||||
if (Array.isArray(actual)) {
|
||||
if (Array.isArray(expected)) {
|
||||
return JSON.stringify(actual) === JSON.stringify(expected);
|
||||
}
|
||||
return actual.length === 1 && String(actual[0]) === expectedStr;
|
||||
}
|
||||
return actualStr === expectedStr;
|
||||
case "neq":
|
||||
return actualStr !== expectedStr;
|
||||
case "eq": return equal(actual, expected);
|
||||
case "neq": return !equal(actual, expected);
|
||||
case "in":
|
||||
case "not_in": {
|
||||
if (!Array.isArray(expected) || Array.isArray(actual)) return null;
|
||||
const matches = expected.some(item => equal(actual, item));
|
||||
return compare === "in" ? matches : !matches;
|
||||
}
|
||||
case "include":
|
||||
if (Array.isArray(actual)) {
|
||||
return actual.some((item) => String(item).includes(expectedStr) || expectedStr.includes(String(item)));
|
||||
}
|
||||
return actualStr.includes(expectedStr);
|
||||
case "not_include":
|
||||
if (Array.isArray(actual)) {
|
||||
return !actual.some((item) => String(item).includes(expectedStr));
|
||||
}
|
||||
return !actualStr.includes(expectedStr);
|
||||
case "empty":
|
||||
return Array.isArray(actual) ? actual.length === 0 : !actual;
|
||||
case "not_empty":
|
||||
return Array.isArray(actual) ? actual.length > 0 : Boolean(actual);
|
||||
default:
|
||||
return actualStr === expectedStr;
|
||||
case "not_include": {
|
||||
if (!Array.isArray(actual) && typeof actual !== "string") return null;
|
||||
const values = Array.isArray(expected) ? expected : [expected];
|
||||
const matches = Array.isArray(actual)
|
||||
? values.every(value => actual.some(item => equal(item, value)))
|
||||
: typeof actual === "string" && values.every(value => actual.includes(String(value)));
|
||||
return compare === "include" ? matches : !matches;
|
||||
}
|
||||
default: {
|
||||
const numeric = (value: unknown) => typeof value === "number" || (typeof value === "string" && value.trim() !== "") ? Number(value) : NaN;
|
||||
const a = numeric(actual), b = numeric(expected);
|
||||
if (!Number.isFinite(a) || !Number.isFinite(b)) return null;
|
||||
return compare === "gt" ? a > b : compare === "gte" ? a >= b : compare === "lt" ? a < b : a <= b;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,135 +147,105 @@ function evaluateRule(actual: any, expected: any, compare: string): boolean {
|
||||
export function explainConditionBranches(
|
||||
tree: WorkflowTaskExecution[]
|
||||
): ConditionBranchExplanation[] {
|
||||
const nodeMap = new Map<string, WorkflowTaskExecution>();
|
||||
const executedNames = new Set<string>();
|
||||
|
||||
for (const node of tree) {
|
||||
if (node.name) {
|
||||
nodeMap.set(node.name, node);
|
||||
executedNames.add(node.name);
|
||||
}
|
||||
if (node.id) {
|
||||
nodeMap.set(node.id, node);
|
||||
}
|
||||
}
|
||||
|
||||
const contexts = indexExecutionContexts(tree);
|
||||
const explanations: ConditionBranchExplanation[] = [];
|
||||
|
||||
for (const node of tree) {
|
||||
for (const [position, context] of contexts.entries()) {
|
||||
const node = context.node;
|
||||
const rawNode = node as Record<string, any>;
|
||||
if (rawNode.type !== "condition") continue;
|
||||
|
||||
const childTasks = Array.isArray(rawNode.tasks) ? rawNode.tasks : [];
|
||||
if (childTasks.length === 0) continue;
|
||||
|
||||
// 检查子任务是否执行过
|
||||
const childNames = childTasks.map((t: any) => t.name || t.id).filter(Boolean);
|
||||
const anyExecuted = childNames.some((name: string) => executedNames.has(name));
|
||||
|
||||
const childNames = childTasks.map((task: any) => task.name || task.id).filter(Boolean);
|
||||
const childContexts = contexts.filter((child, index) => {
|
||||
if (child.loopPath !== context.loopPath || !childNames.includes(child.node.name || child.node.id)) return false;
|
||||
if (child.node.parentId) return child.node.parentId === node.id;
|
||||
const nestedScope = [...context.scope, JSON.stringify([node.name || node.type || "unnamed", context.loopPath])];
|
||||
return JSON.stringify(child.scope) === JSON.stringify(nestedScope) ||
|
||||
(index > position && JSON.stringify(child.scope) === JSON.stringify(context.scope));
|
||||
});
|
||||
const anyExecuted = childContexts.some(child => child.node.status && !["SKIP", "SKIPPED"].includes(child.node.status.toUpperCase()));
|
||||
if (anyExecuted) {
|
||||
// 子分支正常执行,无需诊断跳过
|
||||
continue;
|
||||
}
|
||||
|
||||
const skippedTaskNames = childTasks.map((t: any) => `${t.name || t.id} (${t.label || t.displayName || t.type})`);
|
||||
const skippedTaskNames = childTasks.map((task: any) => `${task.name || task.id} (${task.label || task.displayName || task.type})`);
|
||||
const rules: ConditionRuleExplanation[] = [];
|
||||
|
||||
// 解析 combineFilters
|
||||
const rawFilters = rawNode.combineFilters?.filters;
|
||||
if (Array.isArray(rawFilters)) {
|
||||
for (const group of rawFilters) {
|
||||
const subFilters = Array.isArray(group.filters) ? group.filters : [group];
|
||||
for (const f of subFilters) {
|
||||
const chooseInfo = parseChooseTag(f.key);
|
||||
const rawExpected = f.value;
|
||||
const parsedExpected = parseValueTag(rawExpected);
|
||||
const op = f.compare || "eq";
|
||||
const opLabel = OP_MAP[op] || op;
|
||||
|
||||
let upstreamNode = "";
|
||||
let upstreamProp = "";
|
||||
let leftLabel = String(f.key);
|
||||
|
||||
if (chooseInfo) {
|
||||
upstreamNode = chooseInfo.upstreamNode;
|
||||
upstreamProp = chooseInfo.upstreamProp;
|
||||
leftLabel = chooseInfo.label;
|
||||
} else if (typeof f.key === "string") {
|
||||
upstreamProp = f.key;
|
||||
}
|
||||
|
||||
// 从上游节点提取真实 outputs
|
||||
const upstreamExecution = upstreamNode ? nodeMap.get(upstreamNode) : undefined;
|
||||
const upstreamOutputs = upstreamExecution?.output ?? (upstreamExecution as any)?.outputs;
|
||||
|
||||
let actualVal: any = undefined;
|
||||
let isMissing = false;
|
||||
|
||||
if (upstreamOutputs && typeof upstreamOutputs === "object") {
|
||||
if (upstreamProp in upstreamOutputs) {
|
||||
actualVal = upstreamOutputs[upstreamProp];
|
||||
} else {
|
||||
isMissing = true;
|
||||
}
|
||||
} else if (upstreamExecution) {
|
||||
isMissing = true;
|
||||
}
|
||||
|
||||
// 提取纯净 ID 比对
|
||||
let cleanExpected = rawExpected;
|
||||
if (typeof rawExpected === "string" && rawExpected.includes("@{value(")) {
|
||||
const m = rawExpected.match(/"key":"([^"]+)"/);
|
||||
if (m) cleanExpected = m[1];
|
||||
} else if (Array.isArray(rawExpected) && rawExpected.length > 0 && typeof rawExpected[0] === "string") {
|
||||
const m = rawExpected[0].match(/"key":"([^"]+)"/);
|
||||
if (m) cleanExpected = m[1];
|
||||
}
|
||||
|
||||
const matched = evaluateRule(actualVal, cleanExpected, op);
|
||||
|
||||
let detail = "";
|
||||
if (isMissing) {
|
||||
const availableKeys = upstreamOutputs ? Object.keys(upstreamOutputs).join(", ") : "无出参";
|
||||
detail = `上游节点 [${upstreamNode}] 未返回该属性 [${upstreamProp}](字段名可能脱节,上游可用字段: ${availableKeys})➔ 解析值为 null`;
|
||||
} else {
|
||||
const actStr = typeof actualVal === "object" ? JSON.stringify(actualVal) : String(actualVal ?? "null");
|
||||
const expStr = typeof parsedExpected === "object" ? JSON.stringify(parsedExpected) : String(parsedExpected);
|
||||
detail = `实际值: ${actStr} 与期望值 [${expStr}] 比对结果为 ${matched ? "True" : "False"}`;
|
||||
}
|
||||
|
||||
rules.push({
|
||||
leftLabel,
|
||||
upstreamNode,
|
||||
upstreamProp,
|
||||
operator: op,
|
||||
operatorLabel: opLabel,
|
||||
expectedValue: parsedExpected,
|
||||
actualValue: actualVal,
|
||||
isMissing,
|
||||
matched,
|
||||
detail,
|
||||
});
|
||||
}
|
||||
// 解析 combineFilters;保留 AND/OR 和嵌套分组语义。
|
||||
const explainFilter = (filter: any): boolean | null => {
|
||||
if (!filter || typeof filter !== "object") return null;
|
||||
if (Array.isArray(filter.filters)) {
|
||||
const values = filter.filters.map(explainFilter) as Array<boolean | null>;
|
||||
if (!values.length) return null;
|
||||
const condition = String(filter.condition ?? "AND").toUpperCase();
|
||||
if (condition === "AND") return values.includes(false) ? false : values.includes(null) ? null : true;
|
||||
if (condition === "OR") return values.includes(true) ? true : values.includes(null) ? null : false;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const chooseInfo = parseChooseTag(filter.key);
|
||||
const rawExpected = filter.value;
|
||||
const parsedExpected = parseValueTag(rawExpected);
|
||||
const op = filter.compare || "eq";
|
||||
const upstreamNode = chooseInfo?.upstreamNode || "";
|
||||
const upstreamProp = chooseInfo?.upstreamProp || (typeof filter.key === "string" ? filter.key : "");
|
||||
const leftLabel = chooseInfo?.label || String(filter.key);
|
||||
|
||||
let summary = `条件判定未通过 (False),子任务 [${skippedTaskNames.join(", ")}] 被跳过未执行`;
|
||||
const missingRule = rules.find((r) => r.isMissing);
|
||||
if (missingRule) {
|
||||
// 从上游节点提取真实 outputs;只使用同一次循环或祖先作用域中的执行实例。
|
||||
const candidates = contexts.slice(0, position).filter(candidate =>
|
||||
(candidate.node.name === upstreamNode || candidate.node.id === upstreamNode) &&
|
||||
(!candidate.loopPath || candidate.loopPath === context.loopPath) &&
|
||||
candidate.scope.every((part, i) => context.scope[i] === part)
|
||||
);
|
||||
candidates.sort((a, b) => a.scope.length - b.scope.length);
|
||||
const upstreamExecution = candidates.at(-1)?.node;
|
||||
const upstreamOutputs = upstreamExecution?.output ?? upstreamExecution?.outputs;
|
||||
let actualVal: any = upstreamOutputs;
|
||||
let isMissing = false;
|
||||
for (const part of upstreamProp.split(".")) {
|
||||
if (actualVal && typeof actualVal === "object" && Object.hasOwn(actualVal, part)) actualVal = actualVal[part];
|
||||
else { actualVal = undefined; isMissing = Boolean(upstreamExecution); break; }
|
||||
}
|
||||
// 提取纯净 ID 比对
|
||||
const cleanExpected = cleanRuleValue(rawExpected);
|
||||
const matched = upstreamExecution ? evaluateRule(actualVal, cleanExpected, op) : null;
|
||||
let detail: string;
|
||||
if (isMissing) {
|
||||
const availableKeys = upstreamOutputs && typeof upstreamOutputs === "object" ? Object.keys(upstreamOutputs).join(", ") : "无出参";
|
||||
detail = `上游节点 [${upstreamNode}] 未返回该属性 [${upstreamProp}](字段名可能脱节,上游可用字段: ${availableKeys})➔ 解析值为 null`;
|
||||
} else if (matched === null) {
|
||||
detail = `无法确定:缺少上游执行证据,或操作符/值类型不支持 (${op})`;
|
||||
} else {
|
||||
const actStr = typeof actualVal === "object" ? JSON.stringify(actualVal) : String(actualVal ?? "null");
|
||||
const expStr = typeof parsedExpected === "object" ? JSON.stringify(parsedExpected) : String(parsedExpected);
|
||||
detail = `实际值: ${actStr} 与期望值 [${expStr}] 比对结果为 ${matched ? "True" : "False"}`;
|
||||
}
|
||||
rules.push({ leftLabel, upstreamNode, upstreamProp, operator: op, operatorLabel: OP_MAP[op] || op, expectedValue: parsedExpected, actualValue: actualVal, isMissing, matched, detail });
|
||||
return matched;
|
||||
};
|
||||
const calculated = explainFilter(rawNode.combineFilters);
|
||||
const evaluation = node.status.toUpperCase() === "COMPLETED" ? calculated : null;
|
||||
let summary = evaluation === false
|
||||
? `条件判定未通过 (False),子任务 [${skippedTaskNames.join(", ")}] 被跳过未执行`
|
||||
: evaluation === true
|
||||
? "条件比对为 True,但未见子任务执行记录;请核对执行树是否完整"
|
||||
: "执行证据不足或条件尚未完成,无法确定子任务是否被跳过";
|
||||
const missingRule = rules.find(rule => rule.isMissing);
|
||||
if (evaluation === false && missingRule) {
|
||||
summary = `条件字段脱节: 上游节点 [${missingRule.upstreamNode}] 缺少属性 [${missingRule.upstreamProp}],判定为 False,子任务被跳过`;
|
||||
}
|
||||
|
||||
explanations.push({
|
||||
conditionNodeId: node.id,
|
||||
conditionNodeName: node.name || "-",
|
||||
conditionNodeLabel: node.label || (node as any).displayName || "条件节点",
|
||||
hasSkippedTasks: true,
|
||||
conditionNodeLabel: node.label || rawNode.displayName || "条件节点",
|
||||
hasSkippedTasks: evaluation === false || childContexts.some(child => ["SKIP", "SKIPPED"].includes(child.node.status.toUpperCase())),
|
||||
evaluation,
|
||||
skippedTaskNames,
|
||||
rules,
|
||||
summary,
|
||||
});
|
||||
}
|
||||
|
||||
return explanations;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { runWorkflowDebugTest } from "./services.js";
|
||||
|
||||
function setup(status = "COMPLETED", errors: string[] = []) {
|
||||
const posts: string[] = [];
|
||||
const response = (data: unknown) => new Response(JSON.stringify({ code: 200, data }));
|
||||
const client = {
|
||||
post: async (path: string) => { posts.push(path); return response("job"); },
|
||||
get: async (path: string) => {
|
||||
if (path.endsWith("/level/failed")) {
|
||||
if (errors.includes("failures")) throw new Error("403 failures unavailable");
|
||||
return response([]);
|
||||
}
|
||||
if (path.endsWith("/execution")) {
|
||||
if (errors.includes("tree")) throw new Error("403 execution unavailable");
|
||||
return response([]);
|
||||
}
|
||||
if (errors.includes("job")) throw new Error("403 job unavailable");
|
||||
return response({ id: "job", status });
|
||||
},
|
||||
} as any;
|
||||
return { client, posts };
|
||||
}
|
||||
|
||||
describe("workflow debug completion evidence", () => {
|
||||
it("reports completed only when all diagnostics were fetched", async () => {
|
||||
const { client } = setup();
|
||||
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record" });
|
||||
expect(result.outcome).toBe("completed");
|
||||
expect(result.timedOut).toBe(false);
|
||||
expect(result.diagnosticsComplete).toBe(true);
|
||||
});
|
||||
it("reports a failed terminal job", async () => {
|
||||
const { client } = setup("FAILED");
|
||||
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record" });
|
||||
expect(result.outcome).toBe("failed");
|
||||
});
|
||||
it("keeps timed-out jobs queryable and exposes missing diagnostic evidence", async () => {
|
||||
const { client } = setup("RUNNING", ["tree", "failures"]);
|
||||
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: 0 });
|
||||
expect(result.jobId).toBe("job");
|
||||
expect(result.status).toBe("RUNNING");
|
||||
expect(result.outcome).toBe("timed_out");
|
||||
expect(result.timedOut).toBe(true);
|
||||
expect(result.diagnosticsComplete).toBe(false);
|
||||
expect(result.diagnosticsErrors.map(error => error.source)).toEqual(["executionTree", "failedExecutions"]);
|
||||
});
|
||||
it("marks partial diagnostic reads as incomplete rather than clean success", async () => {
|
||||
const { client } = setup("COMPLETED", ["tree"]);
|
||||
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record" });
|
||||
expect(result.outcome).toBe("incomplete");
|
||||
expect(result.diagnosticsErrors[0]?.message).toContain("403");
|
||||
});
|
||||
it("preserves job identity when polling fails and does not hide the error", async () => {
|
||||
const { client } = setup("RUNNING", ["job"]);
|
||||
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record" });
|
||||
expect(result.jobId).toBe("job");
|
||||
expect(result.outcome).toBe("incomplete");
|
||||
expect(result.diagnosticsErrors[0]?.source).toBe("job");
|
||||
});
|
||||
it("rejects invalid timing options before creating a mutating job", async () => {
|
||||
const { client, posts } = setup();
|
||||
await expect(runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: -1 })).rejects.toThrow("timeoutMs");
|
||||
expect(posts).toEqual([]);
|
||||
});
|
||||
it("retries a newly created job's HTTP 404 instead of reporting an authorization failure", async () => {
|
||||
const { client } = setup();
|
||||
const get = client.get;
|
||||
let jobReads = 0;
|
||||
client.get = async (path: string) => {
|
||||
if (path.endsWith("/job") && jobReads++ === 0) throw { response: { status: 404 } };
|
||||
return get(path);
|
||||
};
|
||||
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: 100, pollIntervalMs: 1 });
|
||||
expect(result.outcome).toBe("completed");
|
||||
expect(jobReads).toBe(2);
|
||||
});
|
||||
});
|
||||
+2
-1
@@ -3,7 +3,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { runCli } from "./cli/runner.js";
|
||||
import { redactSensitiveText } from "./cli/printer.js";
|
||||
import { redactSensitiveText, writeStdoutChunk } from "./cli/printer.js";
|
||||
import { VERSION } from "./version.js";
|
||||
import type { CliResult } from "./cli/types.js";
|
||||
|
||||
@@ -228,6 +228,7 @@ async function runEmbeddedCli() {
|
||||
const result = await runCli(process.argv.slice(3), {
|
||||
appRoot,
|
||||
entryFile: serverEntryFile,
|
||||
writeStdout: writeStdoutChunk,
|
||||
});
|
||||
if (result.stdout) process.stdout.write(result.stdout);
|
||||
if (result.stderr) process.stderr.write(`${result.stderr}${result.stderr.endsWith("\n") ? "" : "\n"}`);
|
||||
|
||||
Reference in new issue
Block a user