From df447917792f896d17ab0441f9360f017cf10a18 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 11 Oct 2026 19:33:19 +0800 Subject: [PATCH 1/7] Add shared outbound-push module for Hose deploy and replay MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The deploy capability and the cross-tenant replay each carried their own copy of the same outbound pipeline: integration selection, the assisted-only gate, payload/URL construction, and push-then-verify. A change to the wire contract could drift into one path and not the other. Move the shared parts into domains/seal/outbound-push.ts and return the raw CloseAPI messageLog query to the hose domain (domains/hose/close/outbound.ts), leaving only the replay-specific log matching on the seal side. The production-target guard is now one implementation (replay-safety.ts) shared by the corp-pair resolver and the channel validator; both call sites are kept deliberately as defense in depth. Behavior note: replay used to silently pick the first integration when the target had several and no --sign-key was given. It now errors and lists the available signKeys, matching what deploy already did — pushing a message to the wrong outbound channel should not depend on array order. --- src/cli/commands/deploy.ts | 13 +- src/domains/hose/close/index.ts | 1 + src/domains/hose/close/outbound.ts | 80 +++++ src/domains/seal/capabilities/deploy.ts | 139 +++----- src/domains/seal/hose-outbound-replay.test.ts | 2 +- src/domains/seal/hose-outbound-replay.ts | 232 ++++-------- src/domains/seal/outbound-push.test.ts | 334 ++++++++++++++++++ src/domains/seal/outbound-push.ts | 200 +++++++++++ src/domains/seal/replay-safety.ts | 28 ++ src/domains/seal/webhook-replay.ts | 15 +- 10 files changed, 774 insertions(+), 270 deletions(-) create mode 100644 src/domains/hose/close/outbound.ts create mode 100644 src/domains/seal/outbound-push.test.ts create mode 100644 src/domains/seal/outbound-push.ts create mode 100644 src/domains/seal/replay-safety.ts diff --git a/src/cli/commands/deploy.ts b/src/cli/commands/deploy.ts index a8b2b9d..940f180 100644 --- a/src/cli/commands/deploy.ts +++ b/src/cli/commands/deploy.ts @@ -6,6 +6,7 @@ import { booleanOption, jsonObject, numberOption, stringOption } from "../parser import { outputOptions } from "../printer.js"; import type { ParsedArgs } from "../types.js"; import * as api from "../../domains/seal/api.js"; +import { listHoseIntegrations } from "../../domains/seal/outbound-push.js"; import { CliError } from "../errors.js"; export async function handleDeployCommand( @@ -68,7 +69,7 @@ export async function handleDeployCommand( const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]); if (!signKey) { const config = await api.getApprovalStylePreferences(client); - const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud"); + const hoseConfigs = listHoseIntegrations(config); if (hoseConfigs.length === 0) { throw new Error( `当前企业 (${corp.name}) 尚未添加合思发布配置。\n` + @@ -78,9 +79,9 @@ export async function handleDeployCommand( console.error(`Usage: seal-use deploy hosecloud get [--corp ${corp.id}]\n`); console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`); for (const item of hoseConfigs) { - const name = (item as any).outboundName ?? "SealAI 审批"; + const name = item.outboundName ?? "SealAI 审批"; const key = item.signKey; - const origin = (item as any).apiOrigin ?? "production"; + const origin = item.apiOrigin ?? "production"; console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`); console.error(` 👉 查看命令: seal-use deploy hosecloud get ${key} --corp ${corp.id}\n`); } @@ -122,7 +123,7 @@ export async function handleDeployCommand( if (!signKey) { const config = await api.getApprovalStylePreferences(client); - const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud"); + const hoseConfigs = listHoseIntegrations(config); if (hoseConfigs.length === 0) { throw new Error( @@ -142,9 +143,9 @@ export async function handleDeployCommand( console.error(`Usage: seal-use deploy hosecloud sync [--corp ${corp.id}]\n`); console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`); for (const item of hoseConfigs) { - const name = (item as any).outboundName ?? "SealAI 审批"; + const name = item.outboundName ?? "SealAI 审批"; const key = item.signKey; - const origin = (item as any).apiOrigin ?? "production"; + const origin = item.apiOrigin ?? "production"; console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`); console.error(` 👉 同步命令: seal-use deploy hosecloud sync ${key} --corp ${corp.id}\n`); } diff --git a/src/domains/hose/close/index.ts b/src/domains/hose/close/index.ts index 498d3bc..db982ae 100644 --- a/src/domains/hose/close/index.ts +++ b/src/domains/hose/close/index.ts @@ -1,3 +1,4 @@ export * from "./types.js"; export * from "./client.js"; export * from "./api.js"; +export * from "./outbound.js"; diff --git a/src/domains/hose/close/outbound.ts b/src/domains/hose/close/outbound.ts new file mode 100644 index 0000000..4883f71 --- /dev/null +++ b/src/domains/hose/close/outbound.ts @@ -0,0 +1,80 @@ +import type { KyInstance } from "ky"; +import { validationError } from "../../../core/errors.js"; +import type { CorpConfig } from "../../../core/config/types.js"; +import { createHoseCloseClient } from "./client.js"; + +/** + * A single row of the CloseAPI outbound message log. The `request` payload is + * the EBot push body, so its fields mirror Seal's `/api/hosecloud/outbound` + * contract (flowId / nodeId / messageId / rejectionNum / corporationId). + */ +export interface HoseOutboundLogItem { + id: string; + name: string; + type: "INVOKING" | "CALLBACK" | string; + state: string; + flowId?: { + id: string; + form?: { + code?: string; + }; + }; + nodeName?: string; + createTime: number; + messageType?: string; + request?: { + flowId?: string; + nodeId?: string; + messageId?: string; + rejectionNum?: number; + corporationId?: string; + action?: string; + comment?: string; + signKey?: string; + [key: string]: unknown; + }; + response?: unknown; +} + +/** + * Query CloseAPI's outbound message log for one document SN (flowId.form.code). + */ +export async function searchOutboundMessageLogs( + client: KyInstance, + corpId: string, + sn: string +): Promise { + const response = (await client + .post("api/outbound/v1/message/messageLog", { + searchParams: { + messageType: "flow", + corpId + }, + json: { + limit: { start: 0, count: 20 }, + orderBy: [{ value: "createTime", order: "DESC" }], + select: "id,name,flowId(id, form(code)),nodeName,type,request,response,state,createTime,messageType", + filterBy: `(flowId.form.code==("${sn}"))` + } + }) + .json()) as { items?: HoseOutboundLogItem[] }; + + return response.items ?? []; +} + +/** + * Fetch historical outbound message logs from Hosecloud's CloseAPI for a given document SN. + */ +export async function fetchHoseOutboundLogs( + sourceCorp: CorpConfig, + sn: string +): Promise { + if (sourceCorp.source.type !== "hose") { + throw validationError( + `源企业「${sourceCorp.name}」非合思(hose)租户,无法通过合思 CloseAPI 查询出站消息日志。` + ); + } + + const client = await createHoseCloseClient(sourceCorp); + return searchOutboundMessageLogs(client, sourceCorp.source.corpId, sn); +} diff --git a/src/domains/seal/capabilities/deploy.ts b/src/domains/seal/capabilities/deploy.ts index eeb36ee..2aeac2d 100644 --- a/src/domains/seal/capabilities/deploy.ts +++ b/src/domains/seal/capabilities/deploy.ts @@ -3,11 +3,19 @@ import type { KyInstance } from "ky"; import { randomBytes } from "node:crypto"; import * as api from "../api.js"; import { probeHoseDomain } from "../../../core/auth/hose.js"; -import { safetyBlocked, validationError } from "../../../core/errors.js"; +import { validationError } from "../../../core/errors.js"; +import { type HosecloudConfigInput } from "../types.js"; import { - type ApprovalRun, - type HosecloudConfigInput -} from "../types.js"; + assertAssistedIntegration, + BLOCKING_NODE_ID, + buildOutboundPayload, + buildOutboundWebhookUrl, + flowIdFromDocumentSn, + listHoseIntegrations, + pushOutboundAndVerify, + resolveCorporationId, + selectHoseIntegration +} from "../outbound-push.js"; import type { CapabilityContext } from "./helpers.js"; @@ -46,7 +54,7 @@ export const deployCapabilities = [ parameters: z.object({}), handler: async (client: KyInstance) => { const config = await api.getApprovalStylePreferences(client); - const integrations = (config.integrations ?? []).filter((item: any) => item.type === "hosecloud"); + const integrations = listHoseIntegrations(config); return { count: integrations.length, integrations: integrations.map(redactIntegrationSecrets) @@ -61,8 +69,8 @@ export const deployCapabilities = [ }), handler: async (client: KyInstance, params: { signKey: string }) => { const config = await api.getApprovalStylePreferences(client); - const integration = (config.integrations ?? []).find( - (item: any) => item.type === "hosecloud" && item.signKey === params.signKey + const integration = listHoseIntegrations(config).find( + (item) => item.signKey === params.signKey ); if (!integration) { throw new Error(`未找到合思配置:${params.signKey}`); @@ -77,7 +85,7 @@ export const deployCapabilities = [ handler: async (client: KyInstance) => { const status = await api.getSimulationIntegrationStatus(client); const config = await api.getApprovalStylePreferences(client); - const integrations = (config.integrations ?? []).filter((item: any) => item.type === "hosecloud"); + const integrations = listHoseIntegrations(config); return { status, integrations: integrations.map(redactIntegrationSecrets) @@ -194,20 +202,20 @@ export const deployCapabilities = [ }), handler: async (client: KyInstance, params: { signKey: string }, context: CapabilityContext) => { const config = await api.getApprovalStylePreferences(client); - const integration = (config.integrations ?? []).find( - (item: any) => item.type === "hosecloud" && item.signKey === params.signKey + const integration = listHoseIntegrations(config).find( + (item) => item.signKey === params.signKey ); if (!integration) { throw new Error(`未找到合思配置:${params.signKey}`); } const sealUrl = (context.corp.seal.url ?? `https://${context.corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, ""); - const messageName = (integration as any).outboundName ?? "SealAI 审批"; + const messageName = integration.outboundName ?? "SealAI 审批"; const result = await api.syncHosecloudOutbound(client, { signKey: params.signKey, - webhookUrl: `${sealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(params.signKey)}`, + webhookUrl: buildOutboundWebhookUrl(context.corp, params.signKey), completionWebhookUrl: `${sealUrl}/api/hosecloud/flow/completion?config_id=${encodeURIComponent(params.signKey)}`, messageName, - mode: (integration as any).mode ?? "assisted" + mode: integration.mode ?? "assisted" }); console.error(`✓ 同步成功!出站消息已在合思开放平台创建/更新: "${messageName}"`); @@ -228,7 +236,7 @@ export const deployCapabilities = [ flowId: z.string().optional().describe("合思单据/流程 ID (flowId / sourceDocumentId)"), sn: z.string().optional().describe("合思单号 (sourceDocumentSN,若未提供 flowId 可自动解析)"), messageId: z.string().describe("合思真实的 messageId(合思开放平台消息凭证,必须提供真实有效值以供拉取单据)"), - nodeId: z.string().optional().default("FLOW:测试模拟节点_禁止流转").describe("合思流程节点 ID(默认填入中文阻断标识)"), + nodeId: z.string().optional().default(BLOCKING_NODE_ID).describe("合思流程节点 ID(默认填入中文阻断标识)"), rejectionNum: z.number().int().optional().default(0).describe("驳回/重提次数(默认 0)"), corporationId: z.string().optional().describe("合思企业 ID(若未提供则取自集成配置)"), dryRun: z.boolean().optional().default(false).describe("是否仅预览请求载荷与安全检查而不实际推送") @@ -248,39 +256,18 @@ export const deployCapabilities = [ context: CapabilityContext ) => { const config = await api.getApprovalStylePreferences(client); - const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud"); - if (hoseConfigs.length === 0) { - throw new Error( - `当前企业 (${context.corp.name}) 尚未添加合思发布配置。\n` + - `👉 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${context.corp.id}` - ); - } - - let integration: any; - if (params.signKey) { - integration = hoseConfigs.find((i: any) => i.signKey === params.signKey); - if (!integration) { - throw validationError( - `未找到 signKey 为「${params.signKey}」的合思集成配置。可用 signKey: ${hoseConfigs.map((i: any) => i.signKey).join(", ")}` - ); - } - } else if (hoseConfigs.length === 1) { - integration = hoseConfigs[0]; - } else { - const list = hoseConfigs.map((i: any) => `"${i.outboundName ?? "SealAI 审批"}" (signKey: ${i.signKey})`).join(", "); - throw validationError( - `当前企业存在多个合思集成 [${list}],请通过 --sign-key 指定目标集成配置。` - ); - } + const integration = selectHoseIntegration({ + integrations: listHoseIntegrations(config), + signKey: params.signKey, + corpName: context.corp.name, + corpId: context.corp.id + }); // 1. 严格安全门禁检查:强制要求目标集成必须为 assisted 模式 - const mode = integration.mode ?? "assisted"; - if (mode !== "assisted") { - throw safetyBlocked( - `安全阻断:目标合思配置「${integration.outboundName ?? integration.signKey}」当前为「${mode}」模式,非 assisted(辅助审核)模式。为防止自动向合思回写审批动作影响生产/线上流程,严禁在此模式下测试出站通道。`, - `请先在目标企业将模式调整为 assisted 模式后重试:seal-use deploy hosecloud configure --json '{"signKey":"${integration.signKey}","mode":"assisted"}' --corp ${context.corp.id}` - ); - } + assertAssistedIntegration(integration, { + corpName: context.corp.name, + corpId: context.corp.id + }); // 2. 消息凭证校验 const messageId = params.messageId?.trim(); @@ -309,8 +296,8 @@ export const deployCapabilities = [ } catch { // 忽略 } - if (!flowId && sn.startsWith("ID01")) { - flowId = sn; + if (!flowId) { + flowId = flowIdFromDocumentSn(sn); } } @@ -321,26 +308,16 @@ export const deployCapabilities = [ } // 4. 解析 corporationId - const corporationId = params.corporationId?.trim() || integration.corporationId; - if (!corporationId) { - throw validationError( - "缺少 corporationId,且当前合思集成未保存有效 corporationId,请通过 --corporation-id 参数显式提供。" - ); - } + const corporationId = resolveCorporationId([params.corporationId, integration.corporationId]); - const nodeId = params.nodeId?.trim() || "FLOW:测试模拟节点_禁止流转"; - const rejectionNum = params.rejectionNum ?? 0; - - const sealUrl = (context.corp.seal.url ?? `https://${context.corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, ""); - const webhookUrl = `${sealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(integration.signKey)}`; - - const payload = { + const payload = buildOutboundPayload({ flowId, - nodeId, messageId, - rejectionNum, + nodeId: params.nodeId, + rejectionNum: params.rejectionNum, corporationId - }; + }); + const webhookUrl = buildOutboundWebhookUrl(context.corp, integration.signKey!); if (params.dryRun) { return { @@ -361,30 +338,18 @@ export const deployCapabilities = [ }; } - const response = await api.postHosecloudOutbound(client, integration.signKey, payload); - - // 等待后台队列消费 (2秒) - await new Promise((r) => setTimeout(r, 2000)); - let createdRecord: ApprovalRun | undefined; - try { - const runs = await api.listApprovalRuns(client, { - limit: 5, - search: flowId - }); - createdRecord = (runs.records || []).find( - (r) => r.sourceDocumentId === flowId || r.sourceDocumentSN === flowId - ); - } catch { - // 非阻塞 - } - - console.error(`✓ 已成功向合思出站通道推送测试消息 (flowId: ${flowId}, signKey: ${integration.signKey})`); - if (createdRecord) { - console.error(`✓ 异步消费成功!已在【${context.corp.name}】生成审核记录: ${createdRecord.id} (任务模式: ${createdRecord.taskMode})`); - console.error(`👉 查看审核详情: seal-use approval-runs get ${createdRecord.id} --corp ${context.corp.id}`); - } else { - console.error(`ℹ️ 消息已入队正在异步消费,可在几秒后刷新后台页面或查询: seal-use approval-runs list --corp ${context.corp.id}`); - } + const { response, createdRecord } = await pushOutboundAndVerify({ + client, + signKey: integration.signKey!, + payload, + flowId, + sn, + corpName: context.corp.name, + corpId: context.corp.id, + pushedMessages: [ + `✓ 已成功向合思出站通道推送测试消息 (flowId: ${flowId}, signKey: ${integration.signKey})` + ] + }); return { success: true, diff --git a/src/domains/seal/hose-outbound-replay.test.ts b/src/domains/seal/hose-outbound-replay.test.ts index fb24ad8..3ab0a6a 100644 --- a/src/domains/seal/hose-outbound-replay.test.ts +++ b/src/domains/seal/hose-outbound-replay.test.ts @@ -173,7 +173,7 @@ describe("validateHoseOutboundReplaySafety", () => { prodTarget, { mode: "assisted", signKey: "k" } ) - ).toThrow(/标记为正式生产环境/); + ).toThrow(/标记为生产正式环境/); }); test("blocks when target mode is NOT assisted", () => { diff --git a/src/domains/seal/hose-outbound-replay.ts b/src/domains/seal/hose-outbound-replay.ts index 97e8f53..5d29bfb 100644 --- a/src/domains/seal/hose-outbound-replay.ts +++ b/src/domains/seal/hose-outbound-replay.ts @@ -1,37 +1,22 @@ import type { KyInstance } from "ky"; import type { CorpConfig } from "../../core/config/types.js"; import { safetyBlocked, validationError } from "../../core/errors.js"; -import { createHoseCloseClient } from "../hose/close/client.js"; +import { fetchHoseOutboundLogs, type HoseOutboundLogItem } from "../hose/close/outbound.js"; import * as api from "./api.js"; +import { + assertAssistedIntegration, + buildOutboundPayload, + buildOutboundWebhookUrl, + flowIdFromDocumentSn, + listHoseIntegrations, + pushOutboundAndVerify, + resolveCorporationId, + selectHoseIntegration +} from "./outbound-push.js"; +import { assertNonProductionReplayTarget } from "./replay-safety.js"; import type { ApprovalRun } from "./types.js"; -export interface HoseOutboundLogItem { - id: string; - name: string; - type: "INVOKING" | "CALLBACK" | string; - state: string; - flowId?: { - id: string; - form?: { - code?: string; - }; - }; - nodeName?: string; - createTime: number; - messageType?: string; - request?: { - flowId?: string; - nodeId?: string; - messageId?: string; - rejectionNum?: number; - corporationId?: string; - action?: string; - comment?: string; - signKey?: string; - [key: string]: unknown; - }; - response?: unknown; -} +export type { HoseOutboundLogItem } from "../hose/close/outbound.js"; export interface HoseOutboundReplayOptions { sourceCorp: CorpConfig; @@ -50,42 +35,12 @@ export interface HoseOutboundReplayOptions { force?: boolean; } -/** - * Fetch historical outbound message logs from Hosecloud's CloseAPI for a given document SN. - */ -export async function fetchHoseOutboundLogs( - sourceCorp: CorpConfig, - sn: string -): Promise { - if (sourceCorp.source.type !== "hose") { - throw validationError( - `源企业「${sourceCorp.name}」非合思(hose)租户,无法通过合思 CloseAPI 查询出站消息日志。` - ); - } - - const client = await createHoseCloseClient(sourceCorp); - const corpId = sourceCorp.source.corpId; - - const response = (await client - .post("api/outbound/v1/message/messageLog", { - searchParams: { - messageType: "flow", - corpId - }, - json: { - limit: { start: 0, count: 20 }, - orderBy: [{ value: "createTime", order: "DESC" }], - select: "id,name,flowId(id, form(code)),nodeName,type,request,response,state,createTime,messageType", - filterBy: `(flowId.form.code==("${sn}"))` - } - }) - .json()) as { items?: HoseOutboundLogItem[] }; - - return response.items ?? []; -} - /** * Select the best matching INVOKING log from a list of outbound message logs. + * + * This is the replay channel's own matching policy — it maps a Seal approval + * record back onto the Hose outbound event that produced it, so it stays here + * rather than in the shared push module. */ export function selectMatchingOutboundLog( logs: HoseOutboundLogItem[], @@ -177,23 +132,17 @@ export function validateHoseOutboundReplaySafety( } // 2. Production target guard - if (targetCorp.environment === "production" && !force) { - throw safetyBlocked( - `安全阻断:目标企业「${targetCorp.name}」标记为正式生产环境 (production)。\n` + - `为防止测试消息污染生产审批流,严禁向生产企业重发出站报文。请通过 --target-corp 指定测试企业。`, - `seal-use approval-runs replay --target-corp ...` - ); - } + assertNonProductionReplayTarget(targetCorp, { + force, + action: "重放出站报文", + nextAction: `seal-use webhook replay --channel hose-outbound --target-corp --source-corp ${sourceCorp.id}` + }); // 3. Mode guard: target Hose integration MUST be assisted - const mode = targetIntegration.mode ?? "assisted"; - if (mode !== "assisted") { - throw safetyBlocked( - `安全阻断:目标测试企业「${targetCorp.name}」的合思配置「${targetIntegration.outboundName ?? targetIntegration.signKey}」当前为「${mode}」模式,非 assisted(辅助审核)模式。\n` + - `为防止自动向合思回写审批动作影响流程,严禁在非 assisted 模式下重放出站单据。`, - `请先将目标企业的合思配置调整为 assisted 模式后重试:seal-use deploy hosecloud configure --json '{"signKey":"${targetIntegration.signKey}","mode":"assisted"}' --corp ${targetCorp.id}` - ); - } + assertAssistedIntegration(targetIntegration, { + corpName: targetCorp.name, + corpId: targetCorp.id + }); } /** @@ -202,44 +151,17 @@ export function validateHoseOutboundReplaySafety( export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptions) { const { sourceCorp, targetCorp, targetClient, dryRun, force } = options; - // 1. Get target corp's Hose integrations + // 1. Resolve the target's hose integration (ambiguous lists are an error, not a guess) const targetConfig = await api.getApprovalStylePreferences( targetClient, targetCorp.seal?.endpoints?.approvalStylePreferences ); - const hoseConfigs: Array<{ - type: string; - signKey?: string; - outboundName?: string; - mode?: string; - corporationId?: string; - [key: string]: unknown; - }> = (targetConfig.integrations ?? []).filter((i: any) => i.type === "hosecloud"); - if (hoseConfigs.length === 0) { - throw validationError( - `目标测试企业「${targetCorp.name}」未配置任何合思出站发布通道。请先运行:seal-use deploy hosecloud configure --corp ${targetCorp.id}` - ); - } - - const foundIntegration = options.targetSignKey - ? hoseConfigs.find((i) => i.signKey === options.targetSignKey) - : hoseConfigs[0]; - - if (!foundIntegration || !foundIntegration.signKey) { - if (options.targetSignKey) { - throw validationError( - `在目标企业中未找到 signKey 为「${options.targetSignKey}」的合思配置。可用配置: ${hoseConfigs.map((i) => i.signKey).filter(Boolean).join(", ")}` - ); - } - throw validationError( - `目标测试企业「${targetCorp.name}」未配置有效的合思 signKey。` - ); - } - - const targetIntegration = { - ...foundIntegration, - signKey: foundIntegration.signKey - }; + const targetIntegration = selectHoseIntegration({ + integrations: listHoseIntegrations(targetConfig), + signKey: options.targetSignKey, + corpName: targetCorp.name, + corpId: targetCorp.id + }); // 2. Validate safety constraints validateHoseOutboundReplaySafety(sourceCorp, targetCorp, targetIntegration, force); @@ -294,11 +216,11 @@ export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptio // 5. Construct payload const flowId = - options.flowId?.trim() ?? - selectedLog?.request?.flowId ?? - selectedLog?.flowId?.id ?? - sourceRecord?.sourceDocumentId ?? - (sn?.startsWith("ID01") ? sn : undefined); + options.flowId?.trim() || + selectedLog?.request?.flowId || + selectedLog?.flowId?.id || + sourceRecord?.sourceDocumentId || + flowIdFromDocumentSn(sn); if (!flowId) { throw validationError( @@ -306,35 +228,26 @@ export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptio ); } - const messageId = options.messageId?.trim() ?? selectedLog?.request?.messageId; + const messageId = options.messageId?.trim() || selectedLog?.request?.messageId; if (!messageId) { throw validationError("未能获取到有效 messageId。"); } - const rejectionNum = - options.rejectionNum ?? selectedLog?.request?.rejectionNum ?? 0; + const corporationId = resolveCorporationId([ + options.corporationId, + selectedLog?.request?.corporationId, + sourceCorp.source.type === "hose" ? sourceCorp.source.corpId : undefined, + targetIntegration.corporationId + ]); - const corporationId = - options.corporationId?.trim() ?? - selectedLog?.request?.corporationId ?? - (sourceCorp.source as any)?.corpId ?? - targetIntegration.corporationId; - - // Crucial: Chinese mock nodeId causes Hose to return HTTP 412 on callback, creating an indestructible safety gate - const nodeId = options.nodeId?.trim() || "FLOW:测试模拟节点_禁止流转"; - - const targetSealUrl = ( - targetCorp.seal.url ?? `https://${targetCorp.id.toLowerCase()}.sealai.cc` - ).replace(/\/+$/, ""); - const targetWebhookUrl = `${targetSealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(targetIntegration.signKey)}`; - - const payload = { + const payload = buildOutboundPayload({ flowId, - nodeId, messageId, - rejectionNum, + nodeId: options.nodeId, + rejectionNum: options.rejectionNum ?? selectedLog?.request?.rejectionNum, corporationId - }; + }); + const targetWebhookUrl = buildOutboundWebhookUrl(targetCorp, targetIntegration.signKey!); // 6. Dry run preview if (dryRun) { @@ -376,36 +289,19 @@ export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptio } // 7. Live execution - const response = await api.postHosecloudOutbound( - targetClient, - targetIntegration.signKey, - payload - ); - - console.error(`✓ 成功从合思出站日志匹配消息 (messageId: ${messageId}, 轮次: ${rejectionNum})`); - console.error(`✓ 已向测试企业「${targetCorp.name}」出站网关推送重放报文 (nodeId: ${nodeId})`); - - // Wait 2.5s for worker queue consumption - await new Promise((r) => setTimeout(r, 2500)); - let createdRecord: ApprovalRun | undefined; - try { - const runs = await api.listApprovalRuns(targetClient, { - limit: 5, - search: flowId - }); - createdRecord = (runs.records || []).find( - (r) => r.sourceDocumentId === flowId || r.sourceDocumentSN === sn - ); - } catch { - // non-blocking - } - - if (createdRecord) { - console.error(`✓ 异步消费成功!已在【${targetCorp.name}】生成审核记录: ${createdRecord.id} (任务模式: ${createdRecord.taskMode})`); - console.error(`👉 查看审核详情: seal-use approval-runs get ${createdRecord.id} --corp ${targetCorp.id}`); - } else { - console.error(`ℹ️ 消息已入队正在异步消费,可稍后在测试后台页面刷新查看。`); - } + const { response, createdRecord } = await pushOutboundAndVerify({ + client: targetClient, + signKey: targetIntegration.signKey!, + payload, + flowId, + sn, + corpName: targetCorp.name, + corpId: targetCorp.id, + pushedMessages: [ + `✓ 成功从合思出站日志匹配消息 (messageId: ${messageId}, 轮次: ${payload.rejectionNum})`, + `✓ 已向测试企业「${targetCorp.name}」出站网关推送重放报文 (nodeId: ${payload.nodeId})` + ] + }); return { success: true, @@ -421,7 +317,7 @@ export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptio targetSignKey: targetIntegration.signKey, mode: targetIntegration.mode, matchedMessageId: messageId, - rejectionNum, + rejectionNum: payload.rejectionNum, payload, response, recordId: createdRecord?.id, diff --git a/src/domains/seal/outbound-push.test.ts b/src/domains/seal/outbound-push.test.ts new file mode 100644 index 0000000..d92d01e --- /dev/null +++ b/src/domains/seal/outbound-push.test.ts @@ -0,0 +1,334 @@ +import { describe, expect, test } from "bun:test"; +import type { KyInstance } from "ky"; +import type { CorpConfig } from "../../core/config/types.js"; +import type { ApprovalIntegration, ApprovalStylePreferences } from "./types.js"; +import { + assertAssistedIntegration, + BLOCKING_NODE_ID, + buildOutboundPayload, + buildOutboundWebhookUrl, + flowIdFromDocumentSn, + listHoseIntegrations, + pushOutboundAndVerify, + resolveCorporationId, + selectHoseIntegration +} from "./outbound-push.js"; + +function corp(overrides: Partial = {}): CorpConfig { + return { + id: "test-corp", + name: "测试企业", + environment: "test", + seal: { url: "https://test.sealai.cc" }, + source: { type: "seal", token: "t", sealUrl: "https://test.sealai.cc" }, + auth: { refreshTtl: 300 }, + ...overrides + } as CorpConfig; +} + +function integration(overrides: Partial = {}): ApprovalIntegration { + return { type: "hosecloud", signKey: "key-1", ...overrides }; +} + +function preferences(items: ApprovalIntegration[]): ApprovalStylePreferences { + return { integrations: items } as ApprovalStylePreferences; +} + +describe("listHoseIntegrations", () => { + test("keeps only hosecloud entries and tolerates a missing list", () => { + const items = listHoseIntegrations( + preferences([ + integration({ signKey: "a" }), + { type: "webhook", signKey: "b" } as ApprovalIntegration + ]) + ); + expect(items.map((item) => item.signKey)).toEqual(["a"]); + expect(listHoseIntegrations({} as ApprovalStylePreferences)).toEqual([]); + }); +}); + +describe("selectHoseIntegration", () => { + const corpName = "目标企业"; + const corpId = "target-corp"; + + test("uses the only integration when no signKey is given", () => { + const selected = selectHoseIntegration({ + integrations: [integration()], + corpName, + corpId + }); + expect(selected.signKey).toBe("key-1"); + }); + + test("resolves an explicit signKey", () => { + const selected = selectHoseIntegration({ + integrations: [integration({ signKey: "a" }), integration({ signKey: "b" })], + signKey: "b", + corpName, + corpId + }); + expect(selected.signKey).toBe("b"); + }); + + test("refuses to guess when several integrations exist and none was named", () => { + expect(() => + selectHoseIntegration({ + integrations: [integration({ signKey: "a" }), integration({ signKey: "b" })], + corpName, + corpId + }) + ).toThrow(/请通过 --sign-key 指定目标集成配置/); + }); + + test("errors when the configured list is empty", () => { + expect(() => selectHoseIntegration({ integrations: [], corpName, corpId })).toThrow( + /未配置任何合思出站发布通道/ + ); + }); + + test("errors when the named signKey is unknown, listing what exists", () => { + expect(() => + selectHoseIntegration({ + integrations: [integration({ signKey: "a" })], + signKey: "nope", + corpName, + corpId + }) + ).toThrow(/可用 signKey: a/); + }); + + test("rejects an integration that never saved a signKey", () => { + expect(() => + selectHoseIntegration({ + integrations: [integration({ signKey: undefined })], + corpName, + corpId + }) + ).toThrow(/未保存 signKey/); + }); +}); + +describe("assertAssistedIntegration", () => { + const options = { corpName: "目标企业", corpId: "target-corp" }; + + test("passes for assisted and for an unset mode (defaults to assisted)", () => { + expect(() => assertAssistedIntegration(integration({ mode: "assisted" }), options)).not.toThrow(); + expect(() => assertAssistedIntegration(integration({ mode: undefined }), options)).not.toThrow(); + }); + + test("blocks every non-assisted mode with an exit-14 safety error", () => { + for (const mode of ["fully_automatic", "semi_automatic"]) { + let thrown: unknown; + try { + assertAssistedIntegration(integration({ mode }), options); + } catch (error) { + thrown = error; + } + expect(thrown).toBeInstanceOf(Error); + expect((thrown as { exitCode?: number }).exitCode).toBe(14); + expect((thrown as Error).message).toContain("非 assisted(辅助审核)模式"); + } + }); + + test("next action tells the operator exactly how to flip the mode back", () => { + try { + assertAssistedIntegration(integration({ mode: "fully_automatic" }), options); + throw new Error("expected a block"); + } catch (error) { + expect((error as { nextAction?: string }).nextAction).toContain( + `"mode":"assisted"` + ); + expect((error as { nextAction?: string }).nextAction).toContain("--corp target-corp"); + } + }); +}); + +describe("payload and url builders", () => { + test("defaults nodeId to the blocking marker and rejectionNum to 0", () => { + const payload = buildOutboundPayload({ + flowId: "ID01abc", + messageId: "msg-1", + corporationId: "corp-1" + }); + expect(payload).toEqual({ + flowId: "ID01abc", + nodeId: BLOCKING_NODE_ID, + messageId: "msg-1", + rejectionNum: 0, + corporationId: "corp-1" + }); + }); + + test("an explicit nodeId wins only when non-blank after trimming", () => { + expect( + buildOutboundPayload({ + flowId: "f", + messageId: "m", + corporationId: "c", + nodeId: "FLOW:custom" + }).nodeId + ).toBe("FLOW:custom"); + expect( + buildOutboundPayload({ + flowId: "f", + messageId: "m", + corporationId: "c", + nodeId: " " + }).nodeId + ).toBe(BLOCKING_NODE_ID); + }); + + test("webhook url falls back to the corp subdomain and strips trailing slashes", () => { + expect(buildOutboundWebhookUrl(corp(), "key-1")).toBe( + "https://test.sealai.cc/api/hosecloud/outbound?config_id=key-1" + ); + expect( + buildOutboundWebhookUrl(corp({ seal: { url: "https://custom.example/" } as CorpConfig["seal"] }), "a/b") + ).toBe("https://custom.example/api/hosecloud/outbound?config_id=a%2Fb"); + expect(buildOutboundWebhookUrl(corp({ seal: {} as CorpConfig["seal"] }), "k")).toBe( + "https://test-corp.sealai.cc/api/hosecloud/outbound?config_id=k" + ); + }); +}); + +describe("flowIdFromDocumentSn", () => { + test("only ID01-prefixed SNs double as a flowId", () => { + expect(flowIdFromDocumentSn("ID01Wah1FQ9faf")).toBe("ID01Wah1FQ9faf"); + expect(flowIdFromDocumentSn("BX9990001")).toBeUndefined(); + expect(flowIdFromDocumentSn(undefined)).toBeUndefined(); + }); +}); + +describe("resolveCorporationId", () => { + test("takes the first non-blank candidate", () => { + expect(resolveCorporationId([undefined, "", " ", "ID01x", "ID01y"])).toBe("ID01x"); + }); + + test("fails with an actionable message when nothing is available", () => { + expect(() => resolveCorporationId([undefined, "", " "])).toThrow( + /请通过 --corporation-id 参数显式提供/ + ); + }); +}); + +describe("pushOutboundAndVerify", () => { + function fakeClient(records: Array>): KyInstance { + return { + post: async () => ({ json: async () => ({ data: { success: true } }) }), + get: async () => ({ json: async () => ({ data: { records } }) }) + } as unknown as KyInstance; + } + + test("reports the created run when the queue consumed the push", async () => { + const lines: string[] = []; + const originalError = console.error; + console.error = (line: string) => lines.push(line); + try { + const { response, createdRecord } = await pushOutboundAndVerify({ + client: fakeClient([ + { id: "run-9", sourceDocumentId: "ID01abc", status: "pending", taskMode: "auto" } + ]), + signKey: "key-1", + payload: buildOutboundPayload({ + flowId: "ID01abc", + messageId: "msg-1", + corporationId: "c" + }), + flowId: "ID01abc", + sn: "BX999", + corpName: "目标企业", + corpId: "target-corp", + pushedMessages: ["✓ pushed"], + verifyWaitMs: 0 + }); + + expect(response).toEqual({ success: true }); + expect(createdRecord?.id).toBe("run-9"); + expect(lines[0]).toBe("✓ pushed"); + expect(lines.join("\n")).toContain("已在【目标企业】生成审核记录: run-9"); + expect(lines.join("\n")).toContain("seal-use approval-runs get run-9 --corp target-corp"); + } finally { + console.error = originalError; + } + }); + + test("matches on SN when flowId is not yet on the record, and downgrades to queued", async () => { + const lines: string[] = []; + const originalError = console.error; + console.error = (line: string) => lines.push(line); + try { + const { createdRecord } = await pushOutboundAndVerify({ + client: fakeClient([{ id: "run-s", sourceDocumentSN: "BX999" }]), + signKey: "key-1", + payload: buildOutboundPayload({ + flowId: "ID01abc", + messageId: "msg-1", + corporationId: "c" + }), + flowId: "ID01abc", + sn: "BX999", + corpName: "目标企业", + corpId: "target-corp", + verifyWaitMs: 0 + }); + expect(createdRecord?.id).toBe("run-s"); + } finally { + console.error = originalError; + } + + const queued: string[] = []; + console.error = (line: string) => queued.push(line); + try { + const { createdRecord } = await pushOutboundAndVerify({ + client: fakeClient([]), + signKey: "key-1", + payload: buildOutboundPayload({ + flowId: "ID01abc", + messageId: "msg-1", + corporationId: "c" + }), + flowId: "ID01abc", + corpName: "目标企业", + corpId: "target-corp", + verifyWaitMs: 0 + }); + expect(createdRecord).toBeUndefined(); + expect(queued.join("\n")).toContain("消息已入队正在异步消费"); + expect(queued.join("\n")).toContain("seal-use approval-runs list --corp target-corp"); + } finally { + console.error = originalError; + } + }); + + test("a failing poll never turns a successful push into an error", async () => { + const originalError = console.error; + console.error = () => {}; + try { + const client = { + post: async () => ({ json: async () => ({ data: { success: true } }) }), + get: async () => { + throw new Error("502 Bad Gateway"); + } + } as unknown as KyInstance; + + const { response, createdRecord } = await pushOutboundAndVerify({ + client, + signKey: "key-1", + payload: buildOutboundPayload({ + flowId: "f", + messageId: "m", + corporationId: "c" + }), + flowId: "f", + corpName: "目标企业", + corpId: "target-corp", + verifyWaitMs: 0 + }); + + expect(response).toEqual({ success: true }); + expect(createdRecord).toBeUndefined(); + } finally { + console.error = originalError; + } + }); +}); diff --git a/src/domains/seal/outbound-push.ts b/src/domains/seal/outbound-push.ts new file mode 100644 index 0000000..849b686 --- /dev/null +++ b/src/domains/seal/outbound-push.ts @@ -0,0 +1,200 @@ +import type { KyInstance } from "ky"; +import { safetyBlocked, validationError } from "../../core/errors.js"; +import type { CorpConfig } from "../../core/config/types.js"; +import * as api from "./api.js"; +import type { ApprovalIntegration, ApprovalRun, ApprovalStylePreferences } from "./types.js"; + +/** + * Shared primitives for pushing a test/replay message into Seal's + * `/api/hosecloud/outbound` gateway. Two callers need them and they must stay + * in lockstep because they build the exact same wire payload: + * - `capabilities/deploy.ts` → `sealDeployHosecloudTestOutbound` (single tenant) + * - `hose-outbound-replay.ts` → `webhook replay --channel hose-outbound` (cross tenant) + * + * Anything that describes the outbound contract (payload shape, blocking nodeId, + * integration selection, the assisted-only gate) lives here so a change to the + * protocol can't drift into one path and not the other. + */ + +/** + * Chinese mock nodeId: Hose rejects the callback with HTTP 412 for this node, + * which is what keeps a pushed message from advancing a real approval flow. + */ +export const BLOCKING_NODE_ID = "FLOW:测试模拟节点_禁止流转"; + +/** Long enough for the worker queue to consume the push before we look for the run. */ +const OUTBOUND_VERIFY_WAIT_MS = 2_500; + +export interface OutboundPayload { + flowId: string; + nodeId: string; + messageId: string; + rejectionNum: number; + corporationId: string; +} + +export function listHoseIntegrations( + preferences: Pick +): ApprovalIntegration[] { + return (preferences.integrations ?? []).filter((item) => item.type === "hosecloud"); +} + +/** + * Pick the hose integration a push should target. An explicit signKey must + * match; without one, an ambiguous list is an error rather than a guess — + * pushing to the wrong outbound channel is not something to default silently. + */ +export function selectHoseIntegration(options: { + integrations: ApprovalIntegration[]; + signKey?: string; + corpName: string; + corpId: string; +}): ApprovalIntegration { + const { integrations, corpName, corpId } = options; + + if (integrations.length === 0) { + throw validationError( + `企业「${corpName}」未配置任何合思出站发布通道。\n` + + `请先运行:seal-use deploy hosecloud configure --json '{...}' --corp ${corpId}` + ); + } + + if (options.signKey) { + const found = integrations.find((item) => item.signKey === options.signKey); + if (!found) { + throw validationError( + `未找到 signKey 为「${options.signKey}」的合思配置。可用 signKey: ` + + `${integrations.map((item) => item.signKey).filter(Boolean).join(", ")}` + ); + } + return requireSignKey(found, corpName); + } + + if (integrations.length > 1) { + const list = integrations + .map((item) => `"${item.outboundName ?? "SealAI 审批"}" (signKey: ${item.signKey})`) + .join(", "); + throw validationError( + `企业「${corpName}」存在多个合思集成 [${list}],请通过 --sign-key 指定目标集成配置。` + ); + } + + return requireSignKey(integrations[0]!, corpName); +} + +function requireSignKey(integration: ApprovalIntegration, corpName: string): ApprovalIntegration { + if (!integration.signKey) { + throw validationError(`企业「${corpName}」的合思出站配置未保存 signKey,请重新执行 configure。`); + } + return integration; +} + +/** + * Every push must target an `assisted` integration: any other mode lets the + * result callback write approval actions back into the flow autonomously. + */ +export function assertAssistedIntegration( + integration: Pick, + options: { corpName: string; corpId: string } +): void { + const mode = integration.mode ?? "assisted"; + if (mode === "assisted") { + return; + } + + throw safetyBlocked( + `安全阻断:企业「${options.corpName}」的合思配置「${integration.outboundName ?? integration.signKey}」` + + `当前为「${mode}」模式,非 assisted(辅助审核)模式。\n` + + `为防止自动向合思回写审批动作影响审批流程,严禁在非 assisted 模式下推送出站报文。`, + `seal-use deploy hosecloud configure --json '{"signKey":"${integration.signKey}","mode":"assisted"}' --corp ${options.corpId}` + ); +} + +export function buildOutboundWebhookUrl(corp: CorpConfig, signKey: string): string { + const sealUrl = (corp.seal.url ?? `https://${corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, ""); + return `${sealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(signKey)}`; +} + +export function buildOutboundPayload(options: { + flowId: string; + messageId: string; + nodeId?: string; + rejectionNum?: number; + corporationId: string; +}): OutboundPayload { + return { + flowId: options.flowId, + nodeId: options.nodeId?.trim() || BLOCKING_NODE_ID, + messageId: options.messageId, + rejectionNum: options.rejectionNum ?? 0, + corporationId: options.corporationId + }; +} + +/** + * Hose document SNs double as flowIds only when they carry the ID01 prefix; + * any other SN needs a lookup to resolve the flow instance. + */ +export function flowIdFromDocumentSn(sn: string | undefined): string | undefined { + return sn?.startsWith("ID01") ? sn : undefined; +} + +export function resolveCorporationId(candidates: Array): string { + const found = candidates.map((value) => value?.trim()).find((value) => value); + if (!found) { + throw validationError( + "缺少 corporationId,且当前合思集成未保存有效 corporationId,请通过 --corporation-id 参数显式提供。" + ); + } + return found; +} + +/** + * Push the payload, then poll approval runs to report whether the queue + * consumed it. The poll is advisory: a miss only downgrades the message to + * "queued", it never fails the push that already succeeded. + */ +export async function pushOutboundAndVerify(options: { + client: KyInstance; + signKey: string; + payload: OutboundPayload; + flowId: string; + sn?: string; + corpName: string; + corpId: string; + /** Channel-specific success lines logged right after the push lands. */ + pushedMessages?: string[]; + /** Queue-drain wait before polling; injectable so tests don't sleep. */ + verifyWaitMs?: number; +}): Promise<{ response: Awaited>; createdRecord?: ApprovalRun }> { + const { client, signKey, payload, flowId, sn, corpName, corpId } = options; + + const response = await api.postHosecloudOutbound(client, signKey, payload); + for (const line of options.pushedMessages ?? []) { + console.error(line); + } + + await new Promise((resolve) => setTimeout(resolve, options.verifyWaitMs ?? OUTBOUND_VERIFY_WAIT_MS)); + + let createdRecord: ApprovalRun | undefined; + try { + const runs = await api.listApprovalRuns(client, { limit: 5, search: flowId }); + createdRecord = (runs.records || []).find( + (record) => + record.sourceDocumentId === flowId || + record.sourceDocumentSN === sn || + record.sourceDocumentSN === flowId + ); + } catch { + // Non-blocking: the run may not exist yet even when the push succeeded. + } + + if (createdRecord) { + console.error(`✓ 异步消费成功!已在【${corpName}】生成审核记录: ${createdRecord.id} (任务模式: ${createdRecord.taskMode})`); + console.error(`👉 查看审核详情: seal-use approval-runs get ${createdRecord.id} --corp ${corpId}`); + } else { + console.error(`ℹ️ 消息已入队正在异步消费,可稍后执行: seal-use approval-runs list --corp ${corpId}`); + } + + return { response, createdRecord }; +} diff --git a/src/domains/seal/replay-safety.ts b/src/domains/seal/replay-safety.ts new file mode 100644 index 0000000..b612b05 --- /dev/null +++ b/src/domains/seal/replay-safety.ts @@ -0,0 +1,28 @@ +import { safetyBlocked } from "../../core/errors.js"; +import type { CorpConfig } from "../../core/config/types.js"; + +/** + * Shared environment guard for every replay channel: test traffic must never + * land in a production tenant. Both the corp-pair resolver and the individual + * channel executors call it — the redundancy is deliberate, so a channel that + * is invoked without going through `resolveReplayCorpPair` is still blocked. + */ +export function assertNonProductionReplayTarget( + targetCorp: CorpConfig, + options: { + force?: boolean; + /** What is being forbidden, e.g. `重放单据` — used verbatim in the message. */ + action: string; + nextAction: string; + } +): void { + if (targetCorp.environment !== "production" || options.force) { + return; + } + + throw safetyBlocked( + `安全阻断:目标企业「${targetCorp.name}」(${targetCorp.id}) 标记为生产正式环境 (production)。\n` + + `为防止测试数据污染生产审批流,禁止向生产环境${options.action}。请指定测试企业 (--target-corp ),或在确有需要时添加 --force。`, + options.nextAction + ); +} diff --git a/src/domains/seal/webhook-replay.ts b/src/domains/seal/webhook-replay.ts index 338a7a8..38673eb 100644 --- a/src/domains/seal/webhook-replay.ts +++ b/src/domains/seal/webhook-replay.ts @@ -2,10 +2,11 @@ import type { KyInstance } from "ky"; import type { ApprovalRun, WebhookIntegration } from "./types.js"; import type { MaterialField } from "./material-pack/types.js"; import { webhookHeaders } from "./material-pack/signature.js"; -import { CliError, safetyBlocked, validationError } from "../../core/errors.js"; +import { CliError, validationError } from "../../core/errors.js"; import type { CorpConfig } from "../../core/config/types.js"; import { resolveSealCustomHeaders } from "../../core/http/request-headers.js"; import * as api from "./api.js"; +import { assertNonProductionReplayTarget } from "./replay-safety.js"; export const ALLOWED_WEBHOOK_FIELD_TYPES = new Set([ "TEXT", @@ -273,13 +274,11 @@ export function resolveReplayCorpPair( } // Safety guard: prevent pushing replay test records to production - if (targetCorp.environment === "production" && !force) { - throw safetyBlocked( - `目标企业「${targetCorp.name}」(${targetCorp.id}) 标记为生产正式环境 (production)。\n` + - `为防止测试单据污染生产审批流,禁止向生产环境重放单据。请指定测试企业 (--target-corp ),或在确有需要时添加 --force。`, - `seal-use webhook replay --target-corp ${sourceCorp.id !== targetCorp.id ? ` --source-corp ${sourceCorp.id}` : ""}` - ); - } + assertNonProductionReplayTarget(targetCorp, { + force, + action: "重放单据", + nextAction: `seal-use webhook replay --target-corp ${sourceCorp.id !== targetCorp.id ? ` --source-corp ${sourceCorp.id}` : ""}` + }); return { sourceCorp, targetCorp }; } From 6e3d4634f140d56cc2915b7d2070b144bf7db0e7 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 11 Oct 2026 19:33:25 +0800 Subject: [PATCH 2/7] Unify duration parsing behind a core/duration tokenizer The two --expire flags each carried a byte-identical copy of the same regex and unit-conversion switch, and a third parser (parseDurationMs) lived in capabilities/helpers.ts with yet another regex. Because the copies were independent, --expire 300 could be read differently on each path without anyone noticing. core/duration.ts now owns the grammar (tokenizeDuration) and the unitless heuristic (expireSeconds: a bare number <= 168 reads as hours, larger as seconds). Each flag keeps only what genuinely differs: Seal delegation links floor to whole hours and cap at 168h, Hose links round to seconds, simulation windows are milliseconds and fall back instead of failing the batch. Adds a cross-flag regression test asserting both --expire parsers read the same literal the same way. --- src/cli/parser.test.ts | 20 +++ src/cli/parser.ts | 165 +++++++------------- src/core/duration.test.ts | 75 +++++++++ src/core/duration.ts | 118 ++++++++++++++ src/domains/seal/capabilities/helpers.ts | 15 -- src/domains/seal/capabilities/simulation.ts | 2 +- 6 files changed, 270 insertions(+), 125 deletions(-) create mode 100644 src/core/duration.test.ts create mode 100644 src/core/duration.ts diff --git a/src/cli/parser.test.ts b/src/cli/parser.test.ts index 57b640d..1d5630c 100644 --- a/src/cli/parser.test.ts +++ b/src/cli/parser.test.ts @@ -157,6 +157,26 @@ describe("option helpers", () => { expect(() => parseHoseExpireSeconds("0s")).toThrow("必须为大于 0 的有效时长"); expect(() => parseHoseExpireSeconds("invalid")).toThrow("必须为有效时长"); }); + + test("both --expire flags read a unitless literal the same way", () => { + // Regression: the two parsers used to each carry their own copy of the + // unitless heuristic, so `--expire 300` meant 5 minutes on one path and + // clamped to 1 hour on the other purely by implementation accident. + for (const literal of [300, "300", 86400, "86400", 7200, "7200"]) { + const hours = parseDelegationExpireHours(literal); + const seconds = parseHoseExpireSeconds(literal); + const unitlessSeconds = typeof literal === "number" ? literal : Number(literal); + expect(seconds).toBe(unitlessSeconds); + // Delegation floors to whole hours and never drops below 1h. + expect(hours).toBe(Math.max(Math.floor(seconds / 3600), 1)); + } + + // A small unitless value is hours on both paths. + expect(parseDelegationExpireHours("24")).toBe(24); + expect(parseHoseExpireSeconds("24")).toBe(86_400); + expect(parseDelegationExpireHours(2)).toBe(2); + expect(parseHoseExpireSeconds(2)).toBe(7200); + }); }); describe("flag registry cross-check", () => { diff --git a/src/cli/parser.ts b/src/cli/parser.ts index cd08e17..5ed41f7 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -1,6 +1,7 @@ import type { WebhookMode } from "../domains/seal/types.js"; import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/policy.js"; import type { ParsedArgs } from "./types.js"; +import { type DurationToken, expireSeconds, tokenizeDuration } from "../core/duration.js"; import { usageError } from "./errors.js"; /** @@ -437,6 +438,42 @@ export function materialPackFilePolicyOptions( }; } +/** + * Read an `--expire` literal through the shared tokenizer, raising the two + * usage errors both link flags share. The format hint differs per flag only in + * which example it recommends. + */ +function readExpireToken( + value: string | boolean | number, + options: { formatHint: string; unitlessHint?: string } +): DurationToken { + if (typeof value === "number") { + if (!Number.isFinite(value) || value <= 0) { + throw usageError( + `Invalid --expire: ${value}。必须为大于 0 的有效时长${options.unitlessHint ? `,推荐使用 ${options.unitlessHint}` : ""}。` + ); + } + const token = tokenizeDuration(value); + if (!token) throw usageError(`Invalid --expire: ${value}。`); + return token; + } + + if (typeof value !== "string") { + throw usageError(`Invalid --expire: ${String(value)}。`); + } + + const token = tokenizeDuration(value); + if (!token) { + throw usageError(`Invalid --expire: '${value}'。必须为有效时长格式${options.formatHint}`); + } + if (token.value <= 0) { + throw usageError( + `Invalid --expire: '${value}'。必须为大于 0 的有效时长${options.unitlessHint ? `,推荐使用 ${options.unitlessHint}` : ""}。` + ); + } + return token; +} + export function parseDelegationExpireHours( value: string | boolean | number | undefined, defaultHours = 24 @@ -444,80 +481,30 @@ export function parseDelegationExpireHours( if (value === undefined || value === null || value === "") { return defaultHours; } - let rawHours: number; - let isFractionalOrTruncated = false; - if (typeof value === "number") { - if (!Number.isFinite(value) || value <= 0) { - throw usageError(`Invalid --expire: ${value}。必须为大于 0 的有效时长,推荐使用 '7d' 或 '24h'。`); - } - if (value > 168) { - rawHours = value / 3600; - if (value % 3600 !== 0) isFractionalOrTruncated = true; - } else { - rawHours = value; - if (!Number.isInteger(value)) isFractionalOrTruncated = true; - } - } else if (typeof value === "string") { - const trimmed = value.trim(); - const match = trimmed.match( - /^(\d+(?:\.\d+)?)\s*(d|day|days|h|hr|hrs|hour|hours|m|min|mins|minute|minutes|s|sec|secs|second|seconds)?$/i - ); - if (!match || !match[1]) { - throw usageError( - `Invalid --expire: '${value}'。必须为有效时长格式,推荐使用 '7d' 或 '24h'(支持 d/h/m/s 及秒数)。` - ); - } - const val = parseFloat(match[1]); - if (!Number.isFinite(val) || val <= 0) { - throw usageError(`Invalid --expire: '${value}'。必须为大于 0 的有效时长,推荐使用 '7d' 或 '24h'。`); - } - const unit = (match[2] ?? "").toLowerCase(); - - if (!unit) { - if (val > 168) { - rawHours = val / 3600; - if (val % 3600 !== 0) isFractionalOrTruncated = true; - } else { - rawHours = val; - if (!Number.isInteger(val)) isFractionalOrTruncated = true; - } - } else if (unit.startsWith("d")) { - rawHours = val * 24; - if (!Number.isInteger(rawHours)) isFractionalOrTruncated = true; - } else if (unit.startsWith("h")) { - rawHours = val; - if (!Number.isInteger(rawHours)) isFractionalOrTruncated = true; - } else if (unit.startsWith("m")) { - rawHours = val / 60; - if (val % 60 !== 0) isFractionalOrTruncated = true; - } else if (unit.startsWith("s")) { - rawHours = val / 3600; - if (val % 3600 !== 0) isFractionalOrTruncated = true; - } else { - rawHours = val; - } - } else { - throw usageError(`Invalid --expire: ${String(value)}。`); - } + const token = readExpireToken(value, { + formatHint: ",推荐使用 '7d' 或 '24h'(支持 d/h/m/s 及秒数)", + unitlessHint: ",推荐使用 '7d' 或 '24h'" + }); + // Seal delegation links are hourly and capped at 7 days. + const rawHours = expireSeconds(token) / 3600; if (rawHours > 168) { throw usageError( `Invalid --expire: 计算得 ${rawHours > 168.1 ? Math.floor(rawHours) : rawHours} 小时。Seal delegation 授权有效期最多为 7 天 (168h)。建议使用 --expire 7d。` ); } - let finalHours = Math.floor(rawHours); + const finalHours = Math.floor(rawHours); if (finalHours < 1) { - finalHours = 1; console.error( `👉 提示: Seal 协助链接按整小时生效(最少 1 小时),输入值 ${String(value)} 已自动保底设置为 1 小时 (1h)。建议后续使用 --expire 1h。` ); - return finalHours; + return 1; } - if (isFractionalOrTruncated) { + if (!Number.isInteger(rawHours)) { console.error( `👉 提示: Seal 协助链接按整小时生效,输入值 ${String(value)} 已自动向下取整为 ${finalHours} 小时 (${finalHours}h)。建议后续使用 --expire ${finalHours}h 或 --expire 7d。` ); @@ -533,59 +520,19 @@ export function parseHoseExpireSeconds( if (value === undefined || value === null || value === "") { return defaultSeconds; } - let seconds: number; - if (typeof value === "number") { - if (!Number.isFinite(value) || value <= 0) { - throw usageError(`Invalid --expire: ${value}。必须为大于 0 的有效时长。`); - } - if (value <= 168) { - seconds = Math.round(value * 3600); - console.error( - `👉 提示: 检测到未加单位的数值 ${value},已按 ${value} 小时 (${seconds}s) 自动换算。建议明确使用 --expire ${value}h。` - ); - } else { - seconds = Math.round(value); - } - } else if (typeof value === "string") { - const trimmed = value.trim(); - const match = trimmed.match( - /^(\d+(?:\.\d+)?)\s*(d|day|days|h|hr|hrs|hour|hours|m|min|mins|minute|minutes|s|sec|secs|second|seconds)?$/i - ); - if (!match || !match[1]) { - throw usageError( - `Invalid --expire: '${value}'。必须为有效时长,推荐使用 '7d' 或 '2h'(支持 d/h/m/s 及秒数)。` - ); - } - const val = parseFloat(match[1]); - if (!Number.isFinite(val) || val <= 0) { - throw usageError(`Invalid --expire: '${value}'。必须为大于 0 的有效时长。`); - } - const unit = (match[2] ?? "").toLowerCase(); - if (!unit) { - if (val <= 168) { - seconds = Math.round(val * 3600); - console.error( - `👉 提示: 检测到未加单位的数值 ${value},已按 ${val} 小时 (${seconds}s) 自动换算。建议明确使用 --expire ${val}h。` - ); - } else { - seconds = Math.round(val); - } - } else if (unit.startsWith("d")) { - seconds = Math.round(val * 86400); - } else if (unit.startsWith("h")) { - seconds = Math.round(val * 3600); - } else if (unit.startsWith("m")) { - seconds = Math.round(val * 60); - } else if (unit.startsWith("s")) { - seconds = Math.round(val); - } else { - seconds = Math.round(val); - } - } else { - throw usageError(`Invalid --expire: ${String(value)}。`); + const token = readExpireToken(value, { + formatHint: ",推荐使用 '7d' 或 '2h'(支持 d/h/m/s 及秒数)" + }); + + // A bare number is ambiguous: <=168 is read as hours, larger as seconds. + if (token.unit === undefined && token.value <= 168) { + console.error( + `👉 提示: 检测到未加单位的数值 ${token.value},已按 ${token.value} 小时 (${Math.round(token.value * 3600)}s) 自动换算。建议明确使用 --expire ${token.value}h。` + ); } + const seconds = Math.round(expireSeconds(token)); if (seconds <= 0) { throw usageError(`Invalid --expire: 计算得 ${seconds} 秒。必须为大于 0 的有效时长。`); } diff --git a/src/core/duration.test.ts b/src/core/duration.test.ts new file mode 100644 index 0000000..3651060 --- /dev/null +++ b/src/core/duration.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, test } from "bun:test"; +import { + durationSeconds, + expireSeconds, + parseDurationMs, + tokenizeDuration +} from "./duration.js"; + +describe("tokenizeDuration", () => { + test("splits magnitude from unit and accepts every alias", () => { + expect(tokenizeDuration("7d")).toEqual({ value: 7, unit: "d" }); + expect(tokenizeDuration("24h")).toEqual({ value: 24, unit: "h" }); + expect(tokenizeDuration("90m")).toEqual({ value: 90, unit: "m" }); + expect(tokenizeDuration("7200s")).toEqual({ value: 7200, unit: "s" }); + expect(tokenizeDuration("1.5h")).toEqual({ value: 1.5, unit: "h" }); + expect(tokenizeDuration("2 hours")).toEqual({ value: 2, unit: "h" }); + expect(tokenizeDuration("500ms")).toEqual({ value: 500, unit: "ms" }); + expect(tokenizeDuration(" 300 ")).toEqual({ value: 300, unit: undefined }); + expect(tokenizeDuration(168)).toEqual({ value: 168, unit: undefined }); + }); + + test("rejects unparseable input instead of guessing", () => { + expect(tokenizeDuration("invalid")).toBeUndefined(); + expect(tokenizeDuration("")).toBeUndefined(); + expect(tokenizeDuration("-5m")).toBeUndefined(); + expect(tokenizeDuration("5parsecs")).toBeUndefined(); + expect(tokenizeDuration(Number.NaN)).toBeUndefined(); + expect(tokenizeDuration(true as unknown as string)).toBeUndefined(); + }); +}); + +describe("expireSeconds", () => { + test("reads a unitless number at most 168 as hours and a larger one as seconds", () => { + // Both --expire paths used to reimplement this rule separately, and they + // disagreed at the boundary; 300 now means 5 minutes everywhere. + expect(expireSeconds({ value: 168, unit: undefined })).toBe(168 * 3600); + expect(expireSeconds({ value: 169, unit: undefined })).toBe(169); + expect(expireSeconds({ value: 300, unit: undefined })).toBe(300); + expect(expireSeconds({ value: 86400, unit: undefined })).toBe(86_400); + }); + + test("converts explicit units regardless of magnitude", () => { + expect(expireSeconds({ value: 7, unit: "d" })).toBe(604_800); + expect(expireSeconds({ value: 7200, unit: "s" })).toBe(7200); + expect(expireSeconds({ value: 30, unit: "m" })).toBe(1800); + }); +}); + +describe("durationSeconds", () => { + test("uses the caller's unitless policy when none is written", () => { + expect(durationSeconds({ value: 5, unit: undefined }, "s")).toBe(5); + expect(durationSeconds({ value: 5, unit: undefined }, "h")).toBe(18_000); + expect(durationSeconds({ value: 5, unit: "ms" }, "h")).toBe(0.005); + }); +}); + +describe("parseDurationMs", () => { + test("converts simulation windows to milliseconds", () => { + expect(parseDurationMs("2s")).toBe(2000); + expect(parseDurationMs("10m")).toBe(600_000); + expect(parseDurationMs("5m")).toBe(300_000); + expect(parseDurationMs("500ms")).toBe(500); + expect(parseDurationMs("1h")).toBe(3_600_000); + expect(parseDurationMs("1d")).toBe(86_400_000); + }); + + test("reads unitless input as seconds, matching the flag's defaults", () => { + expect(parseDurationMs("30")).toBe(30_000); + }); + + test("falls back rather than failing a batch over a bad poll interval", () => { + expect(parseDurationMs("soon")).toBe(600_000); + expect(parseDurationMs("soon", 1000)).toBe(1000); + }); +}); diff --git a/src/core/duration.ts b/src/core/duration.ts new file mode 100644 index 0000000..503f6b3 --- /dev/null +++ b/src/core/duration.ts @@ -0,0 +1,118 @@ +/** + * Duration tokenizing shared by every flag that accepts `7d` / `1.5h` / `300`. + * + * The tokenizer owns exactly one job: turning the written form into a magnitude + * plus a canonical unit. Interpretation stays with each caller, because the + * three consumers genuinely disagree — Seal delegation links take whole hours + * in 1..168, Hose assistance links take seconds, simulation windows take + * milliseconds. Sharing the grammar (and the unitless heuristic) is what stops + * `--expire 300` from parsing two different ways in two files. + */ + +export type DurationUnit = "ms" | "s" | "m" | "h" | "d"; + +export interface DurationToken { + /** The magnitude exactly as written, before any unit conversion. */ + value: number; + /** `undefined` when the input carried no unit, e.g. `300`. */ + unit: DurationUnit | undefined; +} + +const UNIT_ALIASES: Record = { + ms: "ms", + s: "s", + sec: "s", + secs: "s", + second: "s", + seconds: "s", + m: "m", + min: "m", + mins: "m", + minute: "m", + minutes: "m", + h: "h", + hr: "h", + hrs: "h", + hour: "h", + hours: "h", + d: "d", + day: "d", + days: "d" +}; + +const DURATION_PATTERN = /^(\d+(?:\.\d+)?)\s*([a-z]+)?$/i; + +/** + * Parse a duration literal. Returns `undefined` when the input cannot be read + * at all — callers decide whether that is a usage error or a default. + * + * A unitless number keeps whatever magnitude it had; pair it with + * {@link expireSeconds} or an explicit `unitless` argument to resolve it. + */ +export function tokenizeDuration(value: string | number): DurationToken | undefined { + if (typeof value === "number") { + return Number.isFinite(value) ? { value, unit: undefined } : undefined; + } + if (typeof value !== "string") { + return undefined; + } + + const match = value.trim().match(DURATION_PATTERN); + if (!match || !match[1]) { + return undefined; + } + + const rawUnit = match[2]?.toLowerCase(); + if (!rawUnit) { + return { value: parseFloat(match[1]), unit: undefined }; + } + + const unit = UNIT_ALIASES[rawUnit]; + if (!unit) { + return undefined; + } + return { value: parseFloat(match[1]), unit }; +} + +/** Convert a token to seconds, resolving a unitless value as `unitless`. */ +export function durationSeconds(token: DurationToken, unitless: DurationUnit): number { + switch (token.unit ?? unitless) { + case "ms": + return token.value / 1000; + case "m": + return token.value * 60; + case "h": + return token.value * 3600; + case "d": + return token.value * 86400; + case "s": + default: + return token.value; + } +} + +/** + * Unitless `--expire` heuristic shared by the Seal and Hose link flags: + * a bare number at most 168 reads as hours (7 days of them), a larger one + * reads as seconds. Without this, `--expire 300` would mean 300 hours on one + * path and 5 minutes on another. + */ +export function expireSeconds(token: DurationToken): number { + return durationSeconds(token, token.value <= 168 ? "h" : "s"); +} + +/** Default used by {@link parseDurationMs} when the literal is unreadable. */ +export const DEFAULT_DURATION_MS = 600_000; + +/** + * Simulation windows and poll intervals: milliseconds, unitless input read as + * seconds, and an unreadable literal falls back to the default instead of + * failing the call — a poll interval is not worth aborting a batch over. + */ +export function parseDurationMs(duration: string, fallbackMs = DEFAULT_DURATION_MS): number { + const token = tokenizeDuration(duration); + if (!token || token.value < 0) { + return fallbackMs; + } + return Math.round(durationSeconds(token, "s") * 1000); +} diff --git a/src/domains/seal/capabilities/helpers.ts b/src/domains/seal/capabilities/helpers.ts index 24f1fd5..a52d552 100644 --- a/src/domains/seal/capabilities/helpers.ts +++ b/src/domains/seal/capabilities/helpers.ts @@ -254,21 +254,6 @@ export type SimulationBatchCreateInput = { rawParams?: Record; }; -export function parseDurationMs(duration: string): number { - const match = duration.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/i); - if (!match || !match[1]) return 600000; - const val = parseFloat(match[1]); - const unit = (match[2] ?? "s").toLowerCase(); - switch (unit) { - case "ms": return val; - case "s": return val * 1000; - case "m": return val * 60 * 1000; - case "h": return val * 3600 * 1000; - case "d": return val * 86400 * 1000; - default: return val * 1000; - } -} - export function redactIntegrationSecrets(integration: Record) { return Object.fromEntries( Object.entries(integration).map(([key, value]) => [ diff --git a/src/domains/seal/capabilities/simulation.ts b/src/domains/seal/capabilities/simulation.ts index a07970e..25585c4 100644 --- a/src/domains/seal/capabilities/simulation.ts +++ b/src/domains/seal/capabilities/simulation.ts @@ -6,9 +6,9 @@ import { type SimulationBatch } from "../types.js"; import * as helpers from "./helpers.js"; +import { parseDurationMs } from "../../../core/duration.js"; const { - parseDurationMs, buildSimulationBatchParams, summarizeSimulationBatch, summarizeApprovalRun, From 8d7f9305961987448fea249a98a8bfecd3b083c6 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 11 Oct 2026 19:33:29 +0800 Subject: [PATCH 3/7] Split Langfuse flow heuristics out of the trace service MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit service.ts interleaved orchestration (cache-first trace access) with ~200 lines of flow heuristics — stage word tables, evidence collection, source classification — and carried near-isomorphic copies of the collector for the attachment and rule flows. None of it had tests. flows.ts now owns the heuristics: one collectEvidence shared by both flows, stage vocabulary as data tables so tuning a word list cannot alter a code path, and an explicit attachment/rule difference (only the rule flow falls back to scanning every observation when a stage has no named candidates). summary.ts holds the trace/observation projections both the service and the flows need, which also keeps service <-> flows acyclic. Adds 15 tests over the previously untested branches, including the two behaviors the extraction surfaced: the "unknown" classification arm is unreachable as written, and a filename-only needle set can never reach the OCR/inference grading. --- src/domains/langfuse/flows.test.ts | 246 ++++++++++++++++++++++++ src/domains/langfuse/flows.ts | 242 +++++++++++++++++++++++ src/domains/langfuse/service.ts | 295 ++--------------------------- src/domains/langfuse/summary.ts | 62 ++++++ 4 files changed, 567 insertions(+), 278 deletions(-) create mode 100644 src/domains/langfuse/flows.test.ts create mode 100644 src/domains/langfuse/flows.ts create mode 100644 src/domains/langfuse/summary.ts diff --git a/src/domains/langfuse/flows.test.ts b/src/domains/langfuse/flows.test.ts new file mode 100644 index 0000000..15e5920 --- /dev/null +++ b/src/domains/langfuse/flows.test.ts @@ -0,0 +1,246 @@ +import { describe, expect, test } from "bun:test"; +import { + ATTACHMENT_STAGES, + buildAttachmentFlow, + buildRuleFlow, + candidatesForStage, + classifyAttachmentEvidence, + collectEvidence, + RULE_FLOW_STAGES, + stageTerms, + summarizeEvidenceFields +} from "./flows.js"; +import type { LangfuseObservationSummary } from "./types.js"; + +function observation(overrides: Partial & { id: string }): LangfuseObservationSummary { + return { + traceId: "trace-1", + type: "SPAN", + ...overrides + } as LangfuseObservationSummary; +} + +describe("stage vocabulary", () => { + test("every stage resolves bilingual search terms", () => { + for (const stage of ATTACHMENT_STAGES) { + expect(stageTerms(stage, "attachment").length).toBeGreaterThan(0); + } + for (const stage of RULE_FLOW_STAGES) { + expect(stageTerms(stage, "rule").length).toBeGreaterThan(0); + } + }); + + test("matches observation names case-insensitively in either language", () => { + const observations = [ + observation({ id: "a", name: "Attachment_Parsing" }), + observation({ id: "b", name: "文档解析 worker" }), + observation({ id: "c", name: "unrelated" }) + ]; + + const matched = candidatesForStage(observations, stageTerms("document_parsing", "attachment")); + expect(matched.map((item) => item.id)).toEqual(["b"]); + + // The rule vocabulary is broader, so it also picks up the English name. + const ruleParsed = candidatesForStage(observations, stageTerms("document parsing", "rule")); + expect(ruleParsed.map((item) => item.id)).toEqual(["a", "b"]); + }); +}); + +describe("collectEvidence", () => { + const obs = observation({ + id: "obs-1", + name: "attachment parsing", + input: "folder/invoice.pdf", + output: "解析完成 invoice.pdf", + metadata: { file: "invoice.pdf" } + }); + + test("scans input, output and metadata and pads the snippet with context", () => { + const hits = collectEvidence(obs, ["invoice.pdf"], 5, 10); + expect(hits.map((hit) => hit.field)).toEqual(["input", "output", "metadata"]); + expect(hits[0]?.matched).toBe("invoice.pdf"); + // contextChars=5 → 5 chars of lead-in before the needle (index 7 - 5 = 2). + expect(hits[0]?.snippet).toBe("lder/invoice.pdf"); + // Needle sits at index 5 (4 CJK chars + space), so 5 chars of lead-in + // reaches the start of the string. + expect(hits[1]?.snippet).toBe("解析完成 invoice.pdf"); + }); + + test("caps the number of hits so a pathological trace cannot balloon", () => { + const noisy = observation({ + id: "obs-2", + input: "x".repeat(500), + output: "x".repeat(500), + metadata: { a: "x".repeat(500) } + }); + expect(collectEvidence(noisy, ["x"], 10, 3)).toHaveLength(3); + expect(collectEvidence(noisy, ["nope"], 10, 3)).toHaveLength(0); + }); + + test("matching is case-insensitive on both sides", () => { + const hits = collectEvidence(obs, ["INVOICE.PDF"], 5, 10); + expect(hits.length).toBeGreaterThan(0); + // `matched` preserves the original casing from the trace text. + expect(hits[0]?.matched).toBe("invoice.pdf"); + }); +}); + +describe("classifyAttachmentEvidence", () => { + test("returns absent when nothing matched", () => { + expect(classifyAttachmentEvidence([], "file-1", "a.pdf")).toBe("absent"); + }); + + test("filename-only and file-id-only when those are the sole hits", () => { + expect( + classifyAttachmentEvidence([{ matched: "a.pdf", snippet: "a.pdf" }], "file-1", "a.pdf") + ).toBe("filename-only"); + expect( + classifyAttachmentEvidence([{ matched: "file-1", snippet: "file-1" }], "file-1", "a.pdf") + ).toBe("file-id-only"); + }); + + test("some other hint wins over filename/id and is graded by the snippet", () => { + const other = [{ matched: "some extra token", snippet: "..." }]; + expect(classifyAttachmentEvidence(other, "file-1", "a.pdf")).toBe("parsed-text"); + expect( + classifyAttachmentEvidence( + [...other, { matched: "ocr", snippet: "run OCR on the scan" }], + "file-1", + "a.pdf" + ) + ).toBe("image-ocr"); + expect( + classifyAttachmentEvidence( + [...other, { matched: "推断", snippet: "模型认为金额为 120" }], + "file-1", + "a.pdf" + ) + ).toBe("model-inferred"); + }); + + test("with no identifiers every hit is an 'other hint' graded from the snippet", () => { + // fileName/fileId undefined → `matched !== undefined` is always true, so + // hasOtherHint fires and the snippet decides. Note: the union's "unknown" + // arm is unreachable — with both identifiers defined, hasOtherHint false + // already implies one of them matched. Kept as a defensive fallback only. + expect( + classifyAttachmentEvidence([{ matched: "x", snippet: "raw parsed text" }], undefined, undefined) + ).toBe("parsed-text"); + expect( + classifyAttachmentEvidence([{ matched: "x", snippet: "OCR pipeline output" }], undefined, undefined) + ).toBe("image-ocr"); + }); +}); + +describe("summarizeEvidenceFields", () => { + test("counts hits per field and de-duplicates repeated matches", () => { + const summary = summarizeEvidenceFields([ + { field: "input", matched: "rule-a" } as never, + { field: "input", matched: "rule-a" } as never, + { field: "input", matched: "rule-b" } as never, + { field: "output", matched: "rule-a" } as never + ]); + expect(summary.input).toEqual({ count: 3, matched: ["rule-a", "rule-b"] }); + expect(summary.output).toEqual({ count: 1, matched: ["rule-a"] }); + expect(summary.metadata).toBeUndefined(); + }); +}); + +describe("buildAttachmentFlow", () => { + const observations = [ + observation({ id: "p1", name: "attachment parsing", input: "读取 a.pdf" }), + observation({ id: "p2", name: "document_parsing", output: "解析 a.pdf 得到 120 元" }), + observation({ id: "p3", name: "approval_review", output: "OCR 结果 a.pdf 金额 120" }), + observation({ id: "other", name: "unrelated", input: "nothing here" }) + ]; + + test("labels a stage seen and classifies the evidence source", () => { + const stages = buildAttachmentFlow({ + observations, + fileName: "a.pdf", + // A second, non-identifier needle is what makes hasOtherHint fire — a + // filename-only query can never reach the OCR/inference grading. + needles: ["a.pdf", "金额"], + contextChars: 20 + }); + + expect(stages).toHaveLength(ATTACHMENT_STAGES.length); + expect(stages.map((stage) => stage.stage)).toEqual([...ATTACHMENT_STAGES]); + + const parsing = stages.find((stage) => stage.stage === "document_parsing"); + expect(parsing?.status).toBe("seen"); + expect(parsing?.source).toBe("filename-only"); + expect(parsing?.observations.map((item) => item.id)).toEqual(["p2"]); + expect(parsing?.evidence[0]?.observationId).toBe("p2"); + + const review = stages.find((stage) => stage.stage === "approval_review"); + expect(review?.evidence.length).toBeGreaterThan(0); + // 金额 is a non-identifier hit, so hasOtherHint fires and "OCR" in the + // snippet grades this stage as image-ocr. + expect(review?.source).toBe("image-ocr"); + }); + + test("stages with no matching observation report absent", () => { + const stages = buildAttachmentFlow({ + observations, + fileId: "file-xyz", + needles: ["file-xyz"], + contextChars: 20 + }); + const understanding = stages.find( + (stage) => stage.stage === "image/document understanding" + ); + expect(understanding?.status).toBe("absent"); + expect(understanding?.source).toBe("absent"); + expect(understanding?.observations).toEqual([]); + }); +}); + +describe("buildRuleFlow", () => { + const observations = [ + observation({ id: "r1", name: "rule matching", input: "规则:禁止差旅超标" }), + observation({ id: "g1", name: "generic span", output: "命中规则 禁止差旅超标" }), + observation({ id: "f1", name: "final review", output: "审核结论:驳回" }) + ]; + + test("falls back to every observation when no stage name matches", () => { + const flow = buildRuleFlow({ + observations, + needles: ["禁止差旅超标"], + contextChars: 30 + }); + + expect(flow.stages.ruleMatching?.matched).toBe(true); + expect(flow.stages.ruleMatching?.matchedObservationIds).toContain("r1"); + // g1 sits in a generically-named span, reachable only via the fallback pool. + expect(flow.relatedObservationIds).toContain("g1"); + expect(flow.evidenceCount).toBeGreaterThan(0); + + // No observation is named for "document parsing", so the stage has zero + // *named* candidates but still scans the whole trace via the fallback — + // that is what keeps a rule applied inside a generically-named span visible. + const documentParsing = flow.stages.documentParsing; + expect(documentParsing?.observations).toEqual([]); + expect(documentParsing?.matched).toBe(true); + expect(documentParsing?.matchedObservationIds).toContain("r1"); + }); + + test("reports extracted fields grouped by source field", () => { + const flow = buildRuleFlow({ + observations, + needles: ["禁止差旅超标", "驳回"], + contextChars: 30 + }); + + expect(flow.stages.ruleMatching?.extractedFields.input?.matched).toEqual(["禁止差旅超标"]); + expect(flow.stages.finalReview?.extractedFields.output?.matched).toEqual(["驳回"]); + expect(flow.stages.finalReview?.matched).toBe(true); + }); + + test("returns the documented stage keys in order", () => { + const flow = buildRuleFlow({ observations, needles: ["nothing-matches"], contextChars: 30 }); + expect(Object.keys(flow.stages)).toEqual(["ruleMatching", "documentParsing", "finalReview"]); + expect(flow.evidenceCount).toBe(0); + expect(flow.relatedObservationIds).toEqual([]); + }); +}); diff --git a/src/domains/langfuse/flows.ts b/src/domains/langfuse/flows.ts new file mode 100644 index 0000000..70d768b --- /dev/null +++ b/src/domains/langfuse/flows.ts @@ -0,0 +1,242 @@ +import { stringifyValue } from "./search.js"; +import { summarizeObservation, uniqueStrings } from "./summary.js"; +import type { LangfuseObservationSummary } from "./types.js"; + +/** + * Deterministic flow reconstruction from cached Langfuse fields. + * + * Everything here is plain text matching over observation name/input/output/ + * metadata — no network, no model calls. Both flows answer "where does this + * file or rule show up across the stages", so they share one evidence + * collector and differ only in their stage vocabulary and in what they report. + * + * The stage word lists are bilingual heuristics tuned against real traces; + * they are deliberately data, not logic, so tuning them cannot change a code + * path. + */ + +export const ATTACHMENT_STAGES = [ + "attachment parsing", + "image/document understanding", + "pre_analysis", + "document_parsing", + "approval_review" +] as const; + +export const RULE_FLOW_STAGES = ["rule matching", "document parsing", "final review"] as const; + +export type AttachmentStage = (typeof ATTACHMENT_STAGES)[number]; +export type RuleFlowStage = (typeof RULE_FLOW_STAGES)[number]; + +export type EvidenceField = "input" | "output" | "metadata"; + +export interface EvidenceHit { + observationId: string; + name?: string; + type?: string; + field: EvidenceField; + matched: string; + snippet: string; +} + +export type AttachmentSource = + | "filename-only" + | "file-id-only" + | "parsed-text" + | "image-ocr" + | "model-inferred" + | "absent" + | "unknown"; + +const ATTACHMENT_STAGE_TERMS: Record = { + "attachment parsing": ["attachment", "附件", "parse_attachment", "attachment_parsing"], + "image/document understanding": [ + "understanding", + "vision", + "image", + "document_understanding", + "文档理解", + "图片理解" + ], + pre_analysis: ["pre_analysis", "pre-analysis", "预分析"], + document_parsing: ["document_parsing", "document parsing", "文档解析"], + approval_review: ["approval_review", "approval review", "审核"] +}; + +const RULE_STAGE_TERMS: Record = { + "rule matching": ["rule", "规则", "policy", "match", "matching", "命中"], + "document parsing": ["document", "parse", "parsing", "attachment", "ocr", "文档", "解析", "附件", "提取"], + "final review": ["approval_review", "approval review", "review", "审核", "结论", "final"] +}; + +export function stageTerms( + stage: AttachmentStage | RuleFlowStage, + vocabulary: "attachment" | "rule" +): string[] { + return vocabulary === "attachment" + ? ATTACHMENT_STAGE_TERMS[stage as AttachmentStage] + : RULE_STAGE_TERMS[stage as RuleFlowStage]; +} + +/** Observations whose name mentions any of the stage's terms. */ +export function candidatesForStage( + observations: LangfuseObservationSummary[], + terms: string[] +): LangfuseObservationSummary[] { + const lowered = terms.map((term) => term.toLowerCase()); + return observations.filter((observation) => { + const name = observation.name?.toLowerCase() ?? ""; + return lowered.some((term) => name.includes(term)); + }); +} + +/** + * Scan every field of an observation for each needle and return bounded, + * context-padded hits. The cap keeps a pathological trace from ballooning the + * response. + */ +export function collectEvidence( + observation: LangfuseObservationSummary, + needles: string[], + contextChars: number, + limit: number +): EvidenceHit[] { + const fields = [ + ["input", stringifyValue(observation.input)], + ["output", stringifyValue(observation.output)], + ["metadata", stringifyValue(observation.metadata)] + ] as const; + const evidence: EvidenceHit[] = []; + + for (const [field, text] of fields) { + const normalized = text.toLowerCase(); + for (const needle of needles) { + const index = normalized.indexOf(needle.toLowerCase()); + if (index < 0) continue; + evidence.push({ + observationId: observation.id, + name: observation.name, + type: observation.type, + field, + matched: text.slice(index, index + needle.length), + snippet: text.slice( + Math.max(0, index - contextChars), + Math.min(text.length, index + needle.length + contextChars) + ) + }); + } + } + + return evidence.slice(0, limit); +} + +/** + * Decide where an attachment's presence appears to come from. Labels describe + * the text that was found — they never assert that a model understood the file. + */ +export function classifyAttachmentEvidence( + evidence: Array<{ matched: string; snippet: string }>, + fileId: string | undefined, + fileName: string | undefined +): AttachmentSource { + if (evidence.length === 0) return "absent"; + + const hasFileName = fileName ? evidence.some((item) => item.matched === fileName) : false; + const hasFileId = fileId ? evidence.some((item) => item.matched === fileId) : false; + const hasOtherHint = evidence.some((item) => item.matched !== fileId && item.matched !== fileName); + + if (hasOtherHint) { + const joined = evidence + .map((item) => item.snippet) + .join("\n") + .toLowerCase(); + if (/(ocr|图片|image|vision|视觉|识别)/i.test(joined)) return "image-ocr"; + if (/(infer|inferred|推断|模型认为|判断|审核结论)/i.test(joined)) return "model-inferred"; + return "parsed-text"; + } + if (hasFileName) return "filename-only"; + if (hasFileId) return "file-id-only"; + return "unknown"; +} + +/** Count hits per field, de-duplicating the matched substrings. */ +export function summarizeEvidenceFields( + evidence: EvidenceHit[] +): Record { + const summary: Record = {}; + for (const item of evidence) { + const entry = summary[item.field]; + if (entry) { + entry.count += 1; + if (!entry.matched.includes(item.matched)) entry.matched.push(item.matched); + } else { + summary[item.field] = { count: 1, matched: [item.matched] }; + } + } + return summary; +} + +export function buildAttachmentFlow(options: { + observations: LangfuseObservationSummary[]; + fileId?: string; + fileName?: string; + needles: string[]; + contextChars: number; +}) { + const { observations, fileId, fileName, needles, contextChars } = options; + + return ATTACHMENT_STAGES.map((stage) => { + const candidates = candidatesForStage(observations, stageTerms(stage, "attachment")); + const evidence = candidates.flatMap((observation) => + collectEvidence(observation, needles, contextChars, 10) + ); + const source = classifyAttachmentEvidence(evidence, fileId, fileName); + + return { + stage, + source, + status: source === "absent" ? ("absent" as const) : ("seen" as const), + observations: candidates.map(summarizeObservation), + evidence + }; + }); +} + +export function buildRuleFlow(options: { + observations: LangfuseObservationSummary[]; + needles: string[]; + contextChars: number; +}) { + const { observations, needles, contextChars } = options; + + const stages = RULE_FLOW_STAGES.map((stage) => { + const candidates = candidatesForStage(observations, stageTerms(stage, "rule")); + // Unlike attachment flow, a rule query falls back to every observation: + // a rule can be applied inside a generically-named span. + const pool = candidates.length ? candidates : observations; + const evidence = pool + .flatMap((observation) => collectEvidence(observation, needles, contextChars, 20)) + .slice(0, 20); + + return { + stage, + matched: evidence.length > 0, + matchedObservationIds: uniqueStrings(evidence.map((item) => item.observationId)), + observations: candidates.map(summarizeObservation), + extractedFields: summarizeEvidenceFields(evidence), + evidence + }; + }); + + const allEvidence = stages.flatMap((stage) => stage.evidence); + + return { + stages: { + ruleMatching: stages[0], + documentParsing: stages[1], + finalReview: stages[2] + }, + relatedObservationIds: uniqueStrings(allEvidence.map((item) => item.observationId)), + evidenceCount: allEvidence.length + }; +} diff --git a/src/domains/langfuse/service.ts b/src/domains/langfuse/service.ts index 288f2a3..0bc51da 100644 --- a/src/domains/langfuse/service.ts +++ b/src/domains/langfuse/service.ts @@ -3,7 +3,9 @@ import { LangfuseApi } from "./api.js"; import { TraceCache } from "./cache.js"; import type { LangfuseConfig } from "./config.js"; import { LangfuseClient } from "./client.js"; +import { buildAttachmentFlow, buildRuleFlow } from "./flows.js"; import { searchTrace, stringifyValue } from "./search.js"; +import { byteLength, objectKeys, summarizeObservation, summarizeTrace, uniqueStrings } from "./summary.js"; import type { AttachmentFlowInput, CachedTrace, @@ -28,14 +30,6 @@ const DEFAULT_IO_CHARS = 8_000; const DEFAULT_PREVIEW_CHARS = 160; const FULL_OUTPUT_WARNING_THRESHOLD = 30_000; const OUTLINE_FULL_FIELD_THRESHOLD = 20_000; -const ATTACHMENT_STAGES = [ - "attachment parsing", - "image/document understanding", - "pre_analysis", - "document_parsing", - "approval_review" -] as const; -const RULE_FLOW_STAGES = ["rule matching", "document parsing", "final review"] as const; /** * Read-only Langfuse trace service, ported from langfuse-home. @@ -278,15 +272,17 @@ export class LangfuseService { } const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false); - const trace = cached.trace; const contextChars = clamp(input.contextChars ?? DEFAULT_CONTEXT_CHARS, 20, 500); const needles = [input.fileId, input.fileName, ...(input.contentHints ?? [])].filter( (value): value is string => Boolean(value?.trim()) ); - const observations = trace.observations ?? []; - const stages = ATTACHMENT_STAGES.map((stage) => - inspectAttachmentStage(stage, observations, needles, input.fileId, input.fileName, contextChars) - ); + const stages = buildAttachmentFlow({ + observations: cached.trace.observations ?? [], + fileId: input.fileId, + fileName: input.fileName, + needles, + contextChars + }); return { traceId: input.traceId, @@ -304,27 +300,20 @@ export class LangfuseService { async getTraceRuleFlow(input: TraceRuleFlowInput) { const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false); - const trace = cached.trace; const contextChars = clamp(input.contextChars ?? 300, 20, 500); - const needles = uniqueStrings([input.rule, ...(input.ruleHints ?? [])]); - const observations = trace.observations ?? []; - const stageResults = RULE_FLOW_STAGES.map((stage) => - inspectRuleStage(stage, observations, needles, contextChars) - ); - const allEvidence = stageResults.flatMap((stage) => stage.evidence); - const relatedObservationIds = uniqueStrings(allEvidence.map((item) => item.observationId)); + const flow = buildRuleFlow({ + observations: cached.trace.observations ?? [], + needles: uniqueStrings([input.rule, ...(input.ruleHints ?? [])]), + contextChars + }); return { traceId: input.traceId, rule: input.rule, ruleHints: input.ruleHints, - stages: { - ruleMatching: stageResults[0], - documentParsing: stageResults[1], - finalReview: stageResults[2] - }, - relatedObservationIds, - evidenceCount: allEvidence.length, + stages: flow.stages, + relatedObservationIds: flow.relatedObservationIds, + evidenceCount: flow.evidenceCount, note: "Rule flow is deterministic text evidence extraction from cached Langfuse fields. It reports where the rule or hints appear; it does not infer hidden model reasoning or prove causality beyond the recorded trace text.", cache: { @@ -436,45 +425,6 @@ function buildOutlineWarnings( return warnings.slice(0, 20); } -function summarizeTrace(trace: LangfuseTraceSummary) { - return { - id: trace.id, - name: trace.name, - projectId: trace.projectId, - sessionId: trace.sessionId, - userId: trace.userId, - timestamp: trace.timestamp, - environment: trace.environment, - tags: trace.tags, - inputLength: stringifyValue(trace.input).length, - outputLength: stringifyValue(trace.output).length, - metadata: trace.metadata, - latency: trace.latency, - totalCost: trace.totalCost - }; -} - -function summarizeObservation(observation: LangfuseObservationSummary) { - return { - id: observation.id, - traceId: observation.traceId, - parentObservationId: observation.parentObservationId, - type: observation.type, - name: observation.name, - startTime: observation.startTime, - endTime: observation.endTime, - model: observation.providedModelName ?? observation.model, - inputLength: stringifyValue(observation.input).length, - outputLength: stringifyValue(observation.output).length, - inputBytes: byteLength(stringifyValue(observation.input)), - outputBytes: byteLength(stringifyValue(observation.output)), - metadataKeys: objectKeys(observation.metadata), - usageDetails: observation.usageDetails, - costDetails: observation.costDetails, - totalCost: observation.totalCost - }; -} - function buildTraceUrl(baseUrl: string, projectId: string, traceId: string): string { const url = new URL( `/project/${encodeURIComponent(projectId)}/traces/${encodeURIComponent(traceId)}`, @@ -545,209 +495,6 @@ function parsePath(path: string): Array { return segments; } -function inspectAttachmentStage( - stage: (typeof ATTACHMENT_STAGES)[number], - observations: LangfuseObservationSummary[], - needles: string[], - fileId: string | undefined, - fileName: string | undefined, - contextChars: number -) { - const stageTerms = stageSearchTerms(stage); - const candidates = observations.filter((observation) => { - const name = observation.name?.toLowerCase() ?? ""; - return stageTerms.some((term) => name.includes(term)); - }); - const evidence = candidates.flatMap((observation) => - collectAttachmentEvidence(observation, needles, contextChars) - ); - const source = classifyAttachmentEvidence(evidence, fileId, fileName); - - return { - stage, - source, - status: source === "absent" ? "absent" : "seen", - observations: candidates.map(summarizeObservation), - evidence - }; -} - -function stageSearchTerms(stage: (typeof ATTACHMENT_STAGES)[number]): string[] { - switch (stage) { - case "attachment parsing": - return ["attachment", "附件", "parse_attachment", "attachment_parsing"]; - case "image/document understanding": - return ["understanding", "vision", "image", "document_understanding", "文档理解", "图片理解"]; - case "pre_analysis": - return ["pre_analysis", "pre-analysis", "预分析"]; - case "document_parsing": - return ["document_parsing", "document parsing", "文档解析"]; - case "approval_review": - return ["approval_review", "approval review", "审核"]; - } -} - -function collectAttachmentEvidence( - observation: LangfuseObservationSummary, - needles: string[], - contextChars: number -): Array<{ - observationId: string; - name?: string; - field: "input" | "output" | "metadata"; - matched: string; - snippet: string; -}> { - const fields = [ - ["input", stringifyValue(observation.input)], - ["output", stringifyValue(observation.output)], - ["metadata", stringifyValue(observation.metadata)] - ] as const; - const evidence: ReturnType = []; - - for (const [field, text] of fields) { - const normalized = text.toLowerCase(); - for (const needle of needles) { - const index = normalized.indexOf(needle.toLowerCase()); - if (index < 0) continue; - evidence.push({ - observationId: observation.id, - name: observation.name, - field, - matched: text.slice(index, index + needle.length), - snippet: text.slice( - Math.max(0, index - contextChars), - Math.min(text.length, index + needle.length + contextChars) - ) - }); - } - } - - return evidence.slice(0, 10); -} - -function classifyAttachmentEvidence( - evidence: Array<{ matched: string; snippet: string; field?: string }>, - fileId: string | undefined, - fileName: string | undefined -): "filename-only" | "file-id-only" | "parsed-text" | "image-ocr" | "model-inferred" | "absent" | "unknown" { - if (evidence.length === 0) return "absent"; - const hasFileName = fileName ? evidence.some((item) => item.matched === fileName) : false; - const hasFileId = fileId ? evidence.some((item) => item.matched === fileId) : false; - const hasOtherHint = evidence.some((item) => item.matched !== fileId && item.matched !== fileName); - if (hasOtherHint) { - const joined = evidence - .map((item) => item.snippet) - .join("\n") - .toLowerCase(); - if (/(ocr|图片|image|vision|视觉|识别)/i.test(joined)) return "image-ocr"; - if (/(infer|inferred|推断|模型认为|判断|审核结论)/i.test(joined)) return "model-inferred"; - return "parsed-text"; - } - if (hasFileName && !hasOtherHint) return "filename-only"; - if (hasFileId && !hasOtherHint) return "file-id-only"; - return "unknown"; -} - -function inspectRuleStage( - stage: (typeof RULE_FLOW_STAGES)[number], - observations: LangfuseObservationSummary[], - needles: string[], - contextChars: number -) { - const stageTerms = ruleStageSearchTerms(stage); - const candidates = observations.filter((observation) => { - const name = observation.name?.toLowerCase() ?? ""; - return stageTerms.some((term) => name.includes(term)); - }); - const candidatePool = candidates.length ? candidates : observations; - const evidence = candidatePool - .flatMap((observation) => collectRuleEvidence(observation, needles, contextChars)) - .slice(0, 20); - const matchedObservationIds = uniqueStrings(evidence.map((item) => item.observationId)); - - return { - stage, - matched: evidence.length > 0, - matchedObservationIds, - observations: candidates.map(summarizeObservation), - extractedFields: summarizeEvidenceFields(evidence), - evidence - }; -} - -function ruleStageSearchTerms(stage: (typeof RULE_FLOW_STAGES)[number]): string[] { - switch (stage) { - case "rule matching": - return ["rule", "规则", "policy", "match", "matching", "命中"]; - case "document parsing": - return ["document", "parse", "parsing", "attachment", "ocr", "文档", "解析", "附件", "提取"]; - case "final review": - return ["approval_review", "approval review", "review", "审核", "结论", "final"]; - } -} - -function collectRuleEvidence( - observation: LangfuseObservationSummary, - needles: string[], - contextChars: number -): Array<{ - observationId: string; - name?: string; - type?: string; - field: "input" | "output" | "metadata"; - matched: string; - snippet: string; -}> { - const fields = [ - ["input", stringifyValue(observation.input)], - ["output", stringifyValue(observation.output)], - ["metadata", stringifyValue(observation.metadata)] - ] as const; - const evidence: ReturnType = []; - - for (const [field, text] of fields) { - const normalized = text.toLowerCase(); - for (const needle of needles) { - const index = normalized.indexOf(needle.toLowerCase()); - if (index < 0) continue; - evidence.push({ - observationId: observation.id, - name: observation.name, - type: observation.type, - field, - matched: text.slice(index, index + needle.length), - snippet: text.slice( - Math.max(0, index - contextChars), - Math.min(text.length, index + needle.length + contextChars) - ) - }); - } - } - - return evidence; -} - -function summarizeEvidenceFields( - evidence: Array<{ field: "input" | "output" | "metadata"; matched: string }> -): Record { - const summary: Record = {}; - for (const item of evidence) { - const entry = summary[item.field]; - if (entry) { - entry.count += 1; - if (!entry.matched.includes(item.matched)) entry.matched.push(item.matched); - } else { - summary[item.field] = { count: 1, matched: [item.matched] }; - } - } - return summary; -} - -function uniqueStrings(values: Array): string[] { - return [...new Set(values.filter((value): value is string => Boolean(value?.trim())))]; -} - function hasValue(value: unknown): boolean { return stringifyValue(value).length > 0; } @@ -759,14 +506,6 @@ function truncateMiddle(text: string, maxChars: number): string { return `${text.slice(0, head)}\n......\n${text.slice(text.length - tail)}`; } -function objectKeys(value: unknown): string[] { - return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value) : []; -} - -function byteLength(value: string): number { - return Buffer.byteLength(value, "utf8"); -} - function clamp(value: number, min: number, max: number): number { return Math.max(min, Math.min(max, value)); } diff --git a/src/domains/langfuse/summary.ts b/src/domains/langfuse/summary.ts new file mode 100644 index 0000000..994ec48 --- /dev/null +++ b/src/domains/langfuse/summary.ts @@ -0,0 +1,62 @@ +import { stringifyValue } from "./search.js"; +import type { LangfuseObservationSummary, LangfuseTraceSummary } from "./types.js"; + +/** + * Size-before-content projections of a cached trace. + * + * Both the outline/search responses and the flow evidence builders need these + * (a stage reports its candidate observations in summary form), so they live + * here rather than in `service.ts` — otherwise `flows.ts` would have to import + * the service that imports it back. + */ + +export function summarizeTrace(trace: LangfuseTraceSummary) { + return { + id: trace.id, + name: trace.name, + projectId: trace.projectId, + sessionId: trace.sessionId, + userId: trace.userId, + timestamp: trace.timestamp, + environment: trace.environment, + tags: trace.tags, + inputLength: stringifyValue(trace.input).length, + outputLength: stringifyValue(trace.output).length, + metadata: trace.metadata, + latency: trace.latency, + totalCost: trace.totalCost + }; +} + +export function summarizeObservation(observation: LangfuseObservationSummary) { + return { + id: observation.id, + traceId: observation.traceId, + parentObservationId: observation.parentObservationId, + type: observation.type, + name: observation.name, + startTime: observation.startTime, + endTime: observation.endTime, + model: observation.providedModelName ?? observation.model, + inputLength: stringifyValue(observation.input).length, + outputLength: stringifyValue(observation.output).length, + inputBytes: byteLength(stringifyValue(observation.input)), + outputBytes: byteLength(stringifyValue(observation.output)), + metadataKeys: objectKeys(observation.metadata), + usageDetails: observation.usageDetails, + costDetails: observation.costDetails, + totalCost: observation.totalCost + }; +} + +export function objectKeys(value: unknown): string[] { + return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value) : []; +} + +export function byteLength(value: string): number { + return Buffer.byteLength(value, "utf8"); +} + +export function uniqueStrings(values: Array): string[] { + return [...new Set(values.filter((value): value is string => Boolean(value?.trim())))]; +} From 9ece30255e4f0c906a3eecb669df23dffaefe42f Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 11 Oct 2026 19:33:35 +0800 Subject: [PATCH 4/7] Freeze capabilities/helpers.ts with a size ratchet MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The file is the registry's catch-all (~85 exports over unrelated domains), and index.ts re-exports all of it into every capability's namespace — which is why helpers get re-derived rather than reused, and why unrelated work keeps landing here. A comment alone would not stop the next addition, so the ceiling is enforced by test: helpers.freeze.test.ts fails when the file grows past its line or export count, and the failure message names where the logic should go instead. Both ceilings only ever drop — moving an export out to a focused module is the intended change, followed by lowering the constant. Verified by temporarily adding an export: both assertions fire. Records the policy in .agents/rules/typescript-style.md as well, since the ratchet explains what to do and the rule explains why. --- .agents/rules/typescript-style.md | 12 ++++ .../seal/capabilities/helpers.freeze.test.ts | 65 +++++++++++++++++++ src/domains/seal/capabilities/helpers.ts | 13 ++++ 3 files changed, 90 insertions(+) create mode 100644 src/domains/seal/capabilities/helpers.freeze.test.ts diff --git a/.agents/rules/typescript-style.md b/.agents/rules/typescript-style.md index 2d5592b..e1f92d3 100644 --- a/.agents/rules/typescript-style.md +++ b/.agents/rules/typescript-style.md @@ -25,3 +25,15 @@ When modifying or adding TypeScript files in `src/`: 4. **Architecture**: - Prefer small, cohesive domain functions over large generic utility files. + +5. **Frozen Utility Modules**: + - `src/domains/seal/capabilities/helpers.ts` is FROZEN: no new exports. It is + the historical catch-all (~85 exports, re-exported into every capability's + namespace via `export *`), and `helpers.freeze.test.ts` fails CI when it + grows past its line/export ceiling. + - Put new logic in a focused module beside the domain that owns it. Moving an + existing export OUT of `helpers.ts` is encouraged — then lower the ceiling + constants in the ratchet test. + - Apply the same instinct to any other module you are tempted to treat as a + scrap drawer: if the file's name is `helpers`/`utils`/`common`, it is + already a sign the logic belongs somewhere more specific. diff --git a/src/domains/seal/capabilities/helpers.freeze.test.ts b/src/domains/seal/capabilities/helpers.freeze.test.ts new file mode 100644 index 0000000..c161030 --- /dev/null +++ b/src/domains/seal/capabilities/helpers.freeze.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; + +/** + * Size ratchet for `helpers.ts` (see the FROZEN header at the top of that file). + * + * The module is the historical dumping ground for anything a capability needed, + * and `export *` from index.ts leaks all of it into every capability's + * namespace. A comment alone does not stop the next addition, so the ceiling is + * enforced here: adding an export (or growing the file) fails CI with a message + * that says where the logic should go instead. + * + * Both ceilings may go DOWN — moving an export out to a focused module is the + * intended fix. Only `helpers.ts` is measured; sibling modules are unrestricted. + */ + +const HELPERS_PATH = join(import.meta.dirname, "helpers.ts"); + +// Lower these only when logic actually leaves the file. +const MAX_LINES = 1694; +const MAX_EXPORTS = 85; + +function measure(source: string) { + const lines = source.split("\n").length; + // Top-level `export` declarations only; re-exports and `export { x } from` + // lists would be counted by a looser pattern. + const exports = source.match(/^export (?:async )?(?:function|const|class|type|interface|enum) /gm); + return { lines, exports: exports?.length ?? 0 }; +} + +describe("capabilities/helpers.ts freeze", () => { + const source = readFileSync(HELPERS_PATH, "utf8"); + const { lines, exports } = measure(source); + + test("stays under the line ceiling", () => { + expect( + lines, + `helpers.ts is ${lines} lines (ceiling ${MAX_LINES}). It is frozen: add new ` + + `logic to a focused module next to its domain instead of growing this grab-bag, ` + + `or move an existing export out to lower the ceiling.` + ).toBeLessThanOrEqual(MAX_LINES); + }); + + test("stays under the export ceiling", () => { + expect( + exports, + `helpers.ts exports ${exports} symbols (ceiling ${MAX_EXPORTS}). New exports are ` + + `not accepted here — index.ts re-exports the whole file into every capability's ` + + `namespace. Give the function a home beside the domain that owns it.` + ).toBeLessThanOrEqual(MAX_EXPORTS); + }); + + test("the FROZEN header stays in place", () => { + expect(source.startsWith("// FROZEN")).toBe(true); + expect(source).toContain("helpers.freeze.test.ts"); + }); + + test("measures what it claims to measure", () => { + // Guard the ratchet itself: a pattern that matches nothing would silently + // pin the export ceiling at 0 and pass forever. + expect(exports).toBeGreaterThan(0); + expect(lines).toBeGreaterThan(MAX_LINES - 200); + }); +}); diff --git a/src/domains/seal/capabilities/helpers.ts b/src/domains/seal/capabilities/helpers.ts index a52d552..7c7fd2e 100644 --- a/src/domains/seal/capabilities/helpers.ts +++ b/src/domains/seal/capabilities/helpers.ts @@ -1,3 +1,16 @@ +// FROZEN — see helpers.freeze.test.ts, which fails the build if this file grows. +// +// This module started as shared plumbing for the capability registry and has +// been the default place to drop anything for years. It now holds ~85 exports +// spanning unrelated concerns (base URLs, rule versions, Beijing timestamps, +// generic object paths), and `export *` in index.ts pushes every one of them +// into every capability's namespace — which is why the same helper gets +// re-derived instead of reused. +// +// Rules while frozen: +// - No new exports. Put new logic in a focused module next to its domain. +// - Existing exports may move out (update importers) — the budget only drops. +// - Fixes to existing exports are fine; the line/export ceiling is the guard. import { z } from "zod"; import type { KyInstance } from "ky"; import type { CorpConfig } from "../../../core/config/types.js"; From 8c3d98fd980dc4915120e0ef43bceaec82869cfc Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 11 Oct 2026 19:51:29 +0800 Subject: [PATCH 5/7] Fix absent-SN record match and document --sign-key on replay MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two findings from reviewing the outbound-push extraction: The verify poll compared `record.sourceDocumentSN === sn` with `sn` optional, so a caller that only knows the flowId compared against `undefined` and matched any record lacking an SN — reporting an unrelated run as the one this push created, with its id and taskMode in the response. Guard the needle: an absent SN matches nothing. This class did not exist on the deploy path before (it compared against flowId only), so it was introduced by the merge. The replay help text also never listed --sign-key even though the channel resolves the target integration through it, and selectHoseIntegration now errors on an ambiguous list with "请通过 --sign-key 指定" — pointing at a flag the user could not discover from `help approval-runs`. Adds direct tests for replay-safety.ts (the exit-14 wording, the next action, and that --force is the only override), which previously had none. --- src/cli/help.ts | 5 +- src/domains/seal/outbound-push.test.ts | 30 ++++++++++++ src/domains/seal/outbound-push.ts | 9 +++- src/domains/seal/replay-safety.test.ts | 64 ++++++++++++++++++++++++++ 4 files changed, 104 insertions(+), 4 deletions(-) create mode 100644 src/domains/seal/replay-safety.test.ts diff --git a/src/cli/help.ts b/src/cli/help.ts index 2b18735..9e6c277 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -584,14 +584,15 @@ export const HELP_REGISTRY: AreaHelp[] = [ usage: [ "seal-use approval-runs replay [--webhook ] [--sn-suffix ] [--dry-run] [--corp ]", "seal-use approval-runs replay --sn [--webhook ] [--source-corp ] [--target-corp ]", - "seal-use approval-runs replay --sn --channel hose-outbound [--target-corp ] [--dry-run]", - "seal-use approval-runs replay --channel hose-outbound [--target-corp ] [--dry-run]", + "seal-use approval-runs replay --sn --channel hose-outbound [--sign-key ] [--target-corp ] [--dry-run]", + "seal-use approval-runs replay --channel hose-outbound [--sign-key ] [--target-corp ] [--dry-run]", "seal-use approval-runs replay --limit [--status ] [--source-corp ] [--target-corp ]" ], options: [ { flag: "", description: "Approval run record ID" }, { flag: "--sn ", description: "Lookup approval record by source document SN" }, { flag: "--channel ", description: "Replay channel: webhook (default) or hose-outbound (Hosecloud official outbound)" }, + { flag: "--sign-key ", description: "Target Hose integration signKey for hose-outbound; required when the target has several integrations" }, { flag: "--message-id ", description: "Explicit Hose outbound messageId override" }, { flag: "--rejection-num ", description: "Target specific rejection iteration (0, 1, 2, ...)" }, { flag: "--limit ", description: "Batch replay latest N records" }, diff --git a/src/domains/seal/outbound-push.test.ts b/src/domains/seal/outbound-push.test.ts index d92d01e..cf61b86 100644 --- a/src/domains/seal/outbound-push.test.ts +++ b/src/domains/seal/outbound-push.test.ts @@ -300,6 +300,36 @@ describe("pushOutboundAndVerify", () => { } }); + test("an absent sn never matches a record that has no SN", async () => { + // Regression: comparing `record.sourceDocumentSN === sn` with `sn` + // undefined matched any record lacking an SN, so an unrelated run was + // reported as the one this push created. + const lines: string[] = []; + const originalError = console.error; + console.error = (line: string) => lines.push(line); + try { + const { createdRecord } = await pushOutboundAndVerify({ + client: fakeClient([{ id: "unrelated-old-run" }]), + signKey: "key-1", + payload: buildOutboundPayload({ + flowId: "ID01abc", + messageId: "msg-1", + corporationId: "c" + }), + flowId: "ID01abc", + corpName: "目标企业", + corpId: "target-corp", + verifyWaitMs: 0 + }); + + expect(createdRecord).toBeUndefined(); + expect(lines.join("\n")).toContain("消息已入队正在异步消费"); + expect(lines.join("\n")).not.toContain("unrelated-old-run"); + } finally { + console.error = originalError; + } + }); + test("a failing poll never turns a successful push into an error", async () => { const originalError = console.error; console.error = () => {}; diff --git a/src/domains/seal/outbound-push.ts b/src/domains/seal/outbound-push.ts index 849b686..af2900c 100644 --- a/src/domains/seal/outbound-push.ts +++ b/src/domains/seal/outbound-push.ts @@ -176,14 +176,19 @@ export async function pushOutboundAndVerify(options: { await new Promise((resolve) => setTimeout(resolve, options.verifyWaitMs ?? OUTBOUND_VERIFY_WAIT_MS)); + // `sn` is optional: callers that only know the flowId leave it undefined, and + // an undefined needle must never match a record whose SN is absent — that + // would report an unrelated run as the one this push just created. + const snNeedle = sn?.trim() || undefined; + let createdRecord: ApprovalRun | undefined; try { const runs = await api.listApprovalRuns(client, { limit: 5, search: flowId }); createdRecord = (runs.records || []).find( (record) => record.sourceDocumentId === flowId || - record.sourceDocumentSN === sn || - record.sourceDocumentSN === flowId + record.sourceDocumentSN === flowId || + (snNeedle !== undefined && record.sourceDocumentSN === snNeedle) ); } catch { // Non-blocking: the run may not exist yet even when the push succeeded. diff --git a/src/domains/seal/replay-safety.test.ts b/src/domains/seal/replay-safety.test.ts new file mode 100644 index 0000000..359e00b --- /dev/null +++ b/src/domains/seal/replay-safety.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, test } from "bun:test"; +import type { CorpConfig } from "../../core/config/types.js"; +import { assertNonProductionReplayTarget } from "./replay-safety.js"; + +function corp(overrides: Partial = {}): CorpConfig { + return { + id: "corp-test", + name: "测试企业", + environment: "test", + seal: { url: "https://test.sealai.cc" }, + source: { type: "seal", token: "t", sealUrl: "https://test.sealai.cc" }, + auth: { refreshTtl: 300 }, + ...overrides + } as CorpConfig; +} + +const baseOptions = { + action: "重放单据", + nextAction: "seal-use webhook replay --target-corp " +}; + +describe("assertNonProductionReplayTarget", () => { + test("lets a test-environment target through", () => { + expect(() => assertNonProductionReplayTarget(corp(), baseOptions)).not.toThrow(); + }); + + test("blocks a production target with an exit-14 safety error", () => { + let thrown: unknown; + try { + assertNonProductionReplayTarget(corp({ environment: "production" }), baseOptions); + } catch (error) { + thrown = error; + } + expect(thrown).toBeInstanceOf(Error); + expect((thrown as { exitCode?: number }).exitCode).toBe(14); + // The wording must stay regex-classifiable by core/errors SAFETY_GUARD so + // an error crossing a process boundary still lands on exit 14. + expect((thrown as Error).message).toContain("标记为生产正式环境"); + }); + + test("carries the caller's next action and action verb verbatim", () => { + try { + assertNonProductionReplayTarget(corp({ environment: "production" }), { + action: "重放出站报文", + nextAction: "seal-use webhook replay --channel hose-outbound --target-corp " + }); + throw new Error("expected a block"); + } catch (error) { + expect((error as Error).message).toContain("禁止向生产环境重放出站报文"); + expect((error as { nextAction?: string }).nextAction).toContain("--channel hose-outbound"); + } + }); + + test("--force is the only override, and it must be explicit", () => { + const production = corp({ environment: "production" }); + expect(() => assertNonProductionReplayTarget(production, baseOptions)).toThrow(); + expect(() => + assertNonProductionReplayTarget(production, { ...baseOptions, force: true }) + ).not.toThrow(); + expect(() => + assertNonProductionReplayTarget(production, { ...baseOptions, force: false }) + ).toThrow(); + }); +}); From 19c8dd3146426fff0becb730c80e7048321b748b Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 11 Oct 2026 19:51:29 +0800 Subject: [PATCH 6/7] Restore strict --expire units in the shared duration tokenizer The shared tokenizer accepts `ms` for the simulation windows, and without a per-caller unit set that grammar leaked into --expire: `--expire 500ms` was a usage error before the parsers were unified and became silently rounded to a 1h / 1s link after. tokenizeDuration now takes an allowed-unit set; the expire flags pass EXPIRE_UNITS (d/h/m/s) while parseDurationMs keeps the full set. Adds a regression test asserting sub-second input stays exit 2 on both flags. --- src/cli/parser.test.ts | 9 +++++++++ src/cli/parser.ts | 6 +++--- src/core/duration.ts | 23 ++++++++++++++++++++++- 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/src/cli/parser.test.ts b/src/cli/parser.test.ts index 1d5630c..5348da8 100644 --- a/src/cli/parser.test.ts +++ b/src/cli/parser.test.ts @@ -177,6 +177,15 @@ describe("option helpers", () => { expect(parseDelegationExpireHours(2)).toBe(2); expect(parseHoseExpireSeconds(2)).toBe(7200); }); + + test("sub-second input stays a usage error on both --expire flags", () => { + // Regression: the shared tokenizer understands `ms` for the simulation + // windows, and without a per-caller unit set that grammar leaked into + // --expire, silently rounding 500ms up to a 1h / 1s link. + expect(() => parseDelegationExpireHours("500ms")).toThrow("必须为有效时长格式"); + expect(() => parseHoseExpireSeconds("500ms")).toThrow("必须为有效时长"); + expect(() => parseHoseExpireSeconds("200ms")).toThrow("必须为有效时长"); + }); }); describe("flag registry cross-check", () => { diff --git a/src/cli/parser.ts b/src/cli/parser.ts index 5ed41f7..5a246a9 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -1,7 +1,7 @@ import type { WebhookMode } from "../domains/seal/types.js"; import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/policy.js"; import type { ParsedArgs } from "./types.js"; -import { type DurationToken, expireSeconds, tokenizeDuration } from "../core/duration.js"; +import { type DurationToken, EXPIRE_UNITS, expireSeconds, tokenizeDuration } from "../core/duration.js"; import { usageError } from "./errors.js"; /** @@ -453,7 +453,7 @@ function readExpireToken( `Invalid --expire: ${value}。必须为大于 0 的有效时长${options.unitlessHint ? `,推荐使用 ${options.unitlessHint}` : ""}。` ); } - const token = tokenizeDuration(value); + const token = tokenizeDuration(value, { units: EXPIRE_UNITS }); if (!token) throw usageError(`Invalid --expire: ${value}。`); return token; } @@ -462,7 +462,7 @@ function readExpireToken( throw usageError(`Invalid --expire: ${String(value)}。`); } - const token = tokenizeDuration(value); + const token = tokenizeDuration(value, { units: EXPIRE_UNITS }); if (!token) { throw usageError(`Invalid --expire: '${value}'。必须为有效时长格式${options.formatHint}`); } diff --git a/src/core/duration.ts b/src/core/duration.ts index 503f6b3..26e518b 100644 --- a/src/core/duration.ts +++ b/src/core/duration.ts @@ -42,6 +42,15 @@ const UNIT_ALIASES: Record = { const DURATION_PATTERN = /^(\d+(?:\.\d+)?)\s*([a-z]+)?$/i; +export interface TokenizeDurationOptions { + /** + * Units this caller accepts. Restricting the set keeps a shared tokenizer + * from quietly widening a flag's grammar: sub-second input was a usage error + * for `--expire` before the parsers were unified, and must stay one. + */ + units?: readonly DurationUnit[]; +} + /** * Parse a duration literal. Returns `undefined` when the input cannot be read * at all — callers decide whether that is a usage error or a default. @@ -49,7 +58,10 @@ const DURATION_PATTERN = /^(\d+(?:\.\d+)?)\s*([a-z]+)?$/i; * A unitless number keeps whatever magnitude it had; pair it with * {@link expireSeconds} or an explicit `unitless` argument to resolve it. */ -export function tokenizeDuration(value: string | number): DurationToken | undefined { +export function tokenizeDuration( + value: string | number, + options: TokenizeDurationOptions = {} +): DurationToken | undefined { if (typeof value === "number") { return Number.isFinite(value) ? { value, unit: undefined } : undefined; } @@ -71,9 +83,18 @@ export function tokenizeDuration(value: string | number): DurationToken | undefi if (!unit) { return undefined; } + if (options.units && !options.units.includes(unit)) { + return undefined; + } return { value: parseFloat(match[1]), unit }; } +/** + * Units the `--expire` flags accept. Sub-second precision is meaningless for + * an assistance link and was rejected before the parsers were shared. + */ +export const EXPIRE_UNITS: readonly DurationUnit[] = ["d", "h", "m", "s"]; + /** Convert a token to seconds, resolving a unitless value as `unitless`. */ export function durationSeconds(token: DurationToken, unitless: DurationUnit): number { switch (token.unit ?? unitless) { From 0de2db14aee6fd068bcfa1c3ced195dddad1dd07 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 11 Oct 2026 19:51:32 +0800 Subject: [PATCH 7/7] Close the re-export bypass in the helpers freeze ratchet The declaration counter does not see `export { x } from "./y.js"` or `export *`, so a re-export would re-publish helpers from this file's namespace without touching either ceiling. Assert against that syntax. --- src/domains/seal/capabilities/helpers.freeze.test.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/domains/seal/capabilities/helpers.freeze.test.ts b/src/domains/seal/capabilities/helpers.freeze.test.ts index c161030..a0de027 100644 --- a/src/domains/seal/capabilities/helpers.freeze.test.ts +++ b/src/domains/seal/capabilities/helpers.freeze.test.ts @@ -56,6 +56,13 @@ describe("capabilities/helpers.ts freeze", () => { expect(source).toContain("helpers.freeze.test.ts"); }); + test("no re-export syntax sneaks new symbols into the namespace", () => { + // The declaration counter above does not see `export { x } from "..."` or + // `export *`, which would re-publish helpers from this file's namespace + // without touching either ceiling. + expect(source).not.toMatch(/^export\s*(\{|\*)/m); + }); + test("measures what it claims to measure", () => { // Guard the ratchet itself: a pattern that matches nothing would silently // pin the export ceiling at 0 and pass forever.