fix: 标明工作流扫描与分析证据完整性

保留不完整扫描中的既有告警指纹,并展示分页和分析证据不足。
This commit is contained in:
gitea committed 2026-10-30 17:37:05 +08:00
1 parent c6d71843b7
commit c813498da2
8 files changed
+84 -22

No files matched your search

+11 -8
View File
@@ -21,6 +21,7 @@ export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime):
const detail = await getWorkflowDetail(client, pipelineId);
const specIds = extractWorkflowSpecificationIds(detail);
const specifications: Record<string, WorkflowFormSpecLike | undefined> = {};
const evidenceErrors: Array<{ source: string; message: string }> = [];
if (specIds.length > 0) {
const corpId = runtime.selectedCorp!.corpId || runtime.selectedCorp!.id;
await Promise.all(
@@ -28,8 +29,9 @@ export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime):
try {
const spec = await getFormSpecification(clients.ekbClient, corpId, specId);
if (spec) specifications[specId] = spec;
} catch {
// Ignore specification fetch failure in offline or restricted environments
else evidenceErrors.push({ source: `specification:${specId}`, message: "未返回表单规格" });
} catch (error) {
evidenceErrors.push({ source: `specification:${specId}`, message: error instanceof Error ? error.message : String(error) });
}
})
);
@@ -38,8 +40,8 @@ export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime):
try {
const available = await getWorkflowAvailableNodes(client);
availableNodeTypes = available.allTypes;
} catch {
// 离线或受限网络环境下忽略探针失败
} catch (error) {
evidenceErrors.push({ source: "availableNodeTypes", message: error instanceof Error ? error.message : String(error) });
}
let openedPowerCodes: Set<string> | undefined;
@@ -60,22 +62,22 @@ export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime):
}
}
openedPowerCodes = codes;
} catch {
// 离线或无商店应用查询权限时忽略
} catch (error) {
evidenceErrors.push({ source: "openedPowerCodes", message: error instanceof Error ? error.message : String(error) });
}
const result = analyzeWorkflow(detail, { specifications, availableNodeTypes, openedPowerCodes });
const failOnAlert = booleanOption(parsed.options, ["fail", "fail-on-alert", "failOnAlert"]);
const exitCode = failOnAlert && !result.summary.passed ? 2 : 0;
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode };
if (runtime.jsonMode) return { stdout: printJson({ ...result, evidenceComplete: evidenceErrors.length === 0, evidenceErrors }, runtime.outputOptions), stderr: "", exitCode };
const gateDecision =
result.summary.hardBlocks > 0
? `❌ 发现 ${result.summary.hardBlocks} 项硬门禁阻断 (禁止发布上线)`
: result.summary.softAdvices > 0
? `⚠️ 硬门禁全通过,存在 ${result.summary.softAdvices} 项优化建议`
: "✅ 全部门禁通过,可安全发布上线";
: "✅ 已执行的静态检查未发现阻断项";
const diagnosticRows = result.diagnostics.map((item) => [
item.category === "hard_block" ? "⛔ 硬门禁" : "💡 软建议",
@@ -100,6 +102,7 @@ export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime):
}),
`\n依赖引用:\n${dependencyRows.length ? printTable(["节点路径", "类型", "引用"], dependencyRows) : "暂无代码引用"}`,
`\n诊断列表 (硬门禁 ⛔ / 软建议 💡):\n${diagnosticRows.length ? printTable(["分类", "级别", "代码", "节点路径", "说明"], diagnosticRows) : "未发现明显配置问题"}`,
...(evidenceErrors.length ? [`\n⚠️ 分析证据不完整:${evidenceErrors.map((item) => `${item.source}: ${item.message}`).join(";")}`] : []),
"",
].join("\n"),
stderr: "",
+5 -4
View File
@@ -20,7 +20,7 @@ export async function handleCheck(parsed: CliParsedArgs, runtime: CliRuntime): P
}));
const logErrors = logResults.filter((item): item is typeof item & { error: string } => Boolean(item.error)).map((item) => ({ platformId: item.workflow.platformId, platformName: item.workflow.platformName, error: item.error }));
const activeAlerts = logResults
.filter(({ errorCount }) => errorCount > 0)
.filter(({ errorCount, error }) => !error && errorCount > 0)
.map(({ workflow, errorCount }) => ({
id: `${runtime.selectedCorp!.id}:${workflow.platformId}:${workflow.id}`,
pipelineId: workflow.id,
@@ -32,12 +32,13 @@ export async function handleCheck(parsed: CliParsedArgs, runtime: CliRuntime): P
}));
const explicitStateFile = stringOption(parsed.options, ["state-file", "stateFile"]);
const stateFile = explicitStateFile || `sqlite:workflow_error_alerts:${runtime.selectedCorp!.id}`;
const check = new WorkflowAlertStore(explicitStateFile || `corp:${runtime.selectedCorp!.id}`).observe(activeAlerts);
const output = { corpId: runtime.selectedCorp!.id, observedAt, stateFile, activeAlerts: check.activeAlerts, newAlerts: check.newAlerts, scanErrors: [...result.errors, ...logErrors] };
const complete = result.complete === true && logErrors.length === 0;
const check = new WorkflowAlertStore(explicitStateFile || `corp:${runtime.selectedCorp!.id}`).observe(activeAlerts, { complete });
const output = { corpId: runtime.selectedCorp!.id, observedAt, stateFile, activeAlerts: check.activeAlerts, newAlerts: check.newAlerts, scanErrors: [...result.errors, ...logErrors], complete, pages: result.pages };
if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
const rows = check.activeAlerts.map((alert) => [alert.pipelineId, alert.pipelineName || "-", alert.errorCount, alert.state === 1 ? "启用" : "停用", check.newAlerts.some((item) => item.id === alert.id) ? "🔔 新提醒" : "已记录"]);
const warning = check.newAlerts.length ? `\n🔔 新错误管道提醒 ${check.newAlerts.length} 条` : "\n暂无新的错误管道提醒";
const scanErrorCount = result.errors.length + logErrors.length;
const scanWarning = scanErrorCount ? `\n⚠️ 工作流扫描失败 ${scanErrorCount} 个` : "";
const scanWarning = !complete ? `\n⚠️ 扫描不完整(失败 ${scanErrorCount} 个或存在未扫描分页),保留既有告警状态` : "";
return { stdout: `====== 工作流健康检查 [${runtime.selectedCorp!.name}] ======\n${rows.length ? printTable(["工作流 ID", "名称", "错误次数", "状态", "提醒"], rows) : "未发现错误管道"}${warning}${scanWarning}\n状态存储: ${stateFile}\n`, stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
}
+12 -4
View File
@@ -52,12 +52,16 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const scanWarning = rawResult.complete === false || rawResult.errors.length
? `⚠️ 结果不完整:仅查询指定页,或有 ${rawResult.errors.length} 个应用查询失败。\n`
: "";
if (workflows.length === 0) {
const emptyMsg = keyword
? `企业 [${runtime.selectedCorp!.name}] 下未找到包含关键词 "${keyword}" 的工作流\n`
: `企业 [${runtime.selectedCorp!.name}] 下暂无工作流\n`;
return {
stdout: emptyMsg,
stdout: scanWarning + emptyMsg,
stderr: "",
exitCode: 0,
};
@@ -85,7 +89,7 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
const titleSuffix = filterDesc ? ` (过滤: ${filterDesc}, 共 ${workflows.length} 条)` : ` (共 ${workflows.length} 条)`;
return {
stdout: `====== [${runtime.selectedCorp!.name}] 工作流列表${titleSuffix} ======\n${table}\n`,
stdout: `${scanWarning}====== [${runtime.selectedCorp!.name}] 工作流列表${titleSuffix} ======\n${table}\n`,
stderr: "",
exitCode: 0,
};
@@ -163,9 +167,13 @@ export async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Pr
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const scanWarning = result.complete === false || result.errors.length
? `⚠️ 搜索结果不完整:仅查询指定页,或有 ${result.errors.length} 个查询失败。\n`
: "";
if (result.workflows.length === 0) {
return {
stdout: `未找到包含节点类型 [${taskType}] 的工作流\n`,
stdout: `${scanWarning}未找到包含节点类型 [${taskType}] 的工作流\n`,
stderr: "",
exitCode: 0,
};
@@ -185,7 +193,7 @@ export async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Pr
);
return {
stdout: `====== 匹配节点类型 [${taskType}] 的工作流 (共 ${result.workflows.length} 条) ======\n${table}\n`,
stdout: `${scanWarning}====== 匹配节点类型 [${taskType}] 的工作流 (共 ${result.workflows.length} 条) ======\n${table}\n`,
stderr: "",
exitCode: 0,
};
@@ -78,6 +78,8 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
## 调试与诊断结果契约
- 跨应用列表和节点搜索只读取各应用指定页;JSON 的 `pages` 与 `complete` 表示扫描范围,缺少总页数且结果满页时按不完整处理。健康检查在分页不完整或读取失败时保留既有告警指纹,避免误清;返回 `complete` 和 `scanErrors`。
- `analyze` 返回 `evidenceComplete` 和 `evidenceErrors`,区分外部资料读取失败与已执行的静态检查;`--fail` 仍仅根据已发现的硬门禁设置退出码。静态检查通过不保证可安全发布。
- 调试属于写操作:`--dry-run` 仅展示目标、发布选项和风险,不创建客户端或发起 Job;实际执行需要 `--yes` / `--confirm`。启用中的工作流仍可在确认后直接调试。
- JSON 和预览均包含风险信息。执行结果提供 `productionEnabled`(状态未知时为 `null`)和 `warnings`。
- `outcome` 为 `completed`、`failed`、`timed_out` 或 `incomplete`;只有完整成功才返回退出码 `0`。超时不取消已经发起的 Job,保留 `jobId` 以供 `workflow job` 续查。
+6 -4
View File
@@ -75,15 +75,17 @@ export class WorkflowAlertStore {
return { version: 1, alerts: {} };
}
observe(alerts: WorkflowErrorAlert[]): WorkflowAlertCheckResult {
observe(alerts: WorkflowErrorAlert[], options: { complete?: boolean } = {}): WorkflowAlertCheckResult {
const data = this.read();
const activeIds = new Set(alerts.map((alert) => alert.id));
const newAlerts = alerts.filter(
(alert) => data.alerts[alert.id]?.errorCount !== alert.errorCount
);
const updated = { ...data.alerts };
for (const id of Object.keys(updated)) {
if (!activeIds.has(id)) delete updated[id];
if (options.complete !== false) {
for (const id of Object.keys(updated)) {
if (!activeIds.has(id)) delete updated[id];
}
}
for (const alert of alerts) {
updated[alert.id] = { errorCount: alert.errorCount, lastSeen: alert.observedAt };
@@ -102,7 +104,7 @@ export class WorkflowAlertStore {
`);
const tx = db.transaction((items: WorkflowErrorAlert[]) => {
db.run("DELETE FROM workflow_error_alerts WHERE scope_key = ?", [this.scopeKey]);
if (options.complete !== false) db.run("DELETE FROM workflow_error_alerts WHERE scope_key = ?", [this.scopeKey]);
for (const alert of items) {
upsert.run(
this.scopeKey,
@@ -0,0 +1,21 @@
import { expect, it, spyOn } from "bun:test";
import * as applications from "../applications/services.js";
import * as api from "./api.js";
import { listAllWorkflows } from "./queries.js";
it("reports whether cross-application results cover all pages and applications", async () => {
const platforms = spyOn(applications, "listBasicPlatforms").mockResolvedValue([{ id: "p", active: true }] as any);
const list = spyOn(api, "listWorkflows").mockResolvedValue({ pipelineList: [], totalPages: 2, totalItems: 21 } as any);
const clients = { corp: { credentials: { corpId: "corp" } }, ekbClient: {}, easoClient: {} } as any;
const partial = await listAllWorkflows(clients, { page: 1, pageSize: 20 });
expect(partial.complete).toBe(false);
expect(partial.pages?.[0]?.totalPages).toBe(2);
list.mockResolvedValue({ pipelineList: [], totalPages: 1, totalItems: 0 } as any);
expect((await listAllWorkflows(clients)).complete).toBe(true);
list.mockRejectedValue(new Error("unavailable"));
const failed = await listAllWorkflows(clients);
expect(failed.complete).toBe(false);
expect(failed.errors).toHaveLength(1);
platforms.mockRestore();
list.mockRestore();
});
+14 -2
View File
@@ -88,6 +88,8 @@ export interface ListAllWorkflowsOptions {
export interface ListAllWorkflowsResult {
workflows: WorkflowSummary[];
errors: WorkflowListAllError[];
pages?: Array<{ platformId: string; page: number; pageSize: number; totalPages: number; totalItems: number; complete: boolean }>;
complete?: boolean;
}
@@ -104,6 +106,7 @@ export async function listAllWorkflows(
const workflows: WorkflowSummary[] = [];
const errors: WorkflowListAllError[] = [];
const pages: NonNullable<ListAllWorkflowsResult["pages"]> = [];
await Promise.all(
enabledPlatforms.map(async (platform) => {
@@ -114,6 +117,13 @@ export async function listAllWorkflows(
page,
pageSize
);
// 服务端有时不提供分页总数;满页时无法证明没有下一页。
const complete = page === 1 && (pageResult.totalPages > 0
? pageResult.totalPages === 1
: pageResult.totalItems > 0
? pageResult.totalItems <= pageResult.pipelineList.length
: pageResult.pipelineList.length < pageSize);
pages.push({ platformId: platform.id, page, pageSize, totalPages: pageResult.totalPages, totalItems: pageResult.totalItems, complete });
for (const workflow of pageResult.pipelineList) {
workflows.push({
...workflow,
@@ -131,7 +141,7 @@ export async function listAllWorkflows(
})
);
return { workflows, errors };
return { workflows, errors, pages, complete: errors.length === 0 && pages.every((item) => item.complete) };
}
@@ -164,6 +174,8 @@ export interface FindWorkflowsByTaskTypeOptions extends ListAllWorkflowsOptions
export interface FindWorkflowsByTaskTypeResult {
workflows: WorkflowWithMatches[];
errors: WorkflowListAllError[];
pages?: ListAllWorkflowsResult["pages"];
complete?: boolean;
}
@@ -202,5 +214,5 @@ export async function findWorkflowsByTaskType(
}
}
return { workflows: matched, errors: [...all.errors, ...detailErrors] };
return { workflows: matched, errors: [...all.errors, ...detailErrors], pages: all.pages, complete: all.complete === true && detailErrors.length === 0 };
}
@@ -172,6 +172,19 @@ describe("workflow draft state machine", () => {
rmSync(dir, { recursive: true, force: true });
});
it("preserves previously observed alerts when a scan is incomplete", () => {
const dir = mkdtempSync("hose-workflow-alert-partial-");
const file = join(dir, "alerts.json");
const store = new WorkflowAlertStore(file);
const alert = { id: "corp:platform:wf-1", pipelineId: "wf-1", platformId: "platform-1", pipelineName: "测试流程", errorCount: 1, state: 0, observedAt: 1 };
expect(store.observe([alert]).newAlerts).toHaveLength(1);
store.observe([], { complete: false });
expect(store.observe([{ ...alert, observedAt: 2 }], { complete: false }).newAlerts).toHaveLength(0);
store.observe([], { complete: true });
expect(store.observe([alert]).newAlerts).toHaveLength(1);
rmSync(dir, { recursive: true, force: true });
});
it("tracks dirty revisions and commits the server snapshot", () => {
let state = createWorkflowDraft(workflow());
state = patchWorkflowDraft(state, (current) => ({ ...current, label: "已修改" }), ["label"]);