@aiquants/enrichment-core 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @aiquants/enrichment-core
2
2
 
3
- Transport- and DB-agnostic storage metadata AI enrichment core: canonical types, RFC 9562 UUIDv7 utility, and API client SDK.
3
+ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types, RFC 9562 UUIDv7 utility, the document change history contract and diff engine, and API client SDK.
4
4
 
5
5
  ストレージメタデータ・AI エンリッチメント基盤の正準 TypeScript 型定義、RFC 9562 準拠 UUIDv7 ユーティリティ、およびクライアント SDK を提供する共有コアライブラリ。
6
6
 
@@ -11,8 +11,12 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
11
11
  - **EnrichmentClient**: ハイブリッド検索 (`POST /ai/search/hybrid`) を呼ぶ HTTP クライアント SDK。要求・応答のスキーマ (`SearchRequestSchema` / `SearchResponseSchema`) は Python 側 `HybridSearchRequest` / `HybridSearchResponse` と項目ごとに一致する。詳細は下の「Search client contract」。
12
12
  - **Pipeline flow as data** (`flow.ts`): 文書種 (`DOCUMENT_KINDS` / `classifyDocumentKind`)、段 (`PIPELINE_STEPS`)、種類ごとの段の DAG (`PIPELINE_FLOWS` / `flowFor` / `orderedSteps`)。ワーカーの実行順とコンソールの図はこの 1 つの表から導く。段は自分を閉じるテナントのフラグ (`gates`) と、閉じたときの意味 (`skip` / `fail`) を宣言し、流れは段ごとにその意味を上書きできる (`FlowStep.gatePolicy`)。流れの中の門は `flowStepGates` で読む。詳細は下の「Pipeline flow contract」。
13
13
  - **Pipeline records** (`pipelineRecord.ts`): 1 回の実行 (`PipelineRunRecordSchema`) と段ごとの記録 (`PipelineStepRecordSchema`)、段を除いた実行の要約 (`PipelineRunSummarySchema`、一覧向け)、段が自身について報告する値 (`StageProvenanceSchema`、Python 側の `StageProvenance` と項目ごとに一致)、段の集計 (`PipelineStepMetricSchema`)、飛ばした理由の文法 (`SkipReason` / `formatSkipReason` / `parseSkipReason`、読む対象が無かったときの値 `NOTHING_TO_READ_TOKENS` / `NothingToReadTokenSchema`)。測っていない値は `null` で、欠落させない。詳細は下の「Pipeline record contract」。
14
- - **Integrity audit contract** (`integrity.ts`): Tri-Store 整合性監査の記録の語彙 (`IntegrityStoreSchema` を含む 12 の列挙と、所見を記録する区分 `IntegrityFindingItemClassSchema`)、区分の扱いと処置の表 (`INTEGRITY_CLASS_POLICY`)、概況 (`IntegrityAuditOverviewSchema`)、所見の頁と要求 (`IntegrityFindingPageSchema` / `IntegrityFindingsQuerySchema`)、配置の所見が観測したドメイン (`IntegrityPlacementObservedSchema`)、開始・中止の命令と命令ごとの失敗の語彙 (`IntegrityCommandSchema` / `IntegrityCommandFailureSchema`) と (状態, 業務コード) の表 (`integrityCommandCodes.json` / `INTEGRITY_COMMAND_CODES` / `integrityCommandFailureCodeOf`)、ホストのストアの応答 (`IntegrityCommandReplySchema`)、契約の時刻の前後の比較 (`isStrictlyEarlier`)。
14
+ - **Integrity audit contract** (`integrity.ts`): Tri-Store 整合性監査の記録の語彙 (`IntegrityStoreSchema` を含む 12 の列挙と、所見を記録する区分 `IntegrityFindingItemClassSchema`)、区分の扱いと処置の表 (`INTEGRITY_CLASS_POLICY`)、概況 (`IntegrityAuditOverviewSchema`)、所見の頁と要求 (`IntegrityFindingPageSchema` / `IntegrityFindingsQuerySchema`)、
15
+ `UNRECORDED` の組の一括の再同期の 1 回分の要求と答え (`IntegrityCellResyncRequestSchema` / `IntegrityCellResyncResultSchema`)、配置の所見が観測したドメイン (`IntegrityPlacementObservedSchema`)、開始・中止の命令と命令ごとの失敗の語彙 (`IntegrityCommandSchema` / `IntegrityCommandFailureSchema`) と (状態, 業務コード) の表 (`integrityCommandCodes.json` / `INTEGRITY_COMMAND_CODES` / `integrityCommandFailureCodeOf`)、ホストのストアの応答 (`IntegrityCommandReplySchema`)、契約の時刻の前後の比較 (`isStrictlyEarlier`)。
15
16
  詳細は下の「Integrity audit contract」。
17
+ - **Enrichment stages** (`strategy.ts`): ドメインの戦略行が開閉できる段の唯一の表 (`ENRICHMENT_STAGES`、パイプラインの順) と段の型・キー (`EnrichmentStage` / `EnrichmentStageKey`、DB の列名と 1 対 1)、キーの判定と引き当て (`isEnrichmentStageKey` / `enrichmentStage`)。段はテナントの機能フラグと戦略行の 2 つの門を持ちうる (テナントの門の無い段は `featureFlagKey` が `null`)。ナレッジグラフのノードを閲覧するときの境界と既定値 (`GRAPH_INDEX_LIMITS`)。
18
+ - **Vocabularies & search modes** (`vocabulary.ts` / `search.ts`): DB が強制する閉じた語彙 (`ModelProviderSchema`・`ConfidentialityLevelSchema`、検索結果に現れない機密区分 `QUARANTINED_CONFIDENTIALITY_LEVEL`)、検索モードと各モードが走らせる層の表 (`SEARCH_MODES` / `MODE_TIERS` と、そこから導く `modeNeedsRemoteTiers` / `modeScoreIsSimilarity` / `narrowModeToAllowedTiers` / `modeFusesRankings`)、調整可能パラメータの境界と既定値 (`SEARCH_PARAM_LIMITS`)、絞り込める機密区分 (`FILTERABLE_CONFIDENTIALITY_LEVELS`)、遮断器の対象 (`CIRCUIT_BREAKER_SERVICES`) と縮退理由の全集合 (`SEARCH_DEGRADATION_REASONS`)。
19
+ - **Document change history** (`documentHistory.ts` / `revisionDiff/` / `canonicalJson.ts`): 文書の差分履歴 (S1 §8.19) の契約 (語彙・版付きの定数・面ごとの正準の値・変化の計数・比較・行の頁・履歴・直近の変化の一覧と位置・手動の記録の答え・隔離の印 `Restricted*MarkSchema` と読める項目の包み `ReadableEntry`)、記録器と読み手が共有する差分エンジン v1 (`summarizeTransition` / `compareStates`、純粋な関数で入出力もハッシュも持たない)、システムの中の唯一の正準の JSON (`canonicalJson`)。詳細は下の「Document history contract」。
16
20
  - **System parameter ranges** (`systemParameterRanges.ts`): 値域を持つシステムパラメータの唯一の表 (`systemParameterRanges.json` / `SYSTEM_PARAMETER_RANGES`) と、書き手が当てる検査 (`assertSystemParameterInRange`) と読み手が当てる検査 (`assertBoundedSystemParameter`)。詳細は下の「System parameter ranges」。
17
21
 
18
22
  ## Search client contract / 検索クライアントの契約
@@ -56,6 +60,7 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
56
60
 
57
61
  | Field | Writer contract / 書き手の契約 | Checked by the schema / スキーマが検査する規則 |
58
62
  | --- | --- | --- |
63
+ | `stepKey` | 流れの段 (`PIPELINE_STEP_KEYS`) か終端段 `record_document_state` | `LedgerStepKeySchema` (`LEDGER_STEP_KEYS` の 10 語) |
59
64
  | `status` | `RUNNING` / `SUCCEEDED` / `SKIPPED` / `FAILED` | 語彙 |
60
65
  | `skipReason` | `SKIPPED` のときだけ `formatSkipReason` の文字列を書き、それ以外は `null` | `SKIPPED` では非 `null`、`SUCCEEDED` と `FAILED` では `null`。`RUNNING` の値は検査しない。文法の外の文字列も DB の値 (`z.string()`) として受け入れ、解釈は読み手が `parseSkipReason` で行う |
61
66
  | `provenance` | 段が自身について報告する値。`SUCCEEDED` では必須、`SKIPPED` では `null` (読む対象が無いと答えた段も、モデル欄が `null` の応答の報告を写さない) | `SUCCEEDED` では非 `null`、`SKIPPED` では `null`。`RUNNING` と `FAILED` の値は検査しない |
@@ -73,9 +78,22 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
73
78
  | `{ kind: "no_children" }` | `no_children` | 子アセットを生む段は走ったが、子が 1 件も無かった |
74
79
  | `{ kind: "source_skipped", stepKey }` | `source_skipped:extract_assets` | 扇出の元になる段が同じ実行で飛ばされた (子を探していない) |
75
80
  | `{ kind: "nothing_to_read", token }` | `nothing_to_read:no_pages` | 呼ばれた読み取りの段 (`ocr_document`、子ごとの `ocr_children`) が、読む対象が無いと答えた (モデルは呼んでいない)。`token` は `NOTHING_TO_READ_TOKENS` の値 (`no_pages`: 版面を持たない形、`no_pages_rendered`: 版面を持つ形からラスタ化器が 1 枚も作らなかった) で、enrichment-fastapi の OCR 応答の `skipped` と同じ閉じた集合。ワーカーは応答の値を読み替えずに写す |
81
+ | `{ kind: "superseded" }` | `superseded` | 終端段の時に、実行の版の行が文書の現在の行でなくなっていた (状態を写さない) |
82
+ | `{ kind: "recording_disabled" }` | `recording_disabled` | 終端段の時に、配備の文書の履歴の記録の切替が `false` だった |
83
+ | `{ kind: "recording_misconfigured" }` | `recording_misconfigured` | 終端段の時に、配備の切替が無いか `true` / `false` のどちらでもなかった (`false` と見分ける) |
76
84
 
77
85
  - `formatSkipReason(reason)` は `parseSkipReason` が等しい理由へ読み戻せる文字列だけを返し、文法で表せない理由 (書式外のフラグキー・未知の段キー・`NOTHING_TO_READ_TOKENS` に無い値・未知の種類) は `RangeError` を投げる。
78
86
  - `parseSkipReason(text)` は完全一致で照合し、文法の外の文字列 (種類を名乗らない素のフラグ名を含む) には `null` を返す。表示側は `null` のとき文字列をそのまま示す。
87
+ - `source_skipped:<step key>` が名指すのは流れの段 (`PIPELINE_STEP_KEYS`) だけで、終端段の鍵は文法の外 (`null`) である。
88
+
89
+ ### Terminal step / 終端段
90
+
91
+ 実行の流れの後に、ワーカーは文書の状態を捕捉する段を高々 1 つ記録する。鍵は `RUN_TERMINAL_STEP_KEY` (`record_document_state`) で、段の記録の鍵の語彙は `LEDGER_STEP_KEYS` (`PIPELINE_STEP_KEYS` の 9 つの後に終端段を足した 10 語) である。
92
+
93
+ - `PIPELINE_FLOWS` は終端段を名指さない。したがって流れの図と段の集計 (`PipelineStepMetricSchema.stepKey` は `PipelineStepKeySchema`) に終端段は現れない。
94
+ - 終端段は実行を失敗させないので、実行の `failedStepKey` (`PipelineRunRecordSchema` / `PipelineRunSummarySchema`) は流れの段 (`PipelineStepKeySchema`) だけを名指す。
95
+ - `PipelineStepRecordSchema` は終端段の行に次を検め、外れる行を拒む。成功した終端段の報告は `detail` 以外の全ての鍵が `null` で、`strategyId` と `httpStatus` も `null` (API を呼ばない)、`detail` はちょうど `{ outcome }` (`RunTerminalStepDetailSchema`、`outcome` は `RUN_TERMINAL_STEP_OUTCOMES` = `RECORDED` / `UNCHANGED` / `ALREADY_RECORDED`) で、状態の ID・連番・処理時間を持たない。
96
+ - 失敗した終端段の `errorCode` は `RUN_TERMINAL_STEP_ERROR_CODES` (`history_no_current_row` / `history_lock_timeout` / `history_write_failed`) の 3 つのどれかで、飛ばした終端段の `skipReason` は上の表の終端段の 3 種 (`superseded` / `recording_disabled` / `recording_misconfigured`) のどれかである (`PipelineStepRecordSchema` が検める)。
79
97
 
80
98
  ### Run record and summary / 実行の記録と要約
81
99
 
@@ -95,7 +113,7 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
95
113
 
96
114
  監査は API サーバーの中で走り、`td_integrity_audit_run` / `td_integrity_audit_quantity` / `td_integrity_audit_finding` へ記録する。ホストはその行を読み、次の形でコンソールへ渡す。記録の語彙 (下の表の `IntegrityStoreSchema` から `IntegrityRepairSkipReasonSchema` までの 12 の列挙と `IntegrityFindingItemClassSchema`) と区分の方針 (`INTEGRITY_CLASS_POLICY`) は各表の CHECK 制約の写しであり、実行の行の制約が持つ削除印の保持日数の範囲は、実行の見出しを検める `SYSTEM_PARAMETER_RANGES.INTEGRITY_TOMBSTONE_RETENTION_DAYS` の写しである。写しの一致はホストの試験が DDL を読んで確かめる (本パッケージはホストの DDL の置き場所を知らない)。
97
115
 
98
- 命令の語彙 (`IntegrityCommandSchema` / `IntegrityCommandFailureCodeSchema` と命令ごとのその部分集合) はコンソールの契約の持ち物で、DDL に写しを持たない。全てのスキーマは `.strict()` で、未知の鍵と鍵の欠落を拒む (最初の頁で省く `IntegrityFindingsQuerySchema.after` を除く)。`null` は宣言した項目 (測っていない・まだ無い) だけが持てる。
116
+ 命令の語彙 (`IntegrityCommandSchema` / `IntegrityCommandFailureCodeSchema` と命令ごとのその部分集合) はコンソールの契約の持ち物で、DDL に写しを持たない。全てのスキーマは `.strict()` で、未知の鍵と鍵の欠落を拒む (最初の頁で省く `IntegrityFindingsQuerySchema.after` と最初の回で省く `IntegrityCellResyncRequestSchema.after`、`sotDomain` の他の観測値の鍵をそのまま通す `IntegrityPlacementObservedSchema` を除く)。`null` は宣言した項目 (測っていない・まだ無い) だけが持てる。
99
117
 
100
118
  項目の間の規則の出所は 3 つ:
101
119
 
@@ -113,8 +131,8 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
113
131
  | --- | --- |
114
132
  | `IntegrityStoreSchema` | `QDRANT` / `NEO4J` |
115
133
  | `IntegrityScopeRoleSchema` | `PRODUCTION` / `VARIANT` / `LABEL` |
116
- | `IntegrityItemClassSchema` | 25 区分 (`EXPECTED`・`LIVE`・`HISTORY`・`TOMBSTONE`・`AWAITING_SUCCESSOR`・情報の 7 区分・不整合の 13 区分)。意味は監査の判定表 (S1 §6.5) が定める |
117
- | `IntegrityFindingItemClassSchema` | 所見を記録する 22 区分 (`EXPECTED`・`LIVE`・`HISTORY` を除く。`CK_td_integrity_audit_finding_vocabulary`)。所見を開けるのはこの区分の組だけ |
134
+ | `IntegrityItemClassSchema` | 27 区分 (`EXPECTED`・`LIVE`・`HISTORY`・`TOMBSTONE`・`AWAITING_SUCCESSOR`・情報の 7 区分・不整合の 15 区分)。意味は監査の判定表 (S1 §6.5) が定める |
135
+ | `IntegrityFindingItemClassSchema` | 所見を記録する 24 区分 (`EXPECTED`・`LIVE`・`HISTORY` を除く。`CK_td_integrity_audit_finding_vocabulary`)。所見を開けるのはこの区分の組だけ |
118
136
  | `IntegrityUnitSchema` | `POINT` / `NODE` / `CHUNK` / `DOCUMENT` |
119
137
  | `IntegrityDispositionSchema` | `EXPECTED` / `HEALTHY` / `RETAINED` / `INFORMATIONAL` / `DISCREPANCY` |
120
138
  | `IntegrityRepairActionSchema` | `NONE` / `PURGE` / `FLAG` / `REPROJECT` |
@@ -123,7 +141,7 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
123
141
  | `IntegrityVerdictSchema` | `CONSISTENT` / `INCONSISTENT` / `UNDETERMINED` |
124
142
  | `IntegrityPhaseSchema` | `QDRANT` / `NEO4J` / `DOCUMENTS` |
125
143
  | `IntegrityRepairOutcomeSchema` | `APPLIED` / `SKIPPED` / `FAILED` |
126
- | `IntegrityRepairSkipReasonSchema` | `RECLASSIFIED` / `IN_FLIGHT` / `DESTINATION_PENDING` / `BASIS_EXHAUSTED` / `PROJECTION_REFUSED` / `PIPELINE_FAILED` / `UNRECORDED` / `OUTSIDE` (後の 4 つは、文書の再投影で書き直す項目を、文書を再投影しないときに文書の所属で見送る理由: 前段の失敗・投影記録なし・投影の門が拒む・店が文書を期待しない (ドメインが不明・本番の戦略なし・その店の段が閉じている・生きたチャンクなし)) |
144
+ | `IntegrityRepairSkipReasonSchema` | `RECLASSIFIED` / `IN_FLIGHT` / `DESTINATION_PENDING` / `BASIS_EXHAUSTED` / `PROJECTION_REFUSED` / `PIPELINE_FAILED` / `UNRECORDED` / `OUTSIDE` (後の 4 つは、文書の再投影で書き直す項目を、文書を再投影しないときに文書の所属で見送る理由: `PIPELINE_FAILED` は前段の失敗、`UNRECORDED` は投影記録なし、`PROJECTION_REFUSED` は機能フラグか機密区分の方針が投影を拒む、`OUTSIDE` は店が文書を期待しない (ドメインが不明・本番の戦略なし・その店の段が閉じている・生きたチャンクなし)) |
127
145
 
128
146
  区分が扱いと処置を決める (`INTEGRITY_CLASS_POLICY`、`CK_td_integrity_audit_quantity_class_policy` の写し。表と各行は凍結してある):
129
147
 
@@ -133,12 +151,12 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
133
151
  | `LIVE` | `HEALTHY` | `NONE` |
134
152
  | `HISTORY`・`TOMBSTONE`・`AWAITING_SUCCESSOR` | `RETAINED` | `NONE` |
135
153
  | `IN_FLIGHT`・`UNPLACED`・`UNRECORDED`・`UNREFERENCED`・`CHANGED_AFTER_START`・`PIPELINE_FAILED`・`PROJECTION_REFUSED` | `INFORMATIONAL` | `NONE` |
136
- | `ORPHAN`・`TOMBSTONE_EXPIRED`・`STALE_REVISION`・`MISPLACED`・`OUT_OF_TIER` | `DISCREPANCY` | `PURGE` |
154
+ | `ORPHAN`・`TOMBSTONE_EXPIRED`・`STALE_REVISION`・`MISPLACED`・`OUT_OF_TIER`・`DETACHED`・`UNKEYED` | `DISCREPANCY` | `PURGE` |
137
155
  | `UNPROPAGATED_DELETE`・`UNMARKED_SUPERSEDED` | `DISCREPANCY` | `FLAG` |
138
- | `DETACHED`・`UNKEYED`・`VARIANT_FLAG_DRIFT` | `DISCREPANCY` | `NONE` |
139
- | `FLAG_DRIFT`・`MISSING`・`COUNT_MISMATCH` | `DISCREPANCY` | `REPROJECT` |
156
+ | `VARIANT_FLAG_DRIFT`・`UNKEYED_ENTITY` | `DISCREPANCY` | `NONE` |
157
+ | `FLAG_DRIFT`・`MISSING`・`COUNT_MISMATCH`・`UNPROJECTED` | `DISCREPANCY` | `REPROJECT` |
140
158
 
141
- `REPROJECT` は文書に働く。文書の区分 (`MISSING`・`COUNT_MISMATCH`) では文書を再投影し、項目の区分 (`FLAG_DRIFT`) では項目を文書の再投影で書き直し (修復済は文書の再投影が成功したことを表し、項目を読み直さない)、再投影しない文書の項目は理由 (`IntegrityRepairSkipReasonSchema`) を付けて見送る。`OUT_OF_TIER` は `ORPHAN` と同じく除き、その数は根拠の走査の組の件数を上限とする。
159
+ `REPROJECT` は文書に働く。文書の区分 (`MISSING`・`COUNT_MISMATCH` と、段が開いているのにその店の投影の記録も生きた項目も無い文書の `UNPROJECTED`) では文書を再投影し、項目の区分 (`FLAG_DRIFT`) では項目を文書の再投影で書き直し (修復済は文書の再投影が成功したことを表し、項目を読み直さない)、再投影しない文書の項目は理由 (`IntegrityRepairSkipReasonSchema`) を付けて見送る。`OUT_OF_TIER` は `ORPHAN` と同じく除き、形の不整合の `DETACHED` (親の辺の無い旧版のノード) と `UNKEYED` (鍵の無いか記録に収まらない鍵の項目) も除く。どの除去もその数は根拠の走査の組の件数を上限とする。`UNKEYED_ENTITY` (鍵の無い共有の `Entity` のノード) は報告だけ (共有のノードは他の系のマスタの鍵を持ちうる)。
142
160
 
143
161
  判定 (`IntegrityVerdictSchema`) は `DISCREPANCY` の量を数え、`CONSISTENT` になれるのは扱いに依らず全ての量が測れたときだけ (測れた不整合が 1 つでも正なら、他の量の未測定に依らず `INCONSISTENT`)。判定の規則は API サーバーが持ち、この契約は判定と量の突き合わせをしない。判定とタイルは単位 (`IntegrityUnitSchema`) の違う量を足さない。単位を混ぜた唯一の和は、不成功の修復の `repairAppliedItems` (除去したか印を付けた点とノードの数。処置が `PURGE` と `FLAG` の量の直した件数の和で、再投影で書き直した項目は数えない) である。
144
162
 
@@ -152,6 +170,8 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
152
170
  | `IntegrityPlacementObservedSchema` | `UNPLACED` と `OUT_OF_TIER` の所見の `observed` を読む形。`sotDomain` (SoT が項目の現行の文書に与えるドメイン) は必須で文字列か `null`、他の観測値の鍵はそのまま通す。`null` は文書がドメインを持たないこと (再同期が導き直す)、`UNPLACED` の文字列は本番の戦略の無いドメイン、`OUT_OF_TIER` の文字列は戦略がその店の段を閉じたドメイン (`OUT_OF_TIER` は必ず文字列を持つ)。組はドメインを混ぜるので、ドメインは行ごとの値で組の値ではない。SoT が書いた値の写しなので空の文字列も拒まない |
153
171
  | `IntegrityFindingPageSchema` | 行は `sequence` の昇順で重複しない。`nextAfter` は `null` か、この頁の最後の行の `sequence`。`recordedCount` は `totalCount` と突き合わせない (書き手は鍵の無いグラフのノードを数えた後に標本を取るので、その間に作られたノードで標本が全数を超えうる) |
154
172
  | `IntegrityFindingsQuerySchema` | `itemClass` は所見を記録する区分 (`IntegrityFindingItemClassSchema`) だけ。`limit` は必須で 1〜`INTEGRITY_FINDINGS_PAGE_LIMIT_MAX` (100) の整数 (0・負・`NaN`・文字列を拒む)。`after` は 1 以上の整数で、最初の頁では省く |
173
+ | `IntegrityCellResyncRequestSchema` | 一括の再同期の 1 回分の要求 (`runUid`・`store`・`scopeKey`・`itemClass`・`after`)。`itemClass` は `UNRECORDED` だけ (再同期が片付ける唯一の区分。店は文書の生きた項目を持つがその店の投影の記録が無い)。`after` は 1 以上の整数で、最初の回では省く。1 回の件数は要求が選ばず、`INTEGRITY_FINDINGS_PAGE_LIMIT_MAX` (100) に固定する。ホストはテナントの直近の完了した実行にだけ答え、組の所見を記録順に読む |
174
+ | `IntegrityCellResyncResultSchema` | 1 回分の答え (`requeued`・`skipped: { metadataId, reason }[]`・`nextAfter`)。再投入の数と据え置いた文書の数の和 (読んだ文書の数) は 100 以下で、`nextAfter` はちょうど 100 を読んだときだけ在る (最後に読んだ記録順。100 に満たない回は組の終わり)。据え置いた文書は重複しない |
155
175
 
156
176
  - コンソールが監査の実行について送る命令は `IntegrityCommandSchema` (`start` / `cancel`)。命令と失敗の語彙はコンソールの契約の持ち物で、DDL に写しを持たない。
157
177
  - 開始・中止の失敗は `IntegrityCommandFailure` (`{command, code, status: 300〜599 の整数 | null}`、`command` で分かれる和の型) で運ぶ。`code` はコンソールが示す文ごとに 1 つ (`IntegrityCommandFailureCodeSchema`) で、各命令はその部分集合だけを持つ (もう一方の命令だけの語彙は `code` の問題として拒み、型でも持てない):
@@ -172,6 +192,76 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
172
192
 
