diff --git a/src/core/errors.ts b/src/core/errors.ts index 5f83688..f6577a7 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -97,7 +97,13 @@ function isValidationIssueList(error: unknown): boolean { ); } -function responseStatus(error: unknown): number | undefined { +/** + * Read the HTTP status off an error thrown by the HTTP layer, structurally: + * ky's `HTTPError` is not a dependency of this module, and test doubles only + * carry `{ response: { status } }`. `undefined` means the request never got a + * response (DNS failure, connection reset, timeout). + */ +export function responseStatus(error: unknown): number | undefined { if (!error || typeof error !== "object") return undefined; const response = (error as { response?: unknown }).response; if (!response || typeof response !== "object") return undefined; diff --git a/src/domains/seal/capabilities/approval-runs-flow.test.ts b/src/domains/seal/capabilities/approval-runs-flow.test.ts new file mode 100644 index 0000000..d310233 --- /dev/null +++ b/src/domains/seal/capabilities/approval-runs-flow.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, test } from "bun:test"; +import type { KyInstance } from "ky"; +import type { CorpConfig } from "../../../core/config/types.js"; +import { findSealCapability } from "../capabilities.js"; + +/** + * The flow lookup uses a rejected record query as a routing signal ("this was + * not a record ID, treat it as a document number") and a rejected run listing + * as "this document has no AI records". Both are fine for an identifier-shaped + * rejection and catastrophic for anything else: an expired token or a reset + * connection would be reported downstream as 「单据已删除」 or 「AI 从未审核」, + * which is a wrong answer delivered with full confidence. + * + * These cases stop before the Hose client is built, so no tenant is required. + */ + +const HOSE_CORP = { + id: "corp-hose", + name: "测试合思企业", + source: { type: "hose" } +} as unknown as CorpConfig; + +type Handler = ( + client: KyInstance, + params: Record, + context: { corp: CorpConfig } +) => Promise; + +function flowHandler(): Handler { + const capability = findSealCapability("sealApprovalRunFlowGet"); + expect(capability).toBeDefined(); + return capability!.handler as unknown as Handler; +} + +function failingClient(error: unknown): KyInstance { + return { + get: () => { + throw error; + } + } as unknown as KyInstance; +} + +function httpError(status: number): Error { + return Object.assign(new Error(`Request failed with status code ${status}`), { + response: { status } + }); +} + +async function captured(promise: Promise): Promise { + try { + await promise; + return undefined; + } catch (error) { + return error; + } +} + +const SURFACED = [ + ["expired credentials", httpError(401)], + ["forbidden credentials", httpError(403)], + ["upstream service failure", httpError(503)], + ["connection failure without a response", new TypeError("fetch failed")] +] as const; + +describe("sealApprovalRunFlowGet failure attribution", () => { + for (const [label, error] of SURFACED) { + test(`surfaces ${label} instead of absorbing it as a document number`, async () => { + const thrown = await captured( + flowHandler()(failingClient(error), { target: "B26001887" }, { corp: HOSE_CORP }) + ); + // Identity, not message: the original error must reach the CLI layer so + // classifyCliError can still produce exit code 11 for auth failures. + expect(thrown).toBe(error); + }); + } + + test("keeps rejecting non-Hose enterprises before any request", async () => { + let called = false; + const client = { + get: () => { + called = true; + throw new Error("must not be reached"); + } + } as unknown as KyInstance; + + const thrown = await captured( + flowHandler()(client, { target: "B26001887" }, { + corp: { id: "corp-seal", name: "Seal 企业", source: { type: "seal" } } as unknown as CorpConfig + }) + ); + + expect(String(thrown)).toContain("非合思"); + expect(called).toBe(false); + }); +}); diff --git a/src/domains/seal/capabilities/approval-runs.ts b/src/domains/seal/capabilities/approval-runs.ts index 4810e18..465b0b1 100644 --- a/src/domains/seal/capabilities/approval-runs.ts +++ b/src/domains/seal/capabilities/approval-runs.ts @@ -1,4 +1,4 @@ -import { usageError, validationError } from "../../../core/errors.js"; +import { classifyCliError, responseStatus, usageError, validationError } from "../../../core/errors.js"; import { z } from "zod"; import type { KyInstance } from "ky"; import * as api from "../api.js"; @@ -48,6 +48,28 @@ const { summarizeRuleVersion } = helpers; +/** + * Decide whether a failed lookup means "the caller's input was not an ID of + * that kind" or something worse. + * + * Distinguishing them matters because both call sites below use the failure as + * a routing signal: a rejected record lookup means "treat the input as a + * document number", and a rejected run listing means "this document has no AI + * records". Swallowing everything turns a transient failure into a confident + * business verdict — an expired token or a reset connection would surface as + * 「单据已删除」 or 「AI 从未审核」, which is worse than an error. + */ +function isUpstreamLookupMiss(error: unknown): boolean { + const status = responseStatus(error); + if (status !== undefined) { + // Malformed or unknown identifier: the answer we were hoping for. + return status === 400 || status === 404 || status === 422; + } + // No response at all (DNS, reset, timeout) is never a miss. Structural + // validation failures are: the body arrived, it just is not an approval run. + return classifyCliError(error).exitCode === 13; +} + export const approvalRunsCapabilities = [ { name: "sealApprovalRunsSearch", @@ -273,8 +295,9 @@ export const approvalRunsCapabilities = [ if (targetRecord?.sourceDocumentSN || targetRecord?.sourceDocumentId) { sn = (targetRecord.sourceDocumentSN || targetRecord.sourceDocumentId)!; } - } catch { - // Continue as SN + } catch (error) { + if (!isUpstreamLookupMiss(error)) throw error; + // Not a record ID: the caller passed a document number. Continue as SN. } let runs: ApprovalRun[] = []; @@ -287,8 +310,9 @@ export const approvalRunsCapabilities = [ runs = (runsData.records || []).filter( (r) => r.sourceDocumentSN === sn || r.sourceDocumentId === sn || r.id === input ); - } catch { - // ignore + } catch (error) { + if (!isUpstreamLookupMiss(error)) throw error; + // No AI records for this document is a legitimate outcome. } if (runs.length === 0 && targetRecord) {