fix: stabilize auth identity, record operations, and workflow diagnostics

This commit is contained in:
gitea committed 2026-10-15 14:54:10 +08:00
1 parent c74fdda7da
commit 7ec369f77e
36 files changed
+1021 -337

No files matched your search

+4
View File
@@ -20,3 +20,7 @@
- handler 统一签名 `(parsed, runtime, options) => Promise<CliResult>`。
- 命令文件内部不重复做异常体系,只抛/透传 `EkbError` 子类。
## 嵌入调用与流式输出
`runCli` 默认通过 `CliResult` 返回结果,不直接写进进程 stdout。终端入口可显式传入 `CliRunOptions.writeStdout` 异步回调;处理器必须等待回调完成,保证慢管道有背压。MCP / HTTP 不提供该回调,流式记录应使用 `--output-file`,否则返回用法错误。普通命令的返回结构保持不变。
+1 -1
View 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}`,
];
+16 -7
View File
@@ -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;
}
+1 -1
View File
@@ -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 () => {
+14 -2
View File
@@ -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();
});
});
+3 -4
View File
@@ -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 =
+43 -33
View File
@@ -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) {
+63
View File
@@ -0,0 +1,63 @@
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();
});
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");
});
}
});
+4 -2
View File
@@ -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
+1 -1
View File
@@ -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 || "(未执行)",
+1 -1
View File
@@ -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}`);
+27 -10
View File
@@ -7,6 +7,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,
@@ -16,19 +17,28 @@ export async function handleWorkflowTest(
if (!pipelineId) {
return {
stdout: "",
stderr: "用法: hose-use workflow test <pipelineId> --flow=<单号|单据ID> [--auto-publish] [--timeout=<ms>] [--force]\n别名: hose-use workflow debug <pipelineId> --flow=<单号>\n",
stderr: "用法: hose-use workflow test <pipelineId> --flow=<单号|单据ID> [--auto-publish] [--timeout=<ms>] [--dry-run | --yes]\n别名: hose-use workflow debug <pipelineId> --flow=<单号>\n",
exitCode: 1,
};
}
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const flowCodeOrId = stringOption(parsed.options, ["flow", "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 force = booleanOption(parsed.options, ["force", "confirm", "yes", "i-know-it-is-prod"]);
const timeoutMs = numberOption(parsed.options, ["timeout", "timeout-ms", "timeoutMs"]) ?? 15000;
const warnings = ["调试会在真实环境执行工作流节点,可能改变业务数据、发送通知并生成快照;auto-publish 还可能发布流程。"];
if (flowCodeOrId) {
requireMutationConfirmation(parsed, runtime, "执行工作流调试", `hose-use workflow test ${pipelineId} --flow=${flowCodeOrId} --yes`);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, autoPublish, timeoutMs, warnings });
}
}
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
// 获取工作流状态,检测是否处于生产启用中
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;
// 如果没有传入 --flow,先列出当前可用的调试数据源供用户参考
@@ -37,7 +47,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,
};
@@ -73,17 +83,19 @@ export async function handleWorkflowTest(
}
// 执行端到端调试测试
const report = await runWorkflowDebugTest(client, pipelineId, {
const execution = await runWorkflowDebugTest(client, pipelineId, {
flowCodeOrId,
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,
};
}
@@ -114,6 +126,9 @@ export async function handleWorkflowTest(
"生成 Job ID": report.jobId,
"测试目标单据": report.targetEntityId,
"执行结果状态": report.status,
"测试结果": report.outcome,
"是否超时": String(report.timedOut),
"诊断完整": String(report.diagnosticsComplete),
"运行模式": report.runType,
"总耗时(ms)": String(report.durationTime ?? "-"),
"节点执行总数": report.executionTree.length,
@@ -128,6 +143,8 @@ 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("");
@@ -139,7 +156,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}`);
@@ -151,6 +168,6 @@ export async function handleWorkflowTest(
return {
stdout: `${outLines.join("\n")}\n`,
stderr: "",
exitCode: report.status === "FAILED" ? 1 : 0,
exitCode,
};
}
+7
View File
@@ -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>")
+1
View File
@@ -136,6 +136,7 @@ async function dispatchCli(
entryFile: options.entryFile,
launcher: options.launcher,
});
runtime.writeStdout = options.writeStdout;
try {
if (!parsed.area) {
+112
View File
@@ -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()));
}
});
});
+3
View File
@@ -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;