173
193
  - ホストのストアが開始・中止に答える形は `IntegrityCommandReply` (`{ok: true, runUid}` か `{ok: false, status, errorCode: int | null}`) だけで、上流の本文の文面を運ばない。失敗の `status` は転送を辿った応答の成功でない状態 (300〜599)。
174
194
 
195
+ ## Document history contract / 文書の差分履歴の契約
196
+
197
+ 文書の再同期・再取り込み・新しい版のたびに、ホストの記録器が文書の不変の状態の鎖を書き、読み手が履歴と比較を返す (S1 §8.19)。本パッケージはその契約と、記録器と読み手が共有する差分エンジンを持つ。記録器の結果 (`DocumentStateRecordOutcome`) はホストの型で、ここに無い (どの答えも運べない状態の識別子を持つ)。
198
+
199
+ ### Versioned constants / 版付きの定数
200
+
201
+ | Constant | Value | Meaning |
202
+ | --- | --- | --- |
203
+ | `DIFF_ENGINE_VERSION` | 1 | エンジンの版。捕捉の時の計数と共に凍結する |
204
+ | `DIFF_CONTEXT_LINES` | 3 | 塊の文脈の行の数 |
205
+ | `HISTOGRAM_MAX_OCCURRENCES` | 64 | 錨にできる行の、区間の古い側の出現の上限 |
206
+ | `DIFF_REGION_CELL_BOUND` | 1,000,000 | 錨の無い区間を Myers で比べる升目の上限 (超えれば区間ごと置き換える) |
207
+ | `INLINE_REFINE_MAX_GRAPHEMES` / `INLINE_REFINE_MIN_SIMILARITY` | 4,096 / 0.3 | 行の中の精緻化を行う書記素の数の上限と類似度の下限 |
208
+ | `INLINE_REFINE_MAX_EDIT_DISTANCE` | 1,024 | 行の中の精緻化を行う対の編集距離 (削除と追加の書記素の和) の上限 |
209
+ | `INLINE_REFINE_CELL_BUDGET` | 67,108,864 (2^26) | 1 つの本文の差分の中で精緻化に使える手間の総量 (升目) |
210
+ | `STRUCTURED_DATA_ARRAY_CELL_BOUND` | 16,777,216 (2^24) | 1 つの構造化データの差分の中で配列の要素を比べる升目の総量。配列ごとに中ほど (共通の前後を除いた古い要素の数 × 新しい要素の数) を消費し、払えない配列は全体を 1 つの `replace` にする |
211
+ | `DIFF_LINE_PAGE_MAX` | 500 | 差分の行の頁の上限 (`DiffLinePageLimitSchema` は 1〜500 の整数) |
212
+ | `DOCUMENT_CHANGE_FEED_PAGE_MAX` / `DOCUMENT_CHANGE_FEED_PAGE_SIZE` | 50 / 50 | 直近の変化の一覧の頁 (`DocumentChangeFeedLimitSchema` は 1〜50 の整数) |
213
+ | `DOCUMENT_STATE_LOCK_TIMEOUT_MS` | 10,000 | 1 文書の捕捉が文書の履歴の錠を待てる長さ |
214
+ | `CHUNK_MANIFEST_VERSION` | 1 | チャンクの目録の形の版 |
215
+
216
+ ### Vocabularies / 語彙
217
+
218
+ | Vocabulary | Values |
219
+ | --- | --- |
220
+ | `DOCUMENT_FACETS` | `classification` / `metadata` / `labels` / `tags` / `structured_data` / `text` / `summary` / `chunks` / `assets` (表示の順) |
221
+ | `DOCUMENT_STATE_CAUSES` | `RUN` / `PRE_WRITE` / `MANUAL` / `BACKFILL` |
222
+ | `DOCUMENT_STATE_RUN_OUTCOMES` | `SUCCEEDED` / `FAILED` (ワーカーが実行をどう分類したか) |
223
+ | `CHUNK_CHANGE_KINDS` / `CHUNK_PAIRINGS` | `ADDED` / `REMOVED` / `MODIFIED` / `MOVED`、変更の対の規則 `clause` / `breadcrumbs` |
224
+ | `CHUNK_BODY_FIDELITIES` | `EXACT` / `WHITESPACE_NORMALIZED` / `UNVERIFIED` |
225
+ | `RESTRICTED_MARK_SUBJECTS` | `run` / `ingest` / `failure` / `state` / `change` |
226
+ | `LINE_ENDINGS` | `LF` / `CRLF` / `CR` / `MIXED` / `NONE` |
227
+
228
+ 語彙のうち DDL の CHECK 制約が持つもの (面・契機・実行の分類・機密区分・本文の出所) の一致は、ホストの試験が DDL を読んで確かめる。
229
+
230
+ ### Facet values and counts / 面の値と計数
231
+
232
+ - `DocumentFacetValuesSchema` は 1 つの状態の全ての面の正準の値で、鍵は面の綴りそのもの (`structured_data` を含む)。集合の面は正準の順 (ラベルは `labelKey`、タグは文字列、派生の子は `(assetType, assetIndex)`、どれも UTF-16 の符号単位の順で `compareCodeUnits` / `compareAssetKeys` が比べる) で鍵を重ねない。タグの `null` (列が `NULL`) と空の配列、本文の `null` (抽出本文が無い) と空の本文は別の値である。
233
+ - `ChunkManifestSchema` (`CHUNK_MANIFEST_VERSION`) は子チャンクを `index` の昇順に、親を子から初めて辿った順の序数で持ち、行と版に依る値 (親とチャンクの uid・`metadata_id`) を持たない。同じ本文を同じ実装でチャンク化すれば、どの行・版でも目録のバイト列が等しい。チャンクを持たない状態の目録は `null` で、空の目録は無い。
234
+ - `FacetChangeCountsSchema` は変わった 1 つの面の計数で、当てはまる計数 (`FACET_APPLICABLE_COUNTS`) は 0 以上の整数、他は `null` である (`CK_td_file_state_facet_change_counts` の写し)。
235
+
236
+ ### Comparison and line pages / 比較と行の頁
237
+
238
+ - `DocumentComparisonSchema` は全ての面を表示の順に `UNCHANGED` か面ごとの差分 (`FacetDiffSchema`) で持ち、計算したエンジンの版 (`diffEngineVersion`) を持つ。分類とメタデータは項目の変化 (`FieldChange`)、ラベルと派生の子は鍵付き集合 (`KeyedItem` の追加・削除と `KeyedItemChange` の変更)、タグは集合、構造化データは RFC 6902 の操作 (`JsonPatchOperationSchema`: `add` / `remove` / `replace` だけで、取り除く値を `previous` に持つ)、本文と要約は索引 (`TextDiffIndexSchema`: 属性の変化・統計・塊の索引)、チャンクは対応付け (`ChunkChangeSchema`、片側ごとに読み手が確かめた忠実度) と `textUnchangedChunkingChanged` である。
239
+ - 本文・要約・チャンクの本文の行は比較に含めず、`DiffLinePageSchema` (`{ lines, next }`、`next` は塊の次の行の位置か `null`) で頁ごとに読む。チャンクの対の本文は両方の全体を 1 つの塊 (塊 `0`) にする。
240
+
241
+ ### History, change feed and restricted marks / 履歴・直近の変化・隔離の印
242
+
243
+ - `DocumentHistorySchema` は現在の行 (隔離でない)、読める版の行 (新しい順、現在の版はちょうど 1 つ)、状態の一覧 (`DocumentStateEntrySchema`: `ReadableEntry<DocumentStateSummary>` か `RestrictedStateMark`、確定の時刻の新しい順) と実行の一覧 (`DocumentRunEntrySchema`: `ReadableEntry<PipelineRunRecord>` か `RestrictedRunMark`) を持つ。
244
+ - `DocumentStateSummarySchema` は連番を持たない。`previousStateId`・計数・エンジンの版・`modelOnlyChange` は直前の状態が読める時だけ値を持ち、最初の状態と直前を読めない状態はどちらも `previousStateId: null` である。`RUN` の状態だけが `runId` と `runOutcome` を持つ。
245
+ - 隔離の印 (`RestrictedRunMarkSchema` / `RestrictedIngestMarkSchema` / `RestrictedFailureMarkSchema` / `RestrictedStateMarkSchema` / `RestrictedChangeMarkSchema`) は種類・項目自身の時刻・結果か状態だけを持ち (取り込みの印の `syncStatus` は `EnrichmentSyncStatusSchema` の値か、エンリッチメントの行の無い文書 (取り込みがメタデータの行の後に止まった) では `null`、失敗の印の `syncStatus` はその失敗の状態 `PipelineFailureStatusSchema`)、どれも `.strict()` で識別に使える鍵を 1 つでも持てば拒む。一覧の要素は `kind` で分かれる判別和 (`z.discriminatedUnion("kind", [readableEntrySchema(<項目>), <一覧の印>])`) で、印は一覧と合う `subject` だけを許す。ホストの一覧 (取り込み・失敗) は `readableEntrySchema` と印の schema から同じ形の和を作り、直近の実行の表は `RecentPipelineRunEntrySchema` を使う。
246
+ - `DocumentChangeFeedPageSchema` は `{ rows, next }` で保存量を持たない。行は `ReadableEntry<DocumentChangeFeedEntry>` か `RestrictedChangeMark` (到着の状態の時刻の新しい順)。`next` は頁の最後の行 (印を含む) の到着の状態の位置で (位置の時刻は最後の行の時刻と同じ時点でなければならない)、`encodeChangeFeedCursor({ settledAt, id })` が `{ id, settledAt }` の正準の JSON の base64url に書き、`decodeChangeFeedCursor` は自分が書く文字列そのものだけを読み戻す (壊れた base64url・UTF-8 でない・JSON でない・形の外・別の綴りは `null`)。
247
+ - 手動の記録の答え `DocumentCaptureAnswerSchema` は `{ outcome: "RECORDED" | "UNCHANGED" }` だけである。
248
+
249
+ ### Diff engine v1 / 差分エンジン v1
250
+
251
+ - `summarizeTransition(transitions)` は記録器の入口で、変わった面ごとの古い値と新しい値 (`FacetTransition`) から、変わった面ごとの計数の行を表示の順に返す。面が無い・同じ面が 2 度・値の等しい面は `RangeError`。
252
+ - `compareStates(from, to)` は読み手の入口で、両側の面の値と、目録の子ごとに読み手が確かめた忠実度 (`ComparedState`) から比較を返す。行の頁は `textFacetDiff` / `summaryFacetDiff` / `diffChunkBodies` の差分 (`TextDiff`) を `diffLinePage` で読み、索引は `textDiffIndex` で読む (比較と同じ差分なので塊の番号が一致する)。
253
+ - 本文: 行は `\r\n`・`\r`・`\n` で分け (改行は内容でなく属性で、改行だけの変換は 1 つの属性の変化)、共通の前後を除いて histogram 差分 (古い側で出現の最も少ない行を錨にし、連なりはその中で最も稀な行の出現で競い、同点は長い連なり、次に区間の中央に近い連なり、次に新しい側で前から始まる連なり、次に古い側で前から始まる連なりを選ぶ) で区間に分け、錨の無い区間は両側が共有する行の上の Myers で対応付ける (升目が上限を超えれば区間ごと置き換え)。手順は常に正しく、最小は約束せず、同点は削除を先にする。間の等しい行が文脈の 2 倍以下の塊は繋ぐ。
254
+ - 行の中: 変化の塊の i 番目の削除の行と i 番目の追加の行を書記素 (`Intl.Segmenter`) で比べ、両方が上限以下で、編集の間の 1 書記素以下の等しい部分を編集へ繋いだ後の類似度が下限以上なら区切る。最長共通部分列の長さ (ビット並列で測る) が下限に届かない対は Myers を走らせずに外す (結果は変わらない)。類似度は `2 × 等しい書記素 / (古い書記素 + 新しい書記素)` で、両方が空なら `null`。
255
+ - 精緻化の手間の上限 (エンジン v1 の一部): 対の編集距離 (最長共通部分列から Myers の前に決まる) が `INLINE_REFINE_MAX_EDIT_DISTANCE` を超える対は精緻化しない。1 つの本文の差分 (面の古い値と新しい値の 1 組。本文・要約・チャンクの本文の差分はそれぞれ満ちた予算で始まる) は `INLINE_REFINE_CELL_BUDGET` 升の予算を持ち、対を決まった順 (変化の塊の順、その中は i 番目の削除と i 番目の追加) に見て、Myers を走らせる対は自分の升目のうち Myers が探る帯 (`(N + M) × 編集距離`) を消費する。残りに収まらない対が現れた時に予算は尽き、その対から後ろの対は精緻化しない。精緻化しない対は、類似度が下限に届かない対と同じく行全体の削除と追加として数える (出力の形は変わらない)。どちらの上限も入力だけで決まるので、同じ入力は常に同じ計数になる。上限 1,024 は 731 書記素以下の行の対に決して掛からず (精緻化できる対の距離は両側の書記素の和の 0.7 倍以下)、予算は通常の編集 (数行の編集・1 行の編集・短い行の OCR の読み直し・長い段落の誤字の修正) では尽きない。
256
+ - 頁: 状態の頁の区切り (`[{ start, end, page_number }]`、符号位置) の上で各行の始まりを二分探索し、削除の行は古い側、他は新しい側の頁を付ける。頁を名指さない区間 (シート・スライド) と配列でない区切りは頁を持たない。
257
+ - チャンク: (1) ハッシュの列の最長共通部分列が錨 (変わらない。番号のずれは移動でない)、(2) 錨の外の同じハッシュを出現ごとに順に `MOVED`、(3) 残りのうち各側にちょうど 1 度だけ現れる非 NULL の条項を `MODIFIED` (`clause`)、(4) 錨の間の隙間ごとに見出しの等しい残りを位置の順に `MODIFIED` (`breadcrumbs`)、(5) 残りは `REMOVED` / `ADDED`。項目は新しいチャンクの位置の順で、削除は削除された隙間の始まりに置く。
258
+ - 構造化データ: オブジェクトは鍵の順に再帰し、配列は要素の正準の JSON の最長共通部分列で対にし (1 回の差分は配列を辿る順 (鍵の順の深さ優先、要素の順) に `STRUCTURED_DATA_ARRAY_CELL_BOUND` 升の予算から各配列の中ほどの升目を払い、払えない配列は要素ごとに比べず、配列全体を 1 つの `replace` にする)、隙間の同じ位置の要素はどちらもオブジェクトかどちらも配列なら再帰し、それ以外は削除して追加する。操作を順に古い値へ当てると新しい値になる。
259
+ - `codePointSlicer(text)` はチャンクの区間 (Python の符号位置) を 1 度の走査で作る表で切り、本文の外で終わる区間は `null`。`String.prototype.slice` を区間に直接使わない。`stripWhitespace` は JavaScript の `\s` (`u` フラグ) を除き、記録器の `whitespaceFreeHash` と読み手の照合が共に使う。忠実度の SHA-256 はホストが計算する (本パッケージはブラウザでも読み込まれるのでハッシュを持たない)。
260
+
261
+ ### Canonical JSON / 正準の JSON
262
+
263
+ `canonicalJson(value)` は鍵をどの深さでも UTF-16 の符号単位の昇順に並べ、文字列の外に空白を置かず、文字列と数を `JSON.stringify` の書き方で書き、有限でない数は `RangeError` で拒む。1 つの値は 1 つの文字列だけを持ち、内容と状態の digest と規程の衝突の事実のハッシュはこの上で取る。
264
+
175
265
  ## System parameter ranges / システムパラメータの値域
176
266
 
177
267
  | Key | Range |
@@ -194,9 +284,11 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
194
284
  ## Installation / インストール
195
285
 
196
286
  ```bash
197
- pnpm add @aiquants/enrichment-core
287
+ pnpm add @aiquants/enrichment-core 'zod@^3.25.0'
198
288
  ```
199
289
 
290
+ zod `^3.25.0` は peer dependency (素の `zod` は範囲外の `latest` (4.x) を入れる)。
291
+
200
292
  ## Usage / 利用例
201
293
 
