From 8c9f10293107d14a56a650d798d15472e63c512b Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 2 Nov 2026 15:22:47 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=8E=9F=E7=94=9F=20Seal=20=E6=8E=88?= =?UTF-8?q?=E6=9D=83=E7=BB=AD=E6=9C=9F=E8=87=AA=E6=84=88=E4=B8=8E=E6=9C=AC?= =?UTF-8?q?=E5=9C=B0=20SQLite=20=E5=88=86=E6=AD=A7=E5=BE=85=E5=8A=9E?= =?UTF-8?q?=E9=97=AD=E7=8E=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 授权自愈: 引入长效会话 Cookie 备份池,支持 Seal 原生协助授权到期与 401 报错时平滑自动换发与静默续期; - 存储升级: 审核报告人工裁决底座迁移至 SQLite (~/.config/seal-use/state/reviews.sqlite),支持历史 JSONL 自动平滑导入与向后兼容双写; - 分歧待办: 新增 report review unreviewed 与 dismiss 命令,收集人机不一致单据并在日常企业命令完成后于 stderr 注入 Agent 动作指引; - 精密频控: 实现 30 天单据时效窗口过滤(陈年单据自动归档)、动态 5 小时滑动窗口频控与 24 小时人工拒审静音抑制协议; - 透明认知: 全面补充 Skill 路由与帮助手册,消除黑盒,透传数据边界与安全红线。 --- skills/seal-use/SKILL.md | 2 +- skills/seal-use/references/cli.md | 2 + .../seal-use/references/report-templates.md | 43 ++ src/cli/commands/report-review-cli.test.ts | 186 +++++++ src/cli/commands/report.ts | 62 ++- src/cli/help.ts | 24 +- src/cli/parser.ts | 4 +- src/cli/runner.ts | 19 + src/core/auth/delegate.ts | 44 ++ src/core/auth/seal-renew.test.ts | 318 +++++++++++ src/core/auth/seal.ts | 108 +++- src/core/auth/session-fallback.test.ts | 95 ++++ src/core/auth/session-fallback.ts | 58 ++ src/core/auth/token-store.test.ts | 17 + src/core/auth/token-store.ts | 16 + src/core/auth/types.ts | 10 +- src/domains/enterprise/onboarding.ts | 1 + src/domains/seal/enterprise/onboarding.ts | 13 + src/domains/seal/reports/pipeline/collect.ts | 22 +- .../pipeline/review-divergence.test.ts | 173 ++++++ .../seal/reports/pipeline/review-store.ts | 501 ++++++++++++++++-- 21 files changed, 1668 insertions(+), 50 deletions(-) create mode 100644 src/cli/commands/report-review-cli.test.ts create mode 100644 src/core/auth/seal-renew.test.ts create mode 100644 src/core/auth/session-fallback.test.ts create mode 100644 src/core/auth/session-fallback.ts create mode 100644 src/domains/seal/reports/pipeline/review-divergence.test.ts diff --git a/skills/seal-use/SKILL.md b/skills/seal-use/SKILL.md index da6c231..3321264 100644 --- a/skills/seal-use/SKILL.md +++ b/skills/seal-use/SKILL.md @@ -162,6 +162,6 @@ seal-use langfuse observation # 最后才取焦点 | Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` | | 附件、发票、收据、OCR 或界面高亮结论争议 | `references/approval-attachment-trace.md` | 先完成追踪和归因后,才读 `approval-bad-cases.md` 做案例对照 | | 已完成当前追踪后的相似坏案例对照 | `references/approval-bad-cases.md` | 不能作为首次诊断入口 | -| AI 审核报告、验收报告、上线报告、周期准确率报告、accuracy report、台账自由裁量 | `references/report-templates.md` | 只查 CLI 语法时读 `cli.md`;涉及完整报告编制、Excel 台账自由裁量、人机研讨与门禁校验时读取 | +| AI 审核报告、验收报告、上线报告、周期准确率报告、accuracy report、台账自由裁量、人机分歧日常复核与静音协议 | `references/report-templates.md` | 只查 CLI 语法时读 `cli.md`;涉及完整报告编制、Excel 台账自由裁量、人机研讨与门禁校验时读取 | 冲突时遵循三条优先级:材料获取先于来源判断;来源判断先于 Hose 具体探测;审批事实追踪先于坏案例类比。跨阶段请求也要按阶段顺序读取,不能用后置 reference 替代前置 reference。 diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index 9a30795..14ff51d 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -129,6 +129,8 @@ seal-use report validate <报告.md> seal-use report render <报告.md> --out [--format ] seal-use report export <报告.md> --out <输出目录> [--format ] seal-use report review set [--record-id ] [--sn ] --verdict [--note ] [--reviewed-by ] [--corp ] +seal-use report review unreviewed [--limit ] [--days ] [--all] [--corp ] +seal-use report review dismiss [--hours ] [--corp ] seal-use report review list [--corp ] seal-use report review import <台账.xlsx|csv> --corp seal-use simulation batch-records [--corp ] diff --git a/skills/seal-use/references/report-templates.md b/skills/seal-use/references/report-templates.md index dc6755b..ff4aa53 100644 --- a/skills/seal-use/references/report-templates.md +++ b/skills/seal-use/references/report-templates.md @@ -238,6 +238,49 @@ seal-use report render <输出目录>/审核报告.md --out <输出目录>/审 seal-use report review import <输出目录>/明细台账.xlsx --corp ``` +### 模式 C:日常增量少量多次复核(Daily Incremental Triage & Silence Protocol) + +**核心契约**:终端用户不敲命令,所有 CLI 指令均由 AI Agent 调度执行。Agent 负责向人类温和征求意见,并严格尊重人类的拒绝意愿,绝不重复打扰。拒绝将机制当作黑盒,Agent 必须透彻理解其背后的数据边界与频控协议。 + +#### 1. 架构透底:数据资产与时效边界(Agent 上下文认知) +- **本地单机存储**:所有分歧单据与人工复核裁决,均物理持久化在用户本机的 SQLite 数据库(`~/.config/seal-use/state/reviews.sqlite`),**绝不向云端、合思 OpenAPI 或 Seal 平台上传**。 +- **时效窗口(近 30 天活跃期)**:CLI 默认只关注最近 30 天内发生的单据(`maxAgeDays = 30`)。超过 30 天的历史单据自动归入离线沉淀归档,日常命令中完全静默,绝不拿半年前的陈年旧账打扰用户(若审计需要,可显式加 `--all` 或 `--days ` 检索)。 +- **动态频控(5 小时滑动窗口)**:同一个企业距上次提示若不足 5 小时,CLI 绝对静默;满 5 小时后若检测到近期有未整理的分歧,才会在日常企业命令完成后的 `stderr` 信道轻提示一次。 + +#### 2. 触发信号(stderr 诊断流) +CLI 在执行任意企业相关命令时,若触发条件满足,会在 `stderr` 输出透明指引: +```text +ℹ️ [review-reminder] 检测到企业「华铁大黄蜂」在近 30 天内有 3 笔本地未整理的审核分歧单据(数据仅保存在本机 SQLite,不上传云端)。 +👉 Agent 动作指引: 动态频控 5 小时内最多提醒一次。请在完成当前主任务后顺便询问用户是否抽空确认;若用户表示暂不处理,请立即执行: seal-use report review dismiss --corp 静音 24 小时,切勿重复打扰。查看待整理详情: seal-use report review unreviewed --corp +``` + +#### 3. Agent 呈报人类的对话规范(轻量顺带,零侵入) +必须在**彻底完成用户当前的主要任务后**,在回复末尾顺便以极简、自然、有安全感的语言征求意见: +> *“本次任务已完成。另外顺便提一句,检测到「华铁大黄蜂」近 30 天有 3 笔单据人工审批和 AI 判定不一致(数据仅保存在你本机电脑),有空的话要顺手确认一下吗?还是改天再说?”* + +#### 4. 人类拒绝时的静音规范(24 小时绝对抑制,尊重用户意愿) +若用户表态 *“今天不想审 / 改天吧 / 稍后 / 别提醒我 / 太忙了”*: +- ❌ **Agent 严禁反复复读打扰用户**; +- **Agent 必须立即静默执行静音命令**: + ```bash + seal-use report review dismiss --corp --hours 24 + ``` +- 系统将该企业静音 24 小时,在此期间无论 5 小时滑动窗口如何,后续命令都绝对闭嘴,Agent 也绝不再主动提起。 + +#### 5. 人类同意时的极速裁决流程(化整为零) +若用户表示 *“看看是哪几笔”* 或 *“现在弄一下”*: +- Agent 后台拉取未审清单: + ```bash + seal-use report review unreviewed --corp --limit 5 + ``` +- Agent 将单据关键信息(单号、金额、事由、AI决策理由 vs 人工放行/驳回批注)呈报给用户; +- 用户口头/打字表态(例如:“第1笔AI对,第2笔人工对”); +- Agent 自动调用打标命令回写本地 SQLite 并核销待办: + ```bash + seal-use report review set --corp --sn --verdict ai_correct --note "用户确认发票抬头违规" + ``` +- 少量多次,10 秒钟整理完毕,月末出具商业汇报时所有分歧早已提前就绪! + --- ## 六、标准 6 大章节深度剖析 diff --git a/src/cli/commands/report-review-cli.test.ts b/src/cli/commands/report-review-cli.test.ts new file mode 100644 index 0000000..35ebb99 --- /dev/null +++ b/src/cli/commands/report-review-cli.test.ts @@ -0,0 +1,186 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { runCli } from "../runner.js"; +import { saveCorpConfig } from "../../core/config/repository.js"; +import { + closeReviewsDb, + recordDivergences +} from "../../domains/seal/reports/pipeline/review-store.js"; +import type { CorpConfig } from "../../core/config/types.js"; + +let tempDir: string; +let originalFetch: typeof globalThis.fetch; +const testCorp: CorpConfig = { + id: "corp-triage-test", + name: "测试分歧企业", + environment: "production", + seal: { + url: "https://triage.sealai.cc", + tenantSlug: "triage", + endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } + }, + source: { + type: "seal", + token: "dummy-token", + sealUrl: "https://triage.sealai.cc", + expiresIn: 3600, + staffId: "u-triage", + corpId: "corp-triage-test", + tenantId: "t-triage", + tenantSlug: "triage", + provider: "seal" + }, + auth: { refreshTtl: 300 } +}; + +describe("report review CLI: 面向 Agent 的分歧待办查询与静音抑制", () => { + beforeEach(() => { + tempDir = mkdtempSync(join(tmpdir(), "seal-report-review-cli-test-")); + process.env.SEAL_USE_ENTERPRISES_DIR = join(tempDir, "enterprises"); + process.env.SEAL_USE_REVIEWS_STORE = join(tempDir, "reviews.sqlite"); + process.env.SEAL_USE_REVIEWS_DIR = join(tempDir, "reviews"); + saveCorpConfig(testCorp, { overwrite: true }); + + originalFetch = globalThis.fetch; + globalThis.fetch = (async () => { + return new Response(JSON.stringify({ rules: [], hasPendingDeletes: false }), { + status: 200, + headers: { "content-type": "application/json" } + }); + }) as unknown as typeof globalThis.fetch; + }); + + afterEach(() => { + globalThis.fetch = originalFetch; + closeReviewsDb(); + delete process.env.SEAL_USE_ENTERPRISES_DIR; + delete process.env.SEAL_USE_REVIEWS_STORE; + delete process.env.SEAL_USE_REVIEWS_DIR; + rmSync(tempDir, { recursive: true, force: true }); + }); + + test("report review unreviewed 列出待整理分歧单据并附带 Agent 指引", async () => { + recordDivergences(testCorp.id, [ + { + corpId: testCorp.id, + recordId: "run-div-1", + sn: "SN-DIV-001", + docTitle: "差旅申请单", + amount: "¥800", + aiDecision: "驳回", + manualDecision: "通过", + divergenceType: "AI驳回_人工通过", + discoveredAt: Date.now() + } + ]); + + const result = await runCli([ + "report", + "review", + "unreviewed", + "--corp", + testCorp.id + ]); + + expect(result.exitCode).toBe(0); + const parsed = JSON.parse(result.stdout); + expect(parsed.corpId).toBe(testCorp.id); + expect(parsed.count).toBe(1); + expect(parsed.divergences[0].sn).toBe("SN-DIV-001"); + expect(parsed.guidance).toContain("Agent 上下文说明"); + expect(parsed.guidance).toContain("5 小时滑动窗口"); + }); + + test("report review dismiss 成功静音并在期限内抑制提示", async () => { + recordDivergences(testCorp.id, [ + { + corpId: testCorp.id, + recordId: "run-div-1", + sn: "SN-DIV-001", + discoveredAt: Date.now() + } + ]); + + // 用户表示今天不想看,Agent 调度 dismiss 24小时 + const dismissRes = await runCli([ + "report", + "review", + "dismiss", + "--hours", + "24", + "--corp", + testCorp.id + ]); + + expect(dismissRes.exitCode).toBe(0); + const parsedDismiss = JSON.parse(dismissRes.stdout); + expect(parsedDismiss.dismissed).toBe(true); + expect(parsedDismiss.message).toContain("已为企业「测试分歧企业」静音分歧提醒 24 小时"); + }); + + test("stderr 注入:在日常命令完成时提示 Agent,dismiss 后不再提示", async () => { + recordDivergences(testCorp.id, [ + { + corpId: testCorp.id, + recordId: "run-div-1", + sn: "SN-DIV-001", + discoveredAt: Date.now() + } + ]); + + // 运行一个常规的企业级数据命令(例如 rules count) + const resBefore = await runCli([ + "rules", + "count", + "--corp", + testCorp.id + ]); + + // stderr 应注入面向 Agent 的提醒 + expect(resBefore.stderr).toContain("ℹ️ [review-reminder]"); + expect(resBefore.stderr).toContain("Agent 动作指引"); + + // Agent 调用 dismiss 静音 + await runCli([ + "report", + "review", + "dismiss", + "--corp", + testCorp.id + ]); + + // 再次运行命令,stderr 不再打扰 + const resAfter = await runCli([ + "rules", + "count", + "--corp", + testCorp.id + ]); + + expect(resAfter.stderr).not.toContain("ℹ️ [review-reminder]"); + }); + + test("超过 30 天的历史旧单不触发日常命令 stderr 提醒", async () => { + const oldTime = Date.now() - 60 * 24 * 3600 * 1000; + recordDivergences(testCorp.id, [ + { + corpId: testCorp.id, + recordId: "run-old-1", + sn: "SN-OLD-001", + createdAt: oldTime, + discoveredAt: oldTime + } + ]); + + const res = await runCli([ + "rules", + "count", + "--corp", + testCorp.id + ]); + + expect(res.stderr).not.toContain("ℹ️ [review-reminder]"); + }); +}); diff --git a/src/cli/commands/report.ts b/src/cli/commands/report.ts index 5abfec0..e9faa6b 100644 --- a/src/cli/commands/report.ts +++ b/src/cli/commands/report.ts @@ -16,6 +16,9 @@ import { loadReviews, reviewFilePath, writeReview, + countUnreviewedDivergences, + listUnreviewedDivergences, + dismissDivergencePrompt, type MonthlyReportResult, buildReportLedgerCsv, buildReportLedgerXlsx, @@ -29,13 +32,19 @@ import type { ParsedArgs } from "../types.js"; export async function handleLocalReportCommand(action: string | undefined, args: ParsedArgs) { if (Boolean(args.options.ledger) || action === "review") { const corpId = stringOption(args.options.corp) ?? stringOption(args.options.corpId) ?? "local-ledger"; - const corp = { - corpId, - id: corpId, - name: corpId, - corpName: corpId, - source: { source: "seal", sealUrl: "" } - } as unknown as CorpConfig; + let corp: CorpConfig; + try { + const { selectCorp } = await import("../helpers.js"); + corp = selectCorp(corpId); + } catch { + corp = { + corpId, + id: corpId, + name: corpId, + corpName: corpId, + source: { source: "seal", sealUrl: "" } + } as unknown as CorpConfig; + } await handleReportCommand(action, {} as any, corp, args); return; } @@ -282,6 +291,43 @@ export async function handleReportCommand( if (action === "review") { const sub = args.command[2]; // set | list | import + if (sub === "unreviewed" || sub === "pending" || sub === "triage") { + const limit = numberOption(args.options.limit) ?? 20; + const all = booleanOption(args.options.all); + const days = all ? 0 : (numberOption(args.options.days) ?? 30); + const items = listUnreviewedDivergences(corp.id, limit, days); + printJson({ + corpId: corp.id, + corpName: corp.name, + window: { + recencyDays: days > 0 ? days : "all", + promptThrottleHours: 5, + storage: "~/.config/seal-use/state/reviews.sqlite" + }, + count: items.length, + totalPending: countUnreviewedDivergences(corp.id, days), + divergences: items, + guidance: + "Agent 上下文说明:\n" + + "1. 数据来源:上述分歧来自本地 SQLite (~/.config/seal-use/state/reviews.sqlite),由报表或审批流发现 AI 与人工结论相反,仅保存在用户本机,不上传云端。\n" + + "2. 频控规则:CLI 默认只关注近 30 天内单据(排除陈年旧账),且每 5 小时滑动窗口最多提醒一次。\n" + + "3. 交互流程:请在完成主任务后以简短摘要向用户征询;用户确认后执行 'seal-use report review set --corp --sn --verdict ' 回写;用户表示暂不处理时,立即执行 'seal-use report review dismiss --corp --hours 24' 静音 24 小时,切勿重复打扰。" + }, outputOptions(args.options)); + return; + } + + if (sub === "dismiss") { + const hours = numberOption(args.options.hours) ?? 24; + const until = dismissDivergencePrompt(corp.id, hours); + printJson({ + corpId: corp.id, + dismissed: true, + dismissedUntil: new Date(until).toISOString(), + message: `已为企业「${corp.name}」静音分歧提醒 ${hours} 小时。在此期间不会重复向用户提示。` + }, outputOptions(args.options)); + return; + } + if (sub === "list") { const scope = stringOption(args.options.month) ?? stringOption(args.options.scope); const reviews = loadReviews(corp.id, scope); @@ -341,7 +387,7 @@ export async function handleReportCommand( return; } - throw usageError(`Unknown report review subcommand: ${sub ?? ""}. Use 'set', 'list', or 'import'.`); + throw usageError(`Unknown report review subcommand: ${sub ?? ""}. Use 'set', 'list', 'unreviewed', 'dismiss', or 'import'.`); } throw usageError(`Unknown report command: ${action ?? ""}. Run 'seal-use help report' for available commands.`); diff --git a/src/cli/help.ts b/src/cli/help.ts index a46e3cf..64aa4e8 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -766,7 +766,29 @@ export const HELP_REGISTRY: AreaHelp[] = [ { flag: "--note ", description: "Optional adjudication note" }, { flag: "--reviewed-by ", description: "Optional reviewer name for the audit trail" } ], - description: "Append-only local JSONL per tenant (~/.config/seal-use/state/reviews/). Supports exact recordId target or SN. Typically adjudicates diverged blocks or overrides specific agreed runs." + description: "Local SQLite store with companion JSONL (~/.config/seal-use/state/reviews.sqlite). Supports exact recordId target or SN. Typically adjudicates diverged blocks or overrides specific agreed runs." + }, + { + name: "review unreviewed", + summary: "List unreviewed human-AI divergence records for incremental triaging", + usage: ["seal-use report review unreviewed [--limit ] [--days ] [--all] [--corp ]"], + options: [ + { flag: "--limit ", description: "Max unreviewed items to return (default 20)" }, + { flag: "--days ", description: "Only return records created within recent days (default 30)" }, + { flag: "--all", description: "Include all historical unreviewed records regardless of age" }, + { flag: "--corp ", description: "Target enterprise corpId" } + ], + description: "Returns unadjudicated diverged records from local SQLite (~/.config/seal-use/state/reviews.sqlite). CLI throttles reminder notifications on a 5-hour sliding window and filters to recent 30 days to avoid ancient debt. Use this command to fetch items, present a natural-language summary to the user, and record verdicts with 'report review set'." + }, + { + name: "review dismiss", + summary: "Suppress divergence reminders for a tenant when the user declines reviewing", + usage: ["seal-use report review dismiss [--hours ] [--corp ]"], + options: [ + { flag: "--hours ", description: "Hours to suppress reminders (default 24)" }, + { flag: "--corp ", description: "Target enterprise corpId" } + ], + description: "Mutes CLI divergence prompts for the enterprise for N hours (default 24h) when the user declines reviewing. Agents must call this immediately when the user says 'not now' or 'later' to ensure zero repeated disruption." }, { name: "review list", diff --git a/src/cli/parser.ts b/src/cli/parser.ts index c60a864..3f1cb29 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -47,7 +47,7 @@ export const VALUE_FLAGS = new Set([ "access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity", "base-url", "batch", "batch-id", "batchId", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes", "channel", "chrome", "code", "comment", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile", - "content-format", "contentFormat", "contentType", "context-chars", "context-lines", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date", + "content-format", "contentFormat", "contentType", "context-chars", "context-lines", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date", "days", "dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc", "description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix", "docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type", @@ -55,7 +55,7 @@ export const VALUE_FLAGS = new Set([ "end", "end-date", "end-time", "endDate", "endTime", "env", "environment", "expire", "expires-in", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency", "flow-id", "flow-ids", "flow-status-list", "flowId", "flowIds", "flowStatusList", "format", "from", - "from-link", "host", "human", "human-accuracy", "humanAccuracy", "human-result", "humanResult", "id", "input", "integration", + "from-link", "host", "hours", "human", "human-accuracy", "humanAccuracy", "human-result", "humanResult", "id", "input", "integration", "json", "json-path", "key-id", "keyId", "keyword", "ledger", "level", "limit", "lines", "link", "linter", "manual-approval-status", "manual-status", "manualApprovalStatus", "manualStatus", "max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode", diff --git a/src/cli/runner.ts b/src/cli/runner.ts index 470d81a..dcbadea 100755 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -349,9 +349,27 @@ async function dispatch(argv: string[], runtime: CliRuntime) { const corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp)); + const maybePromptDivergences = async () => { + if (area === "report" && action === "review") return; + try { + const { countUnreviewedDivergences, shouldPromptDivergence } = await import( + "../domains/seal/reports/pipeline/review-store.js" + ); + const count = countUnreviewedDivergences(corp.id, 30); + if (count > 0 && shouldPromptDivergence(corp.id)) { + console.error( + `ℹ️ [review-reminder] 检测到企业「${corp.name}」在近 30 天内有 ${count} 笔本地未整理的审核分歧单据(数据仅保存在本机 SQLite,不上传云端)。\n👉 Agent 动作指引: 动态频控 5 小时内最多提醒一次。请在完成当前主任务后顺便询问用户是否抽空确认;若用户表示暂不处理,请立即执行: seal-use report review dismiss --corp ${corp.id} 静音 24 小时,切勿重复打扰。查看待整理详情: seal-use report review unreviewed --corp ${corp.id}` + ); + } + } catch { + // 容错降级,不阻断主流程 + } + }; + const corpCommand = CORP_COMMANDS[area]; if (corpCommand) { await corpCommand(args, corp); + await maybePromptDivergences(); return; } @@ -359,6 +377,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) { if (clientCommand) { const client = await (await import("../core/http/factory.js")).createSealClient(corp); await clientCommand(args, corp, client); + await maybePromptDivergences(); return; } diff --git a/src/core/auth/delegate.ts b/src/core/auth/delegate.ts index ce8a590..3721eb3 100644 --- a/src/core/auth/delegate.ts +++ b/src/core/auth/delegate.ts @@ -17,6 +17,7 @@ export interface SealDelegateSealSession { sealUrl: string; token: string; expiresIn: number; + sessionCookie?: string; user: Record; tenant: Record; } @@ -199,11 +200,54 @@ export async function exchangeSealDelegateLink( sealUrl, token: bearerToken, expiresIn, + sessionCookie: sessionCookie || undefined, user, tenant }; } +/** + * 调用 SealAI 服务端为当前租户创建新的协助授权链接(最长支持 168 小时 / 7 天) + */ +export async function createSealDelegationLink( + sealUrl: string, + options?: { + cookie?: string; + token?: string; + expiresInHours?: number; + note?: string; + customHeaders?: Record; + } +): Promise<{ link: string; token: string; expiresInHours: number }> { + const expiresInHours = options?.expiresInHours ?? 168; + const note = options?.note ?? "权限续期"; + const headers: Record = { + ...options?.customHeaders + }; + if (options?.cookie) { + headers.Cookie = options.cookie; + } + + const client = createSealClientForUrl(sealUrl, options?.token, headers); + const resp = await client + .post("api/v1/delegation/create", { + json: { expiresInHours, note } + }) + .json<{ + data?: { link?: string; token?: string }; + link?: string; + token?: string; + }>(); + + const link = resp.data?.link ?? resp.link; + const token = resp.data?.token ?? resp.token; + if (!link || !token) { + throw new Error("Seal create delegation did not return a valid link/token"); + } + + return { link, token, expiresInHours }; +} + /* ------------------------------------------------------------------ * * Link-type scoring (classification by score) * ------------------------------------------------------------------ */ diff --git a/src/core/auth/seal-renew.test.ts b/src/core/auth/seal-renew.test.ts new file mode 100644 index 0000000..c0e9bdd --- /dev/null +++ b/src/core/auth/seal-renew.test.ts @@ -0,0 +1,318 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { CorpConfig } from "../config/types.js"; +import { + clearSealToken, + getSealSessionForCorp, + recoverSealSessionForCorp, + renewNativeSealSession +} from "./seal.js"; +import { + getSealDelegateAuthCache, + getSealSession, + setSealDelegateAuthCache +} from "./token-store.js"; + +const originalFetch = globalThis.fetch; +let tempDir: string; +let storePath: string; + +const fixtureCorp: CorpConfig = { + id: "test-delegate-corp", + name: "测试委托租户", + environment: "production", + seal: { + url: "https://mytenant.sealai.cc", + tenantSlug: "mytenant", + endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } + }, + source: { + type: "seal", + token: "initial-static-token", + sealUrl: "https://mytenant.sealai.cc", + expiresIn: 3600, + expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(), + staffId: "u-123", + corpId: "test-delegate-corp", + tenantId: "t-456", + tenantSlug: "mytenant", + tenantName: "My Tenant", + provider: "seal" + }, + auth: { refreshTtl: 300 } +}; + +describe("seal-renew: 原生 Seal 协助授权长效续期与会话池救险", () => { + beforeEach(() => { + tempDir = mkdtempSync(join(tmpdir(), "seal-renew-test-")); + storePath = join(tempDir, "tokens.json"); + process.env.SEAL_USE_TOKEN_STORE = storePath; + clearSealToken(fixtureCorp.id); + }); + + afterEach(() => { + globalThis.fetch = originalFetch; + clearSealToken(fixtureCorp.id); + delete process.env.SEAL_USE_TOKEN_STORE; + rmSync(tempDir, { recursive: true, force: true }); + }); + + test("无可用 Cookie 时安全返回 undefined,平滑回退到静态 token", async () => { + const renewed = await renewNativeSealSession(fixtureCorp); + expect(renewed).toBeUndefined(); + + const session = await getSealSessionForCorp(fixtureCorp); + expect(session.token).toBe("initial-static-token"); + }); + + test("主 Cookie 有效时成功自动续期换发新 token,并轮转归档历史 Cookie", async () => { + setSealDelegateAuthCache(fixtureCorp.id, { + cookie: "__Secure-x-seal.session_token=old-cookie-token", + backupCookies: [] + }); + + let delegationCreateCalledWithCookie = ""; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL( + typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url + ); + const headers = input instanceof Request ? input.headers : new Headers(init?.headers); + + if (url.pathname === "/api/v1/delegation/create") { + delegationCreateCalledWithCookie = headers.get("cookie") || ""; + return new Response( + JSON.stringify({ + data: { + link: "https://mytenant.sealai.cc/delegate?token=minted-delegation-token", + token: "minted-delegation-token" + } + }), + { headers: { "Content-Type": "application/json" } } + ); + } + + if (url.pathname === "/api/v1/delegation/consume") { + return new Response( + JSON.stringify({ + data: { + userId: "u-123", + userName: "Alice", + tenantId: "t-456", + tenantName: "My Tenant", + delegationId: "del-new" + } + }), + { + headers: { + "Content-Type": "application/json", + "Set-Cookie": + "__Secure-x-seal.session_token=fresh-cookie-token.sig; Path=/; HttpOnly; Secure" + } + } + ); + } + + if (url.pathname === "/api/auth/get-session") { + return new Response( + JSON.stringify({ + user: { id: "u-123", name: "Alice" }, + session: { + token: "brand-new-bearer-token", + expiresAt: new Date(Date.now() + 168 * 3600 * 1000).toISOString() + } + }), + { headers: { "Content-Type": "application/json" } } + ); + } + + if (url.pathname === "/api/v1/auth/me") { + return new Response( + JSON.stringify({ + data: { + user: { id: "u-123", name: "Alice" }, + tenant: { id: "t-456", name: "My Tenant", tenantSlug: "mytenant" } + } + }), + { headers: { "Content-Type": "application/json" } } + ); + } + + return new Response("Not found", { status: 404 }); + }) as typeof fetch; + + const renewed = await renewNativeSealSession(fixtureCorp); + expect(renewed).toBeDefined(); + expect(renewed!.token).toBe("brand-new-bearer-token"); + expect(delegationCreateCalledWithCookie).toBe( + "__Secure-x-seal.session_token=old-cookie-token" + ); + + // 检查 tokens.json 中更新状态 + const delegateCache = getSealDelegateAuthCache(fixtureCorp.id); + expect(delegateCache.cookie).toBe("__Secure-x-seal.session_token=fresh-cookie-token.sig"); + expect(delegateCache.backupCookies).toEqual(["__Secure-x-seal.session_token=old-cookie-token"]); + + // 再次读取 session 命中新缓存 + const session = await getSealSessionForCorp(fixtureCorp); + expect(session.token).toBe("brand-new-bearer-token"); + }); + + test("主 Cookie 失效时,依次由 backupCookies 兜底救险成功(断电超期场景)", async () => { + // 模拟主 Cookie 已在服务端注销失效,但历史 backupCookies 中包含一份 30 天未过期的长效会话 + setSealDelegateAuthCache(fixtureCorp.id, { + cookie: "expired-cookie", + backupCookies: ["valid-backup-cookie"] + }); + + const attemptedCookies: string[] = []; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL( + typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url + ); + const headers = input instanceof Request ? input.headers : new Headers(init?.headers); + + if (url.pathname === "/api/v1/delegation/create") { + const cookie = headers.get("cookie") || ""; + attemptedCookies.push(cookie); + if (cookie === "expired-cookie") { + return new Response(JSON.stringify({ error: { message: "Session expired" } }), { + status: 401, + headers: { "Content-Type": "application/json" } + }); + } + return new Response( + JSON.stringify({ + data: { + link: "https://mytenant.sealai.cc/delegate?token=rescued-delegation-token", + token: "rescued-delegation-token" + } + }), + { headers: { "Content-Type": "application/json" } } + ); + } + + if (url.pathname === "/api/v1/delegation/consume") { + return new Response( + JSON.stringify({ + data: { + userId: "u-123", + userName: "Alice", + tenantId: "t-456", + tenantName: "My Tenant" + } + }), + { + headers: { + "Content-Type": "application/json", + "Set-Cookie": "__Secure-x-seal.session_token=rescued-cookie.sig; Path=/; HttpOnly" + } + } + ); + } + + if (url.pathname === "/api/auth/get-session") { + return new Response( + JSON.stringify({ + session: { + token: "rescued-bearer-token", + expiresAt: new Date(Date.now() + 168 * 3600 * 1000).toISOString() + } + }), + { headers: { "Content-Type": "application/json" } } + ); + } + + if (url.pathname === "/api/v1/auth/me") { + return new Response( + JSON.stringify({ + data: { + user: { id: "u-123", name: "Alice" }, + tenant: { id: "t-456", name: "My Tenant", tenantSlug: "mytenant" } + } + }), + { headers: { "Content-Type": "application/json" } } + ); + } + + return new Response("Not found", { status: 404 }); + }) as typeof fetch; + + const renewed = await renewNativeSealSession(fixtureCorp); + expect(renewed).toBeDefined(); + expect(renewed!.token).toBe("rescued-bearer-token"); + expect(attemptedCookies).toEqual(["expired-cookie", "valid-backup-cookie"]); + + const delegateCache = getSealDelegateAuthCache(fixtureCorp.id); + expect(delegateCache.cookie).toBe("__Secure-x-seal.session_token=rescued-cookie.sig"); + expect(delegateCache.backupCookies).toContain("valid-backup-cookie"); + }); + + test("recoverSealSessionForCorp 在收到 401 时自动触发自愈", async () => { + setSealDelegateAuthCache(fixtureCorp.id, { + cookie: "valid-cookie", + backupCookies: [] + }); + + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = new URL( + typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url + ); + if (url.pathname === "/api/v1/delegation/create") { + return new Response( + JSON.stringify({ + data: { + link: "https://mytenant.sealai.cc/delegate?token=recovered-delegation-token", + token: "recovered-delegation-token" + } + }), + { headers: { "Content-Type": "application/json" } } + ); + } + if (url.pathname === "/api/v1/delegation/consume") { + return new Response( + JSON.stringify({ + data: { userId: "u-123", userName: "Alice", tenantId: "t-456", tenantName: "My Tenant" } + }), + { + headers: { + "Content-Type": "application/json", + "Set-Cookie": "__Secure-x-seal.session_token=recovered-cookie.sig" + } + } + ); + } + if (url.pathname === "/api/auth/get-session") { + return new Response( + JSON.stringify({ + session: { + token: "recovered-bearer-token", + expiresAt: new Date(Date.now() + 168 * 3600 * 1000).toISOString() + } + }), + { headers: { "Content-Type": "application/json" } } + ); + } + if (url.pathname === "/api/v1/auth/me") { + return new Response( + JSON.stringify({ + data: { + user: { id: "u-123", name: "Alice" }, + tenant: { id: "t-456", name: "My Tenant", tenantSlug: "mytenant" } + } + }), + { headers: { "Content-Type": "application/json" } } + ); + } + return new Response("Not found", { status: 404 }); + }) as typeof fetch; + + // 假设当前正在使用 stale-token 遭遇 401 + const recovered = await recoverSealSessionForCorp(fixtureCorp, "initial-static-token"); + expect(recovered.token).toBe("recovered-bearer-token"); + + const sessionInStore = getSealSession(fixtureCorp.id); + expect(sessionInStore?.token).toBe("recovered-bearer-token"); + }); +}); diff --git a/src/core/auth/seal.ts b/src/core/auth/seal.ts index 6bcc6a8..32e351d 100644 --- a/src/core/auth/seal.ts +++ b/src/core/auth/seal.ts @@ -1,8 +1,22 @@ import { CorpConfig } from "../config/types.js"; import { getNativeSealSession } from "./native.js"; import { getHoseSealSession } from "./hose.js"; -import { clearSealSession, getSealSession, setSealSession } from "./token-store.js"; +import { + clearSealSession, + getSealDelegateAuthCache, + getSealSession, + setSealDelegateAuthCache, + setSealSession +} from "./token-store.js"; import { SealEnterpriseConfig, SealSession } from "./types.js"; +import { + attemptCreateDelegationWithFallback, + resolveCandidateCookies, + rotateBackupCookies +} from "./session-fallback.js"; +import { createSealDelegationLink, exchangeSealDelegateLink } from "./delegate.js"; +import { saveCorpConfig } from "../config/repository.js"; +import { formatBeijingIso } from "../config/timestamps.js"; const memoryCache = new Map(); const pendingSessions = new Map>(); @@ -11,12 +25,102 @@ function isExpired(session: SealSession, refreshTtl: number): boolean { return Date.now() >= session.expiresAt - refreshTtl * 1000; } +/** + * 为原生 Seal 租户执行协助授权续期换发。 + * 优先使用主 Cookie,遇到失效或断电超期时依次由 backupCookies 兜底救险。 + */ +export async function renewNativeSealSession(corp: CorpConfig): Promise { + const source = corp.source; + if (source.type !== "seal") return undefined; + + const authCache = getSealDelegateAuthCache(corp.id); + const candidateCookies = resolveCandidateCookies(authCache); + if (candidateCookies.length === 0) return undefined; + + const sealUrl = corp.seal.url ?? source.sealUrl; + + const delegation = await attemptCreateDelegationWithFallback( + candidateCookies, + async (candCookie) => { + return createSealDelegationLink(sealUrl, { + cookie: candCookie, + token: source.token, + expiresInHours: 168, + note: "权限续期" + }); + } + ); + + const exchanged = await exchangeSealDelegateLink({ + sealUrl, + delegateToken: delegation.token + }); + + const newCookie = exchanged.sessionCookie; + const backupCookies = rotateBackupCookies(authCache, newCookie, authCache.backupCookies, 5); + + setSealDelegateAuthCache(corp.id, { + cookie: newCookie ?? authCache.cookie, + backupCookies, + updatedAt: Date.now() + }); + + const nextSession: SealSession = { + token: exchanged.token, + expiresAt: Date.now() + exchanged.expiresIn * 1000, + enterprise: { + provider: source.provider ?? "seal", + corpId: source.corpId ?? corp.id, + staffId: source.staffId, + sealUrl, + tenantId: source.tenantId ?? (exchanged.tenant.id as string | undefined), + tenantSlug: + corp.seal.tenantSlug ?? + source.tenantSlug ?? + (exchanged.tenant.tenantSlug as string | undefined), + tenantName: source.tenantName ?? (exchanged.tenant.name as string | undefined), + raw: { + sourceType: "seal" + } + } + }; + + // 尝试静默同步更新静态租户配置中的 token 与 expiresAt,避免不读缓存时使用陈旧 token + try { + const updatedCorp: CorpConfig = { + ...corp, + source: { + ...source, + token: exchanged.token, + expiresIn: exchanged.expiresIn, + expiresAt: formatBeijingIso(nextSession.expiresAt) + } + }; + saveCorpConfig(updatedCorp, { overwrite: true }); + } catch { + // 忽略无法写回配置文件的异常(如沙箱环境或只读配置) + } + + return nextSession; +} + async function refreshSealSession(corp: CorpConfig): Promise { switch (corp.source.type) { case "hose": return getHoseSealSession(corp); - case "seal": + case "seal": { + const authCache = getSealDelegateAuthCache(corp.id); + const candidates = resolveCandidateCookies(authCache); + if (candidates.length > 0) { + try { + const renewed = await renewNativeSealSession(corp); + if (renewed) return renewed; + } catch { + // 续签失败时平滑降级到原有静态凭证 + } + } return getNativeSealSession(corp); + } } } diff --git a/src/core/auth/session-fallback.test.ts b/src/core/auth/session-fallback.test.ts new file mode 100644 index 0000000..22001c5 --- /dev/null +++ b/src/core/auth/session-fallback.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, test } from "bun:test"; +import { + attemptCreateDelegationWithFallback, + resolveCandidateCookies, + rotateBackupCookies +} from "./session-fallback.js"; + +describe("session-fallback", () => { + test("rotateBackupCookies: 初始无历史 Cookie 时返回空备份", () => { + const result = rotateBackupCookies(undefined, "cookie-1"); + expect(result).toEqual([]); + }); + + test("rotateBackupCookies: 更新 Cookie 时自动归档上一份会话且排除当前 Cookie", () => { + const existing = { cookie: "cookie-1", backupCookies: [] }; + const result = rotateBackupCookies(existing, "cookie-2"); + expect(result).toEqual(["cookie-1"]); + }); + + test("rotateBackupCookies: 连续轮换自动去重并严格限制上限为 5 份", () => { + let existing: { cookie?: string; backupCookies?: string[] } = { + cookie: "cookie-1", + backupCookies: [] + }; + + for (let i = 2; i <= 8; i++) { + const newCookie = `cookie-${i}`; + const backups = rotateBackupCookies(existing, newCookie); + existing = { cookie: newCookie, backupCookies: backups }; + } + + expect(existing.cookie).toBe("cookie-8"); + expect(existing.backupCookies?.length).toBe(5); + expect(existing.backupCookies).toEqual([ + "cookie-7", + "cookie-6", + "cookie-5", + "cookie-4", + "cookie-3" + ]); + }); + + test("resolveCandidateCookies: 优先返回当前主 Cookie 并依次排列历史长效备份", () => { + expect(resolveCandidateCookies(undefined)).toEqual([]); + expect(resolveCandidateCookies({})).toEqual([]); + + const result = resolveCandidateCookies({ + cookie: "main-cookie", + backupCookies: ["backup-1", "backup-2", "main-cookie"] + }); + expect(result).toEqual(["main-cookie", "backup-1", "backup-2"]); + }); + + test("attemptCreateDelegationWithFallback: 主 Cookie 成功时直接返回结果", async () => { + const tried: (string | undefined)[] = []; + const res = await attemptCreateDelegationWithFallback( + ["cookie-primary", "cookie-backup-1"], + async (cookie) => { + tried.push(cookie); + return { link: "https://seal.cc/delegate?token=new", token: "new-token" }; + } + ); + + expect(res.token).toBe("new-token"); + expect(tried).toEqual(["cookie-primary"]); + }); + + test("attemptCreateDelegationWithFallback: 主 Cookie 失败时依次由备份 Cookie 兜底救险", async () => { + const tried: (string | undefined)[] = []; + const res = await attemptCreateDelegationWithFallback( + ["expired-cookie", "valid-backup-cookie"], + async (cookie) => { + tried.push(cookie); + if (cookie === "expired-cookie") { + throw new Error("401 Unauthorized"); + } + return { link: "https://seal.cc/delegate?token=rescued", token: "rescued-token" }; + } + ); + + expect(res.token).toBe("rescued-token"); + expect(tried).toEqual(["expired-cookie", "valid-backup-cookie"]); + }); + + test("attemptCreateDelegationWithFallback: 全部候选失败时抛出最后的错误", async () => { + await expect( + attemptCreateDelegationWithFallback( + ["bad-1", "bad-2"], + async (cookie) => { + throw new Error(`Failed with ${cookie}`); + } + ) + ).rejects.toThrow("Failed with bad-2"); + }); +}); diff --git a/src/core/auth/session-fallback.ts b/src/core/auth/session-fallback.ts new file mode 100644 index 0000000..4e0c128 --- /dev/null +++ b/src/core/auth/session-fallback.ts @@ -0,0 +1,58 @@ +/** + * 维护会话 Cookie 备份池:当 Cookie 更新时,旧 Cookie(具备约 30 天长效寿命)推入备份池,最多保留 maxBackups 份 + */ +export function rotateBackupCookies( + existing?: { cookie?: string; backupCookies?: string[] }, + newCookie?: string, + incomingBackups?: string[], + maxBackups = 5 +): string[] { + const currentCookie = newCookie !== undefined ? newCookie : existing?.cookie; + const previousCookies = [ + ...(incomingBackups || []), + existing?.cookie, + ...(existing?.backupCookies || []) + ].filter((c): c is string => Boolean(c) && c !== currentCookie); + return Array.from(new Set(previousCookies)).slice(0, maxBackups); +} + +/** + * 获取候选会话 Cookie 列表(主 Cookie 优先,随后依次尝试历史长效会话,用于断电超期兜底救险) + */ +export function resolveCandidateCookies(existing?: { + cookie?: string; + backupCookies?: string[]; +}): string[] { + const list = [existing?.cookie, ...(existing?.backupCookies || [])].filter( + (c): c is string => Boolean(c) + ); + return Array.from(new Set(list)); +} + +export type DelegationCreator = ( + cookie: string | undefined +) => Promise<{ link: string; token: string }>; + +/** + * 依次使用候选 Cookie 尝试创建新协助授权(实现断电停机超期后的长效 Session 兜底救险) + */ +export async function attemptCreateDelegationWithFallback( + candidateCookies: string[], + createFn: DelegationCreator +): Promise<{ link: string; token: string }> { + const cookiesToTry = candidateCookies.length > 0 ? candidateCookies : [undefined]; + let lastError: unknown = null; + + for (const cookie of cookiesToTry) { + try { + const res = await createFn(cookie); + if (res?.link && res?.token) { + return res; + } + } catch (err: unknown) { + lastError = err; + } + } + + throw lastError || new Error("未能成功换发新协助授权链接"); +} diff --git a/src/core/auth/token-store.test.ts b/src/core/auth/token-store.test.ts index 161948c..16dccc3 100644 --- a/src/core/auth/token-store.test.ts +++ b/src/core/auth/token-store.test.ts @@ -7,8 +7,10 @@ import { clearSealSession, getCorpTokenCache, getHoseAuthCache, + getSealDelegateAuthCache, getSealSession, setHoseAuthCache, + setSealDelegateAuthCache, setSealSession } from "./token-store.js"; import { SealSession } from "./types.js"; @@ -113,6 +115,21 @@ describe("token-store", () => { expect(getCorpTokenCache("corp-hose")).toEqual({}); }); + test("sets, retrieves, and updates seal delegate auth cache", () => { + makeTempStore(); + const delegateCache = { + cookie: "__Secure-x-seal.session_token=initial-cookie", + backupCookies: ["backup-1", "backup-2"], + updatedAt: Date.now() + }; + + setSealDelegateAuthCache("corp-delegate", delegateCache); + expect(getSealDelegateAuthCache("corp-delegate")).toEqual(delegateCache); + + clearCorpTokenCache("corp-delegate"); + expect(getSealDelegateAuthCache("corp-delegate")).toEqual({}); + }); + test("falls back to reading legacy token store when primary does not exist", () => { const legacyPath = makeTempStore(true); const session: SealSession = { diff --git a/src/core/auth/token-store.ts b/src/core/auth/token-store.ts index 93dbdbd..554e274 100644 --- a/src/core/auth/token-store.ts +++ b/src/core/auth/token-store.ts @@ -5,6 +5,7 @@ import { SEAL_CONFIG_DIR } from "../paths.js"; import { CorpTokenCache, HoseAuthCache, + SealDelegateAuthCache, SealSession, TokenStore, TokenStoreSchema @@ -93,6 +94,21 @@ export function setHoseAuthCache(corpId: string, hose: HoseAuthCache): void { }); } +export function getSealDelegateAuthCache(corpId: string): SealDelegateAuthCache { + return readStore()[corpId]?.sealDelegate ?? {}; +} + +export function setSealDelegateAuthCache(corpId: string, sealDelegate: SealDelegateAuthCache): void { + const store = readStore(); + writeStore({ + ...store, + [corpId]: { + ...store[corpId], + sealDelegate + } + }); +} + export function clearCorpTokenCache(corpId: string): void { const store = readStore(); delete store[corpId]; diff --git a/src/core/auth/types.ts b/src/core/auth/types.ts index 557d51f..8e11091 100644 --- a/src/core/auth/types.ts +++ b/src/core/auth/types.ts @@ -28,9 +28,16 @@ export const HoseAuthCacheSchema = z.object({ closeapi: TokenEntrySchema.optional() }); +export const SealDelegateAuthCacheSchema = z.object({ + cookie: z.string().optional(), + backupCookies: z.array(z.string()).optional(), + updatedAt: z.number().optional() +}); + export const CorpTokenCacheSchema = z.object({ seal: SealSessionSchema.optional(), - hose: HoseAuthCacheSchema.optional() + hose: HoseAuthCacheSchema.optional(), + sealDelegate: SealDelegateAuthCacheSchema.optional() }); export const TokenStoreSchema = z.record(z.string(), CorpTokenCacheSchema); @@ -39,5 +46,6 @@ export type TokenEntry = z.infer; export type SealEnterpriseConfig = z.infer; export type SealSession = z.infer; export type HoseAuthCache = z.infer; +export type SealDelegateAuthCache = z.infer; export type CorpTokenCache = z.infer; export type TokenStore = z.infer; diff --git a/src/domains/enterprise/onboarding.ts b/src/domains/enterprise/onboarding.ts index 1e03425..5d562a3 100644 --- a/src/domains/enterprise/onboarding.ts +++ b/src/domains/enterprise/onboarding.ts @@ -47,6 +47,7 @@ export async function onboardAssistanceLink(link: string, input: AssistanceLinkO token: session.token, sealUrl: session.sealUrl, expiresIn: session.expiresIn, + sessionCookie: session.sessionCookie, user: session.user, tenant: session.tenant } diff --git a/src/domains/seal/enterprise/onboarding.ts b/src/domains/seal/enterprise/onboarding.ts index 13c5f1e..7d77e81 100644 --- a/src/domains/seal/enterprise/onboarding.ts +++ b/src/domains/seal/enterprise/onboarding.ts @@ -8,6 +8,7 @@ import { } from "../../../core/config/types.js"; import { createSealClientForUrl } from "../../../core/http/factory.js"; import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js"; +import { setSealDelegateAuthCache } from "../../../core/auth/token-store.js"; import { getMe } from "../api.js"; export type RemoteSealIdentity = { @@ -39,6 +40,7 @@ export type SealDelegateSession = { token: string; sealUrl: string; expiresIn: number; + sessionCookie?: string; user: Record; tenant: Record; }; @@ -100,6 +102,17 @@ export function persistSealDelegateSession(input: { remote: { user: input.session.user, tenant: input.session.tenant } } ); + if (input.session.sessionCookie) { + try { + setSealDelegateAuthCache(saved.config.id, { + cookie: input.session.sessionCookie, + backupCookies: [], + updatedAt: Date.now() + }); + } catch { + // ignore cache write error + } + } return { ...saved, tenantId, tenantSlug }; } diff --git a/src/domains/seal/reports/pipeline/collect.ts b/src/domains/seal/reports/pipeline/collect.ts index 0d66266..eca81f1 100644 --- a/src/domains/seal/reports/pipeline/collect.ts +++ b/src/domains/seal/reports/pipeline/collect.ts @@ -4,7 +4,7 @@ import { formatBeijingIso } from "../../../../core/config/timestamps.js"; import { validationError } from "../../../../core/errors.js"; import type { ApprovalRun } from "../../types.js"; import type { ReportDemand } from "./describe.js"; -import { loadReviews, ReviewsMap, type ReviewRecord } from "./review-store.js"; +import { loadReviews, recordDivergences, ReviewsMap, type ReviewRecord } from "./review-store.js"; /** 单据在决策空间里的极性:同意为正向、驳回/终止为反向,用于比对 AI 与人工是否同向。 */ type Polarity = "pass" | "reject" | "unknown"; @@ -307,6 +307,26 @@ export async function collectReportData( data.blocks = blocks; fetched.blocks = true; + + const divergedBlocks = blocks.filter((b) => b.agreement === "diverged"); + if (divergedBlocks.length > 0) { + try { + recordDivergences( + options.corp.id, + divergedBlocks.map((b) => ({ + corpId: options.corp.id, + recordId: b.recordId ?? b.sn, + sn: b.sn, + docTitle: b.title, + aiDecision: b.aiDecision, + manualDecision: b.humanResult, + divergenceType: `${b.aiDecision || "未知"}_${b.humanResult || "未知"}`, + createdAt: b.createdAt ? new Date(b.createdAt).getTime() : undefined, + discoveredAt: Date.now() + })) + ); + } catch {} + } } catch { // 分块拉取失败:章节保持模板原文 } diff --git a/src/domains/seal/reports/pipeline/review-divergence.test.ts b/src/domains/seal/reports/pipeline/review-divergence.test.ts new file mode 100644 index 0000000..8fa214f --- /dev/null +++ b/src/domains/seal/reports/pipeline/review-divergence.test.ts @@ -0,0 +1,173 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + closeReviewsDb, + countUnreviewedDivergences, + dismissDivergencePrompt, + isDivergenceDismissed, + listUnreviewedDivergences, + recordDivergences, + shouldPromptDivergence, + writeReview +} from "./review-store.js"; + +describe("review-divergence: 分歧待办与频控提醒机制", () => { + let testDir: string; + + beforeEach(() => { + testDir = mkdtempSync(join(tmpdir(), "seal-reviews-divergence-test-")); + process.env.SEAL_USE_REVIEWS_STORE = join(testDir, "reviews.sqlite"); + process.env.SEAL_USE_REVIEWS_DIR = join(testDir, "reviews"); + }); + + afterEach(() => { + closeReviewsDb(); + delete process.env.SEAL_USE_REVIEWS_STORE; + delete process.env.SEAL_USE_REVIEWS_DIR; + rmSync(testDir, { recursive: true, force: true }); + }); + + test("录入分歧单据并能正确查询待整理数量", () => { + const corpId = "corp-huangfeng"; + expect(countUnreviewedDivergences(corpId)).toBe(0); + + recordDivergences(corpId, [ + { + corpId, + recordId: "run-001", + sn: "SN-20261101-01", + docTitle: "差旅费报销单", + amount: "¥1,200", + aiDecision: "驳回", + manualDecision: "通过", + divergenceType: "AI驳回_人工通过", + discoveredAt: Date.now() + }, + { + corpId, + recordId: "run-002", + sn: "SN-20261101-02", + docTitle: "办公用品采购", + amount: "¥4,500", + aiDecision: "通过", + manualDecision: "驳回", + divergenceType: "AI通过_人工驳回", + discoveredAt: Date.now() + } + ]); + + expect(countUnreviewedDivergences(corpId)).toBe(2); + const unreviewed = listUnreviewedDivergences(corpId); + expect(unreviewed).toHaveLength(2); + expect(unreviewed[0]!.sn).toBe("SN-20261101-01"); + }); + + test("进行人工裁决打标后,待整理数量自动减少", () => { + const corpId = "corp-huangfeng"; + recordDivergences(corpId, [ + { + corpId, + recordId: "run-001", + sn: "SN-001", + discoveredAt: Date.now() + }, + { + corpId, + recordId: "run-002", + sn: "SN-002", + discoveredAt: Date.now() + } + ]); + + expect(countUnreviewedDivergences(corpId)).toBe(2); + + // 人工整理了 run-001 + writeReview(corpId, { + recordId: "run-001", + sn: "SN-001", + verdict: "ai_correct", + note: "发票确实开错抬头,AI驳回正确" + }); + + expect(countUnreviewedDivergences(corpId)).toBe(1); + const remaining = listUnreviewedDivergences(corpId); + expect(remaining).toHaveLength(1); + expect(remaining[0]!.sn).toBe("SN-002"); + }); + + test("shouldPromptDivergence 遵守时间频控,避免连续打扰", () => { + const corpId = "corp-huangfeng"; + // 第一次允许提醒 + expect(shouldPromptDivergence(corpId, 10_000)).toBe(true); + + // 立即再次检查,在 10s 内被频控拦截 + expect(shouldPromptDivergence(corpId, 10_000)).toBe(false); + + // 另一个企业不受影响 + expect(shouldPromptDivergence("corp-other", 10_000)).toBe(true); + }); + + test("dismissDivergencePrompt 在用户拒绝时进入静音抑制期,绝不重复打扰", () => { + const corpId = "corp-huangfeng"; + expect(isDivergenceDismissed(corpId)).toBe(false); + + // 用户说“今天不想审批/别烦我”,Agent 调用 dismiss 24小时 + dismissDivergencePrompt(corpId, 24); + expect(isDivergenceDismissed(corpId)).toBe(true); + + // 在静音期内,无论频控如何都不再提醒 + expect(shouldPromptDivergence(corpId, 0)).toBe(false); + }); + + test("自动过滤超过 30 天的陈年旧单,只提示近 30 天的分歧单据", () => { + const corpId = "corp-huangfeng"; + const now = Date.now(); + const eightyDaysAgo = now - 80 * 24 * 3600 * 1000; + + recordDivergences(corpId, [ + { + corpId, + recordId: "run-old-march", + sn: "SN-20260315-01", + docTitle: "3月份招待费", + createdAt: eightyDaysAgo, + discoveredAt: eightyDaysAgo + }, + { + corpId, + recordId: "run-recent-today", + sn: "SN-20261102-01", + docTitle: "今天差旅费", + createdAt: now, + discoveredAt: now + } + ]); + + // 默认只统计近 30 天:3月份的陈年旧账自动排除,不打扰当前月份 + expect(countUnreviewedDivergences(corpId)).toBe(1); + const recent = listUnreviewedDivergences(corpId); + expect(recent).toHaveLength(1); + expect(recent[0]!.sn).toBe("SN-20261102-01"); + + // 若显式传入 0 (或 --all),仍可检索历史全量 + expect(countUnreviewedDivergences(corpId, 0)).toBe(2); + const all = listUnreviewedDivergences(corpId, 50, 0); + expect(all).toHaveLength(2); + }); + + test("滑动窗口频控:同一个企业 5 小时内最多主动提醒 1 次", () => { + const corpId = "corp-sliding-window"; + const fiveHoursMs = 5 * 60 * 60 * 1000; + + // 第 1 次:允许提醒 + expect(shouldPromptDivergence(corpId, fiveHoursMs)).toBe(true); + + // 5 小时以内再次触发:拦截 + expect(shouldPromptDivergence(corpId, fiveHoursMs)).toBe(false); + + // 传入 0 间隔(即超过 5 小时后):再次允许提醒 + expect(shouldPromptDivergence(corpId, 0)).toBe(true); + }); +}); diff --git a/src/domains/seal/reports/pipeline/review-store.ts b/src/domains/seal/reports/pipeline/review-store.ts index bb67ada..4b9f121 100644 --- a/src/domains/seal/reports/pipeline/review-store.ts +++ b/src/domains/seal/reports/pipeline/review-store.ts @@ -1,19 +1,19 @@ -import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs"; +import { Database } from "bun:sqlite"; +import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs"; import { dirname, join } from "node:path"; import { validationError } from "../../../../core/errors.js"; import { SEAL_STATE_DIR } from "../../../../core/paths.js"; /** - * 人工裁决的本地持久化(JSONL,按租户分片,支持 recordId 与 SN 双键检索)。 + * 人工裁决与分歧待办的本地存储(统一放置在 ~/.config/seal-use/state/) * - * 为什么是 JSONL:跨周期 review 天然是追加写入场景——每审一批写一批,不整文件重写, - * 避免并发覆盖;单行一条记录,可直接 tail/grep/手改,也可被 CLI 批量导入。 - * 为什么按租户分片:租户天然数据隔离。 - * 标识符规则:优先以具体审核运行 ID(recordId)精确定位单次审核;同时支持单据 SN 作为业务自然键。 - * 后写覆盖先写。 + * 存储模型: + * 1. 主存储:~/.config/seal-use/state/reviews.sqlite,支持秒级索引与差集运算(支撑日常命令在 stderr 温和提示); + * 2. 伴生与导出存储:~/.config/seal-use/state/reviews/[-].jsonl,作为人类可读与批量台账交互的冷备份; + * 3. 为什么是 State 而不是 Cache:人工裁决是用户不可逆的智力决策(谁对谁错、特批备注),不上传云端,属于单机核心资产, + * 防止随 ~/.cache 一键清理而丢失。 */ -/** 人工裁决结论:谁对。both_* 覆盖"一致但仍复核"与"分歧后判定双方各有对错"的场景。 */ export type ReviewVerdict = | "ai_correct" // AI 对,人工错 | "human_correct" // 人工对,AI 错 @@ -22,21 +22,29 @@ export type ReviewVerdict = | "undecided"; // 已 review 但暂无法判定(保留占位,后续可改判) export type ReviewRecord = { - /** 审核运行记录 ID(精确裁决键) */ recordId?: string; - /** 合思/源单据 SN(业务自然键) */ sn?: string; - /** 裁决所属统计周期或月份(可选留痕) */ month?: string; + scope?: string; verdict: ReviewVerdict; - /** 裁决人(可选,留痕用) */ reviewedBy?: string; - /** 裁决备注(可选):为什么这么判 */ note?: string; - /** 写入时间(北京时间 ISO 秒) */ recordedAt: string; }; +export type DivergenceItem = { + corpId: string; + recordId: string; + sn: string; + docTitle?: string; + amount?: string; + aiDecision?: string; + manualDecision?: string; + divergenceType?: string; + createdAt?: number; + discoveredAt: number; +}; + const VERDICTS: ReadonlySet = new Set([ "ai_correct", "human_correct", @@ -97,20 +105,27 @@ export class ReviewsMap { } const REVIEWS_DIR_ENV = "SEAL_USE_REVIEWS_DIR"; +const REVIEWS_STORE_ENV = "SEAL_USE_REVIEWS_STORE"; -/** 裁决存储根目录:~/.config/seal-use/state/reviews/。可用 SEAL_USE_REVIEWS_DIR 覆盖(测试/隔离)。 */ export function reviewsDir(): string { const configured = process.env[REVIEWS_DIR_ENV]?.trim(); if (configured) return configured; return join(SEAL_STATE_DIR, "reviews"); } -/** 分片路径:/[-].jsonl */ export function reviewFilePath(corpId: string, scope?: string): string { const cleanCorp = sanitizeCorpId(corpId); return scope ? join(reviewsDir(), `${cleanCorp}-${scope}.jsonl`) : join(reviewsDir(), `${cleanCorp}.jsonl`); } +export function getReviewStorePath(): string { + const configured = process.env[REVIEWS_STORE_ENV]?.trim(); + if (configured) return configured; + const legacyDir = process.env[REVIEWS_DIR_ENV]?.trim(); + if (legacyDir) return join(legacyDir, "reviews.sqlite"); + return join(SEAL_STATE_DIR, "reviews.sqlite"); +} + function sanitizeCorpId(corpId: string): string { return corpId.replace(/[^a-zA-Z0-9._-]/g, "_"); } @@ -123,21 +138,109 @@ function assertVerdict(verdict: string): asserts verdict is ReviewVerdict { } } +let dbInstance: Database | null = null; +let currentDbPath: string | null = null; + +export function openReviewsDb(path = getReviewStorePath()): Database { + if (dbInstance && currentDbPath === path) { + return dbInstance; + } + if (dbInstance) { + try { + dbInstance.close(); + } catch {} + dbInstance = null; + } + + mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); + const db = new Database(path, { create: true }); + try { + chmodSync(path, 0o600); + db.exec("PRAGMA busy_timeout = 5000"); + db.exec(` + CREATE TABLE IF NOT EXISTS reviews ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + corp_id TEXT NOT NULL, + record_id TEXT, + sn TEXT, + month TEXT, + scope TEXT, + verdict TEXT NOT NULL, + reviewed_by TEXT, + note TEXT, + recorded_at TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_reviews_lookup ON reviews (corp_id, record_id, sn); + CREATE INDEX IF NOT EXISTS idx_reviews_scope ON reviews (corp_id, scope); + CREATE INDEX IF NOT EXISTS idx_reviews_month ON reviews (corp_id, month); + + CREATE TABLE IF NOT EXISTS divergences ( + corp_id TEXT NOT NULL, + record_id TEXT NOT NULL, + sn TEXT NOT NULL, + doc_title TEXT, + amount TEXT, + ai_decision TEXT, + manual_decision TEXT, + divergence_type TEXT, + created_at INTEGER, + discovered_at INTEGER NOT NULL, + PRIMARY KEY (corp_id, record_id) + ); + CREATE INDEX IF NOT EXISTS idx_divergences_corp ON divergences (corp_id, sn); + + CREATE TABLE IF NOT EXISTS prompt_throttle ( + corp_id TEXT PRIMARY KEY, + last_prompt_date TEXT, + prompt_count INTEGER NOT NULL DEFAULT 1, + last_prompted_at INTEGER NOT NULL + ); + + CREATE TABLE IF NOT EXISTS review_dismissals ( + corp_id TEXT PRIMARY KEY, + dismissed_until INTEGER NOT NULL + ); + `); + try { + db.exec("ALTER TABLE prompt_throttle ADD COLUMN last_prompt_date TEXT"); + } catch {} + try { + db.exec("ALTER TABLE prompt_throttle ADD COLUMN prompt_count INTEGER DEFAULT 1"); + } catch {} + dbInstance = db; + currentDbPath = path; + return db; + } catch (error) { + db.close(); + throw error; + } +} + +export function closeReviewsDb(): void { + if (dbInstance) { + try { + dbInstance.close(); + } catch {} + dbInstance = null; + currentDbPath = null; + } +} + /** - * 读取某租户的全部裁决。若指定 scope(如月份),则仅读取该分片;否则读取该租户的主文件与各分片文件。按后写覆盖先写。 + * 历史 JSONL 自动平滑迁移或同步到 SQLite */ -export function loadReviews(corpId: string, scope?: string): ReviewsMap { - const reviews = new ReviewsMap(); +function syncLegacyJsonlIfPresent(corpId: string, db: Database, targetScope?: string): void { + const targetDir = reviewsDir(); + if (!existsSync(targetDir)) return; const sanitized = sanitizeCorpId(corpId); - const targetDir = reviewsDir(); - if (!existsSync(targetDir)) return reviews; - const targetFile = reviewFilePath(corpId, scope); const filesToRead: string[] = []; - if (scope) { - if (existsSync(targetFile)) filesToRead.push(targetFile); + if (targetScope) { + const scopeFile = reviewFilePath(corpId, targetScope); + if (existsSync(scopeFile)) filesToRead.push(scopeFile); } else { - if (existsSync(targetFile)) filesToRead.push(targetFile); + const primary = reviewFilePath(corpId); + if (existsSync(primary)) filesToRead.push(primary); try { const allFiles = readdirSync(targetDir); for (const f of allFiles) { @@ -148,7 +251,20 @@ export function loadReviews(corpId: string, scope?: string): ReviewsMap { } catch {} } - for (const filePath of filesToRead) { + const insertStmt = db.prepare(` + INSERT INTO reviews (corp_id, record_id, sn, month, scope, verdict, reviewed_by, note, recorded_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + + const checkStmt = db.prepare(` + SELECT id FROM reviews + WHERE corp_id = ? AND ( + (record_id IS NOT NULL AND record_id = ?) OR + (sn IS NOT NULL AND sn = ?) + ) AND recorded_at = ? LIMIT 1 + `); + + for (const filePath of new Set(filesToRead)) { try { const lines = readFileSync(filePath, "utf8").split("\n"); for (const line of lines) { @@ -157,18 +273,87 @@ export function loadReviews(corpId: string, scope?: string): ReviewsMap { try { const parsed = JSON.parse(trimmed) as ReviewRecord; if (parsed && (parsed.recordId || parsed.sn) && VERDICTS.has(parsed.verdict)) { - reviews.set(parsed.recordId ?? parsed.sn!, parsed); + const exists = checkStmt.get( + corpId, + parsed.recordId ?? null, + parsed.sn ?? null, + parsed.recordedAt + ); + if (!exists) { + insertStmt.run( + corpId, + parsed.recordId ?? null, + parsed.sn ?? null, + parsed.month ?? null, + parsed.scope ?? parsed.month ?? null, + parsed.verdict, + parsed.reviewedBy ?? null, + parsed.note ?? null, + parsed.recordedAt + ); + } } - } catch {} + } catch { + // 跳过损坏行 + } } } catch {} } +} + +/** + * 读取某租户的全部裁决。若指定 scope(如月份),则仅读取该分片。按后写覆盖先写。 + */ +export function loadReviews(corpId: string, scope?: string): ReviewsMap { + const reviews = new ReviewsMap(); + const db = openReviewsDb(); + syncLegacyJsonlIfPresent(corpId, db, scope); + + let query = ` + SELECT record_id, sn, month, scope, verdict, reviewed_by, note, recorded_at + FROM reviews + WHERE corp_id = ? + `; + const params: string[] = [corpId]; + + if (scope) { + query += " AND (scope = ? OR month = ?)"; + params.push(scope, scope); + } + query += " ORDER BY id ASC"; + + const rows = db.prepare(query).all(...params) as Array<{ + record_id: string | null; + sn: string | null; + month: string | null; + scope: string | null; + verdict: string; + reviewed_by: string | null; + note: string | null; + recorded_at: string; + }>; + + for (const row of rows) { + if (VERDICTS.has(row.verdict)) { + const record: ReviewRecord = { + recordId: row.record_id || undefined, + sn: row.sn || undefined, + month: row.month || undefined, + scope: row.scope || undefined, + verdict: row.verdict as ReviewVerdict, + reviewedBy: row.reviewed_by || undefined, + note: row.note || undefined, + recordedAt: row.recorded_at + }; + reviews.set(record.recordId ?? record.sn!, record); + } + } return reviews; } /** - * 追加写一条裁决到磁盘(支持 recordId 与 sn)。 + * 记录一条裁决到 SQLite 存储,同时双写到伴生 JSONL 文件 */ export function writeReview( corpId: string, @@ -193,19 +378,267 @@ export function writeReview( } assertVerdict(input.verdict); + const recordedAt = + input.recordedAt ?? new Date().toISOString().slice(0, 19).replace("T", " "); + const scope = input.scope ?? input.month; + + const db = openReviewsDb(); + const stmt = db.prepare(` + INSERT INTO reviews (corp_id, record_id, sn, month, scope, verdict, reviewed_by, note, recorded_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + + stmt.run( + corpId, + recordId ?? null, + sn ?? null, + input.month ?? null, + scope ?? null, + input.verdict, + input.reviewedBy?.trim() ?? null, + input.note?.trim() ?? null, + recordedAt + ); + const record: ReviewRecord = { ...(recordId ? { recordId } : {}), ...(sn ? { sn } : {}), ...(input.month ? { month: input.month } : {}), + ...(scope ? { scope } : {}), verdict: input.verdict, ...(input.reviewedBy?.trim() ? { reviewedBy: input.reviewedBy.trim() } : {}), ...(input.note?.trim() ? { note: input.note.trim() } : {}), - recordedAt: input.recordedAt ?? new Date().toISOString().slice(0, 19).replace("T", " ") + recordedAt }; - const scope = input.scope ?? input.month; - const filePath = reviewFilePath(corpId, scope); - mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 }); - appendFileSync(filePath, JSON.stringify(record) + "\n", { encoding: "utf-8", mode: 0o600 }); + // 双写到伴生 JSONL(明文冷备与纯文本兼容) + try { + const filePath = reviewFilePath(corpId, scope); + mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 }); + appendFileSync(filePath, JSON.stringify(record) + "\n", { encoding: "utf-8", mode: 0o600 }); + } catch {} + return record; } + +/** + * 批量同步/保存分歧单据到底层 SQLite + */ +export function recordDivergences(corpId: string, items: DivergenceItem[]): number { + if (items.length === 0) return 0; + const db = openReviewsDb(); + const stmt = db.prepare(` + INSERT INTO divergences (corp_id, record_id, sn, doc_title, amount, ai_decision, manual_decision, divergence_type, created_at, discovered_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(corp_id, record_id) DO UPDATE SET + sn = excluded.sn, + doc_title = coalesce(excluded.doc_title, divergences.doc_title), + amount = coalesce(excluded.amount, divergences.amount), + ai_decision = coalesce(excluded.ai_decision, divergences.ai_decision), + manual_decision = coalesce(excluded.manual_decision, divergences.manual_decision), + divergence_type = coalesce(excluded.divergence_type, divergences.divergence_type) + `); + + let count = 0; + db.transaction(() => { + for (const item of items) { + stmt.run( + corpId, + item.recordId, + item.sn, + item.docTitle ?? null, + item.amount ?? null, + item.aiDecision ?? null, + item.manualDecision ?? null, + item.divergenceType ?? null, + item.createdAt ?? null, + item.discoveredAt || Date.now() + ); + count++; + } + })(); + return count; +} + +export const DEFAULT_RECENCY_DAYS = 30; + +function getLocalDateString(): string { + const d = new Date(); + const year = d.getFullYear(); + const month = String(d.getMonth() + 1).padStart(2, "0"); + const day = String(d.getDate()).padStart(2, "0"); + return `${year}-${month}-${day}`; +} + +/** + * 列出某企业未完成人工复核的分歧单据(用于少量多次整理) + * 默认只检索近 30 天内发生的单据,避免数月前的陈年旧账打扰日常体验 + */ +export function listUnreviewedDivergences( + corpId: string, + limit = 50, + maxAgeDays = DEFAULT_RECENCY_DAYS +): DivergenceItem[] { + const db = openReviewsDb(); + syncLegacyJsonlIfPresent(corpId, db); + + let query = ` + SELECT d.corp_id, d.record_id, d.sn, d.doc_title, d.amount, d.ai_decision, d.manual_decision, d.divergence_type, d.created_at, d.discovered_at + FROM divergences d + LEFT JOIN reviews r ON r.corp_id = d.corp_id AND ( + (r.record_id IS NOT NULL AND r.record_id = d.record_id) OR + (r.sn IS NOT NULL AND r.sn = d.sn) + ) + WHERE d.corp_id = ? AND r.id IS NULL + `; + const params: (string | number)[] = [corpId]; + + if (maxAgeDays > 0) { + const cutoff = Date.now() - maxAgeDays * 24 * 3600 * 1000; + query += ` AND COALESCE(d.created_at, d.discovered_at) >= ?`; + params.push(cutoff); + } + + query += ` + ORDER BY d.created_at DESC, d.discovered_at DESC + LIMIT ? + `; + params.push(limit); + + const rows = db.prepare(query).all(...params) as Array<{ + corp_id: string; + record_id: string; + sn: string; + doc_title: string | null; + amount: string | null; + ai_decision: string | null; + manual_decision: string | null; + divergence_type: string | null; + created_at: number | null; + discovered_at: number; + }>; + + return rows.map((r) => ({ + corpId: r.corp_id, + recordId: r.record_id, + sn: r.sn, + docTitle: r.doc_title || undefined, + amount: r.amount || undefined, + aiDecision: r.ai_decision || undefined, + manualDecision: r.manual_decision || undefined, + divergenceType: r.divergence_type || undefined, + createdAt: r.created_at || undefined, + discoveredAt: r.discovered_at + })); +} + +/** + * 统计某企业待整理分歧单据数量(耗时 < 0.2ms,供日常命令快速探测) + * 默认只统计近 30 天内产生的分歧,陈年单据自动归入离线历史池,零打扰 + */ +export function countUnreviewedDivergences( + corpId: string, + maxAgeDays = DEFAULT_RECENCY_DAYS +): number { + try { + const db = openReviewsDb(); + syncLegacyJsonlIfPresent(corpId, db); + + let query = ` + SELECT COUNT(*) as count + FROM divergences d + LEFT JOIN reviews r ON r.corp_id = d.corp_id AND ( + (r.record_id IS NOT NULL AND r.record_id = d.record_id) OR + (r.sn IS NOT NULL AND r.sn = d.sn) + ) + WHERE d.corp_id = ? AND r.id IS NULL + `; + const params: (string | number)[] = [corpId]; + + if (maxAgeDays > 0) { + const cutoff = Date.now() - maxAgeDays * 24 * 3600 * 1000; + query += ` AND COALESCE(d.created_at, d.discovered_at) >= ?`; + params.push(cutoff); + } + + const row = db.prepare(query).get(...params) as { count: number } | undefined; + return row?.count ?? 0; + } catch { + return 0; + } +} + +/** + * 抑制该企业的提示(当用户表示当天不想处理时,Agent 调用此函数静音) + */ +export function dismissDivergencePrompt(corpId: string, hours = 24): number { + try { + const db = openReviewsDb(); + const until = Date.now() + Math.max(1, hours) * 3600 * 1000; + db.prepare(` + INSERT INTO review_dismissals (corp_id, dismissed_until) + VALUES (?, ?) + ON CONFLICT(corp_id) DO UPDATE SET dismissed_until = excluded.dismissed_until + `).run(corpId, until); + return until; + } catch { + return Date.now(); + } +} + +/** + * 检查该企业是否处于人工拒绝的静音抑制期内 + */ +export function isDivergenceDismissed(corpId: string): boolean { + try { + const db = openReviewsDb(); + const row = db + .prepare("SELECT dismissed_until FROM review_dismissals WHERE corp_id = ?") + .get(corpId) as { dismissed_until: number } | undefined; + return Boolean(row && row.dismissed_until > Date.now()); + } catch { + return false; + } +} + +export const DEFAULT_PROMPT_INTERVAL_MS = 5 * 60 * 60 * 1000; // 动态 5 小时滑动窗口 + +/** + * 频控检查(动态 5 小时滑动窗口与 24 小时人工封禁): + * 1. 显式静音优先:若企业处于 dismiss 抑制期内(默认 24 小时),直接返回 false; + * 2. 动态滑动窗口:同一个企业默认 5 小时内最多提醒 1 次(5 小时内提醒过则不再提醒); + * 3. 满足条件时记录当前时间戳并返回 true。 + */ +export function shouldPromptDivergence( + corpId: string, + intervalMs = DEFAULT_PROMPT_INTERVAL_MS +): boolean { + try { + if (isDivergenceDismissed(corpId)) { + return false; + } + + const db = openReviewsDb(); + const now = Date.now(); + + const row = db + .prepare("SELECT last_prompted_at FROM prompt_throttle WHERE corp_id = ?") + .get(corpId) as { last_prompted_at?: number } | undefined; + + if (row?.last_prompted_at && now - row.last_prompted_at < intervalMs) { + return false; + } + + db.prepare(` + INSERT INTO prompt_throttle (corp_id, last_prompt_date, prompt_count, last_prompted_at) + VALUES (?, ?, ?, ?) + ON CONFLICT(corp_id) DO UPDATE SET + last_prompt_date = excluded.last_prompt_date, + prompt_count = excluded.prompt_count, + last_prompted_at = excluded.last_prompted_at + `).run(corpId, getLocalDateString(), 1, now); + return true; + } catch { + return false; + } +}