diff --git a/README.md b/README.md index 9d5e27c..5552d10 100644 --- a/README.md +++ b/README.md @@ -186,11 +186,15 @@ These tools remain available to the CLI: - `seal_approval_rules_list`: current draft approval rules. Use `{"countOnly":true}` or `{"fields":["id"],"limit":0}` to return only `{"count":...}`; use `fields` for lightweight projections when rule descriptions are not needed. - `seal_approval_rule_create`, `seal_approval_rule_update`, `seal_approval_rule_delete`: maintain approval rules. - `seal_approval_rule_versions_list`, `seal_approval_rule_version_publish`: read and publish rule versions. +- `seal_approval_rule_get`: fetch one rule from a published version by `versionNumber` plus `code` such as `#0038`, or by `recordId` plus `runtimeId` such as `rule-205`. - `seal_approval_documents_list`, `seal_approval_document_get`, `seal_approval_document_create`, `seal_approval_document_update`: maintain approval documents. - `seal_approval_style_preferences_get`, `seal_approval_style_preferences_update`: read and update approval style preferences. - `seal_approval_runs_summary`: summarize approval runs by local date and timezone. Use this for daily questions such as "what approval records did Tawen have today"; it returns status/task-mode counts and compact records. -- `seal_approval_run_get`: fetch one approval run. Pass `fields` such as `"metadata"` or `"document.fields,result.summary"` to avoid returning full document, pipeline, and AI output payloads. -- `seal_approval_run_attachments_get`: return attachment and invoice file metadata for one run without the full document or rule result. +- `seal_approval_run_get`: fetch one approval run. Pass `summary:true` or `fields` such as `"metadata"` or `"document.fields,result.summary"` to avoid returning full document, pipeline, and AI output payloads. +- `seal_approval_run_pick`: locate likely approval run records by document number, batch, latest flag, and optional field projection. +- `seal_approval_run_cited_rules_get`: extract rules cited or matched by the AI result, including runtime ID/code, version, scope, strictness, analysis, result, and findings when present. +- `seal_approval_run_document_summary_get`: return key document fields, invoice/attachment summary, AI result, and manual result. +- `seal_approval_run_attachments_get`: return attachment and invoice file metadata for one run without the full document or rule result; use `summary:true` for the smallest list. - `seal_approval_run_result_get`: return one run result, with `{"summary":true}` for decision, summary, risk point count, matched rule count, trace ID, and record ID only. - `seal_approval_run_url_get`: return the Hose enterprise assist URL, optionally with the original document URL for an approval run by `recordId`, `sourceDocumentSN`, or `sourceDocumentId`. - `seal_simulation_batch_records_get`: read records from one simulation batch via `api/v1/simulation/batch/{batchId}/records`. @@ -198,7 +202,7 @@ These tools remain available to the CLI: For rule list commands, prefer `seal-home rules count` or `seal-home rules list --summary` before requesting full rule descriptions. `seal-home rules list` protects large outputs and asks for `--summary`, `--count`, or explicit `--full` when the response would be too large. -For approval run detail commands, prefer `seal-home approval-runs get --fields metadata`, `seal-home approval-runs attachments `, or `seal-home approval-runs result --summary` before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-home auth hose-link --corp --expire 7200`, which returns the unredacted `getProvisionalAuth` URL. +For approval run detail commands, prefer `seal-home approval-runs pick --sn <单号> --latest`, `seal-home approval-runs get --summary`, `seal-home approval-runs document-summary `, `seal-home approval-runs cited-rules `, `seal-home approval-runs attachments --summary`, or `seal-home approval-runs result --summary` before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-home auth hose-link --corp --expire 7200`, which returns the unredacted `getProvisionalAuth` URL. ## Approval Run To Langfuse Bridge diff --git a/dist/openapi.json b/dist/openapi.json index 9dd28ab..102f32f 100644 --- a/dist/openapi.json +++ b/dist/openapi.json @@ -900,6 +900,83 @@ } } }, + "/v1/approval/rules/by-version": { + "get": { + "tags": [ + "Approval Knowledge" + ], + "operationId": "getApprovalRuleByVersion", + "summary": "Get one wrapped rule from a published version", + "parameters": [ + { + "name": "corpId", + "in": "query", + "schema": { + "type": "string" + }, + "description": "Optional local enterprise config ID. Defaults to the current selected enterprise." + }, + { + "name": "versionNumber", + "in": "query", + "schema": { + "type": "integer" + } + }, + { + "name": "versionId", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "latest", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "code", + "in": "query", + "schema": { + "type": "string" + }, + "description": "Display rule code such as '#0038'." + }, + { + "name": "runtimeId", + "in": "query", + "schema": { + "type": "string" + }, + "description": "Runtime rule ID such as rule-205." + }, + { + "name": "recordId", + "in": "query", + "schema": { + "type": "string" + }, + "description": "Infer versionNumber from an approval run." + } + ], + "responses": { + "200": { + "description": "One rule from a published version.", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + } + } + }, "/v1/approval/rule-versions/publish": { "post": { "tags": [ @@ -1707,11 +1784,41 @@ { "name": "query", "in": "query", - "required": true, "schema": { "type": "string" } }, + { + "name": "sn", + "in": "query", + "schema": { + "type": "string" + }, + "description": "Source document number for direct lookup." + }, + { + "name": "batch", + "in": "query", + "schema": { + "type": "string" + }, + "description": "Optional simulation batch ID." + }, + { + "name": "latest", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "fields", + "in": "query", + "schema": { + "type": "string" + }, + "description": "Comma-separated response fields." + }, { "name": "limit", "in": "query", @@ -1910,6 +2017,23 @@ ], "operationId": "getApprovalRun", "summary": "Get wrapped approval run detail", + "parameters": [ + { + "name": "summary", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "fields", + "in": "query", + "schema": { + "type": "string" + }, + "description": "Comma-separated field paths such as metadata,document.fields,result.summary." + } + ], "responses": { "200": { "description": "Approval run detail plus stable aliases and human result.", @@ -1925,6 +2049,156 @@ } } }, + "/v1/approval-runs/{recordId}/cited-rules": { + "parameters": [ + { + "name": "recordId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "seal-home approval run record ID." + } + ], + "get": { + "tags": [ + "Approval Runs" + ], + "operationId": "getApprovalRunCitedRules", + "summary": "Extract rules cited or matched by the AI result", + "responses": { + "200": { + "description": "Cited rule summaries.", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + } + } + }, + "/v1/approval-runs/{recordId}/document-summary": { + "parameters": [ + { + "name": "recordId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "seal-home approval run record ID." + } + ], + "get": { + "tags": [ + "Approval Runs" + ], + "operationId": "getApprovalRunDocumentSummary", + "summary": "Get key document fields and compact AI/manual result", + "responses": { + "200": { + "description": "Document summary.", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + } + } + }, + "/v1/approval-runs/{recordId}/attachments": { + "parameters": [ + { + "name": "recordId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "seal-home approval run record ID." + } + ], + "get": { + "tags": [ + "Approval Runs" + ], + "operationId": "getApprovalRunAttachments", + "summary": "List compact attachment metadata", + "parameters": [ + { + "name": "summary", + "in": "query", + "schema": { + "type": "boolean" + } + } + ], + "responses": { + "200": { + "description": "Attachment metadata.", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + } + } + }, + "/v1/approval-runs/{recordId}/result": { + "parameters": [ + { + "name": "recordId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "seal-home approval run record ID." + } + ], + "get": { + "tags": [ + "Approval Runs" + ], + "operationId": "getApprovalRunResult", + "summary": "Get AI result, optionally as a compact summary", + "parameters": [ + { + "name": "summary", + "in": "query", + "schema": { + "type": "boolean" + } + } + ], + "responses": { + "200": { + "description": "AI result or summary.", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + } + } + }, "/v1/simulation/batches/{batchId}/records": { "parameters": [ { diff --git a/openapi/paths/approval-knowledge.yaml b/openapi/paths/approval-knowledge.yaml index e542835..e672818 100644 --- a/openapi/paths/approval-knowledge.yaml +++ b/openapi/paths/approval-knowledge.yaml @@ -128,6 +128,48 @@ paths: application/json: schema: $ref: ../components/schemas/index.yaml#/RuleSetVersion + /v1/approval/rules/by-version: + get: + tags: [Approval Knowledge] + operationId: getApprovalRuleByVersion + summary: Get one wrapped rule from a published version + parameters: + - $ref: ../components/parameters.yaml#/CorpId + - name: versionNumber + in: query + schema: + type: integer + - name: versionId + in: query + schema: + type: string + - name: latest + in: query + schema: + type: boolean + - name: code + in: query + schema: + type: string + description: Display rule code such as '#0038'. + - name: runtimeId + in: query + schema: + type: string + description: Runtime rule ID such as rule-205. + - name: recordId + in: query + schema: + type: string + description: Infer versionNumber from an approval run. + responses: + "200": + description: One rule from a published version. + content: + application/json: + schema: + type: object + additionalProperties: true /v1/approval/rule-versions/publish: post: tags: [Approval Knowledge] diff --git a/openapi/paths/approval-runs.yaml b/openapi/paths/approval-runs.yaml index bc103b5..04c1ca9 100644 --- a/openapi/paths/approval-runs.yaml +++ b/openapi/paths/approval-runs.yaml @@ -108,9 +108,27 @@ paths: - $ref: ../components/parameters.yaml#/CorpId - name: query in: query - required: true schema: type: string + - name: sn + in: query + schema: + type: string + description: Source document number for direct lookup. + - name: batch + in: query + schema: + type: string + description: Optional simulation batch ID. + - name: latest + in: query + schema: + type: boolean + - name: fields + in: query + schema: + type: string + description: Comma-separated response fields. - name: limit in: query schema: @@ -192,6 +210,16 @@ paths: tags: [Approval Runs] operationId: getApprovalRun summary: Get wrapped approval run detail + parameters: + - name: summary + in: query + schema: + type: boolean + - name: fields + in: query + schema: + type: string + description: Comma-separated field paths such as metadata,document.fields,result.summary. responses: "200": description: Approval run detail plus stable aliases and human result. @@ -200,3 +228,73 @@ paths: schema: type: object additionalProperties: true + /v1/approval-runs/{recordId}/cited-rules: + parameters: + - $ref: ../components/parameters.yaml#/RecordId + get: + tags: [Approval Runs] + operationId: getApprovalRunCitedRules + summary: Extract rules cited or matched by the AI result + responses: + "200": + description: Cited rule summaries. + content: + application/json: + schema: + type: object + additionalProperties: true + /v1/approval-runs/{recordId}/document-summary: + parameters: + - $ref: ../components/parameters.yaml#/RecordId + get: + tags: [Approval Runs] + operationId: getApprovalRunDocumentSummary + summary: Get key document fields and compact AI/manual result + responses: + "200": + description: Document summary. + content: + application/json: + schema: + type: object + additionalProperties: true + /v1/approval-runs/{recordId}/attachments: + parameters: + - $ref: ../components/parameters.yaml#/RecordId + get: + tags: [Approval Runs] + operationId: getApprovalRunAttachments + summary: List compact attachment metadata + parameters: + - name: summary + in: query + schema: + type: boolean + responses: + "200": + description: Attachment metadata. + content: + application/json: + schema: + type: object + additionalProperties: true + /v1/approval-runs/{recordId}/result: + parameters: + - $ref: ../components/parameters.yaml#/RecordId + get: + tags: [Approval Runs] + operationId: getApprovalRunResult + summary: Get AI result, optionally as a compact summary + parameters: + - name: summary + in: query + schema: + type: boolean + responses: + "200": + description: AI result or summary. + content: + application/json: + schema: + type: object + additionalProperties: true diff --git a/openapi/paths/index.yaml b/openapi/paths/index.yaml index 0c3e809..5f8d56d 100644 --- a/openapi/paths/index.yaml +++ b/openapi/paths/index.yaml @@ -24,6 +24,8 @@ $ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1rule-versions /v1/approval/rule-versions/{versionId}: $ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1rule-versions~1{versionId} +/v1/approval/rules/by-version: + $ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1rules~1by-version /v1/approval/rule-versions/publish: $ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1rule-versions~1publish /v1/approval/documents: @@ -44,5 +46,13 @@ $ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1url /v1/approval-runs/{recordId}: $ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1{recordId} +/v1/approval-runs/{recordId}/cited-rules: + $ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1{recordId}~1cited-rules +/v1/approval-runs/{recordId}/document-summary: + $ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1{recordId}~1document-summary +/v1/approval-runs/{recordId}/attachments: + $ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1{recordId}~1attachments +/v1/approval-runs/{recordId}/result: + $ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1{recordId}~1result /v1/simulation/batches/{batchId}/records: $ref: ./simulation.yaml#/paths/~1v1~1simulation~1batches~1{batchId}~1records diff --git a/skills/seal-home/SKILL.md b/skills/seal-home/SKILL.md index c7e52a2..cde0de5 100644 --- a/skills/seal-home/SKILL.md +++ b/skills/seal-home/SKILL.md @@ -172,10 +172,13 @@ Preferred command forms: ```bash seal-home approval-runs summary --date 2026-06-09 --timezone Asia/Shanghai -seal-home approval-runs search --query B26001887 --limit 20 --includeBridge true -seal-home approval-runs get --fields metadata,document.fields,result.summary -seal-home approval-runs attachments +seal-home approval-runs pick --sn B26001887 --latest +seal-home approval-runs get --summary +seal-home approval-runs document-summary +seal-home approval-runs cited-rules +seal-home approval-runs attachments --summary seal-home approval-runs result --summary +seal-home rules get --version 16 --code '#0038' seal-home approval-runs url seal-home approval-runs url --sourceDocumentSN B26001887 seal-home approval-runs bridge --sourceDocumentSN B26001887 diff --git a/skills/seal-home/references/cli.md b/skills/seal-home/references/cli.md index fa38e30..fdcea53 100644 --- a/skills/seal-home/references/cli.md +++ b/skills/seal-home/references/cli.md @@ -75,10 +75,17 @@ Approval rule maintenance: Approval run lightweight queries: - `seal-home approval-runs get --fields metadata` +- `seal-home approval-runs get --summary` +- `seal-home approval-runs pick --sn <单号> --batch --latest` +- `seal-home approval-runs document-summary ` +- `seal-home approval-runs cited-rules ` - `seal-home approval-runs get --fields document.fields,result.summary` -- `seal-home approval-runs attachments ` +- `seal-home approval-runs attachments --summary` - `seal-home approval-runs result --summary` - `seal_approval_run_get` with `fields` +- `seal_approval_run_pick` +- `seal_approval_run_cited_rules_get` +- `seal_approval_run_document_summary_get` - `seal_approval_run_attachments_get` - `seal_approval_run_result_get` with `{"summary":true}` @@ -93,6 +100,8 @@ Approval search and context: - `seal_approval_search` - `seal_approval_context_get` +- `seal-home rules get --version --code '#0038'` +- `seal-home rules get --record-id --runtime-id rule-205` Style preferences: diff --git a/src/cli.ts b/src/cli.ts index 96f559d..02d3690 100755 --- a/src/cli.ts +++ b/src/cli.ts @@ -185,6 +185,16 @@ async function main() { return; } + if (area === "rules" && action === "get") { + await runTool("seal_approval_rule_get", client, corp, { + ...ruleVersionGetOptions(stringOption(args.options.version)), + code: stringOption(args.options.code), + runtimeId: stringOption(args.options.runtimeId) ?? stringOption(args.options["runtime-id"]), + recordId: stringOption(args.options.recordId) ?? stringOption(args.options["record-id"]) + }, outputOptions(args.options)); + return; + } + if (area === "rules" && action === "search") { const keyword = maybeName ?? stringOption(args.options.query); if (!keyword) throw new Error("Usage: seal-home rules search [--version ]"); @@ -194,6 +204,9 @@ async function main() { maxResults: numberOption(args.options.maxResults), contextLines: numberOption(args.options.contextLines), refresh: booleanOption(args.options.refresh), + snippetOnly: booleanOption(args.options.snippetOnly) ?? booleanOption(args.options["snippet-only"]), + maxChars: numberOption(args.options.maxChars) ?? numberOption(args.options["max-chars"]), + fields: splitOption(args.options.fields), ...ruleVersionSearchOptions(stringOption(args.options.version)) }, outputOptions(args.options)); return; @@ -253,10 +266,14 @@ async function main() { } if (area === "approval-runs" && action === "pick") { - const query = maybeName ?? stringOption(args.options.query); - if (!query) throw new Error("Usage: seal-home approval-runs pick "); + const query = maybeName ?? stringOption(args.options.query) ?? stringOption(args.options.sn); + if (!query) throw new Error("Usage: seal-home approval-runs pick --sn "); await runTool("seal_approval_run_pick", client, corp, { query, + sn: stringOption(args.options.sn), + batchId: stringOption(args.options.batch) ?? stringOption(args.options.batchId), + latest: booleanOption(args.options.latest), + fields: stringOption(args.options.fields), limit: numberOption(args.options.limit), includeBridge: booleanOption(args.options.includeBridge) }, outputOptions(args.options)); @@ -268,15 +285,33 @@ async function main() { if (!recordId) throw new Error("Missing approval run recordId"); await runTool("seal_approval_run_get", client, corp, { recordId, - fields: stringOption(args.options.fields) + fields: stringOption(args.options.fields), + summary: booleanOption(args.options.summary) }, outputOptions(args.options)); return; } + if (area === "approval-runs" && action === "cited-rules") { + const recordId = args.command[2]; + if (!recordId) throw new Error("Usage: seal-home approval-runs cited-rules "); + await runTool("seal_approval_run_cited_rules_get", client, corp, { recordId }, outputOptions(args.options)); + return; + } + + if (area === "approval-runs" && action === "document-summary") { + const recordId = args.command[2]; + if (!recordId) throw new Error("Usage: seal-home approval-runs document-summary "); + await runTool("seal_approval_run_document_summary_get", client, corp, { recordId }, outputOptions(args.options)); + return; + } + if (area === "approval-runs" && action === "attachments") { const recordId = args.command[2]; if (!recordId) throw new Error("Usage: seal-home approval-runs attachments "); - await runTool("seal_approval_run_attachments_get", client, corp, { recordId }, outputOptions(args.options)); + await runTool("seal_approval_run_attachments_get", client, corp, { + recordId, + summary: booleanOption(args.options.summary) + }, outputOptions(args.options)); return; } @@ -961,6 +996,18 @@ function ruleVersionContextOptions(value?: string) { return { ruleVersionId: selector.versionId }; } +function ruleVersionGetOptions(value?: string) { + if (!value) return {}; + const selector = parseRuleVersionSelector(value); + if ("latest" in selector) { + return { latest: true }; + } + if ("versionNumber" in selector) { + return { versionNumber: selector.versionNumber }; + } + return { versionId: selector.versionId }; +} + function parseArgs(argv: string[]): ParsedArgs { const command: string[] = []; const options: Record = {}; @@ -1015,6 +1062,12 @@ function numberOption(value: string | boolean | undefined): number | undefined { return number; } +function splitOption(value: string | boolean | undefined): string[] | undefined { + if (typeof value !== "string") return undefined; + const items = value.split(",").map((item) => item.trim()).filter(Boolean); + return items.length ? items : undefined; +} + function booleanOption(value: string | boolean | undefined): boolean | undefined { if (value === undefined) return undefined; if (typeof value === "boolean") return value; @@ -1079,13 +1132,17 @@ Usage: seal-home rules list [--summary] [--count] [--limit 20] [--offset 0] [--corp ] seal-home rules versions [--corp ] seal-home rules version [--corp ] + seal-home rules get --version --code '#0038' + seal-home rules get --record-id --runtime-id rule-205 seal-home rules search [--version ] [--maxResults 20] seal-home context [--ruleVersion ] [--documentLimit 50] seal-home approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] seal-home approval-runs search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] - seal-home approval-runs pick [--limit 20] - seal-home approval-runs get [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] - seal-home approval-runs attachments + seal-home approval-runs pick --sn [--batch ] [--latest] [--fields recordId,status,aiDecision] + seal-home approval-runs get [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] + seal-home approval-runs cited-rules + seal-home approval-runs document-summary + seal-home approval-runs attachments [--summary] seal-home approval-runs result [--summary] seal-home approval-runs url seal-home approval-runs url diff --git a/src/domains/seal/search.ts b/src/domains/seal/search.ts index 3e98efc..19e1081 100644 --- a/src/domains/seal/search.ts +++ b/src/domains/seal/search.ts @@ -31,6 +31,9 @@ export type ApprovalSearchParams = { ruleVersionId?: string; ruleVersionNumber?: number; latestRuleVersion?: boolean; + snippetOnly?: boolean; + maxChars?: number; + fields?: string[]; }; export type ApprovalSearchResult = { @@ -101,8 +104,13 @@ function searchEntry( entry: SearchEntry, params: Required> & { keywords: string[]; + snippetOnly?: boolean; + maxChars?: number; + fields?: Set; } ): ApprovalSearchResult[] { + if (params.fields && !params.fields.has(entry.field)) return []; + const lines = linesOf(entry.value); const results: ApprovalSearchResult[] = []; @@ -118,7 +126,7 @@ function searchEntry( const beforeStart = Math.max(0, index - params.contextLines); const afterEnd = Math.min(lines.length, index + params.contextLines + 1); - results.push({ + const result: ApprovalSearchResult = { area: entry.area, entityType: entry.entityType, entityId: entry.entityId, @@ -126,19 +134,34 @@ function searchEntry( field: entry.field, lineNumber: index + 1, matchedKeywords: matches, - matchedText: line, + matchedText: truncateText(line, params.maxChars), context: { - before: lines.slice(beforeStart, index), - line, - after: lines.slice(index + 1, afterEnd) + before: params.snippetOnly ? [] : lines.slice(beforeStart, index).map((item) => truncateText(item, params.maxChars)), + line: truncateText(line, params.maxChars), + after: params.snippetOnly ? [] : lines.slice(index + 1, afterEnd).map((item) => truncateText(item, params.maxChars)) }, metadata: entry.metadata - }); + }; + + if (params.snippetOnly) { + result.context = { + before: [], + line: result.context.line, + after: [] + }; + } + + results.push(result); }); return results; } +function truncateText(value: string, maxChars?: number): string { + if (!maxChars || value.length <= maxChars) return value; + return `${value.slice(0, Math.max(0, maxChars))}...`; +} + function ruleEntries(rule: ApprovalRule): SearchEntry[] { return [ { @@ -390,6 +413,7 @@ export async function searchApprovalContent( const maxResults = params.maxResults ?? 50; const ruleVersionScope = params.ruleVersionScope ?? "current"; const keywords = normalizeKeywords(params.keywords, caseSensitive); + const fields = params.fields?.length ? new Set(params.fields) : undefined; if (keywords.length === 0) { throw new Error("keywords must contain at least one non-empty string"); @@ -407,7 +431,15 @@ export async function searchApprovalContent( const results = cached.entries .filter((entry) => areas.has(entry.area)) .flatMap((entry) => - searchEntry(entry, { keywords, matchMode, caseSensitive, contextLines }) + searchEntry(entry, { + keywords, + matchMode, + caseSensitive, + contextLines, + snippetOnly: params.snippetOnly, + maxChars: params.maxChars, + fields + }) ); return { @@ -421,7 +453,10 @@ export async function searchApprovalContent( ruleVersionScope, ruleVersionId: params.ruleVersionId, ruleVersionNumber: params.ruleVersionNumber, - latestRuleVersion: params.latestRuleVersion ?? false + latestRuleVersion: params.latestRuleVersion ?? false, + snippetOnly: params.snippetOnly ?? false, + maxChars: params.maxChars, + fields: params.fields }, cache: { fetchedAt: new Date(cached.fetchedAt).toISOString(), diff --git a/src/domains/seal/tools.test.ts b/src/domains/seal/tools.test.ts index 7901443..a7b5dd7 100644 --- a/src/domains/seal/tools.test.ts +++ b/src/domains/seal/tools.test.ts @@ -135,6 +135,20 @@ describe("sealTools", () => { expect(result.matched).toBe(2); }); + test("routes lightweight approval run actions through seal_action", async () => { + const tool = sealMcpTools.find((item) => item.name === "seal_action"); + expect(tool).toBeDefined(); + + const handler = tool!.handler as ToolHandler; + const result = await handler( + fakeApprovalRunsClient(), + { action: "runs.citedRules", payload: { recordId: "run-1" } }, + fakeContext() + ) as { count: number }; + + expect(result.count).toBe(1); + }); + test("keeps old fine-grained tools available to compatibility callers but hidden from MCP list", () => { expect(sealMcpTools.find((item) => item.name === "seal_approval_rule_create")).toBeUndefined(); expect(findSealMcpTool("seal_approval_rule_create")).toBeUndefined(); @@ -272,12 +286,49 @@ describe("sealTools", () => { }; expect(result.metadata?.recordId).toBe("run-1"); - expect(result.document?.fields).toHaveLength(1); + expect(result.document?.fields).toHaveLength(3); expect(result.result?.summary).toBe("费用存在风险"); expect(result.result?.manualApproval).toBeUndefined(); expect(result.pipelineData).toBeUndefined(); }); + test("approval run get can return summary preset", async () => { + const tool = sealTools.find((item) => item.name === "seal_approval_run_get"); + expect(tool).toBeDefined(); + + const handler = tool!.handler as ToolHandler; + const result = await handler( + fakeApprovalRunsClient(), + { recordId: "run-1", summary: true }, + fakeContext() + ) as { aiResult?: { decision?: string }; manualResult?: string; document?: { title?: string } }; + + expect(result.aiResult?.decision).toBe("驳回"); + expect(result.manualResult).toBe("驳回"); + expect(result.document?.title).toBe("差旅报销单"); + }); + + test("approval run pick supports sn latest and compact candidate fields", async () => { + const tool = sealTools.find((item) => item.name === "seal_approval_run_pick"); + expect(tool).toBeDefined(); + + const requests: string[] = []; + const handler = tool!.handler as ToolHandler; + const result = await handler( + fakeApprovalRunsClient(requests), + { sn: "B26001965", latest: true }, + fakeContext() + ) as { matched: number; records: Array<{ recordId?: string; aiDecision?: string; aiSummary?: string }> }; + + expect(requests[0]).toContain("sourceDocumentSN=B26001965"); + expect(result.matched).toBe(1); + expect(result.records[0]).toMatchObject({ + recordId: "run-1", + aiDecision: "驳回", + aiSummary: "费用存在风险" + }); + }); + test("approval run attachments extracts compact attachment metadata", async () => { const tool = sealTools.find((item) => item.name === "seal_approval_run_attachments_get"); expect(tool).toBeDefined(); @@ -304,6 +355,48 @@ describe("sealTools", () => { })); }); + test("approval run cited rules extracts rule application details", async () => { + const tool = sealTools.find((item) => item.name === "seal_approval_run_cited_rules_get"); + expect(tool).toBeDefined(); + + const handler = tool!.handler as ToolHandler; + const result = await handler( + fakeApprovalRunsClient(), + { recordId: "run-1" }, + fakeContext() + ) as { count: number; rules: Array> }; + + expect(result.count).toBe(1); + expect(result.rules[0]).toMatchObject({ + runtimeRuleId: "rule-38", + ruleCode: "#0038", + versionNumber: 16, + scope: "travel", + strictness: "MUST_FOLLOW", + checkResult: "failed" + }); + }); + + test("approval run document summary returns key fields without raw payload", async () => { + const tool = sealTools.find((item) => item.name === "seal_approval_run_document_summary_get"); + expect(tool).toBeDefined(); + + const handler = tool!.handler as ToolHandler; + const result = await handler( + fakeApprovalRunsClient(), + { recordId: "run-1" }, + fakeContext() + ) as { document?: { amount?: unknown; expenseType?: unknown }; invoices?: Array> }; + + expect(result.document?.amount).toBe("100.00"); + expect(result.document?.expenseType).toBe("差旅费"); + expect(result.invoices?.[0]).toMatchObject({ + buyer: "甲方公司", + seller: "乙方公司", + amount: 100 + }); + }); + test("approval run result can return summary only", async () => { const tool = sealTools.find((item) => item.name === "seal_approval_run_result_get"); expect(tool).toBeDefined(); @@ -427,6 +520,24 @@ describe("sealTools", () => { ]); expect(result.records[0]?.createdAt).toBe("2026-06-08 13:56:04"); }); + + test("approval rule get resolves one rule by version and code", async () => { + const tool = sealTools.find((item) => item.name === "seal_approval_rule_get"); + expect(tool).toBeDefined(); + + const handler = tool!.handler as ToolHandler; + const result = await handler( + fakeRulesClient(), + { versionNumber: 16, code: "#0002" }, + fakeContext() + ) as { ruleCode?: string; description?: string; versionNumber?: number }; + + expect(result).toMatchObject({ + ruleCode: "#0002", + description: "Second published rule", + versionNumber: 16 + }); + }); }); function fakeApprovalRunsClient(requests: string[] = []): KyInstance { @@ -442,11 +553,16 @@ function fakeApprovalRunsClient(requests: string[] = []): KyInstance { sourceDocumentSN: "B26001965", sourceDocumentId: "doc-source-1", documentId: "normalized-doc-1", + ruleSetVersionNumber: 16, document: { id: "normalized-doc-1", + title: "差旅报销单", + templateName: "费用报销", sourceDocumentSN: "B26001965", sourceDocumentId: "doc-source-1", fields: [ + { label: "金额", value: "100.00" }, + { label: "费用类型", value: "差旅费" }, { label: "附件", attachments: [ @@ -461,9 +577,19 @@ function fakeApprovalRunsClient(requests: string[] = []): KyInstance { ] }, result: { + decision: "驳回", summary: "费用存在风险", riskPoints: ["金额异常", "附件缺失"], - matchedRules: [{ id: "rule-1" }], + matchedRules: [{ + runtimeRuleId: "rule-38", + ruleCode: "#0038", + versionNumber: 16, + scope: "travel", + strictness: "MUST_FOLLOW", + appliedAnalysis: "发票信息与报销说明不一致", + checkResult: "failed", + findings: ["金额异常"] + }], manualApproval: { result: "驳回" }, @@ -471,7 +597,12 @@ function fakeApprovalRunsClient(requests: string[] = []): KyInstance { { fileName: "invoice.png", mimeType: "image/png", - signedUrl: "https://signed.example/invoice.png" + signedUrl: "https://signed.example/invoice.png", + buyer: "甲方公司", + seller: "乙方公司", + amount: 100, + taxRate: "6%", + category: "增值税普通发票" } ] }, @@ -494,6 +625,7 @@ function fakeApprovalRunsClient(requests: string[] = []): KyInstance { taskMode: "assisted", sourceDocumentSN: "B26001965", sourceDocumentId: "doc-source-1", + ruleSetVersionNumber: 16, sourceExtendData: { _langfuseTraceId: "trace-1" }, createdAt: 1780898164536 }, @@ -527,33 +659,54 @@ function fakeApprovalRunsClient(requests: string[] = []): KyInstance { function fakeRulesClient(): KyInstance { return { - get: () => ({ + get: (url: string) => ({ json: async () => ({ - data: { - hasPendingDeletes: false, - rules: [ - { - id: "rule-1", - tenantId: "tenant-1", - description: "Must include full invoice detail", - scope: "travel", - strictness: "MUST_FOLLOW", - status: "active", - createdAt: 1780898164536, - updatedAt: 1780898164536 - }, - { - id: "rule-2", - tenantId: "tenant-1", - description: "Prefer matching attendee names", - scope: "meal", - strictness: "SHOULD_FOLLOW", - status: "draft", - createdAt: 1780898164537, - updatedAt: 1780898164537 + data: url === "api/v1/rule-set-versions" + ? [ + { + id: "version-16", + versionNumber: 16, + versionName: "v16", + publishedByName: "Tester", + rules: [ + { + description: "First published rule", + scope: "travel", + strictness: "MUST_FOLLOW" + }, + { + description: "Second published rule", + scope: "meal", + strictness: "SHOULD_FOLLOW" + } + ] + } + ] + : { + hasPendingDeletes: false, + rules: [ + { + id: "rule-1", + tenantId: "tenant-1", + description: "Must include full invoice detail", + scope: "travel", + strictness: "MUST_FOLLOW", + status: "active", + createdAt: 1780898164536, + updatedAt: 1780898164536 + }, + { + id: "rule-2", + tenantId: "tenant-1", + description: "Prefer matching attendee names", + scope: "meal", + strictness: "SHOULD_FOLLOW", + status: "draft", + createdAt: 1780898164537, + updatedAt: 1780898164537 + } + ] } - ] - } }) }) } as unknown as KyInstance; diff --git a/src/domains/seal/tools.ts b/src/domains/seal/tools.ts index bf0b5ff..10ca01d 100644 --- a/src/domains/seal/tools.ts +++ b/src/domains/seal/tools.ts @@ -152,6 +152,39 @@ export const sealTools = [ handler: async (client: KyInstance, params: { versionName: string }) => api.publishApprovalRuleVersion(client, params.versionName) }, + { + name: "seal_approval_rule_get", + description: "按版本号/code/runtime-id/record-id 定位单条规则,避免拉取整版规则快照", + parameters: z.object({ + versionId: z.string().optional().describe("规则版本 ID"), + versionNumber: z.number().int().positive().optional().describe("规则版本号"), + latest: z.boolean().optional().describe("为 true 时取最新版本"), + code: z.string().optional().describe("规则展示编号,如 #0038;没有后端 code 时按版本内序号匹配"), + runtimeId: z.string().optional().describe("运行时规则 ID,如 rule-205;按版本内序号匹配"), + recordId: z.string().optional().describe("从运行记录推断 ruleSetVersionNumber") + }), + handler: async ( + client: KyInstance, + params: { + versionId?: string; + versionNumber?: number; + latest?: boolean; + code?: string; + runtimeId?: string; + recordId?: string; + } + ) => { + const version = await resolveRuleVersionForLookup(client, params); + const rule = findRuleInVersion(version, { + code: params.code, + runtimeId: params.runtimeId + }); + if (!rule) { + throw new Error(`Rule not found in version ${version.versionNumber}`); + } + return rule; + } + }, { name: "seal_approval_documents_list", description: "列出 Seal 审批知识文档", @@ -246,7 +279,10 @@ export const sealTools = [ ruleVersionScope: z.enum(["current", "all", "version"]).optional().describe("规则检索范围,默认 current;all 会检索所有已发布历史版本"), ruleVersionId: z.string().optional().describe("ruleVersionScope=version 时指定版本 ID"), ruleVersionNumber: z.number().int().positive().optional().describe("ruleVersionScope=version 时指定版本号"), - latestRuleVersion: z.boolean().optional().describe("ruleVersionScope=version 时取最新已发布版本") + latestRuleVersion: z.boolean().optional().describe("ruleVersionScope=version 时取最新已发布版本"), + snippetOnly: z.boolean().optional().describe("只返回命中行,不返回前后文"), + maxChars: z.number().int().positive().optional().describe("每个文本片段最多返回字符数"), + fields: z.array(z.string()).optional().describe("只搜索指定字段,如 history.description、description、scope") }), handler: async ( client: KyInstance, @@ -263,6 +299,9 @@ export const sealTools = [ ruleVersionId?: string; ruleVersionNumber?: number; latestRuleVersion?: boolean; + snippetOnly?: boolean; + maxChars?: number; + fields?: string[]; }, context: ToolContext ) => searchApprovalContent(client, context.corp, params) @@ -464,13 +503,15 @@ export const sealTools = [ description: "获取 Seal 单条审批/审核运行记录详情;可用 fields 只取 metadata、document.fields、result.summary 等局部字段", parameters: z.object({ recordId: z.string().describe("Seal approval run record ID"), - fields: z.union([z.string(), z.array(z.string())]).optional().describe("逗号分隔或数组形式的字段路径,如 metadata、document.fields、result.summary") + fields: z.union([z.string(), z.array(z.string())]).optional().describe("逗号分隔或数组形式的字段路径,如 metadata、document.fields、result.summary"), + summary: z.boolean().optional().describe("返回单据摘要、AI 结果、人工结果和版本号") }), handler: async ( client: KyInstance, - params: { recordId: string; fields?: string | string[] } + params: { recordId: string; fields?: string | string[]; summary?: boolean } ) => { const record = await api.getApprovalRun(client, params.recordId); + if (params.summary) return summarizeApprovalRunDetail(record); const full = { ...record, aliases: approvalRunAliases(record), @@ -481,8 +522,8 @@ export const sealTools = [ } }, { - name: "seal_approval_run_attachments_get", - description: "从审批运行记录中抽取附件、发票附件和字段位置,不返回完整单据正文和规则结果", + name: "seal_approval_run_cited_rules_get", + description: "从审批运行结果中抽取 AI 引用或命中的规则及应用分析", parameters: z.object({ recordId: z.string().describe("Seal approval run record ID") }), @@ -491,7 +532,36 @@ export const sealTools = [ params: { recordId: string } ) => { const record = await api.getApprovalRun(client, params.recordId); - return extractApprovalRunAttachments(record); + return extractCitedRules(record); + } + }, + { + name: "seal_approval_run_document_summary_get", + description: "返回单据关键字段、附件摘要、AI/人工结果,避免拉取完整原始单据", + parameters: z.object({ + recordId: z.string().describe("Seal approval run record ID") + }), + handler: async ( + client: KyInstance, + params: { recordId: string } + ) => { + const record = await api.getApprovalRun(client, params.recordId); + return summarizeApprovalRunDocument(record); + } + }, + { + name: "seal_approval_run_attachments_get", + description: "从审批运行记录中抽取附件、发票附件和字段位置,不返回完整单据正文和规则结果", + parameters: z.object({ + recordId: z.string().describe("Seal approval run record ID"), + summary: z.boolean().optional().describe("只返回附件列表摘要") + }), + handler: async ( + client: KyInstance, + params: { recordId: string; summary?: boolean } + ) => { + const record = await api.getApprovalRun(client, params.recordId); + return extractApprovalRunAttachments(record, { summary: params.summary }); } }, { @@ -552,48 +622,55 @@ export const sealTools = [ name: "seal_approval_run_pick", description: "按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则", parameters: z.object({ - query: z.string().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"), + query: z.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"), + sn: z.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"), + batchId: z.string().optional().describe("模拟批次 ID"), + latest: z.boolean().optional().describe("只返回最新一条匹配记录"), + fields: z.union([z.string(), z.array(z.string())]).optional().describe("限制返回字段"), limit: z.number().int().positive().max(100).optional(), maxScan: z.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"), includeBridge: z.boolean().optional() }), handler: async ( client: KyInstance, - params: { query: string; limit?: number; maxScan?: number; includeBridge?: boolean } + params: { + query?: string; + sn?: string; + batchId?: string; + latest?: boolean; + fields?: string | string[]; + limit?: number; + maxScan?: number; + includeBridge?: boolean; + } ) => { + const query = params.sn ?? params.query; + if (!query) throw new Error("query or sn is required"); const picked = await pickApprovalRuns(client, { - query: params.query, - limit: params.limit ?? 20, + query, + sn: params.sn, + batchId: params.batchId, + latest: params.latest, + limit: params.latest ? 1 : params.limit ?? 20, maxScan: params.maxScan ?? 1000 }); const records = await Promise.all( picked.records.map((record) => api.getApprovalRun(client, record.id)) ); + const fields = parseFieldPaths(params.fields); + const projected = records.map((record) => pickApprovalRunCandidate(record, fields)); return { - query: params.query, + query, + sourceDocumentSN: params.sn, + simulationBatchId: params.batchId, + latest: params.latest ?? false, total: picked.total, scanned: picked.scanned, - matched: records.length, - records: records.map((record) => { - const summary = summarizeApprovalRun(record); - return { - recordId: summary.id, - sourceDocumentSN: summary.sourceDocumentSN, - sourceDocumentId: summary.sourceDocumentId, - status: summary.status, - taskMode: summary.taskMode, - finalExecutionMode: summary.finalExecutionMode, - createdAt: summary.createdAt, - ruleSetVersionNumber: summary.ruleSetVersionNumber, - ruleSetPublishedAt: summary.ruleSetPublishedAt, - ruleSetPublishedByName: summary.ruleSetPublishedByName, - langfuseTraceId: summary.langfuseTraceId, - langfuseSessionFallback: summary.langfuseSessionFallback - }; - }), + matched: projected.length, + records: projected, next: { - getDetail: "seal-home approval-runs get ", + getSummary: "seal-home approval-runs get --summary", getRuleVersion: "seal-home rules version ", searchRuleVersion: "seal-home tool seal_approval_search --json '{\"keywords\":[\"关键词\"],\"areas\":[\"rules\"],\"ruleVersionScope\":\"version\",\"ruleVersionNumber\":14}'", getVersionContext: "seal-home tool seal_approval_context_get --json '{\"ruleVersionNumber\":14}'" @@ -692,6 +769,7 @@ const sealActionNames = [ "seal_approval_rule_delete", "seal_approval_rule_versions_list", "seal_approval_rule_version_get", + "seal_approval_rule_get", "seal_approval_rule_version_publish", "seal_approval_documents_list", "seal_approval_document_get", @@ -701,6 +779,10 @@ const sealActionNames = [ "seal_approval_style_preferences_update", "seal_approval_runs_summary", "seal_approval_run_get", + "seal_approval_run_cited_rules_get", + "seal_approval_run_document_summary_get", + "seal_approval_run_attachments_get", + "seal_approval_run_result_get", "seal_approval_run_url_get", "seal_approval_run_pick", "seal_simulation_batch_records_get", @@ -715,6 +797,7 @@ const sealActionAliases: Record = { "rule.delete": "seal_approval_rule_delete", "rule.versions.list": "seal_approval_rule_versions_list", "rule.version.get": "seal_approval_rule_version_get", + "rule.get": "seal_approval_rule_get", "rule.publish": "seal_approval_rule_version_publish", "doc.list": "seal_approval_documents_list", "doc.get": "seal_approval_document_get", @@ -724,6 +807,10 @@ const sealActionAliases: Record = { "style.update": "seal_approval_style_preferences_update", "runs.summary": "seal_approval_runs_summary", "runs.get": "seal_approval_run_get", + "runs.citedRules": "seal_approval_run_cited_rules_get", + "runs.documentSummary": "seal_approval_run_document_summary_get", + "runs.attachments": "seal_approval_run_attachments_get", + "runs.result": "seal_approval_run_result_get", "runs.url": "seal_approval_run_url_get", "runs.pick": "seal_approval_run_pick", "batch.records.get": "seal_simulation_batch_records_get", @@ -835,6 +922,8 @@ type ApprovalRunSummary = { ruleSetPublishedByName?: string; humanResult?: string; humanResultPath?: string; + aiDecision?: unknown; + aiSummary?: unknown; createdAt?: string | number; updatedAt?: string | number; }; @@ -886,6 +975,7 @@ function pickRuleFields(rule: ApprovalRule, fields: readonly RuleField[]) { function summarizeApprovalRun(record: ApprovalRun): ApprovalRunSummary { const sourceDocumentSN = record.sourceDocumentSN; const humanResult = extractHumanResult(record); + const ai = summarizeApprovalRunResult(record); return { id: record.id, @@ -906,6 +996,8 @@ function summarizeApprovalRun(record: ApprovalRun): ApprovalRunSummary { ruleSetPublishedByName: record.ruleSetPublishedByName, humanResult: humanResult?.value, humanResultPath: humanResult?.path, + aiDecision: ai.decision, + aiSummary: ai.summary, createdAt: record.createdAt, updatedAt: record.updatedAt }; @@ -986,6 +1078,19 @@ function approvalRunMetadata(record: ApprovalRun) { }; } +function summarizeApprovalRunDetail(record: ApprovalRun) { + return { + metadata: approvalRunMetadata(record), + document: summarizeApprovalRunDocument(record).document, + aiResult: summarizeApprovalRunResult(record), + manualResult: extractHumanResult(record)?.value, + manualResultPath: extractHumanResult(record)?.path, + ruleSetVersionNumber: record.ruleSetVersionNumber, + ruleSetPublishedAt: record.ruleSetPublishedAt, + ruleSetPublishedByName: record.ruleSetPublishedByName + }; +} + function summarizeApprovalRunResult(record: ApprovalRun) { const result = asRecord(record.result); return { @@ -1023,7 +1128,37 @@ function summarizeApprovalRunResult(record: ApprovalRun) { }; } -function extractApprovalRunAttachments(record: ApprovalRun) { +function summarizeApprovalRunDocument(record: ApprovalRun) { + const document = asRecord(record.document); + const fields = flattenDocumentFields(record.document); + const fieldText = fields.map((field) => `${field.label ?? field.path ?? ""}:${field.value ?? ""}`).join("\n"); + return { + recordId: record.id, + sourceDocumentSN: record.sourceDocumentSN, + sourceDocumentId: record.sourceDocumentId, + document: compactObject({ + id: document?.id, + sn: document?.sn ?? document?.sourceDocumentSN ?? record.sourceDocumentSN, + title: document?.title ?? document?.name, + template: firstPath(document, ["template.name", "templateName", "form.name", "formName", "formTitle"]), + amount: firstByLabel(fields, ["金额", "报销金额", "付款金额", "合计", "价税合计"]) ?? firstPath(document, ["amount", "totalAmount", "expenseAmount"]), + expenseType: firstByLabel(fields, ["费用类型", "费用类别", "报销类型"]), + costCompany: firstByLabel(fields, ["费用承担公司", "承担公司", "成本中心", "费用归属"]), + payee: firstByLabel(fields, ["收款方", "收款账户", "收款信息", "开户名", "银行账号"]), + keyFields: fields.slice(0, 30) + }), + invoices: collectInvoiceSummary(record), + attachments: extractApprovalRunAttachments(record, { summary: true }).attachments, + aiResult: summarizeApprovalRunResult(record), + manualResult: extractHumanResult(record)?.value, + hints: compactObject({ + amountMentions: findKeywordLines(fieldText, ["金额", "合计", "税率"], 8), + partyMentions: findKeywordLines(fieldText, ["买方", "卖方", "甲方", "乙方", "收款"], 8) + }) + }; +} + +function extractApprovalRunAttachments(record: ApprovalRun, options: { summary?: boolean } = {}) { const roots: Array<[string, unknown]> = [ ["document", record.document], ["result", record.result], @@ -1042,7 +1177,68 @@ function extractApprovalRunAttachments(record: ApprovalRun) { sourceDocumentSN: record.sourceDocumentSN, sourceDocumentId: record.sourceDocumentId, count: attachments.length, - attachments + attachments: options.summary + ? attachments.map((attachment) => compactObject({ + path: attachment.path, + kind: attachment.kind, + fileName: attachment.fileName, + mimeType: attachment.mimeType, + fileId: attachment.fileId, + sourceField: attachment.sourceField + })) + : attachments + }; +} + +function extractCitedRules(record: ApprovalRun) { + const candidates: Array<[string, unknown]> = [ + ["result.citedRules", getPath(record, "result.citedRules")], + ["result.matchedRules", getPath(record, "result.matchedRules")], + ["result.ruleResults", getPath(record, "result.ruleResults")], + ["result.rules", getPath(record, "result.rules")], + ["pipelineData.citedRules", getPath(record, "pipelineData.citedRules")], + ["pipelineData.matchedRules", getPath(record, "pipelineData.matchedRules")] + ]; + const rules: Array> = []; + const seen = new Set(); + + for (const [path, value] of candidates) { + const items = Array.isArray(value) + ? value + : value && typeof value === "object" + ? Object.values(value as Record) + : []; + items.forEach((item, index) => { + const object = asRecord(item); + if (!object) return; + const runtimeRuleId = stringFromUnknown(object.runtimeRuleId) ?? stringFromUnknown(object.runtimeId) ?? stringFromUnknown(object.id) ?? stringFromUnknown(object.ruleId); + const ruleCode = stringFromUnknown(object.ruleCode) ?? stringFromUnknown(object.code) ?? (runtimeRuleId ? runtimeRuleIdToCode(runtimeRuleId) : undefined); + const output = compactObject({ + runtimeRuleId, + ruleCode, + versionNumber: numberFromUnknown(object.versionNumber) ?? record.ruleSetVersionNumber, + scope: stringFromUnknown(object.scope), + strictness: stringFromUnknown(object.strictness), + appliedAnalysis: object.appliedAnalysis ?? object.analysis ?? object.reasoning, + checkResult: object.checkResult ?? object.result ?? object.decision, + findings: object.findings ?? object.riskPoints ?? object.evidence, + sourcePath: `${path}.${index}` + }); + const key = JSON.stringify(output); + if (!seen.has(key)) { + seen.add(key); + rules.push(output); + } + }); + } + + return { + recordId: record.id, + sourceDocumentSN: record.sourceDocumentSN, + sourceDocumentId: record.sourceDocumentId, + ruleSetVersionNumber: record.ruleSetVersionNumber, + count: rules.length, + rules }; } @@ -1156,6 +1352,87 @@ function asRecord(value: unknown): Record | undefined { : undefined; } +function numberFromUnknown(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} + +function flattenDocumentFields(value: unknown) { + const fields: Array> = []; + collectDocumentFields(value, "document", fields); + return fields; +} + +function collectDocumentFields(value: unknown, path: string, output: Array>) { + if (Array.isArray(value)) { + value.forEach((item, index) => collectDocumentFields(item, `${path}.${index}`, output)); + return; + } + + const object = asRecord(value); + if (!object) return; + + const label = stringFromUnknown(object.label) ?? stringFromUnknown(object.name) ?? stringFromUnknown(object.title) ?? stringFromUnknown(object.fieldName); + const rawValue = object.value ?? object.displayValue ?? object.text ?? object.content; + if (label && rawValue !== undefined && typeof rawValue !== "object") { + output.push(compactObject({ + path, + label, + value: rawValue, + type: stringFromUnknown(object.type) ?? stringFromUnknown(object.fieldType) + })); + } + + for (const [key, child] of Object.entries(object)) { + if (key === "attachments") continue; + collectDocumentFields(child, `${path}.${key}`, output); + } +} + +function firstByLabel(fields: Array>, labels: string[]) { + const hit = fields.find((field) => { + const label = stringFromUnknown(field.label) ?? ""; + return labels.some((item) => label.includes(item)); + }); + return hit?.value; +} + +function collectInvoiceSummary(record: ApprovalRun) { + const invoices: Array> = []; + collectInvoiceObjects(record.result, "result", invoices); + collectInvoiceObjects(record.document, "document", invoices); + return invoices.slice(0, 20); +} + +function collectInvoiceObjects(value: unknown, path: string, output: Array>) { + if (Array.isArray(value)) { + value.forEach((item, index) => collectInvoiceObjects(item, `${path}.${index}`, output)); + return; + } + const object = asRecord(value); + if (!object) return; + if (/invoice|发票/i.test(path)) { + output.push(compactObject({ + path, + fileName: stringFromUnknown(object.fileName) ?? stringFromUnknown(object.filename) ?? stringFromUnknown(object.name), + buyer: object.buyer ?? object.buyerName ?? object.purchaserName, + seller: object.seller ?? object.sellerName, + amount: object.amount ?? object.totalAmount ?? object.total, + taxRate: object.taxRate, + category: object.category ?? object.type + })); + } + for (const [key, child] of Object.entries(object)) { + collectInvoiceObjects(child, `${path}.${key}`, output); + } +} + +function findKeywordLines(text: string, keywords: string[], limit: number) { + return text + .split(/\r?\n/) + .filter((line) => keywords.some((keyword) => line.includes(keyword))) + .slice(0, limit); +} + function summarizeRunBridge(records: ApprovalRun[]) { return records.map((record) => { const summary = summarizeApprovalRun(record); @@ -1195,6 +1472,97 @@ function summarizeRuleVersion(version: RuleSetVersion) { }; } +async function resolveRuleVersionForLookup( + client: KyInstance, + params: { versionId?: string; versionNumber?: number; latest?: boolean; recordId?: string } +) { + if (params.recordId && !params.versionId && !params.versionNumber && !params.latest) { + const record = await api.getApprovalRun(client, params.recordId); + if (!record.ruleSetVersionNumber) { + throw new Error(`Approval run ${params.recordId} has no ruleSetVersionNumber`); + } + return resolveRuleVersion(client, { versionNumber: record.ruleSetVersionNumber }); + } + return resolveRuleVersion(client, params); +} + +function findRuleInVersion( + version: RuleSetVersion, + selector: { code?: string; runtimeId?: string } +) { + const normalizedCode = normalizeRuleCode(selector.code); + const runtimeIndex = runtimeRuleIndex(selector.runtimeId); + const index = normalizedCode ? Number(normalizedCode.slice(1)) : runtimeIndex; + + if (!index || index < 1) { + throw new Error("Pass --code '#0038' or --runtime-id rule-205"); + } + + const rule = version.rules.find((item, itemIndex) => { + const object = item as Record; + const itemCode = normalizeRuleCode(stringFromUnknown(object.code) ?? stringFromUnknown(object.ruleCode)); + return itemCode === normalizedCode || itemIndex + 1 === index; + }); + if (!rule) return undefined; + + const object = rule as Record; + const position = version.rules.indexOf(rule) + 1; + return compactObject({ + runtimeRuleId: stringFromUnknown(object.runtimeRuleId) ?? `rule-${position}`, + ruleCode: normalizeRuleCode(stringFromUnknown(object.code) ?? stringFromUnknown(object.ruleCode)) ?? formatRuleCode(position), + versionId: version.id, + versionNumber: version.versionNumber, + versionName: version.versionName, + publishedAt: version.publishedAt, + publishedByName: version.publishedByName, + description: rule.description, + scope: rule.scope, + strictness: rule.strictness, + status: stringFromUnknown(object.status) + }); +} + +function normalizeRuleCode(value?: string) { + if (!value) return undefined; + const digits = value.match(/\d+/)?.[0]; + return digits ? formatRuleCode(Number(digits)) : value; +} + +function runtimeRuleIndex(value?: string) { + if (!value) return undefined; + const match = value.match(/(\d+)$/); + return match ? Number(match[1]) : undefined; +} + +function runtimeRuleIdToCode(value: string) { + const index = runtimeRuleIndex(value); + return index ? formatRuleCode(index) : undefined; +} + +function formatRuleCode(value: number) { + return `#${String(value).padStart(4, "0")}`; +} + +function pickApprovalRunCandidate(record: ApprovalRun, fields: string[]) { + const summary = summarizeApprovalRun(record); + const candidate = { + recordId: summary.id, + sourceDocumentSN: summary.sourceDocumentSN, + sourceDocumentId: summary.sourceDocumentId, + simulationBatchId: summary.simulationBatchId, + status: summary.status, + taskMode: summary.taskMode, + ruleSetVersionNumber: summary.ruleSetVersionNumber, + langfuseTraceId: summary.langfuseTraceId, + manualResult: summary.humanResult, + aiDecision: summary.aiDecision, + aiSummary: summary.aiSummary, + createdAt: summary.createdAt + }; + if (fields.length === 0) return candidate; + return pickRunFields(candidate, fields); +} + async function resolveApprovalRunForUrl( client: KyInstance, params: { recordId?: string; sourceDocumentSN?: string; sourceDocumentId?: string } @@ -1230,7 +1598,7 @@ function stringFromUnknown(value: unknown): string | undefined { async function pickApprovalRuns( client: KyInstance, - params: { query: string; limit: number; maxScan: number } + params: { query: string; sn?: string; batchId?: string; latest?: boolean; limit: number; maxScan: number } ) { const pageSize = Math.min(100, Math.max(params.limit, 20)); const records: ApprovalRun[] = []; @@ -1240,24 +1608,40 @@ async function pickApprovalRuns( while (scanned < params.maxScan && records.length < params.limit) { const data = await api.listApprovalRuns(client, { offset: scanned, - limit: Math.min(pageSize, params.maxScan - scanned) + limit: Math.min(pageSize, params.maxScan - scanned), + search: params.sn ?? params.query, + sourceDocumentSN: params.sn }); total = data.total; scanned += data.records.length; - records.push(...filterRuns(data.records, params.query)); + const filtered = filterRuns(data.records, params.query) + .filter((record) => !params.sn || record.sourceDocumentSN === params.sn) + .filter((record) => !params.batchId || record.sourceExtendData?.simulation_batch_id === params.batchId); + records.push(...filtered); if (data.records.length === 0 || (total !== undefined && scanned >= total)) break; } + records.sort((left, right) => timestampOf(right.createdAt) - timestampOf(left.createdAt)); + return { total, scanned, - records: records.slice(0, params.limit) + records: records.slice(0, params.latest ? 1 : params.limit) }; } +function timestampOf(value: unknown): number { + if (typeof value === "number") return value; + if (typeof value === "string") { + const parsed = Date.parse(value); + return Number.isFinite(parsed) ? parsed : 0; + } + return 0; +} + async function resolveRuleVersion( client: KyInstance, params: { versionId?: string; versionNumber?: number; latestRuleVersion?: boolean; latest?: boolean }