202
294
  ```typescript
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var M=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ut=Object.prototype.hasOwnProperty;var mt=(e,t)=>{for(var n in t)M(e,n,{get:t[n],enumerable:!0})},yt=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of dt(t))!ut.call(e,s)&&s!==n&&M(e,s,{get:()=>t[s],enumerable:!(i=pt(t,s))||i.enumerable});return e};var ft=e=>yt(M({},"__esModule",{value:!0}),e);var xn={};mt(xn,{AmountEntrySchema:()=>me,BaseEnrichmentClient:()=>A,BodySourceSchema:()=>Ze,BoundingBoxSchema:()=>Ct,CIRCUIT_BREAKER_SERVICES:()=>ae,CanonicalDomainKeySchema:()=>Ee,ChapterSegmentSchema:()=>de,ChunkingStrategySchema:()=>xt,CircuitBreakerStatusSchema:()=>bt,ConfidentialityLevelSchema:()=>D,DISPATCH_DEGRADATION_REASONS:()=>ce,DOCUMENT_KINDS:()=>Y,DOCUMENT_KIND_LABELS:()=>Dt,DocumentKindSchema:()=>ne,DocumentStructuredDataSchema:()=>Tt,ENRICHMENT_STAGES:()=>re,EnrichmentClient:()=>H,EnrichmentClientError:()=>g,EnrichmentSyncStatusSchema:()=>Nt,FILTERABLE_CONFIDENTIALITY_LEVELS:()=>St,FileUriSchema:()=>At,GRAPH_INDEX_LIMITS:()=>Cn,GraphSearchHitSchema:()=>he,INTEGRITY_CLASS_POLICY:()=>we,INTEGRITY_COMMAND_CODES:()=>W,INTEGRITY_FINDINGS_PAGE_LIMIT_MAX:()=>Be,IntegrityActiveRunSchema:()=>$e,IntegrityAuditOverviewSchema:()=>Zt,IntegrityCancelFailureCodeSchema:()=>qe,IntegrityCommandFailureCodeSchema:()=>k,IntegrityCommandFailureSchema:()=>pn,IntegrityCommandReplySchema:()=>un,IntegrityCommandSchema:()=>X,IntegrityDispositionSchema:()=>ve,IntegrityFindingItemClassSchema:()=>Fe,IntegrityFindingPageSchema:()=>an,IntegrityFindingSchema:()=>Ve,IntegrityFindingsQuerySchema:()=>sn,IntegrityItemClassSchema:()=>Q,IntegrityPhaseSchema:()=>ze,IntegrityPlacementObservedSchema:()=>nn,IntegrityQuantitySchema:()=>je,IntegrityRepairActionSchema:()=>ke,IntegrityRepairOutcomeSchema:()=>Ke,IntegrityRepairSkipReasonSchema:()=>He,IntegrityRunHeaderSchema:()=>v,IntegrityRunModeSchema:()=>Me,IntegrityRunStatusSchema:()=>Ue,IntegrityScopeRoleSchema:()=>Pe,IntegrityStartFailureCodeSchema:()=>Xe,IntegrityStoreSchema:()=>J,IntegrityUnitSchema:()=>Le,IntegrityVerdictSchema:()=>Ge,LOCAL_DEGRADATION_REASONS:()=>se,MIME_KIND_RULES:()=>Ae,MODE_TIERS:()=>N,ModelProviderSchema:()=>oe,NOTHING_TO_READ_TOKENS:()=>tt,NothingToReadTokenSchema:()=>nt,PIPELINE_FLOWS:()=>Ne,PIPELINE_PHASES:()=>Pt,PIPELINE_STEPS:()=>$,PIPELINE_STEP_KEYS:()=>j,PipelineRunRecordSchema:()=>hn,PipelineRunStatusSchema:()=>Je,PipelineRunSummarySchema:()=>In,PipelineStepKeySchema:()=>x,PipelineStepMetricSchema:()=>Rn,PipelineStepRecordSchema:()=>it,PipelineStepStatusSchema:()=>Qe,PipelineTriggerSchema:()=>We,QUARANTINED_CONFIDENTIALITY_LEVEL:()=>O,REMOTE_DEGRADATION_REASONS:()=>le,SEARCH_DEGRADATION_REASONS:()=>_t,SEARCH_MODES:()=>G,SEARCH_PARAM_LIMITS:()=>Et,SYSTEM_PARAMETER_RANGES:()=>b,SearchHitSchema:()=>Se,SearchMetadataSchema:()=>fe,SearchModeSchema:()=>ye,SearchRequestSchema:()=>z,SearchResponseSchema:()=>K,StageProvenanceSchema:()=>et,TenantIdSchema:()=>pe,TranscriptSegmentSchema:()=>ue,assertBoundedSystemParameter:()=>Kt,assertSystemParameterInRange:()=>zt,classifyDocumentKind:()=>Ot,comparePhases:()=>kt,enrichmentStage:()=>Nn,flowFor:()=>Ft,flowStepGates:()=>Lt,formatSkipReason:()=>yn,generateUuidV7:()=>Tn,integrityCommandFailureCodeOf:()=>dn,isEnrichmentStageKey:()=>An,isStrictlyEarlier:()=>T,isValidUuidV7:()=>lt,modeFusesRankings:()=>Rt,modeNeedsRemoteTiers:()=>ht,modeScoreIsSimilarity:()=>It,narrowModeToAllowedTiers:()=>gt,orderedSteps:()=>vt,parseSkipReason:()=>ot,uuidv7ToDate:()=>bn});module.exports=ft(xn);var g=class extends Error{statusCode;responseBody;parsedBody;constructor(t,n,i,s){super(t),this.name="EnrichmentClientError",this.statusCode=n,this.responseBody=i,this.parsedBody=s}},A=class{baseUrl;apiKey;fetchFn;timeoutMs;constructor(t){if(!t||typeof t.baseUrl!="string"||t.baseUrl.trim().length===0)throw new Error("baseUrl is required and must be a non-empty string for EnrichmentClient.");let n=t.baseUrl.trim().replace(/\/$/,"");if(t.apiKey&&n.startsWith("http://")&&!n.includes("localhost")&&!n.includes("127.0.0.1"))throw new Error("Security Violation: Transmitting Bearer tokens over unencrypted HTTP to non-localhost hosts is strictly prohibited.");this.baseUrl=n,this.apiKey=t.apiKey,this.fetchFn=t.fetchFn??fetch,this.timeoutMs=t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:3e4}async request(t,n,i){let s=`${this.baseUrl}${t}`,c={Accept:"application/json","Content-Type":"application/json","X-Tenant-Id":n};this.apiKey&&(c.Authorization=`Bearer ${this.apiKey}`);let d=new AbortController,m=setTimeout(()=>d.abort(),this.timeoutMs),f;try{f=await this.fetchFn(s,{method:"POST",headers:c,body:JSON.stringify(i),signal:d.signal})}catch(y){let I=y instanceof Error?y.message:String(y);throw new g(`Network request failed for POST ${s}: ${I}`,0,"")}finally{clearTimeout(m)}if(!f.ok){let y=await f.text().catch(()=>""),I;try{I=JSON.parse(y)}catch{}throw new g(`API request failed with status ${f.status}: ${y}`,f.status,y,I)}let R=await f.text().catch(()=>"");if(R.trim().length!==0)try{return JSON.parse(R)}catch(y){let I=y instanceof Error?y.message:String(y);throw new g(`Failed to parse response JSON from ${s}: ${I}`,f.status,R)}}};var r=require("zod");var U=require("zod"),oe=U.z.enum(["google_cloud","google_vision","yomitoku_local","faster_whisper_local","google_speech","ollama_local","openai","anthropic","azure_openai","bedrock","custom_openai_compatible"]),D=U.z.enum(["PUBLIC","INTERNAL","DEPARTMENT","CONFIDENTIAL","RESTRICTED"]),O="RESTRICTED";var Et={rrfK:{min:1,max:200,default:60},alpha:{min:0,max:1,default:.7},threshold:{min:0,max:1},limit:{min:1,max:50,default:10}},ie=D.options.filter(e=>e!==O);if(ie.length===0)throw new Error("The confidentiality vocabulary left nothing filterable after removing the quarantined level; a validator built from this list would reject every request.");var St=ie,G=["KEYWORD","SPARSE","DENSE","HYBRID","GRAPH_TRAVERSE"],N={KEYWORD:{dense:!1,sparse:!1,graph:!1,lexical:!0},SPARSE:{dense:!1,sparse:!0,graph:!1,lexical:!1},DENSE:{dense:!0,sparse:!1,graph:!1,lexical:!1},HYBRID:{dense:!0,sparse:!0,graph:!0,lexical:!0},GRAPH_TRAVERSE:{dense:!1,sparse:!1,graph:!0,lexical:!1}};function ht(e){let t=N[e];return t.dense||t.sparse||t.graph}function It(e){let t=N[e];return t.dense&&!t.sparse}function gt(e,t){let n=N[e],i=(n.dense||n.sparse)&&t.vector,s=n.graph&&t.graph;return i||s?i?s?{mode:e,discardGraph:!1}:n.dense&&n.sparse?{mode:e,discardGraph:!0}:{mode:n.dense?"DENSE":"SPARSE",discardGraph:!1}:{mode:"GRAPH_TRAVERSE",discardGraph:!1}:null}function Rt(e){let t=N[e];return[t.dense,t.sparse,t.graph,t.lexical].filter(Boolean).length>1}var ae=["vector","graph"],se=["empty_query","caller_token_unavailable","time_window_unsupported"],le=["vector_tier_not_configured","graph_tier_not_configured","no_active_vector_collection","vector_collections_missing"],ce=["remote_tiers_unavailable","remote_tiers_timed_out","remote_tiers_refused_caller","remote_tiers_rejected_request","remote_tiers_failed","remote_tiers_not_executed","vector_search_disabled","graph_search_disabled"],_t=[...se,...le,...ce,...ae.map(e=>`circuit_breaker_open:${e}`)];var pe=r.z.string().trim().min(1,"tenant_id must be a non-empty string"),At=r.z.string().trim().min(1,"file_uri must be a non-empty string"),Nt=r.z.enum(["PENDING","EXTRACTING","ENRICHING","PROJECTING","SYNCED","FAILED_EXTRACT","FAILED_ENRICH","FAILED_VECTOR","FAILED_GRAPH"]),Ct=r.z.object({page:r.z.number().int().positive().optional(),x:r.z.number().nonnegative().optional(),y:r.z.number().nonnegative().optional(),width:r.z.number().positive().optional(),height:r.z.number().positive().optional(),start_sec:r.z.number().nonnegative().optional(),end_sec:r.z.number().nonnegative().optional(),frame_index:r.z.number().int().nonnegative().optional(),timestamp_sec:r.z.number().nonnegative().optional(),scene_confidence:r.z.number().min(0).max(1).optional()}),de=r.z.object({title:r.z.string().trim().min(1),start_sec:r.z.number().nonnegative(),end_sec:r.z.number().nonnegative(),summary:r.z.string()}),ue=r.z.object({start_sec:r.z.number().nonnegative(),end_sec:r.z.number().nonnegative(),speaker:r.z.string().trim().min(1),text:r.z.string()}),me=r.z.object({label:r.z.string(),value:r.z.number(),currency:r.z.string()}),Tt=r.z.object({document_type:r.z.string().optional(),title:r.z.string().optional(),organization:r.z.string().optional(),key_entities:r.z.array(r.z.string()).optional(),dates:r.z.array(r.z.string()).optional(),amounts:r.z.array(me).optional(),media_type:r.z.enum(["video","audio"]).optional(),duration_sec:r.z.number().nonnegative().optional(),chapters:r.z.array(de).optional(),transcript_segments:r.z.array(ue).optional()}),bt=r.z.enum(["CLOSED","OPEN","HALF_OPEN"]),ye=r.z.enum(G),fe=r.z.object({circuit_breaker_status:r.z.string(),quality_tier:r.z.string(),latency_ms:r.z.number().nonnegative(),total_hits:r.z.number().int().nonnegative(),fallback_applied:r.z.boolean(),degraded_reason:r.z.string().nullable()}),Ee=r.z.enum(["CONTRACT_LEGAL","EMAIL_THREAD","DAILY_REPORT","FINANCIAL_REPORT","TECHNICAL_SPEC","MASTER_DATA","MEDIA_ASSET","GENERAL_DOCUMENT"]),xt=r.z.enum(["hierarchical","conversation","section","fixed_size","table_aware","semantic","none","multimodal"]),Se=r.z.object({metadata_id:r.z.number().int().positive(),chunk_index:r.z.number().int().nonnegative(),text:r.z.string(),score:r.z.number()}),he=r.z.object({metadata_id:r.z.number().int().positive(),relation:r.z.string(),target_name:r.z.string()}),z=r.z.object({query:r.z.string().trim().min(1,"query must not be empty"),tenant_id:pe,domain_key:Ee.optional(),limit:r.z.number().int().positive().optional(),department_id:r.z.number().int().positive().optional(),search_mode:ye.optional(),strategy_id:r.z.number().int().positive().optional()}).strict(),K=r.z.object({hits:r.z.array(Se),graph_hits:r.z.array(he),tiers:r.z.record(r.z.string(),r.z.boolean()),metadata:fe});var H=class extends A{async search(t){let n=z.parse(t),i=await this.request("/ai/search/hybrid",n.tenant_id,n);return K.parse(i)}};var Y=["email","pdf","office","image","media","text","google_native","other"],Dt={email:"\u30E1\u30FC\u30EB",pdf:"PDF",office:"Office \u6587\u66F8",image:"\u753B\u50CF",media:"\u97F3\u58F0\u30FB\u52D5\u753B",text:"\u30C6\u30AD\u30B9\u30C8",google_native:"Google \u30CD\u30A4\u30C6\u30A3\u30D6",other:"\u305D\u306E\u4ED6"},Ae=[["message/rfc822","email"],["application/pdf","pdf"],["application/vnd.openxmlformats-officedocument.*","office"],["application/msword","office"],["application/vnd.ms-excel","office"],["application/vnd.ms-powerpoint","office"],["application/vnd.google-apps.*","google_native"],["image/svg+xml","text"],["image/emf","other"],["image/x-emf","other"],["image/wmf","other"],["image/x-wmf","other"],["image/*","image"],["audio/*","media"],["video/*","media"],["text/*","text"],["application/json","text"],["application/xml","text"]];function Ot(e){let t=(e.split(";")[0]??"").trim().toLowerCase();for(let[n,i]of Ae)if(n.endsWith("*")?t.startsWith(n.slice(0,-1)):t===n)return i;return"other"}var j=["delete_child_assets","extract_text","analyze_media","extract_assets","ocr_children","ocr_document","resolve_body","enrich_document","project_to_indexes"],Pt=["EXTRACTING","ENRICHING","PROJECTING"],B=e=>({featureFlagKey:e,whenClosed:"skip",failureStatus:null}),Ie=(e,t)=>({featureFlagKey:e,whenClosed:"fail",failureStatus:t}),$={delete_child_assets:{key:"delete_child_assets",label:"\u65E7\u7248\u306E\u5B50\u30A2\u30BB\u30C3\u30C8\u524A\u9664",description:"\u3053\u306E\u7248\u3088\u308A\u524D\u306E\u7248\u304C\u751F\u3093\u3060\u5B50\u30A2\u30BB\u30C3\u30C8\u3092\u4FDD\u7BA1\u5C64\u3068\u7D22\u5F15\u304B\u3089\u5916\u3059\u3002",endpoint:"/ai/assets/delete",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:null,fanOut:null},extract_text:{key:"extract_text",label:"\u6587\u5B57\u5C64\u306E\u62BD\u51FA",description:"\u6587\u66F8\u304C\u6301\u3064\u6587\u5B57\u5C64 (PDF \u306E\u6587\u5B57\u30FBOffice \u306E\u672C\u6587\u30FB\u30E1\u30FC\u30EB\u306E\u672C\u6587\u3068\u898B\u51FA\u3057) \u3092\u8AAD\u307F\u3001\u4F4D\u7F6E\u60C5\u5831\u3068\u5171\u306B\u4FDD\u5B58\u3059\u308B\u3002",endpoint:"/ai/enrichment/extract",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:null,fanOut:null},analyze_media:{key:"analyze_media",label:"\u30E1\u30C7\u30A3\u30A2\u89E3\u6790",description:"\u97F3\u58F0\u30FB\u52D5\u753B\u3092\u8EE2\u5199\u3057\u3001\u767A\u8A71\u533A\u9593\u4ED8\u304D\u306E\u30C1\u30E3\u30F3\u30AF\u3068\u30AD\u30FC\u30D5\u30EC\u30FC\u30E0\u6570\u3092\u8A18\u9332\u3059\u308B\u3002",endpoint:"/ai/media/analyze",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[B("ENABLE_MEDIA_ANALYSIS")],capability:"transcription",fanOut:null},extract_assets:{key:"extract_assets",label:"\u5B50\u30A2\u30BB\u30C3\u30C8\u306E\u62BD\u51FA",description:"\u57CB\u3081\u8FBC\u307F\u753B\u50CF\u3084\u30E1\u30FC\u30EB\u306E\u6DFB\u4ED8\u3092\u5B50\u30A2\u30BB\u30C3\u30C8\u3068\u3057\u3066\u5207\u308A\u51FA\u3057\u3001\u6587\u66F8\u306E\u96A3\u306B\u4FDD\u7BA1\u3057\u3066\u767B\u9332\u3059\u308B\u3002",endpoint:"/ai/assets/extract",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[B("ENABLE_ASSET_EXTRACTION")],capability:"asset_extraction",fanOut:null},ocr_children:{key:"ocr_children",label:"\u5B50\u30A2\u30BB\u30C3\u30C8\u306E\u8AAD\u307F\u53D6\u308A",description:"\u5207\u308A\u51FA\u3057\u305F\u5B50\u30A2\u30BB\u30C3\u30C8\u3092\u62BD\u51FA\u9806\u306B 1 \u4EF6\u305A\u3064\u8AAD\u307F\u3001\u6587\u5B57\u5C64\u3092\u8AAD\u3081\u308B\u5B50 (\u30C6\u30AD\u30B9\u30C8\u30FB\u30E1\u30FC\u30EB\u30FBOffice\u30FBPDF) \u306F\u305D\u306E\u6587\u5B57\u5C64\u3092\u3001\u8AAD\u3081\u306A\u3044\u5B50\u306F\u7248\u9762\u3092\u5149\u5B66\u8A8D\u8B58\u3067\u8AAD\u3093\u3067\u3001\u5B50\u3054\u3068\u306B\u672C\u6587\u3068\u51FA\u6240\u3092\u4FDD\u5B58\u3059\u308B\u3002",endpoint:"/ai/ocr/run",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:"ocr",fanOut:"children"},ocr_document:{key:"ocr_document",label:"\u6587\u66F8\u306E OCR",description:"\u6587\u66F8\u81EA\u8EAB\u306E\u7248\u9762 (\u753B\u50CF\u30FBPDF \u306E\u5404\u30DA\u30FC\u30B8) \u3092\u5149\u5B66\u8A8D\u8B58\u306B\u304B\u3051\u308B\u3002",endpoint:"/ai/ocr/run",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[B("ENABLE_OCR")],capability:"ocr",fanOut:null},resolve_body:{key:"resolve_body",label:"\u672C\u6587\u306E\u78BA\u5B9A",description:"\u6587\u5B57\u5C64\u30FBOCR\u30FB\u8EE2\u5199\u306E\u3069\u308C\u3092\u672C\u6587\u3068\u3059\u308B\u304B\u3092\u6C7A\u3081\u3001\u51FA\u6240\u3092\u8A18\u9332\u3059\u308B\u3002",endpoint:"/ai/enrichment/body",phase:"ENRICHING",failureStatus:"FAILED_ENRICH",gates:[],capability:null,fanOut:null},enrich_document:{key:"enrich_document",label:"\u8981\u7D04\u3068\u69CB\u9020\u5316\u62BD\u51FA",description:"\u672C\u6587\u3092\u30E2\u30C7\u30EB\u3078\u6E21\u3057\u3001\u8981\u7D04\u30FB\u30BF\u30B0\u30FB\u69CB\u9020\u5316\u30C7\u30FC\u30BF\u30FB\u30C9\u30E1\u30A4\u30F3\u5206\u985E\u3092\u5F97\u308B\u3002",endpoint:"/ai/enrichment/document",phase:"ENRICHING",failureStatus:"FAILED_ENRICH",gates:[],capability:"enrichment",fanOut:null},project_to_indexes:{key:"project_to_indexes",label:"\u30D9\u30AF\u30C8\u30EB\u3068\u30B0\u30E9\u30D5\u3078\u306E\u6295\u5F71",description:"\u672C\u6587\u3092\u30C1\u30E3\u30F3\u30AF\u306B\u3057\u3066\u57CB\u3081\u8FBC\u307F\u3001\u30D9\u30AF\u30C8\u30EB\u7D22\u5F15\u3068\u30CA\u30EC\u30C3\u30B8\u30B0\u30E9\u30D5\u3078\u66F8\u304F\u3002",endpoint:"/ai/enrichment/project",phase:"PROJECTING",failureStatus:"FAILED_VECTOR",gates:[Ie("ENABLE_VECTOR_INDEXING","FAILED_VECTOR"),Ie("ENABLE_GRAPH_INDEXING","FAILED_GRAPH")],capability:null,fanOut:null}},ge={whenClosed:"fail",failureStatus:"FAILED_EXTRACT"},P=[{step:"delete_child_assets",dependsOn:[]},{step:"extract_text",dependsOn:["delete_child_assets"]},{step:"extract_assets",dependsOn:["extract_text"]},{step:"ocr_children",dependsOn:["extract_assets"]},{step:"ocr_document",dependsOn:["extract_text"]},{step:"resolve_body",dependsOn:["ocr_children","ocr_document"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}],Re=[{step:"delete_child_assets",dependsOn:[]},{step:"extract_text",dependsOn:["delete_child_assets"]},{step:"resolve_body",dependsOn:["extract_text"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}],Ne={email:{kind:"email",steps:P},pdf:{kind:"pdf",steps:P},office:{kind:"office",steps:P},google_native:{kind:"google_native",steps:P},image:{kind:"image",steps:[{step:"delete_child_assets",dependsOn:[]},{step:"ocr_document",dependsOn:["delete_child_assets"],gatePolicy:ge},{step:"resolve_body",dependsOn:["ocr_document"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}]},media:{kind:"media",steps:[{step:"delete_child_assets",dependsOn:[]},{step:"analyze_media",dependsOn:["delete_child_assets"],gatePolicy:ge},{step:"resolve_body",dependsOn:["analyze_media"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"existing"}]},text:{kind:"text",steps:Re},other:{kind:"other",steps:Re}};function Ft(e){return Ne[e]}function Lt(e){let{gates:t}=$[e.step],{gatePolicy:n}=e;return n===void 0?t:t.map(i=>({featureFlagKey:i.featureFlagKey,whenClosed:n.whenClosed,failureStatus:n.failureStatus}))}function vt(e){let t=new Map(e.steps.map(c=>[c.step,c]));for(let c of e.steps){if(c.gatePolicy!==void 0&&$[c.step].gates.length===0)throw new Error(`Flow ${e.kind}: step ${c.step} overrides its gate policy, but the step has no gate to close.`);for(let d of c.dependsOn)if(!t.has(d))throw new Error(`Flow ${e.kind}: step ${c.step} depends on ${d}, which the flow does not contain.`)}let n=[...e.steps],i=new Set,s=[];for(;n.length>0;){let c=n.findIndex(m=>m.dependsOn.every(f=>i.has(f)));if(c===-1)throw new Error(`Flow ${e.kind}: the steps ${n.map(m=>m.step).join(", ")} depend on each other in a cycle.`);let[d]=n.splice(c,1);i.add(d.step),s.push(d)}return s}var _e={EXTRACTING:0,ENRICHING:1,PROJECTING:2};function kt(e,t){return _e[e]-_e[t]}var o=require("zod");var Ce=[{code:"DEPLOYMENT_DISABLED",status:503,errorCode:5035},{code:"RUN_ALREADY_ACTIVE",status:409,errorCode:4091},{code:"BASIS_INVALID",status:409,errorCode:4092},{code:"RUN_ALREADY_FINISHED",status:409,errorCode:4093},{code:"FORBIDDEN",status:403,errorCode:null}];var F=require("zod"),C=F.z.string().uuid().transform(e=>e.toLowerCase()),u=F.z.string().datetime({offset:!0}),l=(e,t,n)=>{e.addIssue({code:F.z.ZodIssueCode.custom,path:[...t],message:n})},Mt=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:Z|([+-])(\d{2}):?(\d{2}))$/,Te=e=>{let t=u.safeParse(e).success?Mt.exec(e):null;if(t===null)return null;let[,n,i,s,c,d,m,f,R,y,I]=t,w=new Date(0);w.setUTCFullYear(Number(n),Number(i)-1,Number(s)),w.setUTCHours(Number(c),Number(d),m===void 0?0:Number(m),0);let ct=R===void 0?0:(R==="+"?1:-1)*(Number(y)*3600+Number(I)*60);return{epochSeconds:w.getTime()/1e3-ct,fraction:f===void 0?"":f}},T=(e,t)=>{let n=Te(e),i=Te(t);if(n===null||i===null)return!1;if(n.epochSeconds!==i.epochSeconds)return n.epochSeconds<i.epochSeconds;let s=Math.max(n.fraction.length,i.fraction.length);return n.fraction.padEnd(s,"0")<i.fraction.padEnd(s,"0")};var be={INTEGRITY_TOMBSTONE_RETENTION_DAYS:{min:1,max:3650},INTEGRITY_FINDING_SAMPLE_LIMIT:{min:1,max:5e3},INTEGRITY_RUN_HEARTBEAT_TIMEOUT_SECONDS:{min:30,max:3600},INTEGRITY_RUN_RETENTION_COUNT:{min:2,max:100},POLICY_CONFLICT_MAX_TIE_GROUP_SIZE:{min:2,max:60}};var Gt=e=>{for(let t of Object.values(e))Object.freeze(t);return Object.freeze(e)},b=Gt(be),xe=e=>Object.hasOwn(b,e),De=(e,t)=>{let{min:n,max:i}=b[e];if(!Number.isInteger(t)||t<n||t>i)throw new RangeError(`${e} \u306F ${n}\u301C${i} \u306E\u6574\u6570\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)},zt=(e,t)=>{xe(e)&&De(e,t)},Kt=(e,t)=>{if(!xe(e))throw new TypeError(`The range table bounds no parameter named ${JSON.stringify(e)}.`);De(e,t)};var J=o.z.enum(["QDRANT","NEO4J"]),Pe=o.z.enum(["PRODUCTION","VARIANT","LABEL"]),Q=o.z.enum(["EXPECTED","LIVE","HISTORY","TOMBSTONE","AWAITING_SUCCESSOR","IN_FLIGHT","UNPLACED","UNRECORDED","UNREFERENCED","CHANGED_AFTER_START","PIPELINE_FAILED","PROJECTION_REFUSED","ORPHAN","TOMBSTONE_EXPIRED","UNPROPAGATED_DELETE","STALE_REVISION","MISPLACED","OUT_OF_TIER","UNMARKED_SUPERSEDED","FLAG_DRIFT","VARIANT_FLAG_DRIFT","DETACHED","UNKEYED","MISSING","COUNT_MISMATCH"]),Fe=Q.exclude(["EXPECTED","LIVE","HISTORY"]),Le=o.z.enum(["POINT","NODE","CHUNK","DOCUMENT"]),ve=o.z.enum(["EXPECTED","HEALTHY","RETAINED","INFORMATIONAL","DISCREPANCY"]),ke=o.z.enum(["NONE","PURGE","FLAG","REPROJECT"]),p=(e,t)=>Object.freeze({disposition:e,repairAction:t}),we=Object.freeze({EXPECTED:p("EXPECTED","NONE"),LIVE:p("HEALTHY","NONE"),HISTORY:p("RETAINED","NONE"),TOMBSTONE:p("RETAINED","NONE"),AWAITING_SUCCESSOR:p("RETAINED","NONE"),IN_FLIGHT:p("INFORMATIONAL","NONE"),UNPLACED:p("INFORMATIONAL","NONE"),UNRECORDED:p("INFORMATIONAL","NONE"),UNREFERENCED:p("INFORMATIONAL","NONE"),CHANGED_AFTER_START:p("INFORMATIONAL","NONE"),PIPELINE_FAILED:p("INFORMATIONAL","NONE"),PROJECTION_REFUSED:p("INFORMATIONAL","NONE"),ORPHAN:p("DISCREPANCY","PURGE"),TOMBSTONE_EXPIRED:p("DISCREPANCY","PURGE"),UNPROPAGATED_DELETE:p("DISCREPANCY","FLAG"),STALE_REVISION:p("DISCREPANCY","PURGE"),MISPLACED:p("DISCREPANCY","PURGE"),OUT_OF_TIER:p("DISCREPANCY","PURGE"),UNMARKED_SUPERSEDED:p("DISCREPANCY","FLAG"),FLAG_DRIFT:p("DISCREPANCY","REPROJECT"),VARIANT_FLAG_DRIFT:p("DISCREPANCY","NONE"),DETACHED:p("DISCREPANCY","NONE"),UNKEYED:p("DISCREPANCY","NONE"),MISSING:p("DISCREPANCY","REPROJECT"),COUNT_MISMATCH:p("DISCREPANCY","REPROJECT")}),Me=o.z.enum(["SCAN","REPAIR"]),Ue=o.z.enum(["RUNNING","COMPLETED","FAILED","CANCELLED","ABANDONED"]),Ge=o.z.enum(["CONSISTENT","INCONSISTENT","UNDETERMINED"]),ze=o.z.enum(["QDRANT","NEO4J","DOCUMENTS"]),Ke=o.z.enum(["APPLIED","SKIPPED","FAILED"]),He=o.z.enum(["RECLASSIFIED","IN_FLIGHT","DESTINATION_PENDING","BASIS_EXHAUSTED","PROJECTION_REFUSED","PIPELINE_FAILED","UNRECORDED","OUTSIDE"]),Be=100,E=o.z.number().int().nonnegative(),L=o.z.number().int().min(300).max(599),V=["repairedCount","repairFailedCount","repairSkippedCount"],Ye=o.z.string().regex(/^[0-9a-f]{64}$/,"A store fingerprint is 64 lowercase hexadecimal digits."),Oe=b.INTEGRITY_TOMBSTONE_RETENTION_DAYS,Ht=o.z.object({runUid:C,mode:Me,status:Ue,requestedBy:o.z.string().min(1),executor:o.z.string().min(1),basisRunUid:C.nullable(),storeFingerprint:Ye,tombstoneRetentionDays:o.z.number().int().min(Oe.min).max(Oe.max),startedAt:u,finishedAt:u.nullable(),verdict:Ge.nullable(),errorClass:o.z.string().min(1).nullable(),reprojectDocuments:E.nullable(),reprojectRebuildDocuments:E.nullable()}).strict(),Bt=(e,t)=>{let n=e.status==="COMPLETED";e.mode==="REPAIR"!=(e.basisRunUid!==null)&&l(t,["basisRunUid"],"A REPAIR run names its basis SCAN run, and a SCAN run names none."),n!==(e.verdict!==null)&&l(t,["verdict"],"Only a COMPLETED run has a verdict."),n!==(e.reprojectDocuments!==null)&&l(t,["reprojectDocuments"],"Only a COMPLETED run has the count of documents to re-project.");let{reprojectDocuments:i,reprojectRebuildDocuments:s}=e;i===null||s===null?i!==s&&l(t,["reprojectRebuildDocuments"],"The documents a re-projection embeds are counted together with the documents it re-projects."):s>i&&l(t,["reprojectRebuildDocuments"],"The documents a re-projection embeds are no more than the documents it re-projects."),e.status==="RUNNING"!=(e.finishedAt===null)&&l(t,["finishedAt"],"Only a RUNNING run has not finished."),e.finishedAt!==null&&T(e.finishedAt,e.startedAt)&&l(t,["finishedAt"],"A run does not finish before it starts."),(e.status==="FAILED"||e.status==="ABANDONED")!=(e.errorClass!==null)&&l(t,["errorClass"],"Only a FAILED or ABANDONED run names an error class.")},v=Ht.superRefine(Bt),Yt=o.z.object({store:J,scopeKey:o.z.string().min(1),scopeRole:Pe,itemClass:Q,unit:Le,disposition:ve,repairAction:ke,itemCount:E.nullable(),unmeasuredReason:o.z.string().min(1).nullable(),measuredAt:u.nullable(),repairedCount:E.nullable(),repairFailedCount:E.nullable(),repairSkippedCount:E.nullable()}).strict(),jt=(e,t)=>{let n=we[e.itemClass];e.disposition!==n.disposition&&l(t,["disposition"],`A ${e.itemClass} quantity is ${n.disposition}.`),e.repairAction!==n.repairAction&&l(t,["repairAction"],`A repair's action on ${e.itemClass} items is ${n.repairAction}.`);let i=e.itemCount===null;i!==(e.unmeasuredReason!==null)&&l(t,["unmeasuredReason"],"An unmeasured quantity (itemCount null) has a reason, and a measured one has none."),i!==(e.measuredAt===null)&&l(t,["measuredAt"],"Only a measured quantity has a measurement time.");let{repairedCount:s,repairFailedCount:c,repairSkippedCount:d}=e;if(s===null||c===null||d===null){if(V.some(m=>e[m]!==null))for(let m of V)e[m]===null&&l(t,[m],"The repaired, failed and skipped counts are recorded together or not at all.");return}e.repairAction==="NONE"&&l(t,["repairAction"],"Only a class with a repair action carries repair counts."),e.itemCount!==null&&s+c+d>e.itemCount&&l(t,["itemCount"],"The repaired, failed and skipped counts together do not exceed the measured count.")},je=Yt.superRefine(jt),$t=o.z.object({run:v,phase:ze.nullable(),phaseScope:o.z.string().min(1).nullable(),phaseDone:E.nullable(),phaseTotal:E.nullable(),heartbeatAt:u,isStale:o.z.boolean(),cancelRequestedAt:u.nullable()}).strict(),Vt=(e,t)=>{if(e.run.status!=="RUNNING"&&l(t,["run","status"],"The active run is a RUNNING run."),T(e.heartbeatAt,e.run.startedAt)&&l(t,["heartbeatAt"],"A run's heartbeat is not earlier than its start."),e.phase===null)for(let n of["phaseScope","phaseDone","phaseTotal"])e[n]!==null&&l(t,[n],"A run with no phase has no phase progress.");e.phase==="DOCUMENTS"&&e.phaseScope!==null&&l(t,["phaseScope"],"The DOCUMENTS phase scans no scope.")},$e=$t.superRefine(Vt),Xt=o.z.object({run:v,quantities:o.z.array(je),previousStoreFingerprint:Ye.nullable()}).strict(),qt=(e,t)=>{e.run.status!=="COMPLETED"&&l(t,["run","status"],"The last completed run is a COMPLETED run.");let n=new Set;for(let[i,s]of e.quantities.entries()){let c=JSON.stringify([s.store,s.scopeKey,s.itemClass]);if(n.has(c)&&l(t,["quantities",i],"A run records each (store, scope, class) cell once."),n.add(c),e.run.mode==="SCAN")for(let d of V)s[d]!==null&&l(t,["quantities",i,d],"A SCAN run repairs nothing, so its quantities carry no repair counts.")}},Jt=["FAILED","CANCELLED","ABANDONED"],Qt=o.z.object({run:v,repairAppliedItems:E.nullable(),hasNewerRepair:o.z.boolean()}).strict(),Wt=(e,t)=>{Jt.includes(e.run.status)||l(t,["run","status"],"A newer unsuccessful run is FAILED, CANCELLED or ABANDONED."),e.run.mode==="SCAN"&&e.repairAppliedItems!==null&&l(t,["repairAppliedItems"],"A SCAN run applies nothing."),e.run.mode==="REPAIR"&&!e.hasNewerRepair&&l(t,["hasNewerRepair"],"An unsuccessful REPAIR run is itself a repair newer than the last completed run.")},Zt=o.z.object({readAt:u,lastCompleted:Xt.superRefine(qt).nullable(),active:$e.nullable(),newerUnsuccessful:Qt.superRefine(Wt).nullable()}).strict(),en=o.z.object({sequence:o.z.number().int().min(1),itemKey:o.z.string().min(1),metadataId:o.z.number().int().positive().nullable(),fileUri:o.z.string().nullable(),revision:o.z.number().int().nullable(),observed:o.z.record(o.z.string(),o.z.unknown()),repairOutcome:Ke.nullable(),repairErrorClass:o.z.string().min(1).nullable(),repairSkipReason:He.nullable()}).strict(),tn=(e,t)=>{e.repairOutcome==="FAILED"!=(e.repairErrorClass!==null)&&l(t,["repairErrorClass"],"Only a FAILED finding names an error class."),e.repairOutcome==="SKIPPED"!=(e.repairSkipReason!==null)&&l(t,["repairSkipReason"],"Only a SKIPPED finding names a skip reason.")},Ve=en.superRefine(tn),nn=o.z.object({sotDomain:o.z.string().nullable()}).passthrough(),rn=o.z.object({rows:o.z.array(Ve),nextAfter:o.z.number().int().min(1).nullable(),recordedCount:E,totalCount:E.nullable()}).strict(),on=(e,t)=>{for(let[n,i]of e.rows.entries()){let s=e.rows[n-1];s!==void 0&&i.sequence<=s.sequence&&l(t,["rows",n,"sequence"],"A page lists its rows in ascending sequence.")}e.nextAfter!==null&&e.nextAfter!==e.rows.at(-1)?.sequence&&l(t,["nextAfter"],"The next page starts after the sequence of this page's last row.")},an=rn.superRefine(on),sn=o.z.object({runUid:C,store:J,scopeKey:o.z.string().min(1),itemClass:Fe,after:o.z.number().int().min(1).optional(),limit:o.z.number().int().min(1).max(Be)}).strict(),k=o.z.enum(["DEPLOYMENT_DISABLED","RUN_ALREADY_ACTIVE","BASIS_INVALID","RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),X=o.z.enum(["start","cancel"]),Xe=k.extract(["DEPLOYMENT_DISABLED","RUN_ALREADY_ACTIVE","BASIS_INVALID","FORBIDDEN","UPSTREAM_FAILED"]),qe=k.extract(["DEPLOYMENT_DISABLED","RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),q={start:Xe,cancel:qe},ln=o.z.object({code:k.exclude(["UPSTREAM_FAILED"]),status:L,errorCode:o.z.number().int().nullable()}).strict(),W=Object.freeze(o.z.array(ln).parse(Ce).map(e=>Object.freeze(e))),cn=(e,t)=>{e.code==="UPSTREAM_FAILED"||e.code==="FORBIDDEN"&&e.status===null||W.some(n=>n.code===e.code&&n.status===e.status)||l(t,["status"],`A ${e.code} failure carries the status of its row in the code table.`)},pn=o.z.discriminatedUnion("command",[o.z.object({command:X.extract(["start"]),code:q.start,status:L.nullable()}).strict(),o.z.object({command:X.extract(["cancel"]),code:q.cancel,status:L.nullable()}).strict()]).superRefine(cn),dn=(e,t,n)=>{let i=q[e],s=W.find(c=>c.status===t&&(c.errorCode===null||c.errorCode===n)&&i.safeParse(c.code).success);return s===void 0?"UPSTREAM_FAILED":s.code},un=o.z.discriminatedUnion("ok",[o.z.object({ok:o.z.literal(!0),runUid:C}).strict(),o.z.object({ok:o.z.literal(!1),status:L,errorCode:o.z.number().int().nullable()}).strict()]);var a=require("zod");var ne=a.z.enum(Y),x=a.z.enum(j),Je=a.z.enum(["RUNNING","SUCCEEDED","FAILED"]),Qe=a.z.enum(["RUNNING","SUCCEEDED","SKIPPED","FAILED"]),We=a.z.enum(["ingest","retry","resync"]),Ze=a.z.enum(["text_layer","ocr","transcript"]),S=a.z.number().int().nonnegative().nullable(),et=a.z.object({provider:a.z.string().nullable(),model:a.z.string().nullable(),engine:a.z.string().nullable(),prompt_key:a.z.string().nullable(),prompt_version:a.z.number().int().nullable(),duration_ms:S,input_chars:S,output_chars:S,pages_read:S,pages_total:S,chunk_count:S,points_upserted:S,collection:a.z.string().nullable(),embedding_model:a.z.string().nullable(),strategy_id:a.z.number().int().positive().nullable(),graph_nodes:S,body_source:Ze.nullable(),detail:a.z.record(a.z.string(),a.z.unknown())}).strict(),tt=["no_pages","no_pages_rendered"],nt=a.z.enum(tt),Z="gate_closed:",ee="source_skipped:",te="nothing_to_read:",rt="no_children",mn=/^[A-Z][A-Z0-9_]*$/;function ot(e){if(e===rt)return{kind:"no_children"};if(e.startsWith(Z)){let t=e.slice(Z.length);return mn.test(t)?{kind:"gate_closed",featureFlagKey:t}:null}if(e.startsWith(ee)){let t=x.safeParse(e.slice(ee.length));return t.success?{kind:"source_skipped",stepKey:t.data}:null}if(e.startsWith(te)){let t=nt.safeParse(e.slice(te.length));return t.success?{kind:"nothing_to_read",token:t.data}:null}return null}function yn(e){let t=fn(e);if(ot(t)===null)throw new RangeError(`Skip reason ${JSON.stringify(e)} has no text form: ${JSON.stringify(t)} is outside the skip-reason grammar.`);return t}function fn(e){switch(e.kind){case"gate_closed":return`${Z}${e.featureFlagKey}`;case"no_children":return rt;case"source_skipped":return`${ee}${e.stepKey}`;case"nothing_to_read":return`${te}${e.token}`;default:{let t=e;throw new RangeError(`Unknown skip reason kind: ${JSON.stringify(t)}`)}}}var En=a.z.object({id:a.z.number().int().positive(),runId:a.z.number().int().positive(),sequence:a.z.number().int().nonnegative(),stepKey:x,targetMetadataId:a.z.number().int().positive(),status:Qe,skipReason:a.z.string().nullable(),provenance:et.nullable(),strategyId:a.z.number().int().positive().nullable(),httpStatus:a.z.number().int().nullable(),errorCode:a.z.string().nullable(),errorMessage:a.z.string().nullable(),startedAt:u,finishedAt:u.nullable(),durationMs:S}).strict();function Sn(e,t){switch(e.status){case"SKIPPED":e.skipReason===null&&l(t,["skipReason"],"A SKIPPED step must record why it was skipped."),e.provenance!==null&&l(t,["provenance"],"A SKIPPED step read nothing, so it has no report.");return;case"SUCCEEDED":e.provenance===null&&l(t,["provenance"],"A SUCCEEDED step must carry its report."),e.skipReason!==null&&l(t,["skipReason"],"A SUCCEEDED step was not skipped.");return;case"RUNNING":e.finishedAt!==null&&l(t,["finishedAt"],"A RUNNING step has not finished.");return;case"FAILED":e.skipReason!==null&&l(t,["skipReason"],"A FAILED step was not skipped.");return}}var it=En.superRefine(Sn),at=a.z.object({id:a.z.number().int().positive(),tenantId:a.z.string().min(1),metadataId:a.z.number().int().positive(),revision:a.z.number().int().positive(),runUid:a.z.string().uuid(),jobId:a.z.string().min(1),attempt:a.z.number().int().positive(),trigger:We,documentKind:ne,flowKey:a.z.string().min(1),status:Je,retryScheduled:a.z.boolean(),failedStepKey:x.nullable(),errorMessage:a.z.string().nullable(),requestedBy:a.z.string().min(1),startedAt:u,finishedAt:u.nullable(),steps:a.z.array(it)}).strict();function st(e,t){e.retryScheduled&&e.status!=="FAILED"&&l(t,["retryScheduled"],"Only a FAILED run can have a retry scheduled.")}var hn=at.superRefine(st),In=at.omit({steps:!0}).superRefine(st);function gn(e,t){e.sampleCount>0||(e.durationP50Ms!==null&&l(t,["durationP50Ms"],"A step with no sample has no median latency."),e.durationP95Ms!==null&&l(t,["durationP95Ms"],"A step with no sample has no 95th-percentile latency."))}var Rn=a.z.object({documentKind:ne,stepKey:x,sampleCount:a.z.number().int().nonnegative(),succeeded:a.z.number().int().nonnegative(),failed:a.z.number().int().nonnegative(),skipped:a.z.number().int().nonnegative(),durationP50Ms:S,durationP95Ms:S,lastStartedAt:u.nullable()}).strict().superRefine(gn);var re=[{key:"enable_summary_generation",featureFlagKey:null,label:"\u8981\u7D04\u751F\u6210"},{key:"enable_structured_extraction",featureFlagKey:null,label:"\u69CB\u9020\u5316\u62BD\u51FA"},{key:"enable_asset_extraction",featureFlagKey:"ENABLE_ASSET_EXTRACTION",label:"\u30A2\u30BB\u30C3\u30C8\u62BD\u51FA"},{key:"enable_vector_indexing",featureFlagKey:"ENABLE_VECTOR_INDEXING",label:"\u30D9\u30AF\u30C8\u30EB\u7D22\u5F15"},{key:"enable_graph_indexing",featureFlagKey:"ENABLE_GRAPH_INDEXING",label:"\u30B0\u30E9\u30D5\u6295\u5F71"}],_n=new Set(re.map(e=>e.key));function An(e){return _n.has(e)}function Nn(e){let t=re.find(n=>n.key===e);if(t===void 0)throw new Error(`ENRICHMENT_STAGES does not carry ${e}; the canonical list and the key type have drifted apart.`);return t}var Cn={pageSize:{min:1,max:200,default:50},topologyLabels:{min:1,max:24,default:24}};var _=-1,h=0;function lt(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function Tn(){let e=typeof globalThis<"u"&&globalThis.crypto?globalThis.crypto:typeof crypto<"u"?crypto:void 0;if(!e||typeof e.getRandomValues!="function")throw new Error("Cryptographically secure random number generator (crypto.getRandomValues) is required but not available.");let t=new Uint8Array(16);e.getRandomValues(t);let n=Date.now();if(n===_){if(h++,h>4095){for(;Date.now()<=_;);n=Date.now(),_=n,h=(t[6]<<4|t[7]&15)&1023}}else n>_?(_=n,h=(t[6]<<4|t[7]&15)&1023):(n=_,h++,h>4095&&(h=0));t[0]=Math.floor(n/1099511627776)&255,t[1]=Math.floor(n/4294967296)&255,t[2]=n>>>24&255,t[3]=n>>>16&255,t[4]=n>>>8&255,t[5]=n&255,t[6]=112|h>>>8&15,t[7]=h&255,t[8]=128|t[8]&63;let i=Array.from(t,c=>c.toString(16).padStart(2,"0")).join("");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function bn(e){if(!lt(e))throw new Error(`Invalid RFC 9562 UUIDv7 string: "${e}"`);let t=e.slice(0,8)+e.slice(9,13),n=parseInt(t,16);if(Number.isNaN(n))throw new Error(`Invalid hex timestamp in UUIDv7: "${t}"`);return new Date(n)}0&&(module.exports={AmountEntrySchema,BaseEnrichmentClient,BodySourceSchema,BoundingBoxSchema,CIRCUIT_BREAKER_SERVICES,CanonicalDomainKeySchema,ChapterSegmentSchema,ChunkingStrategySchema,CircuitBreakerStatusSchema,ConfidentialityLevelSchema,DISPATCH_DEGRADATION_REASONS,DOCUMENT_KINDS,DOCUMENT_KIND_LABELS,DocumentKindSchema,DocumentStructuredDataSchema,ENRICHMENT_STAGES,EnrichmentClient,EnrichmentClientError,EnrichmentSyncStatusSchema,FILTERABLE_CONFIDENTIALITY_LEVELS,FileUriSchema,GRAPH_INDEX_LIMITS,GraphSearchHitSchema,INTEGRITY_CLASS_POLICY,INTEGRITY_COMMAND_CODES,INTEGRITY_FINDINGS_PAGE_LIMIT_MAX,IntegrityActiveRunSchema,IntegrityAuditOverviewSchema,IntegrityCancelFailureCodeSchema,IntegrityCommandFailureCodeSchema,IntegrityCommandFailureSchema,IntegrityCommandReplySchema,IntegrityCommandSchema,IntegrityDispositionSchema,IntegrityFindingItemClassSchema,IntegrityFindingPageSchema,IntegrityFindingSchema,IntegrityFindingsQuerySchema,IntegrityItemClassSchema,IntegrityPhaseSchema,IntegrityPlacementObservedSchema,IntegrityQuantitySchema,IntegrityRepairActionSchema,IntegrityRepairOutcomeSchema,IntegrityRepairSkipReasonSchema,IntegrityRunHeaderSchema,IntegrityRunModeSchema,IntegrityRunStatusSchema,IntegrityScopeRoleSchema,IntegrityStartFailureCodeSchema,IntegrityStoreSchema,IntegrityUnitSchema,IntegrityVerdictSchema,LOCAL_DEGRADATION_REASONS,MIME_KIND_RULES,MODE_TIERS,ModelProviderSchema,NOTHING_TO_READ_TOKENS,NothingToReadTokenSchema,PIPELINE_FLOWS,PIPELINE_PHASES,PIPELINE_STEPS,PIPELINE_STEP_KEYS,PipelineRunRecordSchema,PipelineRunStatusSchema,PipelineRunSummarySchema,PipelineStepKeySchema,PipelineStepMetricSchema,PipelineStepRecordSchema,PipelineStepStatusSchema,PipelineTriggerSchema,QUARANTINED_CONFIDENTIALITY_LEVEL,REMOTE_DEGRADATION_REASONS,SEARCH_DEGRADATION_REASONS,SEARCH_MODES,SEARCH_PARAM_LIMITS,SYSTEM_PARAMETER_RANGES,SearchHitSchema,SearchMetadataSchema,SearchModeSchema,SearchRequestSchema,SearchResponseSchema,StageProvenanceSchema,TenantIdSchema,TranscriptSegmentSchema,assertBoundedSystemParameter,assertSystemParameterInRange,classifyDocumentKind,comparePhases,enrichmentStage,flowFor,flowStepGates,formatSkipReason,generateUuidV7,integrityCommandFailureCodeOf,isEnrichmentStageKey,isStrictlyEarlier,isValidUuidV7,modeFusesRankings,modeNeedsRemoteTiers,modeScoreIsSimilarity,narrowModeToAllowedTiers,orderedSteps,parseSkipReason,uuidv7ToDate});
1
+ "use strict";var Ve=Object.defineProperty;var Eo=Object.getOwnPropertyDescriptor;var Co=Object.getOwnPropertyNames;var bo=Object.prototype.hasOwnProperty;var Ro=(e,t)=>{for(var n in t)Ve(e,n,{get:t[n],enumerable:!0})},Io=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Co(t))!bo.call(e,o)&&o!==n&&Ve(e,o,{get:()=>t[o],enumerable:!(r=Eo(t,o))||r.enumerable});return e};var xo=e=>Io(Ve({},"__esModule",{value:!0}),e);var Di={};Ro(Di,{AmountEntrySchema:()=>nn,AssetFacetItemSchema:()=>Wn,BaseEnrichmentClient:()=>ue,BodySourceSchema:()=>Ne,BoundingBoxSchema:()=>Fo,CHUNK_BODY_FIDELITIES:()=>Hn,CHUNK_CHANGE_KINDS:()=>vn,CHUNK_MANIFEST_VERSION:()=>wn,CHUNK_PAIRINGS:()=>Un,CIRCUIT_BREAKER_SERVICES:()=>qt,CanonicalDomainKeySchema:()=>an,ChangeFeedCursorSchema:()=>Dt,ChapterSegmentSchema:()=>en,ChunkBodyFidelitySchema:()=>Kn,ChunkChangeKindSchema:()=>Mn,ChunkChangeSchema:()=>fr,ChunkManifestChildSchema:()=>Zn,ChunkManifestParentSchema:()=>er,ChunkManifestSchema:()=>tr,ChunkPairingSchema:()=>zn,ChunkRefSchema:()=>mt,ChunkStatsSchema:()=>hr,ChunkingStrategySchema:()=>vo,CircuitBreakerStatusSchema:()=>Lo,ClassificationFacetSchema:()=>$n,ConfidentialityLevelSchema:()=>Q,DIFF_CONTEXT_LINES:()=>we,DIFF_ENGINE_VERSION:()=>ft,DIFF_LINE_FACETS:()=>Bn,DIFF_LINE_PAGE_MAX:()=>Ct,DIFF_REGION_CELL_BOUND:()=>yt,DISPATCH_DEGRADATION_REASONS:()=>Qt,DOCUMENT_CAPTURE_OUTCOMES:()=>Vn,DOCUMENT_CHANGE_FEED_PAGE_MAX:()=>bt,DOCUMENT_CHANGE_FEED_PAGE_SIZE:()=>na,DOCUMENT_FACETS:()=>Z,DOCUMENT_KINDS:()=>Ze,DOCUMENT_KIND_LABELS:()=>Uo,DOCUMENT_STATE_CAUSES:()=>Fn,DOCUMENT_STATE_LOCK_TIMEOUT_MS:()=>ra,DOCUMENT_STATE_RUN_OUTCOMES:()=>Pn,DiffLineFacetSchema:()=>ia,DiffLinePageLimitSchema:()=>At,DiffLinePageSchema:()=>ha,DiffLineSchema:()=>mr,DiffSegmentSchema:()=>pr,DocumentCaptureAnswerSchema:()=>Na,DocumentCaptureOutcomeSchema:()=>Jn,DocumentChangeFeedEntrySchema:()=>Ir,DocumentChangeFeedLimitSchema:()=>ya,DocumentChangeFeedPageSchema:()=>Ta,DocumentChangeFeedRowSchema:()=>xr,DocumentComparisonSchema:()=>Ea,DocumentFacetSchema:()=>Rt,DocumentFacetValuesSchema:()=>ca,DocumentHistorySchema:()=>Aa,DocumentKindSchema:()=>it,DocumentRunEntrySchema:()=>br,DocumentStateCauseSchema:()=>It,DocumentStateEntrySchema:()=>Cr,DocumentStateRunOutcomeSchema:()=>Ln,DocumentStateSummarySchema:()=>Er,DocumentStructuredDataSchema:()=>Po,ENRICHMENT_STAGES:()=>Jt,EnrichmentClient:()=>We,EnrichmentClientError:()=>W,EnrichmentSyncStatusSchema:()=>$e,FACET_APPLICABLE_COUNTS:()=>rr,FACET_COUNT_FIELDS:()=>nr,FILTERABLE_CONFIDENTIALITY_LEVELS:()=>_o,FacetChangeCountsSchema:()=>or,FacetDiffSchema:()=>yr,FieldChangeSchema:()=>Me,FileUriSchema:()=>wo,GRAPH_INDEX_LIMITS:()=>xi,GraphSearchHitSchema:()=>ln,HISTOGRAM_MAX_OCCURRENCES:()=>ht,HunkIndexEntrySchema:()=>cr,INLINE_REFINE_CELL_BUDGET:()=>St,INLINE_REFINE_MAX_EDIT_DISTANCE:()=>gt,INLINE_REFINE_MAX_GRAPHEMES:()=>Fe,INLINE_REFINE_MIN_SIMILARITY:()=>Pe,INTEGRITY_CLASS_POLICY:()=>vr,INTEGRITY_COMMAND_CODES:()=>Ft,INTEGRITY_FINDINGS_PAGE_LIMIT_MAX:()=>ye,IntegrityActiveRunSchema:()=>Vr,IntegrityAuditOverviewSchema:()=>Ja,IntegrityCancelFailureCodeSchema:()=>$r,IntegrityCellResyncRequestSchema:()=>ei,IntegrityCellResyncResultSchema:()=>ri,IntegrityCommandFailureCodeSchema:()=>Ke,IntegrityCommandFailureSchema:()=>ii,IntegrityCommandReplySchema:()=>li,IntegrityCommandSchema:()=>Nt,IntegrityDispositionSchema:()=>Pr,IntegrityFindingItemClassSchema:()=>wt,IntegrityFindingPageSchema:()=>Qa,IntegrityFindingSchema:()=>Jr,IntegrityFindingsQuerySchema:()=>Za,IntegrityItemClassSchema:()=>Ot,IntegrityPhaseSchema:()=>Hr,IntegrityPlacementObservedSchema:()=>qa,IntegrityQuantitySchema:()=>Br,IntegrityRepairActionSchema:()=>Lr,IntegrityRepairOutcomeSchema:()=>Kr,IntegrityRepairSkipReasonSchema:()=>Gr,IntegrityRunHeaderSchema:()=>He,IntegrityRunModeSchema:()=>Mr,IntegrityRunStatusSchema:()=>Ur,IntegrityScopeRoleSchema:()=>wr,IntegrityStartFailureCodeSchema:()=>Yr,IntegrityStoreSchema:()=>ze,IntegrityUnitSchema:()=>Fr,IntegrityVerdictSchema:()=>zr,JsonPatchOperationSchema:()=>sr,JsonValueSchema:()=>j,KeyedItemChangeSchema:()=>ir,KeyedItemSchema:()=>pt,LEDGER_STEP_KEYS:()=>et,LINE_ENDINGS:()=>jn,LOCAL_DEGRADATION_REASONS:()=>Xt,LabelFacetItemSchema:()=>Xn,LedgerStepKeySchema:()=>yn,LineEndingSchema:()=>aa,MIME_KIND_RULES:()=>fn,MODE_TIERS:()=>pe,MetadataFacetSchema:()=>qn,ModelProviderSchema:()=>Yt,NOTHING_TO_READ_TOKENS:()=>_n,NothingToReadTokenSchema:()=>Dn,PIPELINE_FAILURE_STATUSES:()=>tt,PIPELINE_FLOWS:()=>hn,PIPELINE_PHASES:()=>Ho,PIPELINE_STEPS:()=>nt,PIPELINE_STEP_KEYS:()=>Ae,PipelineFailureStatusSchema:()=>st,PipelineRunRecordSchema:()=>ct,PipelineRunStatusSchema:()=>Te,PipelineRunSummarySchema:()=>dt,PipelineStepKeySchema:()=>De,PipelineStepMetricSchema:()=>ta,PipelineStepRecordSchema:()=>Tn,PipelineStepStatusSchema:()=>In,PipelineTriggerSchema:()=>xn,QUARANTINED_CONFIDENTIALITY_LEVEL:()=>oe,REMOTE_DEGRADATION_REASONS:()=>Wt,RESTRICTED_MARK_SUBJECTS:()=>Gn,RUN_TERMINAL_STEP_ERROR_CODES:()=>Cn,RUN_TERMINAL_STEP_KEY:()=>_e,RUN_TERMINAL_STEP_OUTCOMES:()=>gn,ReadableConfidentialityLevelSchema:()=>xt,RecentPipelineRunEntrySchema:()=>Ia,RestrictedChangeMarkSchema:()=>Sr,RestrictedFailureMarkSchema:()=>ba,RestrictedIngestMarkSchema:()=>Ca,RestrictedMarkSubjectSchema:()=>oa,RestrictedRunMarkSchema:()=>_t,RestrictedStateMarkSchema:()=>gr,RunTerminalStepDetailSchema:()=>En,RunTerminalStepErrorCodeSchema:()=>Rn,RunTerminalStepOutcomeSchema:()=>Sn,SEARCH_DEGRADATION_REASONS:()=>Oo,SEARCH_MODES:()=>Ye,SEARCH_PARAM_LIMITS:()=>Ao,STALE_RUN_ERROR_CODE:()=>bn,STRUCTURED_DATA_ARRAY_CELL_BOUND:()=>Et,SYSTEM_PARAMETER_RANGES:()=>he,SearchHitSchema:()=>sn,SearchMetadataSchema:()=>on,SearchModeSchema:()=>rn,SearchRequestSchema:()=>qe,SearchResponseSchema:()=>Xe,StageProvenanceSchema:()=>An,TenantIdSchema:()=>Zt,TextDiffIndexSchema:()=>pa,TextFacetSchema:()=>Qn,TextStatsSchema:()=>lr,TranscriptSegmentSchema:()=>tn,assertBoundedSystemParameter:()=>Pa,assertSystemParameterInRange:()=>Fa,canonicalJson:()=>U,classifyDocumentKind:()=>zo,codePointSlicer:()=>qr,compareAssetKeys:()=>Le,compareCodeUnits:()=>B,compareFacets:()=>ve,comparePhases:()=>Bo,compareStates:()=>go,decodeChangeFeedCursor:()=>_r,diffChunkBodies:()=>so,diffLinePage:()=>lo,encodeChangeFeedCursor:()=>Ar,enrichmentStage:()=>Ii,flowFor:()=>Ko,flowStepGates:()=>Go,formatSkipReason:()=>$o,generateUuidV7:()=>Ai,integrityCommandFailureCodeOf:()=>si,isEnrichmentStageKey:()=>Ri,isStrictlyEarlier:()=>Y,isValidUuidV7:()=>So,modeFusesRankings:()=>ko,modeNeedsRemoteTiers:()=>Do,modeScoreIsSimilarity:()=>To,narrowModeToAllowedTiers:()=>No,orderedSteps:()=>jo,parseSkipReason:()=>lt,readableEntrySchema:()=>fe,stripWhitespace:()=>Xr,summarizeTransition:()=>yo,summaryFacetDiff:()=>Ee,textDiffIndex:()=>Ce,textFacetDiff:()=>Se,uuidv7ToDate:()=>_i});module.exports=xo(Di);var U=e=>{if(e===null||typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new RangeError(`A canonical JSON number is finite: ${e}`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map(U).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${U(t[r])}`).join(",")}}`};var W=class extends Error{statusCode;responseBody;parsedBody;constructor(t,n,r,o){super(t),this.name="EnrichmentClientError",this.statusCode=n,this.responseBody=r,this.parsedBody=o}},ue=class{baseUrl;apiKey;fetchFn;timeoutMs;constructor(t){if(!t||typeof t.baseUrl!="string"||t.baseUrl.trim().length===0)throw new Error("baseUrl is required and must be a non-empty string for EnrichmentClient.");let n=t.baseUrl.trim().replace(/\/$/,"");if(t.apiKey&&n.startsWith("http://")&&!n.includes("localhost")&&!n.includes("127.0.0.1"))throw new Error("Security Violation: Transmitting Bearer tokens over unencrypted HTTP to non-localhost hosts is strictly prohibited.");this.baseUrl=n,this.apiKey=t.apiKey,this.fetchFn=t.fetchFn??fetch,this.timeoutMs=t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:3e4}async request(t,n,r){let o=`${this.baseUrl}${t}`,i={Accept:"application/json","Content-Type":"application/json","X-Tenant-Id":n};this.apiKey&&(i.Authorization=`Bearer ${this.apiKey}`);let l=new AbortController,s=setTimeout(()=>l.abort(),this.timeoutMs),c;try{c=await this.fetchFn(o,{method:"POST",headers:i,body:JSON.stringify(r),signal:l.signal})}catch(u){let y=u instanceof Error?u.message:String(u);throw new W(`Network request failed for POST ${o}: ${y}`,0,"")}finally{clearTimeout(s)}if(!c.ok){let u=await c.text().catch(()=>""),y;try{y=JSON.parse(u)}catch{}throw new W(`API request failed with status ${c.status}: ${u}`,c.status,u,y)}let h=await c.text().catch(()=>"");if(h.trim().length!==0)try{return JSON.parse(h)}catch(u){let y=u instanceof Error?u.message:String(u);throw new W(`Failed to parse response JSON from ${o}: ${y}`,c.status,h)}}};var m=require("zod");var Je=require("zod"),Yt=Je.z.enum(["google_cloud","google_vision","yomitoku_local","faster_whisper_local","google_speech","ollama_local","openai","anthropic","azure_openai","bedrock","custom_openai_compatible"]),Q=Je.z.enum(["PUBLIC","INTERNAL","DEPARTMENT","CONFIDENTIAL","RESTRICTED"]),oe="RESTRICTED";var Ao={rrfK:{min:1,max:200,default:60},alpha:{min:0,max:1,default:.7},threshold:{min:0,max:1},limit:{min:1,max:50,default:10}},$t=Q.options.filter(e=>e!==oe);if($t.length===0)throw new Error("The confidentiality vocabulary left nothing filterable after removing the quarantined level; a validator built from this list would reject every request.");var _o=$t,Ye=["KEYWORD","SPARSE","DENSE","HYBRID","GRAPH_TRAVERSE"],pe={KEYWORD:{dense:!1,sparse:!1,graph:!1,lexical:!0},SPARSE:{dense:!1,sparse:!0,graph:!1,lexical:!1},DENSE:{dense:!0,sparse:!1,graph:!1,lexical:!1},HYBRID:{dense:!0,sparse:!0,graph:!0,lexical:!0},GRAPH_TRAVERSE:{dense:!1,sparse:!1,graph:!0,lexical:!1}};function Do(e){let t=pe[e];return t.dense||t.sparse||t.graph}function To(e){let t=pe[e];return t.dense&&!t.sparse}function No(e,t){let n=pe[e],r=(n.dense||n.sparse)&&t.vector,o=n.graph&&t.graph;return r||o?r?o?{mode:e,discardGraph:!1}:n.dense&&n.sparse?{mode:e,discardGraph:!0}:{mode:n.dense?"DENSE":"SPARSE",discardGraph:!1}:{mode:"GRAPH_TRAVERSE",discardGraph:!1}:null}function ko(e){let t=pe[e];return[t.dense,t.sparse,t.graph,t.lexical].filter(Boolean).length>1}var qt=["vector","graph"],Xt=["empty_query","caller_token_unavailable","time_window_unsupported"],Wt=["vector_tier_not_configured","graph_tier_not_configured","no_active_vector_collection","vector_collections_missing"],Qt=["remote_tiers_unavailable","remote_tiers_timed_out","remote_tiers_refused_caller","remote_tiers_rejected_request","remote_tiers_failed","remote_tiers_not_executed","vector_search_disabled","graph_search_disabled"],Oo=[...Xt,...Wt,...Qt,...qt.map(e=>`circuit_breaker_open:${e}`)];var Zt=m.z.string().trim().min(1,"tenant_id must be a non-empty string"),wo=m.z.string().trim().min(1,"file_uri must be a non-empty string"),$e=m.z.enum(["PENDING","EXTRACTING","ENRICHING","PROJECTING","SYNCED","FAILED_EXTRACT","FAILED_ENRICH","FAILED_VECTOR","FAILED_GRAPH"]),Fo=m.z.object({page:m.z.number().int().positive().optional(),x:m.z.number().nonnegative().optional(),y:m.z.number().nonnegative().optional(),width:m.z.number().positive().optional(),height:m.z.number().positive().optional(),start_sec:m.z.number().nonnegative().optional(),end_sec:m.z.number().nonnegative().optional(),frame_index:m.z.number().int().nonnegative().optional(),timestamp_sec:m.z.number().nonnegative().optional(),scene_confidence:m.z.number().min(0).max(1).optional()}),en=m.z.object({title:m.z.string().trim().min(1),start_sec:m.z.number().nonnegative(),end_sec:m.z.number().nonnegative(),summary:m.z.string()}),tn=m.z.object({start_sec:m.z.number().nonnegative(),end_sec:m.z.number().nonnegative(),speaker:m.z.string().trim().min(1),text:m.z.string()}),nn=m.z.object({label:m.z.string(),value:m.z.number(),currency:m.z.string()}),Po=m.z.object({document_type:m.z.string().optional(),title:m.z.string().optional(),organization:m.z.string().optional(),key_entities:m.z.array(m.z.string()).optional(),dates:m.z.array(m.z.string()).optional(),amounts:m.z.array(nn).optional(),media_type:m.z.enum(["video","audio"]).optional(),duration_sec:m.z.number().nonnegative().optional(),chapters:m.z.array(en).optional(),transcript_segments:m.z.array(tn).optional()}),Lo=m.z.enum(["CLOSED","OPEN","HALF_OPEN"]),rn=m.z.enum(Ye),on=m.z.object({circuit_breaker_status:m.z.string(),quality_tier:m.z.string(),latency_ms:m.z.number().nonnegative(),total_hits:m.z.number().int().nonnegative(),fallback_applied:m.z.boolean(),degraded_reason:m.z.string().nullable()}),an=m.z.enum(["CONTRACT_LEGAL","EMAIL_THREAD","DAILY_REPORT","FINANCIAL_REPORT","TECHNICAL_SPEC","MASTER_DATA","MEDIA_ASSET","GENERAL_DOCUMENT"]),vo=m.z.enum(["hierarchical","conversation","section","fixed_size","table_aware","semantic","none","multimodal"]),sn=m.z.object({metadata_id:m.z.number().int().positive(),chunk_index:m.z.number().int().nonnegative(),text:m.z.string(),score:m.z.number()}),ln=m.z.object({metadata_id:m.z.number().int().positive(),relation:m.z.string(),target_name:m.z.string()}),qe=m.z.object({query:m.z.string().trim().min(1,"query must not be empty"),tenant_id:Zt,domain_key:an.optional(),limit:m.z.number().int().positive().optional(),department_id:m.z.number().int().positive().optional(),search_mode:rn.optional(),strategy_id:m.z.number().int().positive().optional()}).strict(),Xe=m.z.object({hits:m.z.array(sn),graph_hits:m.z.array(ln),tiers:m.z.record(m.z.string(),m.z.boolean()),metadata:on});var We=class extends ue{async search(t){let n=qe.parse(t),r=await this.request("/ai/search/hybrid",n.tenant_id,n);return Xe.parse(r)}};var a=require("zod");var Re=require("zod"),ae=Re.z.string().uuid().transform(e=>e.toLowerCase()),w=Re.z.string().datetime({offset:!0}),Ie=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!Object.hasOwn(e,"__proto__"),d=(e,t,n)=>{e.addIssue({code:Re.z.ZodIssueCode.custom,path:[...t],message:n})},Mo=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:Z|([+-])(\d{2}):?(\d{2}))$/,cn=e=>{let t=w.safeParse(e).success?Mo.exec(e):null;if(t===null)return null;let[,n,r,o,i,l,s,c,h,u,y]=t,E=new Date(0);E.setUTCFullYear(Number(n),Number(r)-1,Number(o)),E.setUTCHours(Number(i),Number(l),s===void 0?0:Number(s),0);let _=h===void 0?0:(h==="+"?1:-1)*(Number(u)*3600+Number(y)*60);return{epochSeconds:E.getTime()/1e3-_,fraction:c===void 0?"":c}},Y=(e,t)=>{let n=cn(e),r=cn(t);if(n===null||r===null)return!1;if(n.epochSeconds!==r.epochSeconds)return n.epochSeconds<r.epochSeconds;let o=Math.max(n.fraction.length,r.fraction.length);return n.fraction.padEnd(o,"0")<r.fraction.padEnd(o,"0")};var S=require("zod");var Ze=["email","pdf","office","image","media","text","google_native","other"],Uo={email:"\u30E1\u30FC\u30EB",pdf:"PDF",office:"Office \u6587\u66F8",image:"\u753B\u50CF",media:"\u97F3\u58F0\u30FB\u52D5\u753B",text:"\u30C6\u30AD\u30B9\u30C8",google_native:"Google \u30CD\u30A4\u30C6\u30A3\u30D6",other:"\u305D\u306E\u4ED6"},fn=[["message/rfc822","email"],["application/pdf","pdf"],["application/vnd.openxmlformats-officedocument.*","office"],["application/msword","office"],["application/vnd.ms-excel","office"],["application/vnd.ms-powerpoint","office"],["application/vnd.google-apps.*","google_native"],["image/svg+xml","text"],["image/emf","other"],["image/x-emf","other"],["image/wmf","other"],["image/x-wmf","other"],["image/*","image"],["audio/*","media"],["video/*","media"],["text/*","text"],["application/json","text"],["application/xml","text"]];function zo(e){let t=(e.split(";")[0]??"").trim().toLowerCase();for(let[n,r]of fn)if(n.endsWith("*")?t.startsWith(n.slice(0,-1)):t===n)return r;return"other"}var Ae=["delete_child_assets","extract_text","analyze_media","extract_assets","ocr_children","ocr_document","resolve_body","enrich_document","project_to_indexes"],_e="record_document_state",et=[...Ae,_e],Ho=["EXTRACTING","ENRICHING","PROJECTING"],tt=["FAILED_EXTRACT","FAILED_ENRICH","FAILED_VECTOR","FAILED_GRAPH"],Qe=e=>({featureFlagKey:e,whenClosed:"skip",failureStatus:null}),dn=(e,t)=>({featureFlagKey:e,whenClosed:"fail",failureStatus:t}),nt={delete_child_assets:{key:"delete_child_assets",label:"\u65E7\u7248\u306E\u5B50\u30A2\u30BB\u30C3\u30C8\u524A\u9664",description:"\u3053\u306E\u7248\u3088\u308A\u524D\u306E\u7248\u304C\u751F\u3093\u3060\u5B50\u30A2\u30BB\u30C3\u30C8\u3092\u4FDD\u7BA1\u5C64\u3068\u7D22\u5F15\u304B\u3089\u5916\u3059\u3002",endpoint:"/ai/assets/delete",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:null,fanOut:null},extract_text:{key:"extract_text",label:"\u6587\u5B57\u5C64\u306E\u62BD\u51FA",description:"\u6587\u66F8\u304C\u6301\u3064\u6587\u5B57\u5C64 (PDF \u306E\u6587\u5B57\u30FBOffice \u306E\u672C\u6587\u30FB\u30E1\u30FC\u30EB\u306E\u672C\u6587\u3068\u898B\u51FA\u3057) \u3092\u8AAD\u307F\u3001\u4F4D\u7F6E\u60C5\u5831\u3068\u5171\u306B\u4FDD\u5B58\u3059\u308B\u3002",endpoint:"/ai/enrichment/extract",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:null,fanOut:null},analyze_media:{key:"analyze_media",label:"\u30E1\u30C7\u30A3\u30A2\u89E3\u6790",description:"\u97F3\u58F0\u30FB\u52D5\u753B\u3092\u8EE2\u5199\u3057\u3001\u767A\u8A71\u533A\u9593\u4ED8\u304D\u306E\u30C1\u30E3\u30F3\u30AF\u3068\u30AD\u30FC\u30D5\u30EC\u30FC\u30E0\u6570\u3092\u8A18\u9332\u3059\u308B\u3002",endpoint:"/ai/media/analyze",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[Qe("ENABLE_MEDIA_ANALYSIS")],capability:"transcription",fanOut:null},extract_assets:{key:"extract_assets",label:"\u5B50\u30A2\u30BB\u30C3\u30C8\u306E\u62BD\u51FA",description:"\u57CB\u3081\u8FBC\u307F\u753B\u50CF\u3084\u30E1\u30FC\u30EB\u306E\u6DFB\u4ED8\u3092\u5B50\u30A2\u30BB\u30C3\u30C8\u3068\u3057\u3066\u5207\u308A\u51FA\u3057\u3001\u6587\u66F8\u306E\u96A3\u306B\u4FDD\u7BA1\u3057\u3066\u767B\u9332\u3059\u308B\u3002",endpoint:"/ai/assets/extract",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[Qe("ENABLE_ASSET_EXTRACTION")],capability:"asset_extraction",fanOut:null},ocr_children:{key:"ocr_children",label:"\u5B50\u30A2\u30BB\u30C3\u30C8\u306E\u8AAD\u307F\u53D6\u308A",description:"\u5207\u308A\u51FA\u3057\u305F\u5B50\u30A2\u30BB\u30C3\u30C8\u3092\u62BD\u51FA\u9806\u306B 1 \u4EF6\u305A\u3064\u8AAD\u307F\u3001\u6587\u5B57\u5C64\u3092\u8AAD\u3081\u308B\u5B50 (\u30C6\u30AD\u30B9\u30C8\u30FB\u30E1\u30FC\u30EB\u30FBOffice\u30FBPDF) \u306F\u305D\u306E\u6587\u5B57\u5C64\u3092\u3001\u8AAD\u3081\u306A\u3044\u5B50\u306F\u7248\u9762\u3092\u5149\u5B66\u8A8D\u8B58\u3067\u8AAD\u3093\u3067\u3001\u5B50\u3054\u3068\u306B\u672C\u6587\u3068\u51FA\u6240\u3092\u4FDD\u5B58\u3059\u308B\u3002",endpoint:"/ai/ocr/run",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:"ocr",fanOut:"children"},ocr_document:{key:"ocr_document",label:"\u6587\u66F8\u306E OCR",description:"\u6587\u66F8\u81EA\u8EAB\u306E\u7248\u9762 (\u753B\u50CF\u30FBPDF \u306E\u5404\u30DA\u30FC\u30B8) \u3092\u5149\u5B66\u8A8D\u8B58\u306B\u304B\u3051\u308B\u3002",endpoint:"/ai/ocr/run",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[Qe("ENABLE_OCR")],capability:"ocr",fanOut:null},resolve_body:{key:"resolve_body",label:"\u672C\u6587\u306E\u78BA\u5B9A",description:"\u6587\u5B57\u5C64\u30FBOCR\u30FB\u8EE2\u5199\u306E\u3069\u308C\u3092\u672C\u6587\u3068\u3059\u308B\u304B\u3092\u6C7A\u3081\u3001\u51FA\u6240\u3092\u8A18\u9332\u3059\u308B\u3002",endpoint:"/ai/enrichment/body",phase:"ENRICHING",failureStatus:"FAILED_ENRICH",gates:[],capability:null,fanOut:null},enrich_document:{key:"enrich_document",label:"\u8981\u7D04\u3068\u69CB\u9020\u5316\u62BD\u51FA",description:"\u672C\u6587\u3092\u30E2\u30C7\u30EB\u3078\u6E21\u3057\u3001\u8981\u7D04\u30FB\u30BF\u30B0\u30FB\u69CB\u9020\u5316\u30C7\u30FC\u30BF\u30FB\u30C9\u30E1\u30A4\u30F3\u5206\u985E\u3092\u5F97\u308B\u3002",endpoint:"/ai/enrichment/document",phase:"ENRICHING",failureStatus:"FAILED_ENRICH",gates:[],capability:"enrichment",fanOut:null},project_to_indexes:{key:"project_to_indexes",label:"\u30D9\u30AF\u30C8\u30EB\u3068\u30B0\u30E9\u30D5\u3078\u306E\u6295\u5F71",description:"\u672C\u6587\u3092\u30C1\u30E3\u30F3\u30AF\u306B\u3057\u3066\u57CB\u3081\u8FBC\u307F\u3001\u30D9\u30AF\u30C8\u30EB\u7D22\u5F15\u3068\u30CA\u30EC\u30C3\u30B8\u30B0\u30E9\u30D5\u3078\u66F8\u304F\u3002",endpoint:"/ai/enrichment/project",phase:"PROJECTING",failureStatus:"FAILED_VECTOR",gates:[dn("ENABLE_VECTOR_INDEXING","FAILED_VECTOR"),dn("ENABLE_GRAPH_INDEXING","FAILED_GRAPH")],capability:null,fanOut:null}},un={whenClosed:"fail",failureStatus:"FAILED_EXTRACT"},xe=[{step:"delete_child_assets",dependsOn:[]},{step:"extract_text",dependsOn:["delete_child_assets"]},{step:"extract_assets",dependsOn:["extract_text"]},{step:"ocr_children",dependsOn:["extract_assets"]},{step:"ocr_document",dependsOn:["extract_text"]},{step:"resolve_body",dependsOn:["ocr_children","ocr_document"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}],pn=[{step:"delete_child_assets",dependsOn:[]},{step:"extract_text",dependsOn:["delete_child_assets"]},{step:"resolve_body",dependsOn:["extract_text"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}],hn={email:{kind:"email",steps:xe},pdf:{kind:"pdf",steps:xe},office:{kind:"office",steps:xe},google_native:{kind:"google_native",steps:xe},image:{kind:"image",steps:[{step:"delete_child_assets",dependsOn:[]},{step:"ocr_document",dependsOn:["delete_child_assets"],gatePolicy:un},{step:"resolve_body",dependsOn:["ocr_document"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}]},media:{kind:"media",steps:[{step:"delete_child_assets",dependsOn:[]},{step:"analyze_media",dependsOn:["delete_child_assets"],gatePolicy:un},{step:"resolve_body",dependsOn:["analyze_media"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"existing"}]},text:{kind:"text",steps:pn},other:{kind:"other",steps:pn}};function Ko(e){return hn[e]}function Go(e){let{gates:t}=nt[e.step],{gatePolicy:n}=e;return n===void 0?t:t.map(r=>({featureFlagKey:r.featureFlagKey,whenClosed:n.whenClosed,failureStatus:n.failureStatus}))}function jo(e){let t=new Map(e.steps.map(i=>[i.step,i]));for(let i of e.steps){if(i.gatePolicy!==void 0&&nt[i.step].gates.length===0)throw new Error(`Flow ${e.kind}: step ${i.step} overrides its gate policy, but the step has no gate to close.`);for(let l of i.dependsOn)if(!t.has(l))throw new Error(`Flow ${e.kind}: step ${i.step} depends on ${l}, which the flow does not contain.`)}let n=[...e.steps],r=new Set,o=[];for(;n.length>0;){let i=n.findIndex(s=>s.dependsOn.every(c=>r.has(c)));if(i===-1)throw new Error(`Flow ${e.kind}: the steps ${n.map(s=>s.step).join(", ")} depend on each other in a cycle.`);let[l]=n.splice(i,1);r.add(l.step),o.push(l)}return o}var mn={EXTRACTING:0,ENRICHING:1,PROJECTING:2};function Bo(e,t){return mn[e]-mn[t]}var it=S.z.enum(Ze),De=S.z.enum(Ae),yn=S.z.enum(et),st=S.z.enum(tt),gn=["RECORDED","UNCHANGED","ALREADY_RECORDED"],Sn=S.z.enum(gn),En=S.z.object({outcome:Sn}).strict(),Cn=["history_no_current_row","history_lock_timeout","history_write_failed"],bn="stale_run",Rn=S.z.enum(Cn),Te=S.z.enum(["RUNNING","SUCCEEDED","FAILED"]),In=S.z.enum(["RUNNING","SUCCEEDED","SKIPPED","FAILED"]),xn=S.z.enum(["ingest","retry","resync"]),Ne=S.z.enum(["text_layer","ocr","transcript"]),G=S.z.number().int().nonnegative().nullable(),An=S.z.object({provider:S.z.string().nullable(),model:S.z.string().nullable(),engine:S.z.string().nullable(),prompt_key:S.z.string().nullable(),prompt_version:S.z.number().int().nullable(),duration_ms:G,input_chars:G,output_chars:G,pages_read:G,pages_total:G,chunk_count:G,points_upserted:G,collection:S.z.string().nullable(),embedding_model:S.z.string().nullable(),strategy_id:S.z.number().int().positive().nullable(),graph_nodes:G,body_source:Ne.nullable(),detail:S.z.custom(Ie,"A report's detail holds no own __proto__ member.").pipe(S.z.record(S.z.string(),S.z.unknown()))}).strict(),_n=["no_pages","no_pages_rendered"],Dn=S.z.enum(_n),rt="gate_closed:",ot="source_skipped:",at="nothing_to_read:",Vo=["no_children","superseded","recording_disabled","recording_misconfigured"],Jo=e=>Vo.includes(e),Yo=/^[A-Z][A-Z0-9_]*$/;function lt(e){if(Jo(e))return{kind:e};if(e.startsWith(rt)){let t=e.slice(rt.length);return Yo.test(t)?{kind:"gate_closed",featureFlagKey:t}:null}if(e.startsWith(ot)){let t=De.safeParse(e.slice(ot.length));return t.success?{kind:"source_skipped",stepKey:t.data}:null}if(e.startsWith(at)){let t=Dn.safeParse(e.slice(at.length));return t.success?{kind:"nothing_to_read",token:t.data}:null}return null}function $o(e){let t=qo(e);if(lt(t)===null)throw new RangeError(`Skip reason ${JSON.stringify(e)} has no text form: ${JSON.stringify(t)} is outside the skip-reason grammar.`);return t}function qo(e){switch(e.kind){case"gate_closed":return`${rt}${e.featureFlagKey}`;case"no_children":case"superseded":case"recording_disabled":case"recording_misconfigured":return e.kind;case"source_skipped":return`${ot}${e.stepKey}`;case"nothing_to_read":return`${at}${e.token}`;default:{let t=e;throw new RangeError(`Unknown skip reason kind: ${JSON.stringify(t)}`)}}}var Xo=S.z.object({id:S.z.number().int().positive(),runId:S.z.number().int().positive(),sequence:S.z.number().int().nonnegative(),stepKey:yn,targetMetadataId:S.z.number().int().positive(),status:In,skipReason:S.z.string().nullable(),provenance:An.nullable(),strategyId:S.z.number().int().positive().nullable(),httpStatus:S.z.number().int().nullable(),errorCode:S.z.string().nullable(),errorMessage:S.z.string().nullable(),startedAt:w,finishedAt:w.nullable(),durationMs:G}).strict();function Wo(e,t){switch(e.stepKey===_e&&Zo(e,t),e.status){case"SKIPPED":e.skipReason===null&&d(t,["skipReason"],"A SKIPPED step must record why it was skipped."),e.provenance!==null&&d(t,["provenance"],"A SKIPPED step read nothing, so it has no report.");return;case"SUCCEEDED":e.provenance===null&&d(t,["provenance"],"A SUCCEEDED step must carry its report."),e.skipReason!==null&&d(t,["skipReason"],"A SUCCEEDED step was not skipped.");return;case"RUNNING":e.finishedAt!==null&&d(t,["finishedAt"],"A RUNNING step has not finished.");return;case"FAILED":e.skipReason!==null&&d(t,["skipReason"],"A FAILED step was not skipped.");return}}var Qo=["superseded","recording_disabled","recording_misconfigured"];function Zo(e,t){if(e.strategyId!==null&&d(t,["strategyId"],"The terminal step applies no strategy."),e.httpStatus!==null&&d(t,["httpStatus"],"The terminal step calls no API, so it has no HTTP status."),e.status==="SUCCEEDED"&&e.provenance!==null){En.safeParse(e.provenance.detail).success||d(t,["provenance","detail"],"A succeeded terminal step's detail is exactly { outcome }.");for(let[n,r]of Object.entries(e.provenance))n!=="detail"&&r!==null&&d(t,["provenance",n],"A succeeded terminal step reports nothing but its outcome.")}if(e.status==="FAILED"&&(e.provenance!==null&&d(t,["provenance"],"Neither the failure close nor the recovery sweeper writes a terminal step's report."),e.errorCode!==bn&&!Rn.safeParse(e.errorCode).success&&d(t,["errorCode"],"A failed terminal step names a history error code, or the stale-run code the sweeper writes.")),e.status==="SKIPPED"&&e.skipReason!==null){let n=lt(e.skipReason);(n===null||!Qo.includes(n.kind))&&d(t,["skipReason"],"A skipped terminal step names one of the terminal skip reasons.")}}var Tn=Xo.superRefine(Wo),Nn=S.z.object({id:S.z.number().int().positive(),tenantId:S.z.string().min(1),metadataId:S.z.number().int().positive(),revision:S.z.number().int().positive(),runUid:S.z.string().uuid(),jobId:S.z.string().min(1),attempt:S.z.number().int().positive(),trigger:xn,documentKind:it,flowKey:S.z.string().min(1),status:Te,retryScheduled:S.z.boolean(),failedStepKey:De.nullable(),errorMessage:S.z.string().nullable(),requestedBy:S.z.string().min(1),startedAt:w,finishedAt:w.nullable(),steps:S.z.array(Tn)}).strict();function kn(e,t){e.retryScheduled&&e.status!=="FAILED"&&d(t,["retryScheduled"],"Only a FAILED run can have a retry scheduled.")}var ct=Nn.superRefine(kn),dt=Nn.omit({steps:!0}).superRefine(kn);function ea(e,t){e.sampleCount>0||(e.durationP50Ms!==null&&d(t,["durationP50Ms"],"A step with no sample has no median latency."),e.durationP95Ms!==null&&d(t,["durationP95Ms"],"A step with no sample has no 95th-percentile latency."))}var ta=S.z.object({documentKind:it,stepKey:De,sampleCount:S.z.number().int().nonnegative(),succeeded:S.z.number().int().nonnegative(),failed:S.z.number().int().nonnegative(),skipped:S.z.number().int().nonnegative(),durationP50Ms:G,durationP95Ms:G,lastStartedAt:w.nullable()}).strict().superRefine(ea);var ft=1,we=3,ht=64,yt=1e6,Fe=4096,Pe=.3,gt=1024,St=67108864,Et=16777216,Ct=500,bt=50,na=50,ra=1e4,wn=1,Z=["classification","metadata","labels","tags","structured_data","text","summary","chunks","assets"],Rt=a.z.enum(Z),Fn=["RUN","PRE_WRITE","MANUAL","BACKFILL"],It=a.z.enum(Fn),Pn=["SUCCEEDED","FAILED"],Ln=a.z.enum(Pn),vn=["ADDED","REMOVED","MODIFIED","MOVED"],Mn=a.z.enum(vn),Un=["clause","breadcrumbs"],zn=a.z.enum(Un),Hn=["EXACT","WHITESPACE_NORMALIZED","UNVERIFIED"],Kn=a.z.enum(Hn),Gn=["run","ingest","failure","state","change"],oa=a.z.enum(Gn),jn=["LF","CRLF","CR","MIXED","NONE"],aa=a.z.enum(jn),Bn=["text","summary","chunks"],ia=a.z.enum(Bn),Vn=["RECORDED","UNCHANGED"],Jn=a.z.enum(Vn),Yn=a.z.lazy(()=>a.z.custom(Ie,"A JSON object here holds no own __proto__ member.").pipe(a.z.record(a.z.string(),j))),j=a.z.lazy(()=>a.z.union([a.z.string(),a.z.number().finite(),a.z.boolean(),a.z.null(),a.z.array(j),Yn])),xt=Q.exclude([oe]),M=a.z.number().int().positive(),I=a.z.number().int().nonnegative(),Oe=a.z.string().regex(/^[0-9a-f]{64}$/,"A SHA-256 is 64 lowercase hexadecimal digits."),B=(e,t)=>e<t?-1:e>t?1:0,Le=(e,t)=>B(e.assetType,t.assetType)||e.assetIndex-t.assetIndex,ie=(e,t,n,r,o)=>{for(let i=1;i<e.length;i++)t(e[i-1],e[i])>=0&&d(n,[...r,i],o)},$n=a.z.object({confidentialityLevel:Q,departmentId:a.z.number().int().nullable(),folderPath:a.z.string().nullable(),createdBy:a.z.string()}).strict(),qn=a.z.object({fileName:a.z.string(),filePath:a.z.string(),fileId:a.z.string().nullable(),revision:M,revisionId:a.z.string().nullable(),fileSize:I,mimeType:a.z.string(),fileHash:a.z.string().nullable(),mtime:w}).strict(),Xn=a.z.object({labelKey:a.z.string().min(1),assignedBy:a.z.string(),confidenceScore:a.z.number().finite()}).strict(),Wn=a.z.object({assetType:a.z.string().min(1),assetIndex:I,mimeType:a.z.string(),fileSize:I,textSha256:Oe.nullable()}).strict(),Qn=a.z.object({body:a.z.string().nullable(),mime:a.z.string().nullable(),source:Ne.nullable(),isTruncated:a.z.boolean(),pageOffsets:j}).strict(),Zn=a.z.object({index:I,hash:Oe,whitespaceFreeHash:Oe,charStart:I,charEnd:I,breadcrumbs:a.z.string(),clause:a.z.string().nullable(),page:a.z.number().int().nullable(),sheet:a.z.string().nullable(),slide:a.z.number().int().nullable(),startSec:a.z.number().finite().nullable(),endSec:a.z.number().finite().nullable(),tokenCount:I,parentOrdinal:I}).strict(),er=a.z.object({ordinal:I,contentHash:Oe,charLength:I}).strict();function sa(e,t){ie(e.children,(r,o)=>r.index-o.index,t,["children"],"Children are listed in strictly ascending index.");let n=0;e.children.forEach((r,o)=>{r.charStart>r.charEnd&&d(t,["children",o,"charEnd"],"A span ends at or after its start."),r.parentOrdinal===n?n++:r.parentOrdinal>n&&d(t,["children",o,"parentOrdinal"],"Parents are numbered in the order they first appear.")}),(e.parents.length!==n||e.parents.some((r,o)=>r.ordinal!==o))&&d(t,["parents"],"Each parent the children reach is listed exactly once, in ordinal order.")}var tr=a.z.object({version:a.z.literal(wn),children:a.z.array(Zn).min(1),parents:a.z.array(er)}).strict().superRefine(sa);function la(e,t){ie(e.labels,(n,r)=>B(n.labelKey,r.labelKey),t,["labels"],"Labels are ordered by labelKey with no key repeated."),ie(e.tags??[],B,t,["tags"],"Tags are ordered with no tag repeated."),ie(e.assets,Le,t,["assets"],"Assets are ordered by (assetType, assetIndex) with no key repeated.")}var ca=a.z.object({classification:$n,metadata:qn,labels:a.z.array(Xn),tags:a.z.array(a.z.string()).nullable(),structured_data:j,text:Qn,summary:a.z.string().nullable(),chunks:tr.nullable(),assets:a.z.array(Wn)}).strict().superRefine(la),nr=["addedCount","removedCount","modifiedCount","movedCount","unchangedCount","charsAdded","charsRemoved"],rr={classification:["modifiedCount"],metadata:["modifiedCount"],labels:["addedCount","removedCount","modifiedCount","unchangedCount"],tags:["addedCount","removedCount","unchangedCount"],structured_data:["addedCount","removedCount","modifiedCount"],text:["addedCount","removedCount","unchangedCount","charsAdded","charsRemoved"],summary:["addedCount","removedCount","unchangedCount","charsAdded","charsRemoved"],chunks:["addedCount","removedCount","modifiedCount","movedCount","unchangedCount"],assets:["addedCount","removedCount","modifiedCount","unchangedCount"]};function da(e,t){let n=rr[e.facet];for(let r of nr)n.includes(r)&&e[r]===null&&d(t,[r],`The ${e.facet} facet always counts ${r}.`),!n.includes(r)&&e[r]!==null&&d(t,[r],`${r} does not apply to the ${e.facet} facet.`)}var or=a.z.object({facet:Rt,addedCount:I.nullable(),removedCount:I.nullable(),modifiedCount:I.nullable(),movedCount:I.nullable(),unchangedCount:I.nullable(),charsAdded:I.nullable(),charsRemoved:I.nullable()}).strict().superRefine(da),On=new Map(Z.map((e,t)=>[e,t])),ve=(e,t)=>On.get(e)-On.get(t),ar=a.z.array(or).min(1).superRefine((e,t)=>ie(e,(n,r)=>ve(n.facet,r.facet),t,[],"A change lists each changed facet once, in display order.")),Me=a.z.object({field:a.z.string().min(1),before:j,after:j}).strict(),pt=a.z.object({key:a.z.string().min(1),value:Yn}).strict(),ir=a.z.object({key:a.z.string().min(1),fields:a.z.array(Me).min(1)}).strict(),ut=a.z.string().refine(e=>e===""||e.startsWith("/"),"A JSON Pointer is empty or starts with '/'."),sr=a.z.discriminatedUnion("op",[a.z.object({op:a.z.literal("add"),path:ut,value:j}).strict(),a.z.object({op:a.z.literal("remove"),path:ut,previous:j}).strict(),a.z.object({op:a.z.literal("replace"),path:ut,value:j,previous:j}).strict()]),lr=a.z.object({linesAdded:I,linesRemoved:I,linesUnchanged:I,charsAdded:I,charsRemoved:I,similarity:a.z.number().min(0).max(1).nullable()}).strict();function ua(e,t){e.linesAdded>e.newLines&&d(t,["linesAdded"],"A hunk adds no more lines than it spans on the new side."),e.linesRemoved>e.oldLines&&d(t,["linesRemoved"],"A hunk removes no more lines than it spans on the old side."),e.linesAdded+e.linesRemoved===0&&d(t,["linesAdded"],"A hunk changes at least one line.")}var cr=a.z.object({hunk:I,oldStart:I,oldLines:I,newStart:I,newLines:I,firstPage:a.z.number().int().nullable(),linesAdded:I,linesRemoved:I}).strict().superRefine(ua),dr=(e,t)=>{e.forEach((n,r)=>{n.hunk!==r&&d(t,["hunks",r,"hunk"],"Hunks are numbered from 0 in order.")})},ur={attributes:a.z.array(Me),stats:lr,hunks:a.z.array(cr)},pa=a.z.object(ur).strict().superRefine((e,t)=>dr(e.hunks,t)),pr=a.z.object({kind:a.z.enum(["equal","removed","added"]),text:a.z.string().min(1)}).strict(),ma={context:["equal"],removed:["equal","removed"],added:["equal","added"]};function fa(e,t){e.oldNumber===null!=(e.kind==="added")&&d(t,["oldNumber"],"Context and removed lines carry their old number; added lines carry none."),e.newNumber===null!=(e.kind==="removed")&&d(t,["newNumber"],"Context and added lines carry their new number; removed lines carry none."),e.segments.forEach((n,r)=>{ma[e.kind].includes(n.kind)||d(t,["segments",r,"kind"],`A ${e.kind} line has no ${n.kind} segment.`)})}var mr=a.z.object({kind:a.z.enum(["context","removed","added"]),oldNumber:M.nullable(),newNumber:M.nullable(),page:a.z.number().int().nullable(),segments:a.z.array(pr)}).strict().superRefine(fa),ha=a.z.object({lines:a.z.array(mr).max(Ct),next:I.nullable()}).strict().superRefine((e,t)=>{e.next!==null&&e.lines.length===0&&d(t,["next"],"An empty page has no next page.")}),At=a.z.number().int().min(1).max(Ct),ya=a.z.number().int().min(1).max(bt),mt=a.z.object({index:I,charStart:I,charEnd:I,page:a.z.number().int().nullable(),sheet:a.z.string().nullable(),slide:a.z.number().int().nullable(),startSec:a.z.number().finite().nullable(),endSec:a.z.number().finite().nullable(),breadcrumbs:a.z.string(),tokenCount:I,fidelity:Kn}).strict();function ga(e,t){e.old===null!=(e.kind==="ADDED")&&d(t,["old"],"Every chunk change but ADDED has an old chunk."),e.new===null!=(e.kind==="REMOVED")&&d(t,["new"],"Every chunk change but REMOVED has a new chunk."),e.pairing===null==(e.kind==="MODIFIED")&&d(t,["pairing"],"A MODIFIED pair names the rule that paired it; no other change has one.")}var fr=a.z.object({entry:I,kind:Mn,pairing:zn.nullable(),old:mt.nullable(),new:mt.nullable()}).strict().superRefine(ga),hr=a.z.object({added:I,removed:I,modified:I,moved:I,unchanged:I}).strict();function Sa(e,t){e.entries.forEach((o,i)=>{o.entry!==i&&d(t,["entries",i,"entry"],"Chunk entries are numbered from 0 in order.")});let n={ADDED:0,REMOVED:0,MODIFIED:0,MOVED:0};for(let o of e.entries)n[o.kind]++;let r=[["added",n.ADDED],["removed",n.REMOVED],["modified",n.MODIFIED],["moved",n.MOVED]];for(let[o,i]of r)e.stats[o]!==i&&d(t,["stats",o],`The ${o} count equals the number of entries of that kind.`)}var yr=a.z.union([a.z.object({facet:Rt,change:a.z.literal("UNCHANGED")}).strict(),a.z.object({facet:a.z.enum(["classification","metadata"]),change:a.z.literal("CHANGED"),fields:a.z.array(Me).min(1)}).strict(),a.z.object({facet:a.z.enum(["labels","assets"]),change:a.z.literal("CHANGED"),added:a.z.array(pt),removed:a.z.array(pt),modified:a.z.array(ir),unchangedCount:I}).strict(),a.z.object({facet:a.z.literal("tags"),change:a.z.literal("CHANGED"),added:a.z.array(a.z.string()),removed:a.z.array(a.z.string()),unchangedCount:I}).strict(),a.z.object({facet:a.z.literal("structured_data"),change:a.z.literal("CHANGED"),operations:a.z.array(sr).min(1)}).strict(),a.z.object({facet:a.z.enum(["text","summary"]),change:a.z.literal("CHANGED"),...ur}).strict().superRefine((e,t)=>dr(e.hunks,t)),a.z.object({facet:a.z.literal("chunks"),change:a.z.literal("CHANGED"),stats:hr,entries:a.z.array(fr),textUnchangedChunkingChanged:a.z.boolean()}).strict().superRefine(Sa)]),Ea=a.z.object({diffEngineVersion:M,facets:a.z.array(yr)}).strict().superRefine((e,t)=>{(e.facets.length!==Z.length||e.facets.some((n,r)=>n.facet!==Z[r]))&&d(t,["facets"],"A comparison carries every facet once, in display order.")}),fe=e=>a.z.object({kind:a.z.literal("readable"),item:e}).strict(),_t=a.z.object({kind:a.z.literal("restricted"),subject:a.z.literal("run"),startedAt:w,finishedAt:w.nullable(),status:Te}).strict(),Ca=a.z.object({kind:a.z.literal("restricted"),subject:a.z.literal("ingest"),createdAt:w,updatedAt:w,syncStatus:$e.nullable()}).strict(),ba=a.z.object({kind:a.z.literal("restricted"),subject:a.z.literal("failure"),failedAt:w.nullable(),syncStatus:st}).strict(),gr=a.z.object({kind:a.z.literal("restricted"),subject:a.z.literal("state"),settledAt:w}).strict(),Sr=a.z.object({kind:a.z.literal("restricted"),subject:a.z.literal("change"),settledAt:w}).strict();function Ra(e,t){let n=e.cause==="RUN";e.runId!==null!==n&&d(t,["runId"],"A RUN state names its run; no other state does."),e.runOutcome!==null!==n&&d(t,["runOutcome"],"A RUN state carries the worker's outcome; no other state does."),e.changes!==null!=(e.previousStateId!==null)&&d(t,["changes"],"A state carries its counts exactly when its predecessor is readable."),e.diffEngineVersion!==null!=(e.changes!==null)&&d(t,["diffEngineVersion"],"The engine version comes with the counts it produced."),e.modelOnlyChange&&e.changes===null&&d(t,["modelOnlyChange"],"Only a change with counts can be a model-only change."),e.previousStateId===e.stateId&&d(t,["previousStateId"],"A state does not precede itself.")}var Er=a.z.object({stateId:M,revision:M,cause:It,runId:M.nullable(),runOutcome:Ln.nullable(),settledAt:w,actor:a.z.string().min(1),classification:a.z.object({confidentialityLevel:xt,departmentId:a.z.number().int().nullable(),folderPath:a.z.string().nullable()}).strict(),modelOnlyChange:a.z.boolean(),previousStateId:M.nullable(),changes:ar.nullable(),diffEngineVersion:M.nullable()}).strict().superRefine(Ra),Cr=a.z.discriminatedUnion("kind",[fe(Er),gr]),br=a.z.discriminatedUnion("kind",[fe(ct),_t]),Ia=a.z.discriminatedUnion("kind",[fe(dt),_t]),Rr=(e,t,n)=>{for(let r=1;r<e.length;r++)Y(e[r-1],e[r])&&d(t,[...n,r],"Entries are listed newest first.")},ke=e=>e.kind==="readable"?e.item.settledAt:e.settledAt;function xa(e,t){ie(e.revisions,(r,o)=>o.revision-r.revision,t,["revisions"],"Revisions are listed newest first, each once.");let n=e.revisions.filter(r=>r.isCurrent);(n.length!==1||n[0]?.metadataId!==e.document.metadataId||n[0].revision!==e.document.revision)&&d(t,["revisions"],"Exactly one revision is current: the row the history names."),Rr(e.states.map(ke),t,["states"])}var Aa=a.z.object({document:a.z.object({metadataId:M,fileName:a.z.string().min(1),fileUri:a.z.string().min(1),revision:M,confidentialityLevel:xt}).strict(),revisions:a.z.array(a.z.object({metadataId:M,revision:M,revisionId:a.z.string().nullable(),isCurrent:a.z.boolean()}).strict()),states:a.z.array(Cr),runs:a.z.array(br)}).strict().superRefine(xa),Ir=a.z.object({stateId:M,previousStateId:M,metadataId:M,fileName:a.z.string().min(1),fileUri:a.z.string().min(1),revision:M,previousRevision:M,cause:It,actor:a.z.string().min(1),settledAt:w,changes:ar}).strict().superRefine((e,t)=>{e.previousStateId===e.stateId&&d(t,["previousStateId"],"A state does not precede itself.")}),xr=a.z.discriminatedUnion("kind",[fe(Ir),Sr]),Dt=a.z.object({settledAt:w,id:M.max(Number.MAX_SAFE_INTEGER)}).strict(),me="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function _a(e){let t="";for(let n=0;n<e.length;n+=3){let r=e.length-n,o=e[n]<<16|(r>1?e[n+1]:0)<<8|(r>2?e[n+2]:0);t+=me[o>>18&63]+me[o>>12&63],r>1&&(t+=me[o>>6&63]),r>2&&(t+=me[o&63])}return t}function Da(e){if(e.length%4===1)return null;let t=[],n=0,r=0;for(let o of e){let i=me.indexOf(o);if(i===-1)return null;n=n<<6|i,r+=6,r>=8&&(r-=8,t.push(n>>r&255),n&=(1<<r)-1)}return Uint8Array.from(t)}function Ar(e){let{settledAt:t,id:n}=Dt.parse(e);return _a(new TextEncoder().encode(U({id:n,settledAt:t})))}function _r(e){let t=Da(e);if(t===null)return null;let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{return null}let r=Dt.safeParse(n);return r.success&&Ar(r.data)===e?r.data:null}var Ta=a.z.object({rows:a.z.array(xr).max(bt),next:a.z.string().nullable()}).strict().superRefine((e,t)=>{Rr(e.rows.map(ke),t,["rows"]),e.next!==null&&e.rows.length===0&&d(t,["next"],"An empty page has no next page.");let n=e.next===null?null:_r(e.next);e.next!==null&&n===null&&d(t,["next"],"The next position is a cursor encodeChangeFeedCursor wrote.");let r=e.rows[e.rows.length-1];n!==null&&r!==void 0&&(Y(n.settledAt,ke(r))||Y(ke(r),n.settledAt))&&d(t,["next"],"The next position is the arriving state of the page's last row."),n!==null&&r?.kind==="readable"&&n.id!==r.item.stateId&&d(t,["next"],"The next position names the arriving state of the page's last readable row.")}),Na=a.z.object({outcome:Jn}).strict();var p=require("zod");var Dr=[{code:"DEPLOYMENT_DISABLED",status:503,errorCode:5035},{code:"RUN_ALREADY_ACTIVE",status:409,errorCode:4091},{code:"BASIS_INVALID",status:409,errorCode:4092},{code:"RUN_ALREADY_FINISHED",status:409,errorCode:4093},{code:"FORBIDDEN",status:403,errorCode:null}];var Tr={INTEGRITY_TOMBSTONE_RETENTION_DAYS:{min:1,max:3650},INTEGRITY_FINDING_SAMPLE_LIMIT:{min:1,max:5e3},INTEGRITY_RUN_HEARTBEAT_TIMEOUT_SECONDS:{min:30,max:3600},INTEGRITY_RUN_RETENTION_COUNT:{min:2,max:100},POLICY_CONFLICT_MAX_TIE_GROUP_SIZE:{min:2,max:60}};var wa=e=>{for(let t of Object.values(e))Object.freeze(t);return Object.freeze(e)},he=wa(Tr),Nr=e=>Object.hasOwn(he,e),kr=(e,t)=>{let{min:n,max:r}=he[e];if(!Number.isInteger(t)||t<n||t>r)throw new RangeError(`${e} \u306F ${n}\u301C${r} \u306E\u6574\u6570\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)},Fa=(e,t)=>{Nr(e)&&kr(e,t)},Pa=(e,t)=>{if(!Nr(e))throw new TypeError(`The range table bounds no parameter named ${JSON.stringify(e)}.`);kr(e,t)};var ze=p.z.enum(["QDRANT","NEO4J"]),wr=p.z.enum(["PRODUCTION","VARIANT","LABEL"]),Ot=p.z.enum(["EXPECTED","LIVE","HISTORY","TOMBSTONE","AWAITING_SUCCESSOR","IN_FLIGHT","UNPLACED","UNRECORDED","UNREFERENCED","CHANGED_AFTER_START","PIPELINE_FAILED","PROJECTION_REFUSED","ORPHAN","TOMBSTONE_EXPIRED","UNPROPAGATED_DELETE","STALE_REVISION","MISPLACED","OUT_OF_TIER","UNMARKED_SUPERSEDED","FLAG_DRIFT","VARIANT_FLAG_DRIFT","DETACHED","UNKEYED","MISSING","COUNT_MISMATCH","UNPROJECTED","UNKEYED_ENTITY"]),wt=Ot.exclude(["EXPECTED","LIVE","HISTORY"]),Fr=p.z.enum(["POINT","NODE","CHUNK","DOCUMENT"]),Pr=p.z.enum(["EXPECTED","HEALTHY","RETAINED","INFORMATIONAL","DISCREPANCY"]),Lr=p.z.enum(["NONE","PURGE","FLAG","REPROJECT"]),k=(e,t)=>Object.freeze({disposition:e,repairAction:t}),vr=Object.freeze({EXPECTED:k("EXPECTED","NONE"),LIVE:k("HEALTHY","NONE"),HISTORY:k("RETAINED","NONE"),TOMBSTONE:k("RETAINED","NONE"),AWAITING_SUCCESSOR:k("RETAINED","NONE"),IN_FLIGHT:k("INFORMATIONAL","NONE"),UNPLACED:k("INFORMATIONAL","NONE"),UNRECORDED:k("INFORMATIONAL","NONE"),UNREFERENCED:k("INFORMATIONAL","NONE"),CHANGED_AFTER_START:k("INFORMATIONAL","NONE"),PIPELINE_FAILED:k("INFORMATIONAL","NONE"),PROJECTION_REFUSED:k("INFORMATIONAL","NONE"),ORPHAN:k("DISCREPANCY","PURGE"),TOMBSTONE_EXPIRED:k("DISCREPANCY","PURGE"),UNPROPAGATED_DELETE:k("DISCREPANCY","FLAG"),STALE_REVISION:k("DISCREPANCY","PURGE"),MISPLACED:k("DISCREPANCY","PURGE"),OUT_OF_TIER:k("DISCREPANCY","PURGE"),UNMARKED_SUPERSEDED:k("DISCREPANCY","FLAG"),FLAG_DRIFT:k("DISCREPANCY","REPROJECT"),VARIANT_FLAG_DRIFT:k("DISCREPANCY","NONE"),DETACHED:k("DISCREPANCY","PURGE"),UNKEYED:k("DISCREPANCY","PURGE"),MISSING:k("DISCREPANCY","REPROJECT"),COUNT_MISMATCH:k("DISCREPANCY","REPROJECT"),UNPROJECTED:k("DISCREPANCY","REPROJECT"),UNKEYED_ENTITY:k("DISCREPANCY","NONE")}),Mr=p.z.enum(["SCAN","REPAIR"]),Ur=p.z.enum(["RUNNING","COMPLETED","FAILED","CANCELLED","ABANDONED"]),zr=p.z.enum(["CONSISTENT","INCONSISTENT","UNDETERMINED"]),Hr=p.z.enum(["QDRANT","NEO4J","DOCUMENTS"]),Kr=p.z.enum(["APPLIED","SKIPPED","FAILED"]),Gr=p.z.enum(["RECLASSIFIED","IN_FLIGHT","DESTINATION_PENDING","BASIS_EXHAUSTED","PROJECTION_REFUSED","PIPELINE_FAILED","UNRECORDED","OUTSIDE"]),ye=100,H=p.z.number().int().nonnegative(),Ue=p.z.number().int().min(300).max(599),Tt=["repairedCount","repairFailedCount","repairSkippedCount"],jr=p.z.string().regex(/^[0-9a-f]{64}$/,"A store fingerprint is 64 lowercase hexadecimal digits."),Or=he.INTEGRITY_TOMBSTONE_RETENTION_DAYS,La=p.z.object({runUid:ae,mode:Mr,status:Ur,requestedBy:p.z.string().min(1),executor:p.z.string().min(1),basisRunUid:ae.nullable(),storeFingerprint:jr,tombstoneRetentionDays:p.z.number().int().min(Or.min).max(Or.max),startedAt:w,finishedAt:w.nullable(),verdict:zr.nullable(),errorClass:p.z.string().min(1).nullable(),reprojectDocuments:H.nullable(),reprojectRebuildDocuments:H.nullable()}).strict(),va=(e,t)=>{let n=e.status==="COMPLETED";e.mode==="REPAIR"!=(e.basisRunUid!==null)&&d(t,["basisRunUid"],"A REPAIR run names its basis SCAN run, and a SCAN run names none."),n!==(e.verdict!==null)&&d(t,["verdict"],"Only a COMPLETED run has a verdict."),n!==(e.reprojectDocuments!==null)&&d(t,["reprojectDocuments"],"Only a COMPLETED run has the count of documents to re-project.");let{reprojectDocuments:r,reprojectRebuildDocuments:o}=e;r===null||o===null?r!==o&&d(t,["reprojectRebuildDocuments"],"The documents a re-projection embeds are counted together with the documents it re-projects."):o>r&&d(t,["reprojectRebuildDocuments"],"The documents a re-projection embeds are no more than the documents it re-projects."),e.status==="RUNNING"!=(e.finishedAt===null)&&d(t,["finishedAt"],"Only a RUNNING run has not finished."),e.finishedAt!==null&&Y(e.finishedAt,e.startedAt)&&d(t,["finishedAt"],"A run does not finish before it starts."),(e.status==="FAILED"||e.status==="ABANDONED")!=(e.errorClass!==null)&&d(t,["errorClass"],"Only a FAILED or ABANDONED run names an error class.")},He=La.superRefine(va),Ma=p.z.object({store:ze,scopeKey:p.z.string().min(1),scopeRole:wr,itemClass:Ot,unit:Fr,disposition:Pr,repairAction:Lr,itemCount:H.nullable(),unmeasuredReason:p.z.string().min(1).nullable(),measuredAt:w.nullable(),repairedCount:H.nullable(),repairFailedCount:H.nullable(),repairSkippedCount:H.nullable()}).strict(),Ua=(e,t)=>{let n=vr[e.itemClass];e.disposition!==n.disposition&&d(t,["disposition"],`A ${e.itemClass} quantity is ${n.disposition}.`),e.repairAction!==n.repairAction&&d(t,["repairAction"],`A repair's action on ${e.itemClass} items is ${n.repairAction}.`);let r=e.itemCount===null;r!==(e.unmeasuredReason!==null)&&d(t,["unmeasuredReason"],"An unmeasured quantity (itemCount null) has a reason, and a measured one has none."),r!==(e.measuredAt===null)&&d(t,["measuredAt"],"Only a measured quantity has a measurement time.");let{repairedCount:o,repairFailedCount:i,repairSkippedCount:l}=e;if(o===null||i===null||l===null){if(Tt.some(s=>e[s]!==null))for(let s of Tt)e[s]===null&&d(t,[s],"The repaired, failed and skipped counts are recorded together or not at all.");return}e.repairAction==="NONE"&&d(t,["repairAction"],"Only a class with a repair action carries repair counts."),e.itemCount!==null&&o+i+l>e.itemCount&&d(t,["itemCount"],"The repaired, failed and skipped counts together do not exceed the measured count.")},Br=Ma.superRefine(Ua),za=p.z.object({run:He,phase:Hr.nullable(),phaseScope:p.z.string().min(1).nullable(),phaseDone:H.nullable(),phaseTotal:H.nullable(),heartbeatAt:w,isStale:p.z.boolean(),cancelRequestedAt:w.nullable()}).strict(),Ha=(e,t)=>{if(e.run.status!=="RUNNING"&&d(t,["run","status"],"The active run is a RUNNING run."),Y(e.heartbeatAt,e.run.startedAt)&&d(t,["heartbeatAt"],"A run's heartbeat is not earlier than its start."),e.phase===null)for(let n of["phaseScope","phaseDone","phaseTotal"])e[n]!==null&&d(t,[n],"A run with no phase has no phase progress.");e.phase==="DOCUMENTS"&&e.phaseScope!==null&&d(t,["phaseScope"],"The DOCUMENTS phase scans no scope.")},Vr=za.superRefine(Ha),Ka=p.z.object({run:He,quantities:p.z.array(Br),previousStoreFingerprint:jr.nullable()}).strict(),Ga=(e,t)=>{e.run.status!=="COMPLETED"&&d(t,["run","status"],"The last completed run is a COMPLETED run.");let n=new Set;for(let[r,o]of e.quantities.entries()){let i=JSON.stringify([o.store,o.scopeKey,o.itemClass]);if(n.has(i)&&d(t,["quantities",r],"A run records each (store, scope, class) cell once."),n.add(i),e.run.mode==="SCAN")for(let l of Tt)o[l]!==null&&d(t,["quantities",r,l],"A SCAN run repairs nothing, so its quantities carry no repair counts.")}},ja=["FAILED","CANCELLED","ABANDONED"],Ba=p.z.object({run:He,repairAppliedItems:H.nullable(),hasNewerRepair:p.z.boolean()}).strict(),Va=(e,t)=>{ja.includes(e.run.status)||d(t,["run","status"],"A newer unsuccessful run is FAILED, CANCELLED or ABANDONED."),e.run.mode==="SCAN"&&e.repairAppliedItems!==null&&d(t,["repairAppliedItems"],"A SCAN run applies nothing."),e.run.mode==="REPAIR"&&!e.hasNewerRepair&&d(t,["hasNewerRepair"],"An unsuccessful REPAIR run is itself a repair newer than the last completed run.")},Ja=p.z.object({readAt:w,lastCompleted:Ka.superRefine(Ga).nullable(),active:Vr.nullable(),newerUnsuccessful:Ba.superRefine(Va).nullable()}).strict(),Ya=p.z.object({sequence:p.z.number().int().min(1),itemKey:p.z.string().min(1),metadataId:p.z.number().int().positive().nullable(),fileUri:p.z.string().nullable(),revision:p.z.number().int().nullable(),observed:p.z.record(p.z.string(),p.z.unknown()),repairOutcome:Kr.nullable(),repairErrorClass:p.z.string().min(1).nullable(),repairSkipReason:Gr.nullable()}).strict(),$a=(e,t)=>{e.repairOutcome==="FAILED"!=(e.repairErrorClass!==null)&&d(t,["repairErrorClass"],"Only a FAILED finding names an error class."),e.repairOutcome==="SKIPPED"!=(e.repairSkipReason!==null)&&d(t,["repairSkipReason"],"Only a SKIPPED finding names a skip reason.")},Jr=Ya.superRefine($a),qa=p.z.object({sotDomain:p.z.string().nullable()}).passthrough(),Xa=p.z.object({rows:p.z.array(Jr),nextAfter:p.z.number().int().min(1).nullable(),recordedCount:H,totalCount:H.nullable()}).strict(),Wa=(e,t)=>{for(let[n,r]of e.rows.entries()){let o=e.rows[n-1];o!==void 0&&r.sequence<=o.sequence&&d(t,["rows",n,"sequence"],"A page lists its rows in ascending sequence.")}e.nextAfter!==null&&e.nextAfter!==e.rows.at(-1)?.sequence&&d(t,["nextAfter"],"The next page starts after the sequence of this page's last row.")},Qa=Xa.superRefine(Wa),Za=p.z.object({runUid:ae,store:ze,scopeKey:p.z.string().min(1),itemClass:wt,after:p.z.number().int().min(1).optional(),limit:p.z.number().int().min(1).max(ye)}).strict(),ei=p.z.object({runUid:ae,store:ze,scopeKey:p.z.string().min(1),itemClass:wt.extract(["UNRECORDED"]),after:p.z.number().int().min(1).optional()}).strict(),ti=p.z.object({requeued:H,skipped:p.z.array(p.z.object({metadataId:p.z.number().int().min(1),reason:p.z.string().min(1)}).strict()),nextAfter:p.z.number().int().min(1).nullable()}).strict(),ni=(e,t)=>{let n=e.requeued+e.skipped.length;n>ye&&d(t,["requeued"],`One chunk settles at most ${ye} documents.`),e.nextAfter!==null!=(n===ye)&&d(t,["nextAfter"],"A chunk continues exactly when it read the limit.");let r=new Set;for(let[o,i]of e.skipped.entries())r.has(i.metadataId)&&d(t,["skipped",o,"metadataId"],"A chunk keeps a document back once."),r.add(i.metadataId)},ri=ti.superRefine(ni),Ke=p.z.enum(["DEPLOYMENT_DISABLED","RUN_ALREADY_ACTIVE","BASIS_INVALID","RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),Nt=p.z.enum(["start","cancel"]),Yr=Ke.extract(["DEPLOYMENT_DISABLED","RUN_ALREADY_ACTIVE","BASIS_INVALID","FORBIDDEN","UPSTREAM_FAILED"]),$r=Ke.extract(["DEPLOYMENT_DISABLED","RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),kt={start:Yr,cancel:$r},oi=p.z.object({code:Ke.exclude(["UPSTREAM_FAILED"]),status:Ue,errorCode:p.z.number().int().nullable()}).strict(),Ft=Object.freeze(p.z.array(oi).parse(Dr).map(e=>Object.freeze(e))),ai=(e,t)=>{e.code==="UPSTREAM_FAILED"||e.code==="FORBIDDEN"&&e.status===null||Ft.some(n=>n.code===e.code&&n.status===e.status)||d(t,["status"],`A ${e.code} failure carries the status of its row in the code table.`)},ii=p.z.discriminatedUnion("command",[p.z.object({command:Nt.extract(["start"]),code:kt.start,status:Ue.nullable()}).strict(),p.z.object({command:Nt.extract(["cancel"]),code:kt.cancel,status:Ue.nullable()}).strict()]).superRefine(ai),si=(e,t,n)=>{let r=kt[e],o=Ft.find(i=>i.status===t&&(i.errorCode===null||i.errorCode===n)&&r.safeParse(i.code).success);return o===void 0?"UPSTREAM_FAILED":o.code},li=p.z.discriminatedUnion("ok",[p.z.object({ok:p.z.literal(!0),runUid:ae}).strict(),p.z.object({ok:p.z.literal(!1),status:Ue,errorCode:p.z.number().int().nullable()}).strict()]);function qr(e){let t=[];for(let r=0;r<e.length;r++){t.push(r);let o=e.charCodeAt(r);o>=55296&&o<=56319&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320&&r++}t.push(e.length);let n=t.length-1;return{length:n,slice(r,o){if(!(Number.isInteger(r)&&Number.isInteger(o))||r<0||r>o)throw new RangeError(`A code-point span is [charStart, charEnd) with 0 <= charStart <= charEnd: [${r}, ${o})`);return o>n?null:e.slice(t[r],t[o])}}}var Xr=e=>e.replace(/\s/gu,"");function ee(e,t){let n=new Map,r=i=>{let l=new Int32Array(i.length);return i.forEach((s,c)=>{let h=n.get(s);h===void 0&&(h=n.size,n.set(s,h)),l[c]=h}),l};return{old:r(e),new:r(t),alphabetSize:n.size}}function Ge(e,t,n,r){if(r===0)return;let o=e[e.length-1];if(o!==void 0&&o.oldStart+o.length===t&&o.newStart+o.length===n){o.length+=r;return}e.push({oldStart:t,newStart:n,length:r})}function Wr(e,t,n,r,o,i,l){let s=0;for(;n+s<r&&o+s<i&&e[n+s]===t[o+s];)s++;Ge(l,n,o,s);let c=0;for(;r-c>n+s&&i-c>o+s&&e[r-1-c]===t[i-1-c];)c++;return{oldLow:n+s,oldHigh:r-c,newLow:o+s,newHigh:i-c,suffix:c}}function ci(e,t,n){let{oldLow:r,oldHigh:o,newLow:i,newHigh:l}=n,s=o-r,c=l-i,h=Math.ceil((s+c)/2),u=h,y=2*h+2,E=new Int32Array(y).fill(-1),_=new Int32Array(y).fill(-1);E[u+1]=0,_[u+1]=0;let C=s-c,N=C%2!==0,O=0,g=0,T=0,f=0;for(let R=0;R<h;R++){for(let D=-R+O;D<=R-g;D+=2){let x=u+D,A=D===-R||D!==R&&E[x-1]<E[x+1]?E[x+1]:E[x-1]+1,P=A-D;for(;A<s&&P<c&&e[r+A]===t[i+P];)A++,P++;if(E[x]=A,A>s)g+=2;else if(P>c)O+=2;else if(N){let v=u+C-D;if(v>=0&&v<y&&_[v]!==-1&&A>=s-_[v])return{kind:"split",oldSplit:r+A,newSplit:i+P}}}for(let D=-R+T;D<=R-f;D+=2){let x=u+D,A=D===-R||D!==R&&_[x-1]<_[x+1]?_[x+1]:_[x-1]+1,P=A-D;for(;A<s&&P<c&&e[o-1-A]===t[l-1-P];)A++,P++;if(_[x]=A,A>s)f+=2;else if(P>c)T+=2;else if(!N){let v=u+C-D;if(v>=0&&v<y&&E[v]!==-1){let b=E[v];if(b>=s-A)return{kind:"split",oldSplit:r+b,newSplit:i+u+b-v}}}}}return{kind:"disjoint"}}function te(e,t){let n=[],r=[{kind:"region",oldLow:0,oldHigh:e.length,newLow:0,newHigh:t.length}];for(let o=r.pop();o!==void 0;o=r.pop()){if(o.kind==="run"){Ge(n,o.oldStart,o.newStart,o.length);continue}let i=Wr(e,t,o.oldLow,o.oldHigh,o.newLow,o.newHigh,n);if(r.push({kind:"run",oldStart:i.oldHigh,newStart:i.newHigh,length:i.suffix}),i.oldLow===i.oldHigh||i.newLow===i.newHigh)continue;let l=ci(e,t,i);l.kind==="split"&&(r.push({kind:"region",oldLow:l.oldSplit,oldHigh:i.oldHigh,newLow:l.newSplit,newHigh:i.newHigh}),r.push({kind:"region",oldLow:i.oldLow,oldHigh:l.oldSplit,newLow:i.newLow,newHigh:l.newSplit}))}return n}function Qr(e,t,n){let r=Math.ceil(t.length/32),o=new Array(n);t.forEach((s,c)=>{let h=o[s];h===void 0&&(h=new Uint32Array(r),o[s]=h),h[c>>>5]=(h[c>>>5]|1<<(c&31))>>>0});let i=new Uint32Array(r).fill(4294967295);for(let s of e){let c=o[s];if(c===void 0)continue;let h=0;for(let u=0;u<r;u++){let y=i[u],E=(y&c[u])>>>0,_=y+E+h;h=_>4294967295?1:0,i[u]=(_>>>0|y&~c[u])>>>0}}let l=0;for(let s=0;s<t.length;s++)l+=i[s>>>5]>>>(s&31)&1;return t.length-l}function di(e,t,n){if(e.occurrences!==t.occurrences)return e.occurrences<t.occurrences;if(e.length!==t.length)return e.length>t.length;let r=Math.abs(2*e.oldStart+e.length-n),o=Math.abs(2*t.oldStart+t.length-n);return r!==o?r<o:e.newStart<t.newStart||e.newStart===t.newStart&&e.oldStart<t.oldStart}function Zr(e,t){let{old:n,new:r,alphabetSize:o}=e,i=new Int32Array(o),l=new Int32Array(o),s=new Int32Array(o).fill(-1),c=new Int32Array(n.length),h=[],u=[{kind:"region",oldLow:0,oldHigh:n.length,newLow:0,newHigh:r.length}];for(let y=u.pop();y!==void 0;y=u.pop()){if(y.kind==="run"){Ge(h,y.oldStart,y.newStart,y.length);continue}let E=Wr(n,r,y.oldLow,y.oldHigh,y.newLow,y.newHigh,h),_={kind:"run",oldStart:E.oldHigh,newStart:E.newHigh,length:E.suffix},{oldLow:C,oldHigh:N,newLow:O,newHigh:g}=E;if(C===N||O===g){u.push(_);continue}for(let x=N-1;x>=C;x--){let A=n[x];i[A]++,c[x]=s[A],s[A]=x}let T={best:null},f=x=>{(T.best===null||di(x,T.best,C+N))&&(T.best=x)},R=new Map;for(let x=O;x<g;x++){let A=r[x],P=i[A];if(!(P===0||P>t.maxOccurrences||T.best!==null&&P>T.best.occurrences))for(let v=s[A];v!==-1;v=c[v]){let b=R.get(x-v);if(b!==void 0&&x>=b.newStart&&x<b.newEnd){P<b.occurrences&&(b.occurrences=P,f({occurrences:P,oldStart:b.oldStart,newStart:b.newStart,length:b.newEnd-b.newStart}));continue}let L=v,F=x;for(;L>C&&F>O&&n[L-1]===r[F-1];)L--,F--;let z=v-L+1;for(;L+z<N&&F+z<g&&n[L+z]===r[F+z];)z++;R.set(x-v,{oldStart:L,newStart:F,newEnd:F+z,occurrences:P}),f({occurrences:P,oldStart:L,newStart:F,length:z})}}let D=T.best;D!==null?(u.push(_),u.push({kind:"region",oldLow:D.oldStart+D.length,oldHigh:N,newLow:D.newStart+D.length,newHigh:g}),u.push({kind:"run",oldStart:D.oldStart,newStart:D.newStart,length:D.length}),u.push({kind:"region",oldLow:C,oldHigh:D.oldStart,newLow:O,newHigh:D.newStart})):(ui(n,r,E,i,l,t.cellBound,h),u.push(_));for(let x=C;x<N;x++){let A=n[x];i[A]=0,s[A]=-1}}return h}function ui(e,t,n,r,o,i,l){let{oldLow:s,oldHigh:c,newLow:h,newHigh:u}=n;if((c-s)*(u-h)>i)return;for(let C=h;C<u;C++)o[t[C]]++;let y=[];for(let C=s;C<c;C++)o[e[C]]>0&&y.push(C);let E=[];for(let C=h;C<u;C++)r[t[C]]>0&&E.push(C),o[t[C]]=0;let _=te(Int32Array.from(y,C=>e[C]),Int32Array.from(E,C=>t[C]));for(let C of _)for(let N=0;N<C.length;N++)Ge(l,y[C.oldStart+N],E[C.newStart+N],1)}function eo(e,t,n){let r=[],o=0,i=0;for(let l of[...n,{oldStart:e,newStart:t,length:0}])(l.oldStart>o||l.newStart>i)&&r.push({oldStart:o,oldEnd:l.oldStart,newStart:i,newEnd:l.newStart}),o=l.oldStart+l.length,i=l.newStart+l.length;return r}function Pt(e,t,n,r){let o=new Map;for(let l of t){let s=r(l);s!==null&&o.set(s,[...o.get(s)??[],l])}let i=[];for(let l of e){let s=n(l),c=s===null?void 0:o.get(s)?.shift();c!==void 0&&i.push([l,c])}return i}function to(e,t){let n=new Map;for(let r of e){let o=t[r].clause;o!==null&&n.set(o,(n.get(o)??0)+1)}return n}var V=e=>e.flatMap((t,n)=>t===null?[n]:[]);function Lt(e,t){let n=e?.children??[],r=t?.children??[],o=ee(n.map(f=>f.hash),r.map(f=>f.hash)),i=n.map(()=>null),l=r.map(()=>null),s=[],c=n.map(()=>0),h=r.map(()=>0);for(let f of te(o.old,o.new))for(let R=0;R<f.length;R++)i[f.oldStart+R]=f.newStart+R,l[f.newStart+R]=f.oldStart+R;let u=0;n.forEach((f,R)=>{c[R]=u,u+=i[R]===null?0:1}),u=0,r.forEach((f,R)=>{h[R]=u,l[R]!==null&&(s.push(R),u++)});let y=[],E=(f,R,D)=>{for(let[x,A]of f)i[x]=A,l[A]=x,y.push({entry:{kind:R,pairing:D,oldPosition:x,newPosition:A},order:[A,1,A]})},_=f=>n[f],C=f=>r[f];E(Pt(V(i),V(l),f=>_(f).hash,f=>C(f).hash),"MOVED",null);let N=to(V(i),n),O=to(V(l),r),g=f=>f.clause!==null&&N.get(f.clause)===1&&O.get(f.clause)===1?f.clause:null;E(Pt(V(i),V(l),f=>g(_(f)),f=>g(C(f))),"MODIFIED","clause"),E(Pt(V(i),V(l),f=>JSON.stringify([c[f],_(f).breadcrumbs]),f=>JSON.stringify([h[f],C(f).breadcrumbs])),"MODIFIED","breadcrumbs");for(let f of V(i)){let R=c[f],D=R===0?0:s[R-1]+1;y.push({entry:{kind:"REMOVED",pairing:null,oldPosition:f,newPosition:null},order:[D,0,f]})}for(let f of V(l))y.push({entry:{kind:"ADDED",pairing:null,oldPosition:null,newPosition:f},order:[f,1,f]});y.sort((f,R)=>f.order[0]-R.order[0]||f.order[1]-R.order[1]||f.order[2]-R.order[2]);let T=f=>y.filter(({entry:R})=>R.kind===f).length;return{entries:y.map(({entry:f})=>f),stats:{added:T("ADDED"),removed:T("REMOVED"),modified:T("MODIFIED"),moved:T("MOVED"),unchanged:s.length}}}var je=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),se=(e,t)=>`${e}/${String(t).replace(/~/g,"~0").replace(/\//g,"~1")}`;function vt(e,t,n,r,o){U(t)!==U(n)&&(je(t)&&je(n)?pi(e,t,n,r,o):Array.isArray(t)&&Array.isArray(n)?mi(e,t,n,r,o):r.push({op:"replace",path:e,value:n,previous:t}))}function pi(e,t,n,r,o){let i=[...new Set([...Object.keys(t),...Object.keys(n)])].sort(B);for(let l of i){let s=se(e,l);Object.hasOwn(n,l)?Object.hasOwn(t,l)?vt(s,t[l],n[l],r,o):r.push({op:"add",path:s,value:n[l]}):r.push({op:"remove",path:s,previous:t[l]})}}function mi(e,t,n,r,o){let i=ee(t.map(U),n.map(U)),l=0;for(;l<t.length&&l<n.length&&i.old[l]===i.new[l];)l++;let s=0;for(;s<t.length-l&&s<n.length-l&&i.old[t.length-1-s]===i.new[n.length-1-s];)s++;let c=(t.length-l-s)*(n.length-l-s);if(c>o.remaining){r.push({op:"replace",path:e,value:n,previous:t});return}o.remaining-=c;let h=0,u=0,y=0;for(let E of[...te(i.old,i.new),{oldStart:t.length,newStart:n.length,length:0}]){let _=t.slice(u,E.oldStart),C=n.slice(y,E.newStart),N=Math.min(_.length,C.length);for(let O=0;O<N;O++){let g=_[O],T=C[O];je(g)&&je(T)||Array.isArray(g)&&Array.isArray(T)?vt(se(e,h),g,T,r,o):(r.push({op:"remove",path:se(e,h),previous:g}),r.push({op:"add",path:se(e,h),value:T})),h++}for(let O of _.slice(N))r.push({op:"remove",path:se(e,h),previous:O});for(let O of C.slice(N))r.push({op:"add",path:se(e,h),value:O}),h++;h+=E.length,u=E.oldStart+E.length,y=E.newStart+E.length}}function Mt(e,t){let n=[];return vt("",e,t,n,{remaining:Et}),n}function no(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="object"||n===null||Array.isArray(n))continue;let{start:r,end:o,page_number:i}=n;Number.isInteger(r)&&Number.isInteger(o)&&Number.isInteger(i)&&t.push({start:r,end:o,pageNumber:i})}return t.sort((n,r)=>n.start-r.start)}function Ut(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e[i].start<=t?n=i+1:r=i}let o=e[n-1];return o!==void 0&&t<o.end?o.pageNumber:null}function ro(e){let t=[],n=[],r={LF:0,CRLF:0,CR:0},o=0,i=0,l=0;for(let u=0;u<e.length;){let y=e.charCodeAt(u);if(y===10||y===13){t.push(e.slice(o,u)),n.push(l);let E=y===13&&e.charCodeAt(u+1)===10?2:1;r[E===2?"CRLF":y===13?"CR":"LF"]++,u+=E,i+=E,o=u,l=i;continue}u+=y>=55296&&y<=56319&&(e.charCodeAt(u+1)&64512)===56320?2:1,i++}o<e.length&&(t.push(e.slice(o)),n.push(l));let s=r.LF+r.CRLF+r.CR,c=["LF","CRLF","CR"].filter(u=>r[u]>0),h=s===0?"NONE":c.length===1?c[0]:"MIXED";return{lines:t,starts:n,lineEnding:h,finalNewline:s>0&&o===e.length}}var oo=null;function ao(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>767)return!1;return!0}function Kt(e){return ao(e)?e.split(""):(oo??=new Intl.Segmenter("und",{granularity:"grapheme"}),Array.from(oo.segment(e),t=>t.segment))}function zt(e){return ao(e)?e.length:Kt(e).length}function fi(e,t,n){let r=e.length+t.length;if(n.exhausted||e.length>Fe||t.length>Fe||r===0)return null;let o=ee(e,t),i=Qr(o.old,o.new,o.alphabetSize);if(2*i/r<Pe||r-2*i>gt)return null;let l=r*(r-2*i);if(l>n.remaining)return n.exhausted=!0,null;n.remaining-=l;let s=te(o.old,o.new),c=[],h=0,u=0;for(let g of[...s,{oldStart:e.length,newStart:t.length,length:0}])(g.oldStart>h||g.newStart>u)&&c.push({equal:!1,oldStart:h,oldEnd:g.oldStart,newStart:u,newEnd:g.newStart}),g.length>0&&c.push({equal:!0,oldStart:g.oldStart,oldEnd:g.oldStart+g.length,newStart:g.newStart,newEnd:g.newStart+g.length}),h=g.oldStart+g.length,u=g.newStart+g.length;let y=[];c.forEach((g,T)=>{let f=y[y.length-1],R=f!==void 0&&!f.equal,D=g.equal&&g.oldEnd-g.oldStart<=1&&R&&T+1<c.length;if(R&&(D||!g.equal)){f.oldEnd=g.oldEnd,f.newEnd=g.newEnd;return}y.push({...g})});let E=0,_=0,C=0,N=[],O=[];for(let g of y){let T=e.slice(g.oldStart,g.oldEnd).join(""),f=t.slice(g.newStart,g.newEnd).join("");if(g.equal){E+=g.oldEnd-g.oldStart,N.push({kind:"equal",text:T}),O.push({kind:"equal",text:f});continue}_+=g.oldEnd-g.oldStart,C+=g.newEnd-g.newStart,T!==""&&N.push({kind:"removed",text:T}),f!==""&&O.push({kind:"added",text:f})}return 2*E/r<Pe?null:{oldSegments:N,newSegments:O,removed:_,added:C}}var io={old:[],new:[]};function ge(e){return e.filter(([,t,n])=>U(t)!==U(n)).map(([t,n,r])=>({field:t,before:n,after:r}))}var Ht=(e,t)=>t===""?[]:[{kind:e,text:t}];function hi(e,t,n){let r=[],o=(s,c)=>({kind:"context",oldNumber:s+1,newNumber:c+1,page:Ut(n.pages.new,n.newText.starts[c]),segments:Ht("equal",n.newText.lines[c])}),i=t.oldStart,l=t.newStart;for(let s of e){for(;i<s.oldStart;i++,l++)r.push(o(i,l));for(let c=s.oldStart;c<s.oldEnd;c++){let h=n.oldText.lines[c];r.push({kind:"removed",oldNumber:c+1,newNumber:null,page:Ut(n.pages.old,n.oldText.starts[c]),segments:n.removedSegments.get(c)??Ht("removed",h)})}for(let c=s.newStart;c<s.newEnd;c++){let h=n.newText.lines[c];r.push({kind:"added",oldNumber:null,newNumber:c+1,page:Ut(n.pages.new,n.newText.starts[c]),segments:n.addedSegments.get(c)??Ht("added",h)})}i=s.oldEnd,l=s.newEnd}for(;i<t.oldEnd;i++,l++)r.push(o(i,l));return r}function Gt(e,t,n,r){let o=ro(e??""),i=ro(t??""),l=ge([["present",e!==null,t!==null],["lineEnding",o.lineEnding,i.lineEnding],["finalNewline",o.finalNewline,i.finalNewline]]),s=Zr(ee(o.lines,i.lines),{maxOccurrences:ht,cellBound:yt}),c=eo(o.lines.length,i.lines.length,s),h=new Map,u=new Map,y={remaining:St,exhausted:!1},E=0,_=0,C=0,N=0,O=0,g=0;for(let b of c){C+=b.oldEnd-b.oldStart,N+=b.newEnd-b.newStart;let L=Math.min(b.oldEnd-b.oldStart,b.newEnd-b.newStart);for(let F=0;b.oldStart+F<b.oldEnd||b.newStart+F<b.newEnd;F++){let z=b.oldStart+F,K=b.newStart+F;if(F>=L){let ce=z<b.oldEnd?zt(o.lines[z]):0,re=K<b.newEnd?zt(i.lines[K]):0;O+=ce,g+=re,E+=ce,_+=re;continue}let J=Kt(o.lines[z]),q=Kt(i.lines[K]);O+=J.length,g+=q.length;let X=fi(J,q,y);if(X!==null){h.set(z,X.oldSegments),u.set(K,X.newSegments),E+=X.removed,_+=X.added;continue}E+=J.length,_+=q.length}}let T=0;for(let b of s)for(let L=b.oldStart;L<b.oldStart+b.length;L++)T+=zt(o.lines[L]);let f=T+O,R=T+g,D={linesAdded:N,linesRemoved:C,linesUnchanged:o.lines.length-C,charsAdded:_,charsRemoved:E,similarity:f+R===0?null:2*(f-E)/(f+R)},x=r==="whole"?Math.max(o.lines.length,i.lines.length):r,A=[];for(let b of c){let L=A[A.length-1],F=L?.[L.length-1];L!==void 0&&F!==void 0&&b.oldStart-F.oldEnd<=2*x?L.push(b):A.push([b])}let P={oldText:o,newText:i,pages:n,removedSegments:h,addedSegments:u},v=A.map((b,L)=>{let F=b[0],z=b[b.length-1],K=Math.max(0,F.oldStart-x),J=F.newStart-(F.oldStart-K),q=Math.min(o.lines.length,z.oldEnd+x),X=z.newEnd+(q-z.oldEnd),ce=hi(b,{oldStart:K,oldEnd:q,newStart:J},P);return{hunk:L,oldStart:q>K?K+1:K,oldLines:q-K,newStart:X>J?J+1:J,newLines:X-J,firstPage:ce[0].page,linesAdded:b.reduce((re,de)=>re+de.newEnd-de.newStart,0),linesRemoved:b.reduce((re,de)=>re+de.oldEnd-de.oldStart,0),lines:ce}});return{attributes:l,stats:D,hunks:v}}function Se(e,t){let n=Gt(e.body,t.body,{old:no(e.pageOffsets),new:no(t.pageOffsets)},we),r=ge([["mime",e.mime,t.mime],["source",e.source,t.source],["isTruncated",e.isTruncated,t.isTruncated],["pageOffsets",e.pageOffsets,t.pageOffsets]]);return{...n,attributes:[...r,...n.attributes]}}function Ee(e,t){return Gt(e,t,io,we)}function so(e,t){return Gt(e,t,io,"whole")}function Ce(e){return{attributes:[...e.attributes],stats:e.stats,hunks:e.hunks.map(({lines:t,...n})=>n)}}function lo(e,t,n,r){let o=Number.isInteger(t)&&t>=0?e.hunks[t]:void 0;if(o===void 0)throw new RangeError(`The diff has no hunk ${t}.`);if(!Number.isInteger(n)||n<0||n>=o.lines.length)throw new RangeError(`Hunk ${t} has no line at offset ${n}.`);if(!At.safeParse(r).success)throw new RangeError(`A line page holds 1 to the page maximum lines, not ${r}.`);let i=Math.min(n+r,o.lines.length);return{lines:o.lines.slice(n,i),next:i<o.lines.length?i:null}}function Be(e,t,n){let r=[...e].sort(t);for(let o=1;o<r.length;o++)if(t(r[o-1],r[o])===0)throw new RangeError(`A facet set holds the key ${JSON.stringify(n(r[o]))} more than once.`);return r}function co(e,t,n,r){let o=0,i=0;for(;o<e.length||i<t.length;){let l=e[o],s=t[i],c=l===void 0?1:s===void 0?-1:n(l,s);r(c<=0?l:null,c>=0?s:null),o+=c<=0?1:0,i+=c>=0?1:0}}function jt(e,t){let n=[],r=[],o=0;return co(Be(e??[],B,String),Be(t??[],B,String),B,(i,l)=>{i!==null&&l!==null?o++:i!==null?r.push(i):n.push(l)}),{added:n,removed:r,unchangedCount:o}}function uo(e,t,n){let r=[],o=[],i=[],l=0;return co(Be(e,n.compare,n.keyOf),Be(t,n.compare,n.keyOf),n.compare,(s,c)=>{if(s===null){r.push({key:n.keyOf(c),value:{...c}});return}if(c===null){o.push({key:n.keyOf(s),value:{...s}});return}let h=new Map(n.fieldsOf(c)),u=ge(n.fieldsOf(s).map(([y,E])=>[y,E,h.get(y)]));u.length===0?l++:i.push({key:n.keyOf(s),fields:u})}),{added:r,removed:o,modified:i,unchangedCount:l}}var yi={compare:(e,t)=>B(e.labelKey,t.labelKey),keyOf:e=>e.labelKey,fieldsOf:e=>[["assignedBy",e.assignedBy],["confidenceScore",e.confidenceScore]]},gi={compare:Le,keyOf:e=>`${e.assetType}:${e.assetIndex}`,fieldsOf:e=>[["mimeType",e.mimeType],["fileSize",e.fileSize],["textSha256",e.textSha256]]},Bt=(e,t)=>uo(e,t,yi),Vt=(e,t)=>uo(e,t,gi);function be(e,t,n){return ge(n.map(r=>[r,e[r],t[r]]))}var fo=["confidentialityLevel","departmentId","folderPath","createdBy"],ho=["fileName","filePath","fileId","revision","revisionId","fileSize","mimeType","fileHash","mtime"],ne=(e,t)=>({facet:e,addedCount:null,removedCount:null,modifiedCount:null,movedCount:null,unchangedCount:null,charsAdded:null,charsRemoved:null,...t}),po=(e,t)=>ne(e,{addedCount:t.stats.linesAdded,removedCount:t.stats.linesRemoved,unchangedCount:t.stats.linesUnchanged,charsAdded:t.stats.charsAdded,charsRemoved:t.stats.charsRemoved});function Si(e){switch(e.facet){case"classification":return ne("classification",{modifiedCount:be(e.from,e.to,fo).length});case"metadata":return ne("metadata",{modifiedCount:be(e.from,e.to,ho).length});case"labels":case"assets":{let t=e.facet==="labels"?Bt(e.from,e.to):Vt(e.from,e.to);return ne(e.facet,{addedCount:t.added.length,removedCount:t.removed.length,modifiedCount:t.modified.length,unchangedCount:t.unchangedCount})}case"tags":{let t=jt(e.from,e.to);return ne("tags",{addedCount:t.added.length,removedCount:t.removed.length,unchangedCount:t.unchangedCount})}case"structured_data":{let t=Mt(e.from,e.to),n=r=>t.filter(o=>o.op===r).length;return ne("structured_data",{addedCount:n("add"),removedCount:n("remove"),modifiedCount:n("replace")})}case"text":return po("text",Se(e.from,e.to));case"summary":return po("summary",Ee(e.from,e.to));case"chunks":{let{stats:t}=Lt(e.from,e.to);return ne("chunks",{addedCount:t.added,removedCount:t.removed,modifiedCount:t.modified,movedCount:t.moved,unchangedCount:t.unchanged})}}}function yo(e){if(e.length===0)throw new RangeError("A change has at least one changed facet.");let t=new Set;for(let n of e){if(t.has(n.facet))throw new RangeError(`The ${n.facet} facet is given twice.`);if(t.add(n.facet),U(n.from)===U(n.to))throw new RangeError(`The ${n.facet} facet has equal values on both sides, so it did not change.`)}return[...e].sort((n,r)=>ve(n.facet,r.facet)).map(Si)}var Ei=(e,t)=>({index:e.index,charStart:e.charStart,charEnd:e.charEnd,page:e.page,sheet:e.sheet,slide:e.slide,startSec:e.startSec,endSec:e.endSec,breadcrumbs:e.breadcrumbs,tokenCount:e.tokenCount,fidelity:t});function mo(e,t){let n=e.facets.chunks?.children.length??0;if(e.chunkFidelities.length!==n)throw new RangeError(`The ${t} state has ${n} child chunks but ${e.chunkFidelities.length} fidelity checks.`)}function Ci(e,t,n){let r=t.facets,o=n.facets;if(U(r[e])===U(o[e]))return{facet:e,change:"UNCHANGED"};switch(e){case"classification":return{facet:e,change:"CHANGED",fields:be(r.classification,o.classification,fo)};case"metadata":return{facet:e,change:"CHANGED",fields:be(r.metadata,o.metadata,ho)};case"labels":case"assets":{let i=e==="labels"?Bt(r.labels,o.labels):Vt(r.assets,o.assets);return{facet:e,change:"CHANGED",added:[...i.added],removed:[...i.removed],modified:[...i.modified],unchangedCount:i.unchangedCount}}case"tags":{let i=jt(r.tags,o.tags);return{facet:e,change:"CHANGED",added:[...i.added],removed:[...i.removed],unchangedCount:i.unchangedCount}}case"structured_data":return{facet:e,change:"CHANGED",operations:Mt(r.structured_data,o.structured_data)};case"text":return{facet:e,change:"CHANGED",...Ce(Se(r.text,o.text))};case"summary":return{facet:e,change:"CHANGED",...Ce(Ee(r.summary,o.summary))};case"chunks":{let i=Lt(r.chunks,o.chunks),l=r.chunks?.children??[],s=o.chunks?.children??[],c=(h,u,y)=>y===null?null:Ei(h[y],u[y]);return{facet:e,change:"CHANGED",stats:i.stats,entries:i.entries.map((h,u)=>({entry:u,kind:h.kind,pairing:h.pairing,old:c(l,t.chunkFidelities,h.oldPosition),new:c(s,n.chunkFidelities,h.newPosition)})),textUnchangedChunkingChanged:r.text.body===o.text.body}}}}function go(e,t){return mo(e,"from"),mo(t,"to"),{diffEngineVersion:ft,facets:Z.map(n=>Ci(n,e,t))}}var Jt=[{key:"enable_summary_generation",featureFlagKey:null,label:"\u8981\u7D04\u751F\u6210"},{key:"enable_structured_extraction",featureFlagKey:null,label:"\u69CB\u9020\u5316\u62BD\u51FA"},{key:"enable_asset_extraction",featureFlagKey:"ENABLE_ASSET_EXTRACTION",label:"\u30A2\u30BB\u30C3\u30C8\u62BD\u51FA"},{key:"enable_vector_indexing",featureFlagKey:"ENABLE_VECTOR_INDEXING",label:"\u30D9\u30AF\u30C8\u30EB\u7D22\u5F15"},{key:"enable_graph_indexing",featureFlagKey:"ENABLE_GRAPH_INDEXING",label:"\u30B0\u30E9\u30D5\u6295\u5F71"}],bi=new Set(Jt.map(e=>e.key));function Ri(e){return bi.has(e)}function Ii(e){let t=Jt.find(n=>n.key===e);if(t===void 0)throw new Error(`ENRICHMENT_STAGES does not carry ${e}; the canonical list and the key type have drifted apart.`);return t}var xi={pageSize:{min:1,max:200,default:50},topologyLabels:{min:1,max:24,default:24}};var le=-1,$=0;function So(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function Ai(){let e=typeof globalThis<"u"&&globalThis.crypto?globalThis.crypto:typeof crypto<"u"?crypto:void 0;if(!e||typeof e.getRandomValues!="function")throw new Error("Cryptographically secure random number generator (crypto.getRandomValues) is required but not available.");let t=new Uint8Array(16);e.getRandomValues(t);let n=Date.now();if(n===le){if($++,$>4095){for(;Date.now()<=le;);n=Date.now(),le=n,$=(t[6]<<4|t[7]&15)&1023}}else n>le?(le=n,$=(t[6]<<4|t[7]&15)&1023):(n=le,$++,$>4095&&($=0));t[0]=Math.floor(n/1099511627776)&255,t[1]=Math.floor(n/4294967296)&255,t[2]=n>>>24&255,t[3]=n>>>16&255,t[4]=n>>>8&255,t[5]=n&255,t[6]=112|$>>>8&15,t[7]=$&255,t[8]=128|t[8]&63;let r=Array.from(t,i=>i.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function _i(e){if(!So(e))throw new Error(`Invalid RFC 9562 UUIDv7 string: "${e}"`);let t=e.slice(0,8)+e.slice(9,13),n=parseInt(t,16);if(Number.isNaN(n))throw new Error(`Invalid hex timestamp in UUIDv7: "${t}"`);return new Date(n)}0&&(module.exports={AmountEntrySchema,AssetFacetItemSchema,BaseEnrichmentClient,BodySourceSchema,BoundingBoxSchema,CHUNK_BODY_FIDELITIES,CHUNK_CHANGE_KINDS,CHUNK_MANIFEST_VERSION,CHUNK_PAIRINGS,CIRCUIT_BREAKER_SERVICES,CanonicalDomainKeySchema,ChangeFeedCursorSchema,ChapterSegmentSchema,ChunkBodyFidelitySchema,ChunkChangeKindSchema,ChunkChangeSchema,ChunkManifestChildSchema,ChunkManifestParentSchema,ChunkManifestSchema,ChunkPairingSchema,ChunkRefSchema,ChunkStatsSchema,ChunkingStrategySchema,CircuitBreakerStatusSchema,ClassificationFacetSchema,ConfidentialityLevelSchema,DIFF_CONTEXT_LINES,DIFF_ENGINE_VERSION,DIFF_LINE_FACETS,DIFF_LINE_PAGE_MAX,DIFF_REGION_CELL_BOUND,DISPATCH_DEGRADATION_REASONS,DOCUMENT_CAPTURE_OUTCOMES,DOCUMENT_CHANGE_FEED_PAGE_MAX,DOCUMENT_CHANGE_FEED_PAGE_SIZE,DOCUMENT_FACETS,DOCUMENT_KINDS,DOCUMENT_KIND_LABELS,DOCUMENT_STATE_CAUSES,DOCUMENT_STATE_LOCK_TIMEOUT_MS,DOCUMENT_STATE_RUN_OUTCOMES,DiffLineFacetSchema,DiffLinePageLimitSchema,DiffLinePageSchema,DiffLineSchema,DiffSegmentSchema,DocumentCaptureAnswerSchema,DocumentCaptureOutcomeSchema,DocumentChangeFeedEntrySchema,DocumentChangeFeedLimitSchema,DocumentChangeFeedPageSchema,DocumentChangeFeedRowSchema,DocumentComparisonSchema,DocumentFacetSchema,DocumentFacetValuesSchema,DocumentHistorySchema,DocumentKindSchema,DocumentRunEntrySchema,DocumentStateCauseSchema,DocumentStateEntrySchema,DocumentStateRunOutcomeSchema,DocumentStateSummarySchema,DocumentStructuredDataSchema,ENRICHMENT_STAGES,EnrichmentClient,EnrichmentClientError,EnrichmentSyncStatusSchema,FACET_APPLICABLE_COUNTS,FACET_COUNT_FIELDS,FILTERABLE_CONFIDENTIALITY_LEVELS,FacetChangeCountsSchema,FacetDiffSchema,FieldChangeSchema,FileUriSchema,GRAPH_INDEX_LIMITS,GraphSearchHitSchema,HISTOGRAM_MAX_OCCURRENCES,HunkIndexEntrySchema,INLINE_REFINE_CELL_BUDGET,INLINE_REFINE_MAX_EDIT_DISTANCE,INLINE_REFINE_MAX_GRAPHEMES,INLINE_REFINE_MIN_SIMILARITY,INTEGRITY_CLASS_POLICY,INTEGRITY_COMMAND_CODES,INTEGRITY_FINDINGS_PAGE_LIMIT_MAX,IntegrityActiveRunSchema,IntegrityAuditOverviewSchema,IntegrityCancelFailureCodeSchema,IntegrityCellResyncRequestSchema,IntegrityCellResyncResultSchema,IntegrityCommandFailureCodeSchema,IntegrityCommandFailureSchema,IntegrityCommandReplySchema,IntegrityCommandSchema,IntegrityDispositionSchema,IntegrityFindingItemClassSchema,IntegrityFindingPageSchema,IntegrityFindingSchema,IntegrityFindingsQuerySchema,IntegrityItemClassSchema,IntegrityPhaseSchema,IntegrityPlacementObservedSchema,IntegrityQuantitySchema,IntegrityRepairActionSchema,IntegrityRepairOutcomeSchema,IntegrityRepairSkipReasonSchema,IntegrityRunHeaderSchema,IntegrityRunModeSchema,IntegrityRunStatusSchema,IntegrityScopeRoleSchema,IntegrityStartFailureCodeSchema,IntegrityStoreSchema,IntegrityUnitSchema,IntegrityVerdictSchema,JsonPatchOperationSchema,JsonValueSchema,KeyedItemChangeSchema,KeyedItemSchema,LEDGER_STEP_KEYS,LINE_ENDINGS,LOCAL_DEGRADATION_REASONS,LabelFacetItemSchema,LedgerStepKeySchema,LineEndingSchema,MIME_KIND_RULES,MODE_TIERS,MetadataFacetSchema,ModelProviderSchema,NOTHING_TO_READ_TOKENS,NothingToReadTokenSchema,PIPELINE_FAILURE_STATUSES,PIPELINE_FLOWS,PIPELINE_PHASES,PIPELINE_STEPS,PIPELINE_STEP_KEYS,PipelineFailureStatusSchema,PipelineRunRecordSchema,PipelineRunStatusSchema,PipelineRunSummarySchema,PipelineStepKeySchema,PipelineStepMetricSchema,PipelineStepRecordSchema,PipelineStepStatusSchema,PipelineTriggerSchema,QUARANTINED_CONFIDENTIALITY_LEVEL,REMOTE_DEGRADATION_REASONS,RESTRICTED_MARK_SUBJECTS,RUN_TERMINAL_STEP_ERROR_CODES,RUN_TERMINAL_STEP_KEY,RUN_TERMINAL_STEP_OUTCOMES,ReadableConfidentialityLevelSchema,RecentPipelineRunEntrySchema,RestrictedChangeMarkSchema,RestrictedFailureMarkSchema,RestrictedIngestMarkSchema,RestrictedMarkSubjectSchema,RestrictedRunMarkSchema,RestrictedStateMarkSchema,RunTerminalStepDetailSchema,RunTerminalStepErrorCodeSchema,RunTerminalStepOutcomeSchema,SEARCH_DEGRADATION_REASONS,SEARCH_MODES,SEARCH_PARAM_LIMITS,STALE_RUN_ERROR_CODE,STRUCTURED_DATA_ARRAY_CELL_BOUND,SYSTEM_PARAMETER_RANGES,SearchHitSchema,SearchMetadataSchema,SearchModeSchema,SearchRequestSchema,SearchResponseSchema,StageProvenanceSchema,TenantIdSchema,TextDiffIndexSchema,TextFacetSchema,TextStatsSchema,TranscriptSegmentSchema,assertBoundedSystemParameter,assertSystemParameterInRange,canonicalJson,classifyDocumentKind,codePointSlicer,compareAssetKeys,compareCodeUnits,compareFacets,comparePhases,compareStates,decodeChangeFeedCursor,diffChunkBodies,diffLinePage,encodeChangeFeedCursor,enrichmentStage,flowFor,flowStepGates,formatSkipReason,generateUuidV7,integrityCommandFailureCodeOf,isEnrichmentStageKey,isStrictlyEarlier,isValidUuidV7,modeFusesRankings,modeNeedsRemoteTiers,modeScoreIsSimilarity,narrowModeToAllowedTiers,orderedSteps,parseSkipReason,readableEntrySchema,stripWhitespace,summarizeTransition,summaryFacetDiff,textDiffIndex,textFacetDiff,uuidv7ToDate});