@aiquants/enrichment-react-router 0.3.0 → 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
@@ -80,6 +80,7 @@ The host implements one object and injects it through `createStorageAdminApp`. B
80
80
  | `readIntegrityAuditOverview(tenantId)` | `IntegrityAuditOverview` | The integrity audit's overview read from the recorded runs (`@aiquants/enrichment-core`): the database's clock (`readAt`), the last completed run with its quantities, the active run, a newer unsuccessful run. No store is measured. The loader checks the answer against `IntegrityAuditOverviewSchema` and catches this read alone: a throw or a contract violation becomes the overview's own failure (`integrityAudit`), and the rest of the console is still drawn. A thrown error's message is that failure's reason, shipped in the loader data and shown to the operator as given, so throw only sentences an operator may read: log a database driver's error (its message can carry the query and its parameters) and throw your own sentence; keep the core's range sentences (`assertSystemParameterInRange`). |
81
81
  | `startIntegrityRun(tenantId, mode, basisRunUid, accessToken)` | `IntegrityCommandReply` | Starts a `SCAN` (`basisRunUid` `null`) or a `REPAIR` (the basis scan's UID) upstream in the operator's name; the token is required. Answers `{ ok: true, runUid }` or `{ ok: false, status, errorCode }` (the upstream status and business code; no upstream wording). A throw is answered `UPSTREAM_FAILED` without a status and its cause is discarded (the package has no logger and shows no upstream wording), so the store logs a failure it throws for. |
82
82
  | `cancelIntegrityRun(tenantId, runUid, accessToken)` | `IntegrityCommandReply` | Cancels a run (or closes one whose heartbeat stopped), answered like the start. |
83
+ | `resyncIntegrityCell(tenantId, request, actor, accessToken)` | `IntegrityCellResyncResult` | One chunk of the findings inspector's bulk resync: requeues the documents recorded in one `UNRECORDED` cell of the tenant's latest completed run, in recorded order after `request.after`, at most `INTEGRITY_FINDINGS_PAGE_LIMIT_MAX` (100), each through the host's one requeue rule (the rule `retrySyncItem` and `retryAllFailedSyncItems` apply), and answers `{ requeued, skipped: { metadataId, reason }[], nextAfter }` (`@aiquants/enrichment-core`'s `IntegrityCellResyncResultSchema`; `nextAfter` is the last sequence read when the chunk read exactly the limit, else `null`). The action calls it only for an operator `canReadIntegrityFindings` admits, with a request `IntegrityCellResyncRequestSchema` accepted, and checks the answer before the console reads it. Throw an operator-facing `Error` to stop (e.g. the run is no longer the tenant's latest completed run, so the findings the operator approved are no longer shown); the action answers its message as the inspector's refusal. `accessToken` is `undefined` when the operator holds none. |
83
84
  | `getCircuitBreakerStatus()` | `Record<string, CircuitBreakerState>` | The search path's breakers (`vector` / `graph`). Only the search reads and feeds them, so only the search workbench is given them; the pipeline figure is not. |
84
85
  | `getSystemParameters(tenantId)` | `SystemParameter[]` | The `value` arrives already in the type `data_type` names: `boolean` for `bool`, `number` for `int` / `float`, `string` for `string` / `json`. The store owns the conversion from stored text. |
85
86
 
@@ -92,7 +93,7 @@ The store reads no single run and no document history: the history panel reads t
92
93
  | Field | Type | Meaning |
93
94
  | --- | --- | --- |
94
95
  | `email` | `string` | The address every write of the action is attributed to (`updated_by`, and the `actor` argument of the store's writes). An `id` or a display name is not an identity the audit trail can be read back through, so there is no other field to fall back on. |
95
- | `accessToken` | `string \| null` | The operator's OAuth access token, forwarded unchanged to the store calls that take one (`retrySyncItem`, `retryAllFailedSyncItems`, `startIntegrityRun`, `cancelIntegrityRun`, `ingestDocument`, `inspectFileUri`). `null` when the session holds no token the upstream services accept — a mock or test session included; the package knows no host's mock values, so the host answers `null` for them, and a start or cancel is then refused with `FORBIDDEN` without calling the store. `""` is not a token: the action throws. |
96
+ | `accessToken` | `string \| null` | The operator's OAuth access token, forwarded unchanged to the store calls that take one (`retrySyncItem`, `retryAllFailedSyncItems`, `resyncIntegrityCell`, `startIntegrityRun`, `cancelIntegrityRun`, `ingestDocument`, `inspectFileUri`). `null` when the session holds no token the upstream services accept — a mock or test session included; the package knows no host's mock values, so the host answers `null` for them, and a start or cancel is then refused with `FORBIDDEN` without calling the store. `""` is not a token: the action throws. |
96
97
 
97
98
  The host maps its own session profile onto these two fields (for a Google session profile, `email` is `emails[0].value`). The package reads nothing else from the session and never probes the host's object, so a profile that does not carry `email` and `accessToken` does not type-check as an operator.
98
99
 
@@ -153,6 +154,7 @@ Each intent then answers `{ success: true, ... }` or refuses with `{ error }`:
153
154
  | `reorder_rules` | `400` | `orderedRuleIds` is not valid JSON, or is not a non-empty array of distinct positive safe integers. |
154
155
  | `retry_job` | `400` | `fileId` is empty; the store throws. |
155
156
  | `retry_all_failed` | `400` | The store throws. Success answers `{ success, requeued, skipped }`. |
157
+ | `resync_findings` | `403` / `400` / `502` | `403 { error }` when `canReadIntegrityFindings` answers `false` (checked before the form; the store is not called; a throw of the judgment is thrown, never read as `false`). `400 { error }` naming the issues unless the form (every field but `intent`) passes `IntegrityCellResyncRequestSchema`: `runUid` (a UUID), `store`, `scopeKey`, `itemClass` `UNRECORDED`, and an optional `after` written as a positive decimal integer (any other spelling, an unknown field such as `limit`, or another class is refused; the store is not called). `400 { error }` with the store's message when it throws. `502 { error }` when the store's answer breaks `IntegrityCellResyncResultSchema` (not shown as a result). Success answers `{ success, cellResync }`. |
156
158
  | `start_integrity_run` | `400` / failure | `400 { error }` unless the form is `mode=SCAN` without `basisRunUid` or `mode=REPAIR` with a UUID `basisRunUid`. Success answers `{ success, runUid }`. A failure answers `{ failure }` (below). |
157
159
  | `cancel_integrity_run` | `400` / failure | `400 { error }` unless `runUid` is a UUID. Success answers `{ success, runUid }`. A failure answers `{ failure }` (below). |
158
160
  | `resolve_entity` | `400` | `entityId` is empty or `action` is neither `merge` nor `promote`; the store throws. |
@@ -192,7 +194,7 @@ A host read answers every failure it can describe as an outcome. The reads whose
192
194
  | `onSimulateGovernance?: SimulationRunner` | no | Governance dry run; the dry-run console is absent without it. |
193
195
  | `onLoadDocumentRuns?: DocumentRunsLoader` | no | `(metadataId, signal) => Promise<ResourceOutcome<readonly PipelineRunRecord[]>>` — every recorded run of one document, with steps, **newest first**, read with the caller's tenant (an empty `value` is a document with no run). A failed read's `reason` is shown inside `処理履歴を読めませんでした (<reason>)。`, so answer it as a short phrase without a final 。 (e.g. `HTTP 503 で拒まれました`); a 403 is shown as `処理履歴を閲覧する権限がありません。` followed by its `reason` as a second sentence, so a 403's `reason` names only the cause the route declared (which permission or scope to fix), or is `""` when it declared none (`@aiquants/console-ui`'s `ResourceOutcome` contract). The panel aborts the read (`signal`) when it opens another document or closes. Without it the history panel, the 詳細 button on each recent run and the 履歴 button on each ingest row are all absent. |
194
196
  | `onCompareVariants?: ModelComparisonRunner` | no | Runs a side-by-side search over two strategy rows (`ComparisonInput.strategyIds`, answered per `strategyId`); the model-comparison workbench (below the search workbench) is absent without it. A search that could not run should be answered as `{ ok: false, reason }` (the reason is shown as given); a rejection is shown as a failure too and clears the previous outcome. |
195
- | `data?` / `fetcher?` / `integrityFetcher?` / `renderHeader?` | no | Overrides for tests and special mounts (`integrityFetcher` carries the audit card's start and cancel only). The view is mounted under a data router in every case: it re-reads the route's loader (`useRevalidator`) after a start or cancel failure that outdates the overview, and an injected `data` does not receive that re-read. |
197
+ | `data?` / `fetcher?` / `integrityFetcher?` / `inspectorFetcher?` / `renderHeader?` | no | Overrides for tests and special mounts (`integrityFetcher` carries the audit card's start and cancel only; `inspectorFetcher` the findings inspector's presses only: `retry_job` and `resync_findings`). The view is mounted under a data router in every case: it re-reads the route's loader (`useRevalidator`) after a start or cancel failure that outdates the overview, and an injected `data` does not receive that re-read. |
196
198
 
197
199
  ## Tabs
198
200
 
@@ -230,16 +232,19 @@ Only the selected panel is mounted, so leaving a tab discards what was typed the
230
232
  For a failure other than 403, the reload is, besides the loader's next answer, the only way back (neither the polling nor a return to the tab reads without an overview); a 403 card offers no reload, so only the loader's next answer brings the overview back. Focus that was on `再読み込み` moves to the audit card's heading on success, or to this card's heading when the reload answers 403.
231
233
  - While the shown overview has an active run, the tab is shown and the document is visible, the overview is re-read every 2 s (`INTEGRITY_RUN_POLL_MS`), or every 10 s while the run's heartbeat is stale; a hidden document or another tab stops the polling and aborts the read in flight. The polling stops when a read shows the run ended, when a re-read is refused with 401 (repeating it would only repeat the refusal; the shown overview stays with `更新に失敗しました (<reason>)。`), and when a 403 withdraws the overview.
232
234
  - Whenever the tab is shown and the document visible again after either was not — the first visit to the tab after the console mounted on another included — the overview is read once at once, with or without an active run: the card, mounted again with the tab, counts its age label from `readAt` plus the time since its own mount, and a successful read corrects the time away. A failed read leaves the relative age short by the time away, while the absolute 最終測定 time and `更新に失敗しました (<reason>)。` stay correct. A mount on the tab itself reads nothing: the loader has just answered.
233
- - The audit card's start (`start_integrity_run`) and cancel (`cancel_integrity_run`) go through a fetcher of their own (`integrityFetcher`), so a sync retry on the same tab never aborts them, nor they a retry (React Router aborts a fetcher's earlier submission when it submits again); the card is told which one is in flight. The console's alert states the `{ error }` of whichever fetcher settled last, except the findings inspector's own resync (below), which the inspector states instead.
235
+ - The audit card's start (`start_integrity_run`) and cancel (`cancel_integrity_run`) go through a fetcher of their own (`integrityFetcher`), so a sync retry on the same tab never aborts them, nor they a retry (React Router aborts a fetcher's earlier submission when it submits again); the card is told which one is in flight. The console's alert states the `{ error }` of whichever fetcher settled last, except a settlement the open findings inspector states itself (below), which leaves the alert as it was.
234
236
  A failure the action answers as `{ failure }` — the `storage_admin:update` refusal included — reaches the card as `{ failure, occurrence }`, never the console's error alert (the occurrence advances with every failure, so a repeated failure is announced again).
235
237
  The session and operator gates (no session, a blank `email`) and a malformed form answer `{ error }` in the console's alert, as for every intent. Any answer without a failure clears the card's, and so does leaving the tab, so a failure is announced once: one that settled while another tab was shown is shown when the operator returns. After a failure that outdates the overview the view re-reads the loader.
236
238
  - The card's findings inspector gets the console's document controls and remedy places:
237
239
  - `onShowHistory` is the ingest rows' history entry: a row's `履歴` opens the document history panel on the row's document and selects its newest run. Without `onLoadDocumentRuns` the rows offer no `履歴` and no remedy names it.
238
- - `resync`: a row's `再同期` or `再試行` sets the console's one press state (`InspectorResync`: `{ metadataId, intent: "retry_job", status: "pending", error: null }`) and submits `retry_job` with the document's metadata id as `fileId` on the shared fetcher, as the sync monitor's retries do. The inspector draws the state (`pending` busy row buttons; `accepted` a sentence read once; `refused` an alert in the inspector with the action's `error`) and dismisses it once it goes away (a cell switch, 閉じる, Escape, a link to another tab, a tab switch, a newer run), which sets the state to `null`.
239
- - A press while the shared fetcher is not idle (submitting or revalidating anything: the sync monitor's `retry_all_failed` or `retry_job`, the press of an inspector that went away, a command still in flight from another tab) sends nothing: submitting would make React Router drop that submission's answer, such as the `retry-all-skipped` rows or a retry's refusal.
240
- The state becomes `refused` with the reason `送信中の操作 (同期の再試行など) の結果を待っているため、送っていません。結果が出てから押し直してください。`, which the inspector states as its own refusal (once per press); the console's alert and the other submission's settlement are untouched. Pressing again once the fetcher is idle submits.
241
- - A settlement of the shared fetcher while the state is `pending` is routed by its intent. `retry_job` is the press's own (while it is in flight `isRetrying` disables the sync monitor's retries, and a fetcher settles only its latest submission): the state becomes `accepted`, or `refused` with the answer's `error`, and the console's alert states nothing until the next settlement of either fetcher. Any other intent superseded the press, so the state is dropped and the settlement reaches the console's alert as usual.
242
- Without a `pending` state (dismissed, never pressed, or a press refused because the fetcher was busy) every settlement reaches the console's alert: a press whose inspector went away shows its refusal there, and its success stays silent like the sync monitor's own retries.
240
+ - The inspector's presses go through a fetcher of their own (`inspectorFetcher`), never the shared one, and are always sent: on the shared fetcher a press during the sync monitor's `retry_all_failed` or `retry_job` would make React Router drop that submission's answer (the `retry-all-skipped` rows, a retry's refusal), and a sync retry would drop the press's.
241
+ `resync.sending` is `inspectorFetcher.state !== "idle"`: while it is true the inspector shows every row's `再同期` / `再試行` and its bulk resync busy, so a press never replaces another of its own in flight. `isRetrying` (the sync monitor's retries) follows the shared fetcher only.
242
+ - `resync`: a row's `再同期` or `再試行` sets the console's one press state (`InspectorResync`: `{ metadataId, intent: "retry_job", status: "pending", error: null }`) and submits `retry_job` with the document's metadata id as `fileId`. The inspector draws the state (`pending` busy row buttons; `accepted` a sentence read once; `refused` an alert in the inspector with the action's `error`) and dismisses it once it goes away (a cell switch, 閉じる, Escape, a link to another tab, a tab switch, a newer run), which sets the state (and the bulk resync's) to `null`.
243
+ - `resync.cellResync`: on an `UNRECORDED` cell with recorded findings the inspector offers the bulk resync of its recorded documents; each chunk is `onResyncCell(request)` (`IntegrityCellResyncRequest`), submitted as `resync_findings` with the request's fields (`after` as text).
244
+ The first chunk (no `after`) replaces the console's state (`InspectorCellResync`) with `{ settled: 0, status: "pending", requeued: 0, skipped: [], nextAfter: null, error: null }` in the same event; the inspector sends each continuation itself (`after` = the last chunk's `nextAfter`, once per settlement), which leaves the state as it is.
245
+ Each settled chunk adds one to `settled`, adds its `requeued`, appends its `skipped` and carries its `nextAfter` (`done` once it is `null`, else `pending`). An `{ error }` answer, or an answer `IntegrityCellResyncResultSchema` refuses (read again in the view), makes it `refused` with the reason (`まとめての再同期の答えの形が想定と異なります。開発担当に連絡してください。` for the latter) and no continuation; the counts so far are kept.
246
+ - A settlement of the inspector's fetcher is routed by the intent it carried: a `retry_job` while the press state is `pending` becomes `accepted` or `refused` (the answer's `error`), and a `resync_findings` while the bulk state is `pending` is accumulated as above; the inspector states both and the console's alert is untouched.
247
+ Without such a pending state (the inspector went away, or never pressed) nothing is set, so a late settlement never brings a dismissed inspector's state back; its refusal is shown in the console's alert (kept as it was routed there, so a later press in an open inspector neither replaces nor repeats it), and its success stays silent like the sync monitor's own retries.
243
248
  - `remedyDestinations`: the strategies are the `パイプライン & 接続状態` tab and the projection policy the `モデル & パラメータ設定` tab, each named by its tab's label; their links open the tab and move focus to its tab button, which takes the card and its inspector away (`closesInspector: true`). The failed-sync list is `エンリッチメント同期ステータス`: its link moves focus to the region around `SyncStatusMonitor` on the same tab and leaves the inspector open (`closesInspector: false`).
244
249
  - The route must re-read its loader after a successful start or cancel: that re-read is how the new run appears and the polling begins. React Router's default `shouldRevalidate` does; a host that skips the re-read for intents without a loader effect must not list these two.
245
250
 
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Pe=Object.defineProperty;var Ct=Object.getOwnPropertyDescriptor;var Ot=Object.getOwnPropertyNames;var xt=Object.prototype.hasOwnProperty;var kt=(e,t)=>{for(var n in t)Pe(e,n,{get:t[n],enumerable:!0})},Lt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ot(t))!xt.call(e,o)&&o!==n&&Pe(e,o,{get:()=>t[o],enumerable:!(r=Ct(t,o))||r.enumerable});return e};var Ft=e=>Lt(Pe({},"__esModule",{value:!0}),e);var Nn={};kt(Nn,{StorageAdminConsoleView:()=>Fe,checkAllSystemHealth:()=>De,checkBackendApiHealth:()=>mt,checkNeo4jHealth:()=>dt,checkQdrantHealth:()=>ut,checkRedisHealth:()=>ct,checkSqlServerHealth:()=>pt,createStorageAdminApp:()=>Pn,createStorageAdminServer:()=>$e});module.exports=Ft(Nn);var _=require("@aiquants/console-ui"),D=require("@aiquants/enrichment-core"),R=require("@aiquants/enrichment-react"),h=require("@aiquants/governance-react"),g=require("react"),K=require("react-router");var ce="ja-JP";var jt=/[^\s\x1c-\x1f\x85\ufeff]/;function pe(e){return jt.test(e)}function re(e,t){return new Promise(n=>n(e())).catch(n=>t(n instanceof Error?n.message:String(n)))}var me=require("@aiquants/console-ui/core"),Je=require("@aiquants/enrichment-core"),T=require("react");var Ut=2e3,Dt=1e4;function Ne(e,t){return t.ok&&e.kind==="ready"&&(0,Je.isStrictlyEarlier)(t.value.readAt,e.value.readAt)?e:(0,me.keepLastGood)(e,t)}var Mt=401;function Ht(e){return e.kind==="failed"||e.refreshFailure!==null&&e.refreshFailure.status===Mt?null:e.value.active}function We(e,t){let[n,r]=(0,T.useState)(()=>({loaded:e,overview:Ne({kind:"loading"},e)}));n.loaded!==e&&r({loaded:e,overview:Ne(n.overview,e)});let o=(0,T.useRef)(t);o.current=t;let s=(0,T.useRef)(null);(0,T.useEffect)(()=>()=>s.current?.abort(),[]);let l=(0,T.useCallback)((c,m)=>re(m,y=>({ok:!1,status:null,reason:y})).then(y=>{c.aborted||r(I=>({loaded:I.loaded,overview:Ne(I.overview,y)}))}),[]),u=(0,T.useCallback)(()=>{let c=new AbortController;s.current=c,r(m=>({loaded:m.loaded,overview:(0,me.beginReload)(m.overview,"reload")})),l(c.signal,()=>o.current(c.signal))},[l]),d=(0,T.useCallback)(c=>l(c,()=>o.current(c)),[l]);return{overview:n.overview,reload:u,poll:d}}function $t(e){return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)}function Kt(){return document.visibilityState==="visible"}function qt(){return!0}function Ye(e,t,n){let r=(0,T.useSyncExternalStore)($t,Kt,qt),o=t&&r,s=(0,T.useRef)(o),l=e.kind==="ready",u=Ht(e),d=u===null?null:u.run.runUid,c=u===null?!1:u.isStale;(0,T.useEffect)(()=>{let m=o&&!s.current;if(s.current=o,!o||d===null&&!(m&&l))return;let y=new AbortController,I=c?Dt:Ut,b,w=async()=>{await n(y.signal),!y.signal.aborted&&d!==null&&(b=setTimeout(w,I))};return b=setTimeout(w,m?0:I),()=>{y.abort(),clearTimeout(b)}},[o,l,d,c,n])}var Te={columns:2,className:"grid-cols-2",spanClassNames:{1:"col-span-1",2:"col-span-2"}},_e={columns:4,className:"@min-[41.5rem]:grid-cols-4",spanClassNames:{1:"@min-[41.5rem]:col-span-1",2:"@min-[41.5rem]:col-span-2",3:"@min-[41.5rem]:col-span-3",4:"@min-[41.5rem]:col-span-4"}},Ee={className:"@min-[82rem]:grid-flow-col @min-[82rem]:auto-cols-fr @min-[82rem]:grid-cols-none",lastTabClassName:"@min-[82rem]:col-auto"};function Ce(e,t){let n=t%e.columns,r=n===0?1:e.columns-n+1;return e.spanClassNames[r]}var a=require("react/jsx-runtime"),Ze="tab",xe={key:"knowledge-authority",phrases:["\u6A29\u5A01\u53F0\u5E33 & \u898F\u7A0B\u885D\u7A81"]},ke={key:"pipeline",phrases:["\u30D1\u30A4\u30D7\u30E9\u30A4\u30F3 & \u63A5\u7D9A\u72B6\u614B"]},Le={key:"parameters",phrases:["\u30E2\u30C7\u30EB & \u30D1\u30E9\u30E1\u30FC\u30BF\u8A2D\u5B9A"]},Xe="\u30A8\u30F3\u30EA\u30C3\u30C1\u30E1\u30F3\u30C8\u540C\u671F\u30B9\u30C6\u30FC\u30BF\u30B9",Bt="\u9001\u4FE1\u4E2D\u306E\u64CD\u4F5C (\u540C\u671F\u306E\u518D\u8A66\u884C\u306A\u3069) \u306E\u7D50\u679C\u3092\u5F85\u3063\u3066\u3044\u308B\u305F\u3081\u3001\u9001\u3063\u3066\u3044\u307E\u305B\u3093\u3002\u7D50\u679C\u304C\u51FA\u3066\u304B\u3089\u62BC\u3057\u76F4\u3057\u3066\u304F\u3060\u3055\u3044\u3002",q=[{key:"search",phrases:["\u30E1\u30BF\u30C7\u30FC\u30BF\u691C\u7D22","\u30EF\u30FC\u30AF\u30D9\u30F3\u30C1"]},{key:"ingest",phrases:["\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8","\u53D6\u308A\u8FBC\u307F & \u30E1\u30BF\u751F\u6210"]},ke,{key:"knowledge-graph",phrases:["\u30CA\u30EC\u30C3\u30B8\u30B0\u30E9\u30D5","\u63A2\u7D22"]},Le,{key:"prompts",phrases:["\u30D7\u30ED\u30F3\u30D7\u30C8 & \u30C9\u30E9\u30A4\u30E9\u30F3"]},xe,{key:"data-retention",phrases:["\u30C7\u30FC\u30BF\u4FDD\u6301 & \u6574\u5408\u6027\u76E3\u67FB"]}];function Oe(e){return e.phrases.join("")}function Vt(e){return e!==null&&q.some(t=>t.key===e)}var Gt="Tri-Store \u30C7\u30FC\u30BF\u6574\u5408\u6027\u76E3\u67FB";function Qt(e){return`\u76E3\u67FB\u306E\u6982\u6CC1\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F${(0,_.reasonAside)(e)}\u3002`}var zt=(0,_.resolveConsoleUiLabels)("ja");function Jt(e){return zt.failureSentence(e,"\u51E6\u7406\u5C65\u6B74\u3092\u95B2\u89A7\u3059\u308B\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002",t=>`\u51E6\u7406\u5C65\u6B74\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F${(0,_.reasonAside)(t)}\u3002`)}var et={state:"idle",formData:null,data:null,submit:()=>Promise.resolve()};function it({data:e,fetcher:t,integrityFetcher:n,renderHeader:r,graphTraversal:o,onBrowseGraphNodes:s,onSimulateGovernance:l,onRefreshIngestQueue:u,onSearch:d,onLoadDocumentRuns:c,onCompareVariants:m,loadIntegrityOverview:y,loadIntegrityFindings:I,policyConflicts:b,documentAuthority:w}){let[f,V]=(0,g.useState)(null),[$,x]=(0,g.useState)(null),[k,L]=(0,g.useState)(!1),G=(0,g.useMemo)(()=>{if(s!==void 0)return(i,S)=>{L(!0),re(()=>s(i,S),v=>({ok:!1,reason:v})).then(v=>{L(!1),x(v.ok?null:v.reason),v.ok&&V(v.page)})}},[s]),[Q,z]=(0,K.useSearchParams)(),F=Q.get(Ze),A=Vt(F)?F:q[0].key,j=i=>{z(S=>{let v=new URLSearchParams(S);return v.set(Ze,i),v},{replace:!1,preventScrollReset:!0})},ie=Yt(e.recentIngestItems,u,A==="ingest"),U=We(e.integrityAudit,y);Ye(U.overview,A==="data-retention",U.poll);let Z=(0,g.useRef)(null),ae=(0,_.useFocusRescue)(()=>Z.current),[fe,be]=(0,g.useState)(0),Se=(0,g.useCallback)(()=>be(i=>i+1),[]),p=ie===null?e:{...e,recentIngestItems:[...ie]},J=(0,g.useRef)({}),Re=(0,g.useCallback)(()=>J.current[A]??null,[A]),oe=(0,g.useMemo)(()=>Zt(e.enrichmentStrategies),[e.enrichmentStrategies]),he=(0,g.useMemo)(()=>e.strategyVariants.map(Xt),[e.strategyVariants]),E=nn(c),W=E.open,le=W===void 0?void 0:i=>W(i,null),ve=W===void 0?void 0:i=>W(i.metadataId,i.id),ue=(i,S)=>{let v=q.length-1,C;if(i.key==="ArrowRight"||i.key==="ArrowDown")C=S===v?0:S+1;else if(i.key==="ArrowLeft"||i.key==="ArrowUp")C=S===0?v:S-1;else if(i.key==="Home")C=0;else if(i.key==="End")C=v;else return;i.preventDefault();let de=q[C].key;j(de),J.current[de]?.focus()},Ke={...p.featureFlags};if(t.formData&&t.formData.get("intent")==="toggle_flag"){let i=String(t.formData.get("flagKey")??""),S=String(t.formData.get("enabled")??"")==="true";i&&(Ke[i]=S)}let bt=t.data&&"inspection"in t.data?t.data.inspection:void 0,X=t.state==="idle"?null:t.formData?.get("intent"),St=X==="inspect_uri",Rt=X==="ingest_document",ht=X==="retry_job"||X==="retry_all_failed",vt=X==="resolve_entity",qe=n.state==="idle"?null:n.formData?.get("intent"),It=qe==="start_integrity_run"?{kind:"starting",mode:D.IntegrityRunModeSchema.parse(n.formData?.get("mode"))}:qe==="cancel_integrity_run"?{kind:"cancelling"}:{kind:"idle"},wt=(0,K.useRevalidator)(),[At,Ie]=(0,g.useState)(null),Be=A!=="data-retention";(0,g.useEffect)(()=>{Be&&Ie(null)},[Be]);let Pt=i=>{let S=i?.failure;if(S===void 0){Ie(null);return}Ie(v=>({failure:S,occurrence:v===null?1:v.occurrence+1})),(0,h.integrityFailureNeedsOverviewReread)(S)&&wt.revalidate()},[ee,te]=(0,g.useState)(null),Nt=i=>{if(t.state!=="idle"){te({metadataId:i,intent:"retry_job",status:"refused",error:Bt});return}te({metadataId:i,intent:"retry_job",status:"pending",error:null}),t.submit({intent:"retry_job",fileId:String(i)},{method:"post"})},[Ve,we]=(0,g.useState)("console"),Tt=(i,S)=>{if(ee!==null&&ee.status==="pending"){if(S==="retry_job"){let v=i?.error;te(v===void 0?{...ee,status:"accepted",error:null}:{...ee,status:"refused",error:v}),we("inspector");return}te(null)}we("console")},{settledIntent:_t,submitAndAwait:Ge}=nt(t,Tt);nt(n,i=>{we("integrity"),Pt(i)});let Qe=Ve==="inspector"?void 0:(Ve==="console"?t:n).data?.error,Ae=i=>{j(i),J.current[i]?.focus()},ze=(0,g.useRef)(null),Et={strategies:{label:Oe(ke),onOpen:()=>Ae(ke.key),closesInspector:!0},projectionPolicy:{label:Oe(Le),onOpen:()=>Ae(Le.key),closesInspector:!0},failedSync:{label:Xe,onOpen:()=>ze.current?.focus(),closesInspector:!1}},ne=_t==="retry_all_failed"&&t.data?.skipped!==void 0&&t.data.requeued!==void 0?{requeued:t.data.requeued,skipped:t.data.skipped}:null;return(0,a.jsx)(_.ConsoleUiRoot,{locale:"ja",formatLocale:ce,timeZone:p.displayTimeZone,testId:"storage-admin-console-ui",children:(0,a.jsxs)("div",{className:"container mx-auto space-y-6 p-6 font-sans text-slate-900","data-testid":"storage-admin-console",children:[Qe&&(0,a.jsx)("div",{className:"rounded-lg border border-red-200 border-solid bg-red-50 p-4 font-medium text-red-700 text-sm shadow-sm",role:"alert","data-testid":"storage-admin-error-alert",children:Qe}),r?r({title:"\u30B9\u30C8\u30EC\u30FC\u30B8 AI \u30A8\u30F3\u30EA\u30C3\u30C1\u30E1\u30F3\u30C8 & \u30AC\u30D0\u30CA\u30F3\u30B9\u904B\u7528\u7BA1\u7406",tenantId:p.tenantId}):(0,a.jsxs)("header",{className:"flex flex-col justify-between gap-2 border-slate-200 border-b border-solid pb-4 md:flex-row md:items-center",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("h1",{className:"font-bold text-2xl tracking-tight",children:"\u30B9\u30C8\u30EC\u30FC\u30B8 AI \u30A8\u30F3\u30EA\u30C3\u30C1\u30E1\u30F3\u30C8 & \u30AC\u30D0\u30CA\u30F3\u30B9\u904B\u7528\u7BA1\u7406"}),(0,a.jsxs)("p",{className:"mt-1 text-slate-500 text-sm",children:["\u30C6\u30CA\u30F3\u30C8: ",(0,a.jsx)("code",{className:"font-semibold text-slate-800",children:p.tenantId})," | \u5168\u30B7\u30B9\u30C6\u30E0\u72B6\u614B\u30FB\u30D1\u30E9\u30E1\u30FC\u30BF\u5236\u5FA1\u30FB\u6574\u5408\u6027\u76E3\u67FB"]})]}),(0,a.jsx)("div",{className:"flex items-center gap-2",children:(0,a.jsxs)("button",{type:"button","data-testid":"header-health-status-button",onClick:()=>j("pipeline"),className:"inline-flex items-center gap-2 rounded-full border border-slate-200 border-solid bg-slate-50 px-3 py-1.5 font-medium text-slate-700 text-xs transition-colors hover:bg-slate-100",children:[(0,a.jsx)("span",{className:`h-2 w-2 rounded-full ${p.systemHealth.allHealthy?"bg-emerald-500":"bg-amber-500"}`}),(0,a.jsxs)("span",{children:["\u5468\u8FBA\u6A5F\u80FD: ",p.systemHealth.allHealthy?"\u5168\u30B5\u30FC\u30D3\u30B9\u6B63\u5E38":"\u63A5\u7D9A\u8981\u78BA\u8A8D"]})]})})]}),(0,a.jsxs)("div",{className:"w-full space-y-6",children:[(0,a.jsx)("div",{className:"@container w-full","data-testid":"storage-admin-tablist-frame",children:(0,a.jsx)("div",{className:`grid w-full ${Te.className} ${_e.className} ${Ee.className} gap-1 rounded-xl bg-slate-100 p-1`,role:"tablist","aria-label":"\u904B\u7528\u7BA1\u7406\u30B3\u30F3\u30BD\u30FC\u30EB\u306E\u753B\u9762",children:q.map((i,S)=>{let v=A===i.key;return(0,a.jsx)("button",{id:`tab-${i.key}`,type:"button",role:"tab",ref:C=>{J.current[i.key]=C},"aria-selected":v,"aria-controls":`panel-${i.key}`,tabIndex:v?0:-1,"data-testid":`tab-trigger-${i.key}`,onKeyDown:C=>ue(C,S),onClick:()=>j(i.key),className:`wrap-anywhere break-keep rounded-lg px-3 py-2.5 text-center font-medium text-sm transition-all ${S===q.length-1?`${Ce(Te,q.length)} ${Ce(_e,q.length)} ${Ee.lastTabClassName}`:""} ${v?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:bg-slate-200/50 hover:text-slate-900"}`,children:i.phrases.map((C,de)=>(0,a.jsxs)(g.Fragment,{children:[de>0&&(0,a.jsx)("wbr",{}),C]},C))},i.key)})})}),E.metadataId!==null&&(0,a.jsx)(R.PipelineRunInspector,{metadataId:E.metadataId,runs:E.runs,selectedRunId:E.selectedRunId,onSelectRun:E.selectRun,isLoading:E.isLoading,failure:E.failure,onClose:E.close,openRequest:E.openRequest,returnFocusFallback:Re}),A==="search"&&(0,a.jsxs)("div",{role:"tabpanel",id:"panel-search","aria-labelledby":"tab-search",className:"space-y-6","data-testid":"tab-content-search",children:[(0,a.jsx)(R.MetadataSearchWorkbench,{tenantId:p.tenantId,onSearch:d,circuitBreakerStatus:p.circuitBreakerStatus}),m!==void 0&&(0,a.jsx)(R.ModelComparisonWorkbench,{variants:he,onCompare:m})]}),A==="ingest"&&(0,a.jsx)("div",{role:"tabpanel",id:"panel-ingest","aria-labelledby":"tab-ingest",className:"space-y-6","data-testid":"tab-content-ingest",children:(0,a.jsx)(R.DocumentIngestConsole,{tenantId:p.tenantId,policies:p.confidentialityPolicies,domainOptions:oe,recentItems:p.recentIngestItems,inspectionResult:bt,isInspecting:St,isSubmitting:Rt,onInspectUri:i=>{t.submit({intent:"inspect_uri",fileUri:i},{method:"post"})},onIngestDocument:i=>{t.submit({intent:"ingest_document",payload:JSON.stringify(i)},{method:"post"})},onRetryItem:i=>{t.submit({intent:"retry_job",fileId:String(i)},{method:"post"})},onShowHistory:le})}),A==="pipeline"&&(0,a.jsxs)("div",{role:"tabpanel",id:"panel-pipeline","aria-labelledby":"tab-pipeline",className:"space-y-6","data-testid":"tab-content-pipeline",children:[(0,a.jsx)(R.PipelineFlowViewer,{featureFlags:p.featureFlags,metrics:p.pipelineStepMetrics,metricSampleWindow:p.pipelineStepMetricWindow}),(0,a.jsx)(en,{runs:p.recentPipelineRuns,onOpenRun:ve}),(0,a.jsx)(R.EnrichmentStrategyBoard,{strategies:p.enrichmentStrategies,featureFlags:p.featureFlags,isUpdating:t.state!=="idle",onToggleStage:(i,S,v)=>t.submit({intent:"update_enrichment_strategy",strategyId:String(i.id),domainId:String(i.domainId),stage:S,enabled:String(v)},{method:"post"})}),(0,a.jsx)(R.InfrastructureHealthMonitor,{health:p.systemHealth,isRefreshing:t.state!=="idle",onRefresh:()=>t.submit({intent:"refresh_health"},{method:"post"})})]}),A==="knowledge-graph"&&(0,a.jsxs)("div",{role:"tabpanel",id:"panel-knowledge-graph","aria-labelledby":"tab-knowledge-graph",className:"space-y-6","data-testid":"tab-content-knowledge-graph",children:[(0,a.jsx)(R.OntologyStatusCard,{tenantId:p.tenantId,ontologyStatus:p.ontologyStatus}),(0,a.jsx)(h.KnowledgeGraphExplorer,{topologyMaxLabels:D.GRAPH_INDEX_LIMITS.topologyLabels.default,schema:p.graphSchema,tenantId:p.tenantId,unresolvedEntities:p.unresolvedEntities,traversal:o,onBrowseLabel:G,nodeIndexPage:f,nodeIndexFailure:$,isNodeIndexLoading:k,isResolving:vt,onResolveEntity:(i,S)=>{t.submit({intent:"resolve_entity",entityId:i,action:S},{method:"post"})}})]}),A==="parameters"&&(0,a.jsxs)("div",{role:"tabpanel",id:"panel-parameters","aria-labelledby":"tab-parameters",className:"space-y-6","data-testid":"tab-content-parameters",children:[(0,a.jsxs)("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2",children:[(0,a.jsx)(h.FeatureFlagBoard,{flags:Ke,isUpdating:t.state!=="idle",onToggleFlag:(i,S)=>{t.submit({intent:"toggle_flag",flagKey:i,enabled:String(S)},{method:"post"})}}),(0,a.jsx)(h.ClassificationRuleEditor,{rules:p.classificationRules,domainOptions:oe,consultedBy:p.classificationRuleConsumer,onReorderRules:i=>{t.submit({intent:"reorder_rules",orderedRuleIds:JSON.stringify(i)},{method:"post"})}})]}),p.policiesMissingDestination.length>0&&(0,a.jsxs)("div",{"data-testid":"policies-missing-destination",role:"alert",style:{padding:"10px 12px",borderRadius:"6px",backgroundColor:"#fef2f2",color:"#b91c1c",fontSize:"12px"},children:[(0,a.jsx)("strong",{children:"\u6B21\u306E\u533A\u5206\u30FB\u6A5F\u80FD\u306F\u5B9F\u884C\u6642\u306B\u5931\u6557\u3057\u307E\u3059\u3002"})," \u53C2\u7167\u3059\u308B\u30D7\u30ED\u30F3\u30D7\u30C8\u884C\u306B\u5B9B\u5148\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002",(0,a.jsx)("ul",{style:{margin:"6px 0 0",paddingInlineStart:"18px"},children:p.policiesMissingDestination.map(i=>(0,a.jsxs)("li",{"data-testid":`missing-destination-${i.confidentialityLevel}-${i.capability}`,children:[i.confidentialityLevel," / ",i.capability," \u2192 ",i.promptKey," (",i.modelProvider,") \u306E ",(0,a.jsx)("code",{children:"extra_params.base_url"})]},`${i.confidentialityLevel}:${i.capability}`))}),(0,a.jsx)("span",{style:{display:"block",marginTop:"4px",fontSize:"11px"},children:"\u5B9B\u5148\u3092\u8A2D\u5B9A\u3057\u3066\u3082\u3001\u305D\u306E\u30DB\u30B9\u30C8\u304C\u914D\u5099\u5185\u3068\u3057\u3066\u767B\u9332\u3055\u308C\u3066\u3044\u306A\u3051\u308C\u3070\u62D2\u5426\u3055\u308C\u307E\u3059\u3002"})]}),(0,a.jsx)(h.ConfidentialityPolicyBoard,{policies:p.confidentialityPolicies,promptKeys:p.promptTemplates.map(i=>i.template_key),isUpdating:t.state!=="idle",onChangePolicy:i=>{t.submit({intent:"update_confidentiality_policy",confidentialityLevel:i.confidentialityLevel,capability:i.capability,isEnabled:String(i.isEnabled),allowCloudProvider:String(i.allowCloudProvider),promptKey:i.promptKey??""},{method:"post"})}}),(0,a.jsx)(h.TranscriptionAdaptationBoard,{vocabulary:p.transcriptionVocabulary,references:p.transcriptionReferences,unresolvedUris:p.unresolvedReferenceUris,isUpdating:t.state!=="idle",onSaveTerm:i=>Ge({intent:"save_transcription_term",id:i.id===null?"":String(i.id),term:i.term,reading:i.reading??"",boost:i.boost===null?"":String(i.boost),domainKey:i.domainKey??"",isActive:String(i.isActive)},{method:"post"}),onSaveReference:i=>Ge({intent:"save_transcription_reference",id:i.id===null?"":String(i.id),fileUri:i.fileUri,domainKey:i.domainKey??"",isActive:String(i.isActive)},{method:"post"})}),(0,a.jsx)(h.SystemParameterTable,{parameters:p.systemParameters,onSaveParameter:(i,S)=>{t.submit({intent:"update_parameter",paramKey:i,paramValue:String(S)},{method:"post"})}})]}),A==="prompts"&&(0,a.jsxs)("div",{role:"tabpanel",id:"panel-prompts","aria-labelledby":"tab-prompts",className:"space-y-6","data-testid":"tab-content-prompts",children:[(0,a.jsx)(h.PromptTemplateConsole,{templates:p.promptTemplates,isSaving:t.state!=="idle",onSaveTemplate:i=>{t.submit({intent:"update_prompt",templateKey:i.template_key,payload:JSON.stringify({templateText:i.template_text,modelName:i.model_name,temperature:i.temperature,maxOutputTokens:i.max_output_tokens,responseSchema:i.response_schema,endpointBaseUrl:i.endpoint_base_url??null})},{method:"post"})}}),(0,a.jsx)(h.GovernanceDryRunConsole,{onSimulate:l})]}),A==="knowledge-authority"&&(0,a.jsxs)("div",{role:"tabpanel",id:"panel-knowledge-authority","aria-labelledby":"tab-knowledge-authority",className:"space-y-6","data-testid":"tab-content-knowledge-authority",children:[(0,a.jsx)(h.DocumentAuthorityRegistry,{host:w,canUpdate:p.canUpdateKnowledge,onPolicyConflictsChanged:Se}),(0,a.jsx)(h.PolicyConflictQueue,{host:b,revision:fe})]}),A==="data-retention"&&(0,a.jsxs)("div",{role:"tabpanel",id:"panel-data-retention","aria-labelledby":"tab-data-retention",className:"space-y-6","data-testid":"tab-content-data-retention",children:[U.overview.kind==="ready"?(0,a.jsx)("div",{ref:ae,children:(0,a.jsx)(h.TriStoreIntegrityAudit,{overview:U.overview.value,canReadFindings:p.canReadIntegrityFindings,command:It,commandFailure:At,onStartRun:(i,S)=>{n.submit(S===null?{intent:"start_integrity_run",mode:i}:{intent:"start_integrity_run",mode:i,basisRunUid:S},{method:"post"})},onCancelRun:i=>{n.submit({intent:"cancel_integrity_run",runUid:i},{method:"post"})},loadFindings:I,refreshFailure:U.overview.refreshFailure===null?null:U.overview.refreshFailure.reason,headingRef:Z,onShowHistory:le,resync:{onResync:Nt,onDismiss:()=>te(null),feedback:ee},remedyDestinations:Et})}):(0,a.jsx)(_.Card,{title:Gt,testId:"audit-overview-failed",headingRef:Z,children:(0,a.jsx)(_.ResourceFailed,{failure:U.overview,onReload:U.reload,forbiddenMessage:"\u76E3\u67FB\u306E\u6982\u6CC1\u3092\u95B2\u89A7\u3059\u308B\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002",failureMessage:Qt,rescueRef:ae,testId:"audit-overview-failed-resource"})}),(0,a.jsx)(h.PolicyConflictSummaryCard,{host:b,knowledgeTabLabel:Oe(xe),onOpenKnowledgeTab:()=>Ae(xe.key)}),ne!==null&&ne.skipped.length>0&&(0,a.jsxs)("div",{role:"status","data-testid":"retry-all-skipped",className:"rounded-lg border border-amber-200 border-solid bg-amber-50 p-4 text-amber-800 text-sm",children:[(0,a.jsxs)("strong",{children:["\u4E00\u62EC\u518D\u8A66\u884C: ",ne.requeued," \u4EF6\u3092\u518D\u6295\u5165\u3057\u3001",ne.skipped.length," \u4EF6\u3092\u636E\u3048\u7F6E\u304D\u307E\u3057\u305F\u3002"]})," ","\u636E\u3048\u7F6E\u3044\u305F\u884C\u306F\u5931\u6557\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059\u3002",(0,a.jsx)("ul",{className:"mt-1.5 list-disc ps-5",children:ne.skipped.map(i=>(0,a.jsxs)("li",{"data-testid":`retry-all-skipped-${i.metadataId}`,children:["#",i.metadataId,": ",i.reason]},i.metadataId))})]}),(0,a.jsxs)("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2",children:[(0,a.jsx)("section",{ref:ze,tabIndex:-1,"aria-label":Xe,"data-testid":"sync-status-region",children:(0,a.jsx)(R.SyncStatusMonitor,{counts:p.syncCounts,totalFiles:p.totalFiles,failedItems:p.failedSyncItems,isRetrying:ht,onRetryItem:i=>{t.submit({intent:"retry_job",fileId:String(i)},{method:"post"})},onRetryAll:()=>{t.submit({intent:"retry_all_failed"},{method:"post"})}})}),(0,a.jsx)(R.QdrantStorageCard,{overview:p.qdrantCollections,health:{healthy:p.systemHealth.services.qdrant.status==="connected",latency_ms:p.systemHealth.services.qdrant.latencyMs}})]})]})]})]})})}var Wt=new Set(D.EnrichmentSyncStatusSchema.options.filter(e=>e!=="SYNCED"&&!e.startsWith("FAILED"))),tt=2e3;function Yt(e,t,n){let[r,o]=(0,g.useState)(null),s=(0,g.useRef)(t);s.current=t;let l=(0,g.useRef)(e);l.current!==e&&(l.current=e,r!==null&&o(null));let d=(r??e)?.some(c=>Wt.has(c.syncStatus))===!0;return(0,g.useEffect)(()=>{if(!(n&&d&&s.current))return;let c=!1,m,y=async()=>{let I=s.current;if(I!==void 0){try{let b=await I();if(c)return;o(b)}catch{if(c)return}m=setTimeout(y,tt)}};return m=setTimeout(y,tt),()=>{c=!0,clearTimeout(m)}},[d,n]),r}function nt(e,t){let n=(0,g.useRef)(t);n.current=t;let r=(0,g.useRef)(null),o=(0,g.useRef)(!1),s=(0,g.useRef)(null);if(e.state!=="idle"){o.current=!0;let u=e.formData?.get("intent");typeof u=="string"&&(r.current=u)}(0,g.useEffect)(()=>{if(e.state!=="idle"||!o.current)return;o.current=!1,n.current(e.data,r.current);let u=s.current;if(u===null)return;s.current=null;let d=e.data?.error;typeof d=="string"?u.reject(new Error(d)):u.resolve()},[e.state,e.data]);let l=(0,g.useCallback)((...u)=>new Promise((d,c)=>{s.current?.reject(new Error("\u3053\u306E\u4FDD\u5B58\u306F\u5F8C\u7D9A\u306E\u9001\u4FE1\u306B\u7F6E\u304D\u63DB\u3048\u3089\u308C\u307E\u3057\u305F\u3002")),s.current={resolve:d,reject:c},e.submit(...u)}),[e]);return{settledIntent:e.state==="idle"?r.current:null,submitAndAwait:l}}function Zt(e){let t=new Set,n=[];for(let r of e)t.has(r.domainKey)||(t.add(r.domainKey),n.push({key:r.domainKey,label:r.domainLabel}));return n}function Xt(e){return{strategyId:e.strategyId,label:`${e.domainKey} / ${e.variantKey}`,embeddingModel:e.embeddingModel}}function en({runs:e,onOpenRun:t}){return(0,a.jsxs)("section",{className:"rounded-xl border border-slate-200 border-solid bg-white p-6 shadow-sm","aria-labelledby":"pipeline-recent-runs-heading","data-testid":"pipeline-recent-runs",children:[(0,a.jsx)("h2",{id:"pipeline-recent-runs-heading",className:"font-bold text-base text-slate-900",children:"\u76F4\u8FD1\u306E\u5B9F\u884C"}),e.length===0?(0,a.jsx)("p",{className:"mt-4 text-[13px] text-slate-500","data-testid":"pipeline-recent-runs-empty",children:"\u8A18\u9332\u3055\u308C\u305F\u5B9F\u884C\u304C\u3042\u308A\u307E\u305B\u3093\u3002"}):(0,a.jsx)("div",{className:"relative mt-4 overflow-x-auto","data-testid":"pipeline-recent-runs-scroll",children:(0,a.jsxs)("table",{className:"w-full text-left text-[13px]",children:[(0,a.jsx)("thead",{children:(0,a.jsxs)("tr",{className:"whitespace-nowrap border-slate-200 border-b border-solid text-[11px] text-slate-500 uppercase",children:[(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u5B9F\u884C"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u6587\u66F8"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u7A2E\u985E"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u304D\u3063\u304B\u3051"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u8A66\u884C"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u72B6\u614B"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u6B62\u307E\u3063\u305F\u6BB5"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u958B\u59CB"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u7D42\u4E86"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u8981\u6C42\u8005"}),t!==void 0&&(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:(0,a.jsx)("span",{className:"sr-only","data-testid":"pipeline-recent-runs-action-header",children:"\u64CD\u4F5C"})})]})}),(0,a.jsx)("tbody",{children:e.map(n=>{let r=(0,R.pipelineRunPresentationKey)(n),o=R.PIPELINE_RUN_STATUS_PRESENTATION[r];return(0,a.jsxs)("tr",{className:"border-slate-100 border-b border-solid","data-testid":`pipeline-run-row-${n.id}`,"data-status":n.status,children:[(0,a.jsxs)("td",{className:"whitespace-nowrap px-3 py-2 font-mono","data-testid":`pipeline-run-id-${n.id}`,children:["#",n.id]}),(0,a.jsxs)("td",{className:"whitespace-nowrap px-3 py-2 font-mono","data-testid":`pipeline-run-metadata-${n.id}`,children:["#",n.metadataId]}),(0,a.jsx)("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-kind-${n.id}`,children:D.DOCUMENT_KIND_LABELS[n.documentKind]}),(0,a.jsx)("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-trigger-${n.id}`,"data-trigger":n.trigger,children:R.PIPELINE_TRIGGER_LABELS[n.trigger]}),(0,a.jsx)("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-attempt-${n.id}`,children:n.attempt}),(0,a.jsx)("td",{className:"px-3 py-2",children:(0,a.jsx)("span",{className:`inline-flex whitespace-nowrap rounded-full px-2 py-0.5 font-semibold text-[11px] ${o.className}`,"data-testid":`pipeline-run-status-${n.id}`,"data-status":n.status,"data-presentation":r,children:o.label})}),(0,a.jsx)("td",{className:"px-3 py-2","data-testid":`pipeline-run-failed-step-${n.id}`,children:n.failedStepKey===null?"\u2014":D.PIPELINE_STEPS[n.failedStepKey].label}),(0,a.jsx)("td",{className:"whitespace-nowrap px-3 py-2 text-slate-500","data-testid":`pipeline-run-started-${n.id}`,children:(0,a.jsx)(R.RecordedInstant,{iso:n.startedAt,testId:`pipeline-run-started-value-${n.id}`})}),(0,a.jsx)("td",{className:"whitespace-nowrap px-3 py-2 text-slate-500","data-testid":`pipeline-run-finished-${n.id}`,children:(0,a.jsx)(R.FinishedInstant,{iso:n.finishedAt,testId:`pipeline-run-finished-value-${n.id}`})}),(0,a.jsx)("td",{className:"wrap-anywhere px-3 py-2","data-testid":`pipeline-run-requested-by-${n.id}`,children:n.requestedBy}),t!==void 0&&(0,a.jsx)("td",{className:"whitespace-nowrap px-3 py-2 text-right",children:(0,a.jsx)("button",{type:"button",onClick:()=>t(n),"aria-label":`\u5B9F\u884C #${n.id} (\u6587\u66F8 #${n.metadataId}) \u306E\u8A73\u7D30`,className:"whitespace-nowrap rounded-sm border border-slate-300 border-solid bg-white px-2 py-0.5 font-semibold text-[11px] text-slate-700 hover:bg-slate-50","data-testid":`pipeline-run-open-${n.id}`,children:"\u8A73\u7D30"})})]},n.id)})})]})})]})}var rt={metadataId:null,runs:[],selectedRunId:null,isLoading:!1,failure:null};function tn(e){for(let t of e)for(let n of t.steps){let r=n.provenance;if(r!==null){for(let[o,s]of Object.entries(r))if(typeof s=="string"&&!pe(s))return`\u51E6\u7406\u5C65\u6B74\u306E\u8A18\u9332\u306B\u8AAD\u3081\u306A\u3044\u6765\u6B74\u306E\u5024\u304C\u3042\u308A\u307E\u3059 (\u5B9F\u884C ${t.id} \u306E\u6BB5 ${n.sequence} \u306E ${o})\u3002`}}return null}function nn(e){let[t,n]=(0,g.useState)(rt),[r,o]=(0,g.useState)(0),s=(0,g.useRef)(0),l=(0,g.useRef)(null),u=(0,g.useMemo)(()=>{if(e!==void 0)return(m,y)=>{s.current+=1;let I=s.current;l.current?.abort();let b=new AbortController;l.current=b,o(w=>w+1),n({metadataId:m,runs:[],selectedRunId:y,isLoading:!0,failure:null}),re(()=>e(m,b.signal),w=>({ok:!1,status:null,reason:w})).then(w=>{if(s.current!==I)return;let f=w.ok?tn(w.value):Jt(w);if(!w.ok||f!==null){n({metadataId:m,runs:[],selectedRunId:y,isLoading:!1,failure:f});return}n({metadataId:m,runs:w.value,selectedRunId:y===null?rn(w.value):y,isLoading:!1,failure:null})})}},[e]),d=(0,g.useCallback)(m=>{n(y=>({...y,selectedRunId:m}))},[]),c=(0,g.useCallback)(()=>{s.current+=1,l.current?.abort(),l.current=null,n(rt)},[]);return{...t,openRequest:r,open:u,selectRun:d,close:c}}function rn(e){return e.length===0?null:e[0].id}function sn(e){let t=(0,K.useLoaderData)(),n=(0,K.useFetcher)(),r=(0,K.useFetcher)(),o=e.data??t,s=e.fetcher??n,l=e.integrityFetcher??r;return o?(0,a.jsx)(it,{...e,data:o,fetcher:s,integrityFetcher:l}):(0,a.jsx)("div",{className:"p-8 text-center text-slate-500","data-testid":"storage-admin-loading",children:"\u30C7\u30FC\u30BF\u8AAD\u307F\u8FBC\u307F\u4E2D..."})}function Fe(e){return e.data?(0,a.jsx)(it,{...e,data:e.data,fetcher:e.fetcher??et,integrityFetcher:e.integrityFetcher??et}):(0,a.jsx)(sn,{...e})}var He=require("@aiquants/authz-core"),yt=require("@aiquants/console-ui/core"),P=require("@aiquants/enrichment-core"),B=require("@aiquants/governance-core"),N=require("zod");var Ue=3e3;function H(e){return Math.round(performance.now()-e)}function O(e){return typeof e=="string"&&pe(e)?e:null}function M(e){let t=globalThis.process;return t===void 0?void 0:t.env[e]}function ge(e,t){let n=e?.trim();if(!n)throw new Error(`${t} is not configured; this probe will not guess an endpoint to send credentials to.`);return n}function at(e,t,n){let r=e??(t?.trim()?Number(t):Number.NaN);if(!Number.isInteger(r)||r<=0||r>65535)throw new Error(`${n} is not configured with a valid port; this probe will not guess one.`);return r}function ot(e,t){if(e!==void 0)return e;let n=t?.trim().toLowerCase();if(!(n===void 0||n===""))return n==="1"||n==="true"||n==="yes"||n==="on"}function lt(e){let t=e.trim().split("://",1)[0]?.toLowerCase();if(t&&e.includes("://"))return t.endsWith("s")||t.includes("+s")}function an(e){let n=e.split("://").slice(-1)[0].split("/",1)[0],r=n.split(":").pop();if(!r||r===n)return;let o=Number(r);return Number.isInteger(o)&&o>0&&o<=65535?o:void 0}async function je(e,t){let n;try{return await Promise.race([e,new Promise((r,o)=>{n=setTimeout(()=>o(new Error(`Probe timed out after ${t}ms`)),t)})])}finally{clearTimeout(n)}}async function ut(e){let t=e?.qdrantApiKey??M("QDRANT_API_KEY")??"",n=e?.timeoutMs??Ue,r=performance.now(),o="";try{o=ge(e?.qdrantUrl??M("QDRANT_URL"),"QDRANT_URL");let s={};t&&(s["api-key"]=t);let[l,u]=await Promise.all([fetch(`${o}/`,{headers:s,signal:AbortSignal.timeout(n)}),fetch(`${o}/collections`,{headers:s,signal:AbortSignal.timeout(n)})]);if(!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);if(!u.ok)throw new Error(`HTTP ${u.status}: ${u.statusText} (/collections)`);let d=await l.json(),c=H(r),y=(await u.json()).result?.collections?.length??0;return{serviceName:"Qdrant",category:"vector",status:"connected",version:O(d.version),endpoint:o,latencyMs:c,details:{engine:O(d.title),collectionsCount:y,restPort:an(o)??null,tls:lt(o)??null}}}catch(s){let l=H(r),u=s instanceof Error?s.message:String(s);return{serviceName:"Qdrant",category:"vector",status:"error",version:null,endpoint:o,latencyMs:l,details:{},errorMessage:u}}}async function dt(e){let t=e?.timeoutMs??Ue,n=performance.now(),r=O(e?.neo4jBoltUri??M("NEO4J_URI")),o=r===null?"":r;try{let s=e?.graphReader;if(!s)throw new Error("Graph reader not configured");let l=e?.tenantId,[u,d]=await Promise.all([je(s("CALL dbms.components() YIELD versions, edition RETURN versions[0] AS version, edition",{}),t),je(l?s("MATCH (n {tenantId: $tenantId}) RETURN count(n) AS node_count",{tenantId:l}):s("RETURN null AS node_count",{}),t)]);if(!u.ok)throw new Error(u.reason);if(!d.ok)throw new Error(d.reason);let[c,m]=u.rows[0]??[],y=d.rows[0]?.[0],I=H(n);return{serviceName:"Neo4j",category:"graph",status:"connected",version:O(c),endpoint:o,latencyMs:I,details:{edition:O(m),boltUri:r,nodeCount:typeof y=="number"?y:null,tls:r===null?null:lt(r)??null}}}catch(s){let l=H(n),u=s instanceof Error?s.message:String(s);return{serviceName:"Neo4j",category:"graph",status:"error",version:null,endpoint:o,latencyMs:l,details:{},errorMessage:u}}}async function ct(e){let t=performance.now(),n="",r=ot(e?.redisTls,M("REDIS_TLS")),o=Number.NaN;try{let s=e?.redisClient;if(!s)throw new Error("Redis client not configured");let l=ge(e?.redisHost??M("REDIS_HOST"),"REDIS_HOST");o=at(e?.redisPort,M("REDIS_PORT"),"REDIS_PORT"),n=`${r===!1?"redis":"rediss"}://${l}:${o}`,await s.ping();let u=await s.info("server"),d=O(u.match(/redis_version:([^\r\n]+)/)?.[1]),c=null;if(typeof s.dbSize=="function")try{c=await s.dbSize()}catch{c=null}let m=H(t);return{serviceName:"Redis",category:"cache",status:"connected",version:d,endpoint:n,latencyMs:m,details:{totalKeys:c,port:o,tls:r??null,database:0}}}catch(s){let l=H(t),u=s instanceof Error?s.message:String(s);return{serviceName:"Redis",category:"cache",status:"error",version:null,endpoint:n,latencyMs:l,details:{},errorMessage:u}}}function on(e){let t=e.match(/Microsoft SQL Server \d+ \([^)]+\)/);return O(t===null?e.substring(0,30):t[0].replace("Microsoft SQL Server ",""))}async function pt(e){let t=performance.now(),n="",r=ot(e?.sqlServerTls,M("SQL_SERVER_TLS")),o=Number.NaN;try{let s=e?.sqlServerExecute;if(!s)throw new Error("SQL Server executor not configured");let l=ge(e?.sqlServerHost??M("SQL_SERVER_HOST"),"SQL_SERVER_HOST");o=at(e?.sqlServerPort,M("SQL_SERVER_PORT"),"SQL_SERVER_PORT"),n=`${l}:${o}`;let u=await s(),d=O(u.db_name),c=O(u.version),m=c===null?null:O(c.split(`
2
- `)[0]),y=m===null?null:on(m),I=H(t);return{serviceName:"SQL Server",category:"database",status:"connected",version:y,endpoint:n,latencyMs:I,details:{database:d,port:o,tls:r??null,fullVersion:m}}}catch(s){let l=H(t),u=s instanceof Error?s.message:String(s);return{serviceName:"SQL Server",category:"database",status:"error",version:null,endpoint:n,latencyMs:l,details:{},errorMessage:u}}}async function mt(e){let t=e?.timeoutMs??Ue,n=performance.now(),r="";try{r=ge(e?.backendApiHost??M("BACKEND_API_HOST"),"BACKEND_API_HOST");let o=await fetch(`${r}/openapi.json`,{signal:AbortSignal.timeout(t)});if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);let s=await o.json(),l=Object.keys(s.paths??{}).length,u=H(n);return{serviceName:"AI Quant API",category:"api",status:"connected",version:O(s.info?.version),endpoint:r,latencyMs:u,details:{title:O(s.info?.title),endpointsCount:l}}}catch(o){let s=H(n),l=o instanceof Error?o.message:String(o);return{serviceName:"AI Quant API",category:"api",status:"error",version:null,endpoint:r,latencyMs:s,details:{},errorMessage:l}}}async function De(e){let[t,n,r,o,s]=await Promise.all([ut(e),dt(e),ct(e),pt(e),mt(e)]),l=t.status==="connected"&&n.status==="connected"&&r.status==="connected"&&o.status==="connected"&&s.status==="connected";return{services:{qdrant:t,neo4j:n,redis:r,sqlServer:o,quantsApi:s},allHealthy:l,checkedAt:new Date().toISOString()}}var ln=N.z.object({templateText:N.z.string(),modelName:N.z.string(),temperature:N.z.number(),maxOutputTokens:N.z.number(),responseSchema:N.z.union([N.z.record(N.z.string(),N.z.unknown()),N.z.string(),N.z.null()]).optional(),endpointBaseUrl:N.z.string().nullable()}).strict(),un=N.z.discriminatedUnion("mode",[N.z.object({mode:P.IntegrityRunModeSchema.extract(["SCAN"]),basisRunUid:N.z.null()}).strict(),N.z.object({mode:P.IntegrityRunModeSchema.extract(["REPAIR"]),basisRunUid:N.z.string().uuid()}).strict()]),dn=N.z.object({runUid:N.z.string().uuid()}).strict();function ft(e){return e==="start_integrity_run"?"start":e==="cancel_integrity_run"?"cancel":null}function Y(e,t){return e.issues.map(n=>`${n.path.length===0?t:n.path.join(".")}: ${n.message}`).join("; ")}function cn(e,t){if(e==="bool")return t==="true"||t==="false"?null:"paramValue must be 'true' or 'false' for a bool parameter";if(e==="int")return/^[+-]?\d+$/.test(t)&&Number.isSafeInteger(Number(t))?null:"paramValue must be a safe integer for an int parameter";if(e==="float")return t.trim()!==""&&Number.isFinite(Number(t))?null:"paramValue must be a finite number for a float parameter";if(e==="json")try{return JSON.parse(t),null}catch{return"paramValue must be valid JSON for a json parameter"}return null}function pn(e){let t=P.PipelineRunSummarySchema.array().safeParse(e);if(!t.success)throw new Error(`getRecentPipelineRuns answered something that is not a run summary: ${Y(t.error,"getRecentPipelineRuns")}`);return t.data}function mn(e){let t=P.PipelineStepMetricSchema.array().safeParse(e);if(!t.success)throw new Error(`getPipelineStepMetrics answered something that is not a step metric: ${Y(t.error,"getPipelineStepMetrics")}`);let n=new Set;for(let r of t.data){let o=`${r.documentKind}/${r.stepKey}`;if(n.has(o))throw new Error(`getPipelineStepMetrics answered more than one metric for (documentKind, stepKey) = (${r.documentKind}, ${r.stepKey})`);n.add(o)}return t.data}function gn(e){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`pipelineStepMetricWindow must be a positive safe integer, got ${String(e)}`);return e}async function yn(e,t){let n;try{n=await e.readIntegrityAuditOverview(t)}catch(o){return{ok:!1,status:null,reason:o instanceof Error?o.message:String(o)}}let r=P.IntegrityAuditOverviewSchema.safeParse(n);return r.success?{ok:!0,value:r.data}:{ok:!1,status:null,reason:`readIntegrityAuditOverview answered something that is not an audit overview: ${Y(r.error,"readIntegrityAuditOverview")}`}}function fn(e){return!Array.isArray(e)||e.length===0?"orderedRuleIds must be a non-empty array of rule ids":e.every(t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>0)?new Set(e).size!==e.length?"orderedRuleIds must not name a rule twice":null:"orderedRuleIds must contain positive integers only"}function $e(e){let{store:t,healthProbeOptions:n,resourceKey:r="storage_admin",requireUser:o,requirePermission:s,resolveTenantId:l,authorizeIngest:u,canReadIntegrityFindings:d,canUpdateKnowledge:c}=e;async function m(I){let{request:b}=I;if(!await o(b))throw new Response("\u8A8D\u8A3C\u304C\u5FC5\u8981\u3067\u3059\u3002",{status:401});try{await s(b,{resourceKey:r,action:"read"})}catch(ue){throw ue instanceof He.AuthzDeniedError?new Response("\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002",{status:403}):ue}let f=await l(b),V=gn(t.pipelineStepMetricWindow),[$,x,k]=await Promise.all([t.getFeatureFlags(f),t.getSystemParameters(f),t.getSyncCounts(f)]),L={featureFlags:$,systemParameters:x,syncCounts:k},[G,Q,z,F,A,j,ie,U,Z,ae,fe,be,Se,p,J,Re,oe,he,E,W,le]=await Promise.all([t.getConfidentialityPolicies(f),t.getTranscriptionVocabulary(f),t.getTranscriptionReferences(f),t.getUnresolvedReferenceUris(f),t.getPoliciesMissingDestination(f),t.getPromptTemplates(f),t.getClassificationRules(f),t.getFailedSyncItems(f),t.getGraphSchema(f),yn(t,f),d(b),c(b),t.getUnresolvedEntities(f),t.getQdrantCollections(f),De({...n,tenantId:f}),t.getRecentIngestItems(f),t.getOntologyStatus(f,L),t.getEnrichmentStrategies(f),t.getStrategyVariants(f),t.getPipelineStepMetrics(f),t.getRecentPipelineRuns(f)]),ve=t.getCircuitBreakerStatus();return{tenantId:f,featureFlags:L.featureFlags,confidentialityPolicies:G,transcriptionVocabulary:Q,transcriptionReferences:z,unresolvedReferenceUris:F,policiesMissingDestination:A,systemParameters:L.systemParameters,promptTemplates:j,classificationRules:ie,classificationRuleConsumer:t.classificationRuleConsumer??null,syncCounts:L.syncCounts.counts,totalFiles:L.syncCounts.total,failedSyncItems:U,circuitBreakerStatus:ve,pipelineStepMetrics:mn(W),pipelineStepMetricWindow:V,recentPipelineRuns:pn(le),displayTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,graphSchema:Z,enrichmentStrategies:he,strategyVariants:E,integrityAudit:ae,canReadIntegrityFindings:fe,canUpdateKnowledge:be,unresolvedEntities:Se,qdrantCollections:p,systemHealth:J,recentIngestItems:Re,ontologyStatus:oe}}async function y(I){let{request:b}=I,w=await o(b);if(!w)return Response.json({error:"\u8A8D\u8A3C\u304C\u5FC5\u8981\u3067\u3059\u3002"},{status:401});if(w.email.trim()==="")return Response.json({error:"\u64CD\u4F5C\u8005\u3092\u7279\u5B9A\u3067\u304D\u306A\u3044\u305F\u3081\u8A2D\u5B9A\u3092\u5909\u66F4\u3067\u304D\u307E\u305B\u3093\u3002"},{status:403});if(w.accessToken==="")throw new Error("requireUser resolved an operator whose accessToken is an empty string; answer null when the session holds no token the upstream services accept");let f=w.email,V=w.accessToken===null?void 0:w.accessToken;try{await s(b,{resourceKey:r,action:"update"})}catch(F){if(F instanceof He.AuthzDeniedError)return await hn(b);throw F}let $=await l(b),x=await b.formData(),k=String(x.get("intent")??"");if(k==="refresh_health")return Response.json({success:!0,refreshed:!0});let L=await Sn(t,$,k,x,f);if(L)return L;let G=await Rn(t,$,k,x,f,V);if(G)return G;let Q=await vn(t,$,k,x,V,()=>d(b));if(Q)return Q;if(k==="resolve_entity"){let F=String(x.get("entityId")??""),A=String(x.get("action")??"");if(!F||A!=="merge"&&A!=="promote")return Response.json({error:"Valid entityId and action ('merge' | 'promote') are required"},{status:400});try{return await t.resolveEntity($,F,A),Response.json({success:!0,entityId:F,action:A})}catch(j){return Response.json({error:j instanceof Error?j.message:String(j)},{status:400})}}let z=await An(t,$,k,x,f,b,u,V);return z||Response.json({error:`Unknown intent: ${k}`},{status:400})}return{loader:m,action:y}}function Me(e){let t=String(e??"").trim();return t===""?null:t}function ye(e){let t=String(e??"").trim();if(t==="")return null;let n=Number(t);if(!(!Number.isSafeInteger(n)||n<=0))return n}function bn(e){let t=String(e??"").trim();if(t==="")return null;let n=Number(t);if(!(!Number.isFinite(n)||n<=0))return n}async function Sn(e,t,n,r,o){if(n==="update_enrichment_strategy"){let s=String(r.get("stage")??"");if(!(0,P.isEnrichmentStageKey)(s))return Response.json({error:"stage must be a canonical enrichment stage key"},{status:400});let l=ye(r.get("strategyId")),u=ye(r.get("domainId"));if(l==null||u===void 0||u===null)return Response.json({error:"strategyId and domainId must be positive integers naming existing rows"},{status:400});let d=String(r.get("enabled")??"")==="true";try{await e.updateEnrichmentStrategy(t,{strategyId:l,domainId:u,stage:s,enabled:d},o)}catch(c){return Response.json({error:c instanceof Error?c.message:"\u53D6\u308A\u8FBC\u307F\u6226\u7565\u3092\u66F4\u65B0\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},{status:400})}return Response.json({success:!0,strategyId:l,domainId:u,stage:s,enabled:d})}if(n==="toggle_flag"){let s=String(r.get("flagKey")??""),l=String(r.get("enabled")??"")==="true";if(!s)return Response.json({error:"flagKey is required"},{status:400});let u=await e.getFeatureFlags(t);return Object.hasOwn(u,s)?(await e.toggleFeatureFlag(t,s,l,o),Response.json({success:!0,flagKey:s,enabled:l})):Response.json({error:`flagKey names no feature flag of this tenant: ${s}`},{status:400})}if(n==="update_confidentiality_policy"){let s=String(r.get("confidentialityLevel")??""),l=String(r.get("capability")??"");if(!(B.ConfidentialityLevelSchema.safeParse(s).success&&B.GovernedCapabilitySchema.safeParse(l).success))return Response.json({error:"confidentialityLevel and capability must be canonical values"},{status:400});let u=String(r.get("allowCloudProvider")??"")==="true";if(u&&!B.CLOUD_CAPABLE_CAPABILITIES.includes(l))return Response.json({error:`${l} sends nothing outside the deployment, so it has no cloud permission to grant`},{status:400});let d=String(r.get("promptKey")??"");return await e.updateConfidentialityPolicy(t,{confidentialityLevel:s,capability:l,isEnabled:String(r.get("isEnabled")??"")==="true",allowCloudProvider:u,promptKey:d===""?null:d},o),Response.json({success:!0,confidentialityLevel:s,capability:l})}if(n==="save_transcription_term"){let s=String(r.get("term")??"").trim();if(!s)return Response.json({error:"term is required"},{status:400});let l=bn(r.get("boost"));if(l===void 0)return Response.json({error:"boost must be a number greater than zero, or absent to let the service decide"},{status:400});let u=ye(r.get("id"));if(u===void 0)return Response.json({error:"id must be a positive integer naming an existing row, or absent for a new one"},{status:400});try{await e.saveTranscriptionTerm(t,{id:u,term:s,reading:Me(r.get("reading")),boost:l,domainKey:Me(r.get("domainKey")),isActive:String(r.get("isActive")??"true")==="true"},o)}catch(d){return Response.json({error:d instanceof Error?d.message:"\u8A9E\u5F59\u3092\u4FDD\u5B58\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},{status:400})}return Response.json({success:!0,term:s})}if(n==="save_transcription_reference"){let s=String(r.get("fileUri")??"").trim();if(!s)return Response.json({error:"fileUri is required"},{status:400});let l=ye(r.get("id"));if(l===void 0)return Response.json({error:"id must be a positive integer naming an existing row, or absent for a new one"},{status:400});try{await e.saveTranscriptionReference(t,{id:l,fileUri:s,domainKey:Me(r.get("domainKey")),isActive:String(r.get("isActive")??"true")==="true"},o)}catch(u){return Response.json({error:u instanceof Error?u.message:"\u53C2\u7167\u8CC7\u6599\u3092\u4FDD\u5B58\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},{status:400})}return Response.json({success:!0,fileUri:s})}if(n==="update_parameter"){let s=String(r.get("paramKey")??""),l=String(r.get("paramValue")??"");if(!s)return Response.json({error:"paramKey is required"},{status:400});let u=(await e.getSystemParameters(t)).find(c=>c.key===s);if(u===void 0)return Response.json({error:`paramKey names no parameter of this tenant: ${s}`},{status:400});let d=cn(u.data_type,l);if(d!==null)return Response.json({error:d},{status:400});try{(0,P.assertSystemParameterInRange)(s,Number(l))}catch(c){return Response.json({error:c.message},{status:400})}return await e.updateSystemParameter(t,s,l,o),Response.json({success:!0,paramKey:s,paramValue:l})}if(n==="update_prompt"){let s=String(r.get("templateKey")??""),l=String(r.get("payload")??"{}"),u;try{u=JSON.parse(l)}catch{return Response.json({error:"Invalid JSON payload"},{status:400})}if(!s)return Response.json({error:"templateKey is required"},{status:400});let d=ln.safeParse(u);if(!d.success)return Response.json({error:`payload does not carry a prompt template update: ${Y(d.error,"payload")}`},{status:400});let c=d.data;try{return await e.updatePromptTemplate(t,s,c,o),Response.json({success:!0,templateKey:s})}catch(m){return Response.json({error:m instanceof Error?m.message:String(m)},{status:400})}}if(n==="reorder_rules"){let s=String(r.get("orderedRuleIds")??"[]"),l;try{l=JSON.parse(s)}catch{return Response.json({error:"Invalid orderedRuleIds JSON"},{status:400})}let u=fn(l);if(u!==null)return Response.json({error:u},{status:400});let d=l;return await e.reorderClassificationRules(t,d,o),Response.json({success:!0,orderedRuleIds:d})}return null}async function Rn(e,t,n,r,o,s){if(n==="retry_job"){let l=String(r.get("fileId")??"");if(!l)return Response.json({error:"fileId is required"},{status:400});try{return await e.retrySyncItem(t,l,o,s),Response.json({success:!0,fileId:l})}catch(u){return Response.json({error:u instanceof Error?u.message:String(u)},{status:400})}}if(n==="retry_all_failed")try{let{requeued:l,skipped:u}=await e.retryAllFailedSyncItems(t,o,s);return Response.json({success:!0,requeued:l,skipped:u})}catch(l){return Response.json({error:l instanceof Error?l.message:String(l)},{status:400})}return null}function se(e,t,n){let r=P.IntegrityCommandFailureSchema.parse({command:e,code:t,status:n}),o=P.INTEGRITY_COMMAND_CODES.find(s=>s.code===r.code);return Response.json({failure:r},{status:o===void 0?502:o.status})}async function hn(e){let t=await e.formData().catch(()=>null),n=t===null?null:ft(t.get("intent"));return n===null?Response.json({error:"\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002"},{status:403}):se(n,"FORBIDDEN",null)}async function gt(e,t){let n;try{n=P.IntegrityCommandReplySchema.parse(await t())}catch{return se(e,"UPSTREAM_FAILED",null)}return n.ok?Response.json({success:!0,runUid:n.runUid}):se(e,(0,P.integrityCommandFailureCodeOf)(e,n.status,n.errorCode),n.status)}async function vn(e,t,n,r,o,s){let l=ft(n);if(l==="start"){let u=un.safeParse({mode:r.get("mode"),basisRunUid:r.get("basisRunUid")});if(!u.success)return Response.json({error:`start_integrity_run takes mode SCAN without basisRunUid, or mode REPAIR with basisRunUid (a UUID): ${Y(u.error,"form")}`},{status:400});let{mode:d,basisRunUid:c}=u.data;return o===void 0||d==="REPAIR"&&!await s()?se(l,"FORBIDDEN",null):await gt(l,()=>e.startIntegrityRun(t,d,c,o))}if(l==="cancel"){let u=dn.safeParse({runUid:r.get("runUid")});return u.success?o===void 0?se(l,"FORBIDDEN",null):await gt(l,()=>e.cancelIntegrityRun(t,u.data.runUid,o)):Response.json({error:`cancel_integrity_run takes runUid (a UUID): ${Y(u.error,"form")}`},{status:400})}return null}function In(e){if(typeof e!="object"||e===null)return"payload must be an object";let t=e;if(typeof t.fileUri!="string"||t.fileUri.trim()==="")return"payload.fileUri is required";if(!B.ConfidentialityLevelSchema.safeParse(t.confidentialityLevel).success)return`payload.confidentialityLevel must be one of ${B.ConfidentialityLevelSchema.options.join(", ")}`;let r=t.departmentId;return r!=null&&(typeof r!="number"||!Number.isInteger(r))?"payload.departmentId must be an integer or null":null}function wn(e){try{return(0,yt.formatCount)(e,ce),null}catch{return`inspectFileUri answered a fileSize that is not a byte count (a non-negative safe integer): ${String(e)}`}}async function An(e,t,n,r,o,s,l,u){if(n==="ingest_document"){let d=String(r.get("payload")??"");if(!d)return Response.json({error:"payload is required"},{status:400});let c;try{c=JSON.parse(d)}catch{return Response.json({error:"Invalid JSON payload"},{status:400})}let m=In(c);if(m)return Response.json({error:m},{status:400});let y=c,I=await l(s,y);if(I!==null)return Response.json({error:I},{status:403});try{let b=u===void 0?await e.ingestDocument(t,y,o):await e.ingestDocument(t,y,o,u);return Response.json({success:!0,result:b})}catch(b){return Response.json({error:b instanceof Error?b.message:String(b)},{status:400})}}if(n==="inspect_uri"){let d=String(r.get("fileUri")??"").trim();if(!d)return Response.json({error:"fileUri is required"},{status:400});if(!e.inspectFileUri)return Response.json({error:"inspectFileUri is not implemented"},{status:501});let c;try{c=u===void 0?await e.inspectFileUri(t,d):await e.inspectFileUri(t,d,u)}catch(y){return Response.json({error:y instanceof Error?y.message:String(y)},{status:400})}let m=wn(c.fileSize);return m!==null?Response.json({error:m},{status:400}):Response.json({success:!0,inspection:c})}return null}function Pn(e){let t=$e(e);return{loader:t.loader,action:t.action,View:Fe,server:t}}0&&(module.exports={StorageAdminConsoleView,checkAllSystemHealth,checkBackendApiHealth,checkNeo4jHealth,checkQdrantHealth,checkRedisHealth,checkSqlServerHealth,createStorageAdminApp,createStorageAdminServer});
1
+ "use strict";var Ne=Object.defineProperty;var Dt=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var Mt=Object.prototype.hasOwnProperty;var Ht=(e,t)=>{for(var n in t)Ne(e,n,{get:t[n],enumerable:!0})},$t=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ut(t))!Mt.call(e,o)&&o!==n&&Ne(e,o,{get:()=>t[o],enumerable:!(r=Dt(t,o))||r.enumerable});return e};var Kt=e=>$t(Ne({},"__esModule",{value:!0}),e);var Un={};Ht(Un,{StorageAdminConsoleView:()=>Me,checkAllSystemHealth:()=>Ke,checkBackendApiHealth:()=>yt,checkNeo4jHealth:()=>pt,checkQdrantHealth:()=>dt,checkRedisHealth:()=>mt,checkSqlServerHealth:()=>gt,createStorageAdminApp:()=>Dn,createStorageAdminServer:()=>Be});module.exports=Kt(Un);var E=require("@aiquants/console-ui"),k=require("@aiquants/enrichment-core"),S=require("@aiquants/enrichment-react"),v=require("@aiquants/governance-react"),g=require("react"),H=require("react-router");var pe="ja-JP";var qt=/[^\s\x1c-\x1f\x85\ufeff]/;function me(e){return qt.test(e)}function re(e,t){return new Promise(n=>n(e())).catch(n=>t(n instanceof Error?n.message:String(n)))}var ge=require("@aiquants/console-ui/core"),Xe=require("@aiquants/enrichment-core"),N=require("react");var Vt=2e3,Bt=1e4;function Ee(e,t){return t.ok&&e.kind==="ready"&&(0,Xe.isStrictlyEarlier)(t.value.readAt,e.value.readAt)?e:(0,ge.keepLastGood)(e,t)}var Gt=401;function Qt(e){return e.kind==="failed"||e.refreshFailure!==null&&e.refreshFailure.status===Gt?null:e.value.active}function et(e,t){let[n,r]=(0,N.useState)(()=>({loaded:e,overview:Ee({kind:"loading"},e)}));n.loaded!==e&&r({loaded:e,overview:Ee(n.overview,e)});let o=(0,N.useRef)(t);o.current=t;let s=(0,N.useRef)(null);(0,N.useEffect)(()=>()=>s.current?.abort(),[]);let l=(0,N.useCallback)((d,p)=>re(p,y=>({ok:!1,status:null,reason:y})).then(y=>{d.aborted||r(A=>({loaded:A.loaded,overview:Ee(A.overview,y)}))}),[]),u=(0,N.useCallback)(()=>{let d=new AbortController;s.current=d,r(p=>({loaded:p.loaded,overview:(0,ge.beginReload)(p.overview,"reload")})),l(d.signal,()=>o.current(d.signal))},[l]),c=(0,N.useCallback)(d=>l(d,()=>o.current(d)),[l]);return{overview:n.overview,reload:u,poll:c}}function zt(e){return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)}function Jt(){return document.visibilityState==="visible"}function Wt(){return!0}function tt(e,t,n){let r=(0,N.useSyncExternalStore)(zt,Jt,Wt),o=t&&r,s=(0,N.useRef)(o),l=e.kind==="ready",u=Qt(e),c=u===null?null:u.run.runUid,d=u===null?!1:u.isStale;(0,N.useEffect)(()=>{let p=o&&!s.current;if(s.current=o,!o||c===null&&!(p&&l))return;let y=new AbortController,A=d?Bt:Vt,b,w=async()=>{await n(y.signal),!y.signal.aborted&&c!==null&&(b=setTimeout(w,A))};return b=setTimeout(w,p?0:A),()=>{y.abort(),clearTimeout(b)}},[o,l,c,d,n])}var Te={columns:2,className:"grid-cols-2",spanClassNames:{1:"col-span-1",2:"col-span-2"}},_e={columns:4,className:"@min-[41.5rem]:grid-cols-4",spanClassNames:{1:"@min-[41.5rem]:col-span-1",2:"@min-[41.5rem]:col-span-2",3:"@min-[41.5rem]:col-span-3",4:"@min-[41.5rem]:col-span-4"}},Oe={className:"@min-[82rem]:grid-flow-col @min-[82rem]:auto-cols-fr @min-[82rem]:grid-cols-none",lastTabClassName:"@min-[82rem]:col-auto"};function xe(e,t){let n=t%e.columns,r=n===0?1:e.columns-n+1;return e.spanClassNames[r]}var a=require("react/jsx-runtime"),nt="tab",je={key:"knowledge-authority",phrases:["\u6A29\u5A01\u53F0\u5E33 & \u898F\u7A0B\u885D\u7A81"]},De={key:"pipeline",phrases:["\u30D1\u30A4\u30D7\u30E9\u30A4\u30F3 & \u63A5\u7D9A\u72B6\u614B"]},Ue={key:"parameters",phrases:["\u30E2\u30C7\u30EB & \u30D1\u30E9\u30E1\u30FC\u30BF\u8A2D\u5B9A"]},rt="\u30A8\u30F3\u30EA\u30C3\u30C1\u30E1\u30F3\u30C8\u540C\u671F\u30B9\u30C6\u30FC\u30BF\u30B9";function Yt(e,t){let n=e.settled+1,r=t?.error;if(r!==void 0)return{...e,settled:n,status:"refused",nextAfter:null,error:r};let o=k.IntegrityCellResyncResultSchema.safeParse(t?.cellResync);if(!o.success)return{...e,settled:n,status:"refused",nextAfter:null,error:"\u307E\u3068\u3081\u3066\u306E\u518D\u540C\u671F\u306E\u7B54\u3048\u306E\u5F62\u304C\u60F3\u5B9A\u3068\u7570\u306A\u308A\u307E\u3059\u3002\u958B\u767A\u62C5\u5F53\u306B\u9023\u7D61\u3057\u3066\u304F\u3060\u3055\u3044\u3002"};let{requeued:s,skipped:l,nextAfter:u}=o.data;return{settled:n,status:u===null?"done":"pending",requeued:e.requeued+s,skipped:[...e.skipped,...l],nextAfter:u,error:null}}var V=[{key:"search",phrases:["\u30E1\u30BF\u30C7\u30FC\u30BF\u691C\u7D22","\u30EF\u30FC\u30AF\u30D9\u30F3\u30C1"]},{key:"ingest",phrases:["\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8","\u53D6\u308A\u8FBC\u307F & \u30E1\u30BF\u751F\u6210"]},De,{key:"knowledge-graph",phrases:["\u30CA\u30EC\u30C3\u30B8\u30B0\u30E9\u30D5","\u63A2\u7D22"]},Ue,{key:"prompts",phrases:["\u30D7\u30ED\u30F3\u30D7\u30C8 & \u30C9\u30E9\u30A4\u30E9\u30F3"]},je,{key:"data-retention",phrases:["\u30C7\u30FC\u30BF\u4FDD\u6301 & \u6574\u5408\u6027\u76E3\u67FB"]}];function ke(e){return e.phrases.join("")}function Zt(e){return e!==null&&V.some(t=>t.key===e)}var Xt="Tri-Store \u30C7\u30FC\u30BF\u6574\u5408\u6027\u76E3\u67FB";function en(e){return`\u76E3\u67FB\u306E\u6982\u6CC1\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F${(0,E.reasonAside)(e)}\u3002`}var tn=(0,E.resolveConsoleUiLabels)("ja");function nn(e){return tn.failureSentence(e,"\u51E6\u7406\u5C65\u6B74\u3092\u95B2\u89A7\u3059\u308B\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002",t=>`\u51E6\u7406\u5C65\u6B74\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F${(0,E.reasonAside)(t)}\u3002`)}var Le={state:"idle",formData:null,data:null,submit:()=>Promise.resolve()};function at({data:e,fetcher:t,integrityFetcher:n,inspectorFetcher:r,renderHeader:o,graphTraversal:s,onBrowseGraphNodes:l,onSimulateGovernance:u,onRefreshIngestQueue:c,onSearch:d,onLoadDocumentRuns:p,onCompareVariants:y,loadIntegrityOverview:A,loadIntegrityFindings:b,policyConflicts:w,documentAuthority:R}){let[q,j]=(0,g.useState)(null),[T,_]=(0,g.useState)(null),[D,Q]=(0,g.useState)(!1),z=(0,g.useMemo)(()=>{if(l!==void 0)return(i,f)=>{Q(!0),re(()=>l(i,f),h=>({ok:!1,reason:h})).then(h=>{Q(!1),_(h.ok?null:h.reason),h.ok&&j(h.page)})}},[l]),[J,W]=(0,H.useSearchParams)(),F=J.get(nt),P=Zt(F)?F:V[0].key,U=i=>{W(f=>{let h=new URLSearchParams(f);return h.set(nt,i),h},{replace:!1,preventScrollReset:!0})},ie=sn(e.recentIngestItems,c,P==="ingest"),M=et(e.integrityAudit,A);tt(M.overview,P==="data-retention",M.poll);let X=(0,g.useRef)(null),oe=(0,E.useFocusRescue)(()=>X.current),[Re,be]=(0,g.useState)(0),Se=(0,g.useCallback)(()=>be(i=>i+1),[]),m=ie===null?e:{...e,recentIngestItems:[...ie]},Y=(0,g.useRef)({}),he=(0,g.useCallback)(()=>Y.current[P]??null,[P]),ae=(0,g.useMemo)(()=>on(e.enrichmentStrategies),[e.enrichmentStrategies]),ve=(0,g.useMemo)(()=>e.strategyVariants.map(an),[e.strategyVariants]),O=cn(p),Z=O.open,le=Z===void 0?void 0:i=>Z(i,null),ue=Z===void 0?void 0:i=>Z(i.metadataId,i.id),St=(i,f)=>{let h=V.length-1,x;if(i.key==="ArrowRight"||i.key==="ArrowDown")x=f===h?0:f+1;else if(i.key==="ArrowLeft"||i.key==="ArrowUp")x=f===0?h:f-1;else if(i.key==="Home")x=0;else if(i.key==="End")x=h;else return;i.preventDefault();let de=V[x].key;U(de),Y.current[de]?.focus()},Ge={...m.featureFlags};if(t.formData&&t.formData.get("intent")==="toggle_flag"){let i=String(t.formData.get("flagKey")??""),f=String(t.formData.get("enabled")??"")==="true";i&&(Ge[i]=f)}let ht=t.data&&"inspection"in t.data?t.data.inspection:void 0,ee=t.state==="idle"?null:t.formData?.get("intent"),vt=ee==="inspect_uri",It=ee==="ingest_document",wt=ee==="retry_job"||ee==="retry_all_failed",At=ee==="resolve_entity",Qe=n.state==="idle"?null:n.formData?.get("intent"),Pt=Qe==="start_integrity_run"?{kind:"starting",mode:k.IntegrityRunModeSchema.parse(n.formData?.get("mode"))}:Qe==="cancel_integrity_run"?{kind:"cancelling"}:{kind:"idle"},Ct=(0,H.useRevalidator)(),[Nt,Ie]=(0,g.useState)(null),ze=P!=="data-retention";(0,g.useEffect)(()=>{ze&&Ie(null)},[ze]);let Et=i=>{let f=i?.failure;if(f===void 0){Ie(null);return}Ie(h=>({failure:f,occurrence:h===null?1:h.occurrence+1})),(0,v.integrityFailureNeedsOverviewReread)(f)&&Ct.revalidate()},[te,we]=(0,g.useState)(null),[ce,Ae]=(0,g.useState)(null),Tt=i=>{we({metadataId:i,intent:"retry_job",status:"pending",error:null}),r.submit({intent:"retry_job",fileId:String(i)},{method:"post"})},_t=i=>{i.after===void 0&&Ae({settled:0,status:"pending",requeued:0,skipped:[],nextAfter:null,error:null});let{after:f,...h}=i;r.submit(f===void 0?{intent:"resync_findings",...h}:{intent:"resync_findings",...h,after:String(f)},{method:"post"})},Ot=()=>{we(null),Ae(null)},[Je,Pe]=(0,g.useState)("console"),[xt,kt]=(0,g.useState)(void 0),Lt=(i,f)=>{if(f==="retry_job"&&te!==null&&te.status==="pending"){let h=i?.error;we(h===void 0?{...te,status:"accepted",error:null}:{...te,status:"refused",error:h});return}if(f==="resync_findings"&&ce!==null&&ce.status==="pending"){Ae(Yt(ce,i));return}kt(i?.error),Pe("inspector")},{settledIntent:Ft,submitAndAwait:We}=Fe(t,()=>Pe("console"));Fe(n,i=>{Pe("integrity"),Et(i)}),Fe(r,Lt);let Ye=Je==="inspector"?xt:(Je==="console"?t:n).data?.error,Ce=i=>{U(i),Y.current[i]?.focus()},Ze=(0,g.useRef)(null),jt={strategies:{label:ke(De),onOpen:()=>Ce(De.key),closesInspector:!0},projectionPolicy:{label:ke(Ue),onOpen:()=>Ce(Ue.key),closesInspector:!0},failedSync:{label:rt,onOpen:()=>Ze.current?.focus(),closesInspector:!1}},ne=Ft==="retry_all_failed"&&t.data?.skipped!==void 0&&t.data.requeued!==void 0?{requeued:t.data.requeued,skipped:t.data.skipped}:null;return(0,a.jsx)(E.ConsoleUiRoot,{locale:"ja",formatLocale:pe,timeZone:m.displayTimeZone,testId:"storage-admin-console-ui",children:(0,a.jsxs)("div",{className:"container mx-auto space-y-6 p-6 font-sans text-slate-900","data-testid":"storage-admin-console",children:[Ye&&(0,a.jsx)("div",{className:"rounded-lg border border-red-200 border-solid bg-red-50 p-4 font-medium text-red-700 text-sm shadow-sm",role:"alert","data-testid":"storage-admin-error-alert",children:Ye}),o?o({title:"\u30B9\u30C8\u30EC\u30FC\u30B8 AI \u30A8\u30F3\u30EA\u30C3\u30C1\u30E1\u30F3\u30C8 & \u30AC\u30D0\u30CA\u30F3\u30B9\u904B\u7528\u7BA1\u7406",tenantId:m.tenantId}):(0,a.jsxs)("header",{className:"flex flex-col justify-between gap-2 border-slate-200 border-b border-solid pb-4 md:flex-row md:items-center",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("h1",{className:"font-bold text-2xl tracking-tight",children:"\u30B9\u30C8\u30EC\u30FC\u30B8 AI \u30A8\u30F3\u30EA\u30C3\u30C1\u30E1\u30F3\u30C8 & \u30AC\u30D0\u30CA\u30F3\u30B9\u904B\u7528\u7BA1\u7406"}),(0,a.jsxs)("p",{className:"mt-1 text-slate-500 text-sm",children:["\u30C6\u30CA\u30F3\u30C8: ",(0,a.jsx)("code",{className:"font-semibold text-slate-800",children:m.tenantId})," | \u5168\u30B7\u30B9\u30C6\u30E0\u72B6\u614B\u30FB\u30D1\u30E9\u30E1\u30FC\u30BF\u5236\u5FA1\u30FB\u6574\u5408\u6027\u76E3\u67FB"]})]}),(0,a.jsx)("div",{className:"flex items-center gap-2",children:(0,a.jsxs)("button",{type:"button","data-testid":"header-health-status-button",onClick:()=>U("pipeline"),className:"inline-flex items-center gap-2 rounded-full border border-slate-200 border-solid bg-slate-50 px-3 py-1.5 font-medium text-slate-700 text-xs transition-colors hover:bg-slate-100",children:[(0,a.jsx)("span",{className:`h-2 w-2 rounded-full ${m.systemHealth.allHealthy?"bg-emerald-500":"bg-amber-500"}`}),(0,a.jsxs)("span",{children:["\u5468\u8FBA\u6A5F\u80FD: ",m.systemHealth.allHealthy?"\u5168\u30B5\u30FC\u30D3\u30B9\u6B63\u5E38":"\u63A5\u7D9A\u8981\u78BA\u8A8D"]})]})})]}),(0,a.jsxs)("div",{className:"w-full space-y-6",children:[(0,a.jsx)("div",{className:"@container w-full","data-testid":"storage-admin-tablist-frame",children:(0,a.jsx)("div",{className:`grid w-full ${Te.className} ${_e.className} ${Oe.className} gap-1 rounded-xl bg-slate-100 p-1`,role:"tablist","aria-label":"\u904B\u7528\u7BA1\u7406\u30B3\u30F3\u30BD\u30FC\u30EB\u306E\u753B\u9762",children:V.map((i,f)=>{let h=P===i.key;return(0,a.jsx)("button",{id:`tab-${i.key}`,type:"button",role:"tab",ref:x=>{Y.current[i.key]=x},"aria-selected":h,"aria-controls":`panel-${i.key}`,tabIndex:h?0:-1,"data-testid":`tab-trigger-${i.key}`,onKeyDown:x=>St(x,f),onClick:()=>U(i.key),className:`wrap-anywhere break-keep rounded-lg px-3 py-2.5 text-center font-medium text-sm transition-all ${f===V.length-1?`${xe(Te,V.length)} ${xe(_e,V.length)} ${Oe.lastTabClassName}`:""} ${h?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:bg-slate-200/50 hover:text-slate-900"}`,children:i.phrases.map((x,de)=>(0,a.jsxs)(g.Fragment,{children:[de>0&&(0,a.jsx)("wbr",{}),x]},x))},i.key)})})}),O.metadataId!==null&&(0,a.jsx)(S.PipelineRunInspector,{metadataId:O.metadataId,runs:O.runs,selectedRunId:O.selectedRunId,onSelectRun:O.selectRun,isLoading:O.isLoading,failure:O.failure,onClose:O.close,openRequest:O.openRequest,returnFocusFallback:he}),P==="search"&&(0,a.jsxs)("div",{role:"tabpanel",id:"panel-search","aria-labelledby":"tab-search",className:"space-y-6","data-testid":"tab-content-search",children:[(0,a.jsx)(S.MetadataSearchWorkbench,{tenantId:m.tenantId,onSearch:d,circuitBreakerStatus:m.circuitBreakerStatus}),y!==void 0&&(0,a.jsx)(S.ModelComparisonWorkbench,{variants:ve,onCompare:y})]}),P==="ingest"&&(0,a.jsx)("div",{role:"tabpanel",id:"panel-ingest","aria-labelledby":"tab-ingest",className:"space-y-6","data-testid":"tab-content-ingest",children:(0,a.jsx)(S.DocumentIngestConsole,{tenantId:m.tenantId,policies:m.confidentialityPolicies,domainOptions:ae,recentItems:m.recentIngestItems,inspectionResult:ht,isInspecting:vt,isSubmitting:It,onInspectUri:i=>{t.submit({intent:"inspect_uri",fileUri:i},{method:"post"})},onIngestDocument:i=>{t.submit({intent:"ingest_document",payload:JSON.stringify(i)},{method:"post"})},onRetryItem:i=>{t.submit({intent:"retry_job",fileId:String(i)},{method:"post"})},onShowHistory:le})}),P==="pipeline"&&(0,a.jsxs)("div",{role:"tabpanel",id:"panel-pipeline","aria-labelledby":"tab-pipeline",className:"space-y-6","data-testid":"tab-content-pipeline",children:[(0,a.jsx)(S.PipelineFlowViewer,{featureFlags:m.featureFlags,metrics:m.pipelineStepMetrics,metricSampleWindow:m.pipelineStepMetricWindow}),(0,a.jsx)(ln,{runs:m.recentPipelineRuns,onOpenRun:ue}),(0,a.jsx)(S.EnrichmentStrategyBoard,{strategies:m.enrichmentStrategies,featureFlags:m.featureFlags,isUpdating:t.state!=="idle",onToggleStage:(i,f,h)=>t.submit({intent:"update_enrichment_strategy",strategyId:String(i.id),domainId:String(i.domainId),stage:f,enabled:String(h)},{method:"post"})}),(0,a.jsx)(S.InfrastructureHealthMonitor,{health:m.systemHealth,isRefreshing:t.state!=="idle",onRefresh:()=>t.submit({intent:"refresh_health"},{method:"post"})})]}),P==="knowledge-graph"&&(0,a.jsxs)("div",{role:"tabpanel",id:"panel-knowledge-graph","aria-labelledby":"tab-knowledge-graph",className:"space-y-6","data-testid":"tab-content-knowledge-graph",children:[(0,a.jsx)(S.OntologyStatusCard,{tenantId:m.tenantId,ontologyStatus:m.ontologyStatus}),(0,a.jsx)(v.KnowledgeGraphExplorer,{topologyMaxLabels:k.GRAPH_INDEX_LIMITS.topologyLabels.default,schema:m.graphSchema,tenantId:m.tenantId,unresolvedEntities:m.unresolvedEntities,traversal:s,onBrowseLabel:z,nodeIndexPage:q,nodeIndexFailure:T,isNodeIndexLoading:D,isResolving:At,onResolveEntity:(i,f)=>{t.submit({intent:"resolve_entity",entityId:i,action:f},{method:"post"})}})]}),P==="parameters"&&(0,a.jsxs)("div",{role:"tabpanel",id:"panel-parameters","aria-labelledby":"tab-parameters",className:"space-y-6","data-testid":"tab-content-parameters",children:[(0,a.jsxs)("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2",children:[(0,a.jsx)(v.FeatureFlagBoard,{flags:Ge,isUpdating:t.state!=="idle",onToggleFlag:(i,f)=>{t.submit({intent:"toggle_flag",flagKey:i,enabled:String(f)},{method:"post"})}}),(0,a.jsx)(v.ClassificationRuleEditor,{rules:m.classificationRules,domainOptions:ae,consultedBy:m.classificationRuleConsumer,onReorderRules:i=>{t.submit({intent:"reorder_rules",orderedRuleIds:JSON.stringify(i)},{method:"post"})}})]}),m.policiesMissingDestination.length>0&&(0,a.jsxs)("div",{"data-testid":"policies-missing-destination",role:"alert",style:{padding:"10px 12px",borderRadius:"6px",backgroundColor:"#fef2f2",color:"#b91c1c",fontSize:"12px"},children:[(0,a.jsx)("strong",{children:"\u6B21\u306E\u533A\u5206\u30FB\u6A5F\u80FD\u306F\u5B9F\u884C\u6642\u306B\u5931\u6557\u3057\u307E\u3059\u3002"})," \u53C2\u7167\u3059\u308B\u30D7\u30ED\u30F3\u30D7\u30C8\u884C\u306B\u5B9B\u5148\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002",(0,a.jsx)("ul",{style:{margin:"6px 0 0",paddingInlineStart:"18px"},children:m.policiesMissingDestination.map(i=>(0,a.jsxs)("li",{"data-testid":`missing-destination-${i.confidentialityLevel}-${i.capability}`,children:[i.confidentialityLevel," / ",i.capability," \u2192 ",i.promptKey," (",i.modelProvider,") \u306E ",(0,a.jsx)("code",{children:"extra_params.base_url"})]},`${i.confidentialityLevel}:${i.capability}`))}),(0,a.jsx)("span",{style:{display:"block",marginTop:"4px",fontSize:"11px"},children:"\u5B9B\u5148\u3092\u8A2D\u5B9A\u3057\u3066\u3082\u3001\u305D\u306E\u30DB\u30B9\u30C8\u304C\u914D\u5099\u5185\u3068\u3057\u3066\u767B\u9332\u3055\u308C\u3066\u3044\u306A\u3051\u308C\u3070\u62D2\u5426\u3055\u308C\u307E\u3059\u3002"})]}),(0,a.jsx)(v.ConfidentialityPolicyBoard,{policies:m.confidentialityPolicies,promptKeys:m.promptTemplates.map(i=>i.template_key),isUpdating:t.state!=="idle",onChangePolicy:i=>{t.submit({intent:"update_confidentiality_policy",confidentialityLevel:i.confidentialityLevel,capability:i.capability,isEnabled:String(i.isEnabled),allowCloudProvider:String(i.allowCloudProvider),promptKey:i.promptKey??""},{method:"post"})}}),(0,a.jsx)(v.TranscriptionAdaptationBoard,{vocabulary:m.transcriptionVocabulary,references:m.transcriptionReferences,unresolvedUris:m.unresolvedReferenceUris,isUpdating:t.state!=="idle",onSaveTerm:i=>We({intent:"save_transcription_term",id:i.id===null?"":String(i.id),term:i.term,reading:i.reading??"",boost:i.boost===null?"":String(i.boost),domainKey:i.domainKey??"",isActive:String(i.isActive)},{method:"post"}),onSaveReference:i=>We({intent:"save_transcription_reference",id:i.id===null?"":String(i.id),fileUri:i.fileUri,domainKey:i.domainKey??"",isActive:String(i.isActive)},{method:"post"})}),(0,a.jsx)(v.SystemParameterTable,{parameters:m.systemParameters,onSaveParameter:(i,f)=>{t.submit({intent:"update_parameter",paramKey:i,paramValue:String(f)},{method:"post"})}})]}),P==="prompts"&&(0,a.jsxs)("div",{role:"tabpanel",id:"panel-prompts","aria-labelledby":"tab-prompts",className:"space-y-6","data-testid":"tab-content-prompts",children:[(0,a.jsx)(v.PromptTemplateConsole,{templates:m.promptTemplates,isSaving:t.state!=="idle",onSaveTemplate:i=>{t.submit({intent:"update_prompt",templateKey:i.template_key,payload:JSON.stringify({templateText:i.template_text,modelName:i.model_name,temperature:i.temperature,maxOutputTokens:i.max_output_tokens,responseSchema:i.response_schema,endpointBaseUrl:i.endpoint_base_url??null})},{method:"post"})}}),(0,a.jsx)(v.GovernanceDryRunConsole,{onSimulate:u})]}),P==="knowledge-authority"&&(0,a.jsxs)("div",{role:"tabpanel",id:"panel-knowledge-authority","aria-labelledby":"tab-knowledge-authority",className:"space-y-6","data-testid":"tab-content-knowledge-authority",children:[(0,a.jsx)(v.DocumentAuthorityRegistry,{host:R,canUpdate:m.canUpdateKnowledge,onPolicyConflictsChanged:Se}),(0,a.jsx)(v.PolicyConflictQueue,{host:w,revision:Re})]}),P==="data-retention"&&(0,a.jsxs)("div",{role:"tabpanel",id:"panel-data-retention","aria-labelledby":"tab-data-retention",className:"space-y-6","data-testid":"tab-content-data-retention",children:[M.overview.kind==="ready"?(0,a.jsx)("div",{ref:oe,children:(0,a.jsx)(v.TriStoreIntegrityAudit,{overview:M.overview.value,canReadFindings:m.canReadIntegrityFindings,command:Pt,commandFailure:Nt,onStartRun:(i,f)=>{n.submit(f===null?{intent:"start_integrity_run",mode:i}:{intent:"start_integrity_run",mode:i,basisRunUid:f},{method:"post"})},onCancelRun:i=>{n.submit({intent:"cancel_integrity_run",runUid:i},{method:"post"})},loadFindings:b,refreshFailure:M.overview.refreshFailure===null?null:M.overview.refreshFailure.reason,headingRef:X,onShowHistory:le,resync:{onResync:Tt,onDismiss:Ot,feedback:te,sending:r.state!=="idle",cellResync:{onResyncCell:_t,feedback:ce}},remedyDestinations:jt})}):(0,a.jsx)(E.Card,{title:Xt,testId:"audit-overview-failed",headingRef:X,children:(0,a.jsx)(E.ResourceFailed,{failure:M.overview,onReload:M.reload,forbiddenMessage:"\u76E3\u67FB\u306E\u6982\u6CC1\u3092\u95B2\u89A7\u3059\u308B\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002",failureMessage:en,rescueRef:oe,testId:"audit-overview-failed-resource"})}),(0,a.jsx)(v.PolicyConflictSummaryCard,{host:w,knowledgeTabLabel:ke(je),onOpenKnowledgeTab:()=>Ce(je.key)}),ne!==null&&ne.skipped.length>0&&(0,a.jsxs)("div",{role:"status","data-testid":"retry-all-skipped",className:"rounded-lg border border-amber-200 border-solid bg-amber-50 p-4 text-amber-800 text-sm",children:[(0,a.jsxs)("strong",{children:["\u4E00\u62EC\u518D\u8A66\u884C: ",ne.requeued," \u4EF6\u3092\u518D\u6295\u5165\u3057\u3001",ne.skipped.length," \u4EF6\u3092\u636E\u3048\u7F6E\u304D\u307E\u3057\u305F\u3002"]})," ","\u636E\u3048\u7F6E\u3044\u305F\u884C\u306F\u5931\u6557\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059\u3002",(0,a.jsx)("ul",{className:"mt-1.5 list-disc ps-5",children:ne.skipped.map(i=>(0,a.jsxs)("li",{"data-testid":`retry-all-skipped-${i.metadataId}`,children:["#",i.metadataId,": ",i.reason]},i.metadataId))})]}),(0,a.jsxs)("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2",children:[(0,a.jsx)("section",{ref:Ze,tabIndex:-1,"aria-label":rt,"data-testid":"sync-status-region",children:(0,a.jsx)(S.SyncStatusMonitor,{counts:m.syncCounts,totalFiles:m.totalFiles,failedItems:m.failedSyncItems,isRetrying:wt,onRetryItem:i=>{t.submit({intent:"retry_job",fileId:String(i)},{method:"post"})},onRetryAll:()=>{t.submit({intent:"retry_all_failed"},{method:"post"})}})}),(0,a.jsx)(S.QdrantStorageCard,{overview:m.qdrantCollections,health:{healthy:m.systemHealth.services.qdrant.status==="connected",latency_ms:m.systemHealth.services.qdrant.latencyMs}})]})]})]})]})})}var rn=new Set(k.EnrichmentSyncStatusSchema.options.filter(e=>e!=="SYNCED"&&!e.startsWith("FAILED"))),st=2e3;function sn(e,t,n){let[r,o]=(0,g.useState)(null),s=(0,g.useRef)(t);s.current=t;let l=(0,g.useRef)(e);l.current!==e&&(l.current=e,r!==null&&o(null));let c=(r??e)?.some(d=>rn.has(d.syncStatus))===!0;return(0,g.useEffect)(()=>{if(!(n&&c&&s.current))return;let d=!1,p,y=async()=>{let A=s.current;if(A!==void 0){try{let b=await A();if(d)return;o(b)}catch{if(d)return}p=setTimeout(y,st)}};return p=setTimeout(y,st),()=>{d=!0,clearTimeout(p)}},[c,n]),r}function Fe(e,t){let n=(0,g.useRef)(t);n.current=t;let r=(0,g.useRef)(null),o=(0,g.useRef)(!1),s=(0,g.useRef)(null);if(e.state!=="idle"){o.current=!0;let u=e.formData?.get("intent");typeof u=="string"&&(r.current=u)}(0,g.useEffect)(()=>{if(e.state!=="idle"||!o.current)return;o.current=!1,n.current(e.data,r.current);let u=s.current;if(u===null)return;s.current=null;let c=e.data?.error;typeof c=="string"?u.reject(new Error(c)):u.resolve()},[e.state,e.data]);let l=(0,g.useCallback)((...u)=>new Promise((c,d)=>{s.current?.reject(new Error("\u3053\u306E\u4FDD\u5B58\u306F\u5F8C\u7D9A\u306E\u9001\u4FE1\u306B\u7F6E\u304D\u63DB\u3048\u3089\u308C\u307E\u3057\u305F\u3002")),s.current={resolve:c,reject:d},e.submit(...u)}),[e]);return{settledIntent:e.state==="idle"?r.current:null,submitAndAwait:l}}function on(e){let t=new Set,n=[];for(let r of e)t.has(r.domainKey)||(t.add(r.domainKey),n.push({key:r.domainKey,label:r.domainLabel}));return n}function an(e){return{strategyId:e.strategyId,label:`${e.domainKey} / ${e.variantKey}`,embeddingModel:e.embeddingModel}}function ln({runs:e,onOpenRun:t}){return(0,a.jsxs)("section",{className:"rounded-xl border border-slate-200 border-solid bg-white p-6 shadow-sm","aria-labelledby":"pipeline-recent-runs-heading","data-testid":"pipeline-recent-runs",children:[(0,a.jsx)("h2",{id:"pipeline-recent-runs-heading",className:"font-bold text-base text-slate-900",children:"\u76F4\u8FD1\u306E\u5B9F\u884C"}),e.length===0?(0,a.jsx)("p",{className:"mt-4 text-[13px] text-slate-500","data-testid":"pipeline-recent-runs-empty",children:"\u8A18\u9332\u3055\u308C\u305F\u5B9F\u884C\u304C\u3042\u308A\u307E\u305B\u3093\u3002"}):(0,a.jsx)("div",{className:"relative mt-4 overflow-x-auto","data-testid":"pipeline-recent-runs-scroll",children:(0,a.jsxs)("table",{className:"w-full text-left text-[13px]",children:[(0,a.jsx)("thead",{children:(0,a.jsxs)("tr",{className:"whitespace-nowrap border-slate-200 border-b border-solid text-[11px] text-slate-500 uppercase",children:[(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u5B9F\u884C"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u6587\u66F8"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u7A2E\u985E"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u304D\u3063\u304B\u3051"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u8A66\u884C"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u72B6\u614B"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u6B62\u307E\u3063\u305F\u6BB5"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u958B\u59CB"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u7D42\u4E86"}),(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u8981\u6C42\u8005"}),t!==void 0&&(0,a.jsx)("th",{scope:"col",className:"px-3 py-2",children:(0,a.jsx)("span",{className:"sr-only","data-testid":"pipeline-recent-runs-action-header",children:"\u64CD\u4F5C"})})]})}),(0,a.jsx)("tbody",{children:e.map(n=>{let r=(0,S.pipelineRunPresentationKey)(n),o=S.PIPELINE_RUN_STATUS_PRESENTATION[r];return(0,a.jsxs)("tr",{className:"border-slate-100 border-b border-solid","data-testid":`pipeline-run-row-${n.id}`,"data-status":n.status,children:[(0,a.jsxs)("td",{className:"whitespace-nowrap px-3 py-2 font-mono","data-testid":`pipeline-run-id-${n.id}`,children:["#",n.id]}),(0,a.jsxs)("td",{className:"whitespace-nowrap px-3 py-2 font-mono","data-testid":`pipeline-run-metadata-${n.id}`,children:["#",n.metadataId]}),(0,a.jsx)("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-kind-${n.id}`,children:k.DOCUMENT_KIND_LABELS[n.documentKind]}),(0,a.jsx)("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-trigger-${n.id}`,"data-trigger":n.trigger,children:S.PIPELINE_TRIGGER_LABELS[n.trigger]}),(0,a.jsx)("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-attempt-${n.id}`,children:n.attempt}),(0,a.jsx)("td",{className:"px-3 py-2",children:(0,a.jsx)("span",{className:`inline-flex whitespace-nowrap rounded-full px-2 py-0.5 font-semibold text-[11px] ${o.className}`,"data-testid":`pipeline-run-status-${n.id}`,"data-status":n.status,"data-presentation":r,children:o.label})}),(0,a.jsx)("td",{className:"px-3 py-2","data-testid":`pipeline-run-failed-step-${n.id}`,children:n.failedStepKey===null?"\u2014":k.PIPELINE_STEPS[n.failedStepKey].label}),(0,a.jsx)("td",{className:"whitespace-nowrap px-3 py-2 text-slate-500","data-testid":`pipeline-run-started-${n.id}`,children:(0,a.jsx)(S.RecordedInstant,{iso:n.startedAt,testId:`pipeline-run-started-value-${n.id}`})}),(0,a.jsx)("td",{className:"whitespace-nowrap px-3 py-2 text-slate-500","data-testid":`pipeline-run-finished-${n.id}`,children:(0,a.jsx)(S.FinishedInstant,{iso:n.finishedAt,testId:`pipeline-run-finished-value-${n.id}`})}),(0,a.jsx)("td",{className:"wrap-anywhere px-3 py-2","data-testid":`pipeline-run-requested-by-${n.id}`,children:n.requestedBy}),t!==void 0&&(0,a.jsx)("td",{className:"whitespace-nowrap px-3 py-2 text-right",children:(0,a.jsx)("button",{type:"button",onClick:()=>t(n),"aria-label":`\u5B9F\u884C #${n.id} (\u6587\u66F8 #${n.metadataId}) \u306E\u8A73\u7D30`,className:"whitespace-nowrap rounded-sm border border-slate-300 border-solid bg-white px-2 py-0.5 font-semibold text-[11px] text-slate-700 hover:bg-slate-50","data-testid":`pipeline-run-open-${n.id}`,children:"\u8A73\u7D30"})})]},n.id)})})]})})]})}var it={metadataId:null,runs:[],selectedRunId:null,isLoading:!1,failure:null};function un(e){for(let t of e)for(let n of t.steps){let r=n.provenance;if(r!==null){for(let[o,s]of Object.entries(r))if(typeof s=="string"&&!me(s))return`\u51E6\u7406\u5C65\u6B74\u306E\u8A18\u9332\u306B\u8AAD\u3081\u306A\u3044\u6765\u6B74\u306E\u5024\u304C\u3042\u308A\u307E\u3059 (\u5B9F\u884C ${t.id} \u306E\u6BB5 ${n.sequence} \u306E ${o})\u3002`}}return null}function cn(e){let[t,n]=(0,g.useState)(it),[r,o]=(0,g.useState)(0),s=(0,g.useRef)(0),l=(0,g.useRef)(null),u=(0,g.useMemo)(()=>{if(e!==void 0)return(p,y)=>{s.current+=1;let A=s.current;l.current?.abort();let b=new AbortController;l.current=b,o(w=>w+1),n({metadataId:p,runs:[],selectedRunId:y,isLoading:!0,failure:null}),re(()=>e(p,b.signal),w=>({ok:!1,status:null,reason:w})).then(w=>{if(s.current!==A)return;let R=w.ok?un(w.value):nn(w);if(!w.ok||R!==null){n({metadataId:p,runs:[],selectedRunId:y,isLoading:!1,failure:R});return}n({metadataId:p,runs:w.value,selectedRunId:y===null?dn(w.value):y,isLoading:!1,failure:null})})}},[e]),c=(0,g.useCallback)(p=>{n(y=>({...y,selectedRunId:p}))},[]),d=(0,g.useCallback)(()=>{s.current+=1,l.current?.abort(),l.current=null,n(it)},[]);return{...t,openRequest:r,open:u,selectRun:c,close:d}}function dn(e){return e.length===0?null:e[0].id}function pn(e){let t=(0,H.useLoaderData)(),n=(0,H.useFetcher)(),r=(0,H.useFetcher)(),o=(0,H.useFetcher)(),s=e.data??t,l=e.fetcher??n,u=e.integrityFetcher??r,c=e.inspectorFetcher??o;return s?(0,a.jsx)(at,{...e,data:s,fetcher:l,integrityFetcher:u,inspectorFetcher:c}):(0,a.jsx)("div",{className:"p-8 text-center text-slate-500","data-testid":"storage-admin-loading",children:"\u30C7\u30FC\u30BF\u8AAD\u307F\u8FBC\u307F\u4E2D..."})}function Me(e){return e.data?(0,a.jsx)(at,{...e,data:e.data,fetcher:e.fetcher??Le,integrityFetcher:e.integrityFetcher??Le,inspectorFetcher:e.inspectorFetcher??Le}):(0,a.jsx)(pn,{...e})}var Ve=require("@aiquants/authz-core"),Rt=require("@aiquants/console-ui/core"),I=require("@aiquants/enrichment-core"),B=require("@aiquants/governance-core"),C=require("zod");var $e=3e3;function K(e){return Math.round(performance.now()-e)}function L(e){return typeof e=="string"&&me(e)?e:null}function $(e){let t=globalThis.process;return t===void 0?void 0:t.env[e]}function ye(e,t){let n=e?.trim();if(!n)throw new Error(`${t} is not configured; this probe will not guess an endpoint to send credentials to.`);return n}function lt(e,t,n){let r=e??(t?.trim()?Number(t):Number.NaN);if(!Number.isInteger(r)||r<=0||r>65535)throw new Error(`${n} is not configured with a valid port; this probe will not guess one.`);return r}function ut(e,t){if(e!==void 0)return e;let n=t?.trim().toLowerCase();if(!(n===void 0||n===""))return n==="1"||n==="true"||n==="yes"||n==="on"}function ct(e){let t=e.trim().split("://",1)[0]?.toLowerCase();if(t&&e.includes("://"))return t.endsWith("s")||t.includes("+s")}function mn(e){let n=e.split("://").slice(-1)[0].split("/",1)[0],r=n.split(":").pop();if(!r||r===n)return;let o=Number(r);return Number.isInteger(o)&&o>0&&o<=65535?o:void 0}async function He(e,t){let n;try{return await Promise.race([e,new Promise((r,o)=>{n=setTimeout(()=>o(new Error(`Probe timed out after ${t}ms`)),t)})])}finally{clearTimeout(n)}}async function dt(e){let t=e?.qdrantApiKey??$("QDRANT_API_KEY")??"",n=e?.timeoutMs??$e,r=performance.now(),o="";try{o=ye(e?.qdrantUrl??$("QDRANT_URL"),"QDRANT_URL");let s={};t&&(s["api-key"]=t);let[l,u]=await Promise.all([fetch(`${o}/`,{headers:s,signal:AbortSignal.timeout(n)}),fetch(`${o}/collections`,{headers:s,signal:AbortSignal.timeout(n)})]);if(!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);if(!u.ok)throw new Error(`HTTP ${u.status}: ${u.statusText} (/collections)`);let c=await l.json(),d=K(r),y=(await u.json()).result?.collections?.length??0;return{serviceName:"Qdrant",category:"vector",status:"connected",version:L(c.version),endpoint:o,latencyMs:d,details:{engine:L(c.title),collectionsCount:y,restPort:mn(o)??null,tls:ct(o)??null}}}catch(s){let l=K(r),u=s instanceof Error?s.message:String(s);return{serviceName:"Qdrant",category:"vector",status:"error",version:null,endpoint:o,latencyMs:l,details:{},errorMessage:u}}}async function pt(e){let t=e?.timeoutMs??$e,n=performance.now(),r=L(e?.neo4jBoltUri??$("NEO4J_URI")),o=r===null?"":r;try{let s=e?.graphReader;if(!s)throw new Error("Graph reader not configured");let l=e?.tenantId,[u,c]=await Promise.all([He(s("CALL dbms.components() YIELD versions, edition RETURN versions[0] AS version, edition",{}),t),He(l?s("MATCH (n {tenantId: $tenantId}) RETURN count(n) AS node_count",{tenantId:l}):s("RETURN null AS node_count",{}),t)]);if(!u.ok)throw new Error(u.reason);if(!c.ok)throw new Error(c.reason);let[d,p]=u.rows[0]??[],y=c.rows[0]?.[0],A=K(n);return{serviceName:"Neo4j",category:"graph",status:"connected",version:L(d),endpoint:o,latencyMs:A,details:{edition:L(p),boltUri:r,nodeCount:typeof y=="number"?y:null,tls:r===null?null:ct(r)??null}}}catch(s){let l=K(n),u=s instanceof Error?s.message:String(s);return{serviceName:"Neo4j",category:"graph",status:"error",version:null,endpoint:o,latencyMs:l,details:{},errorMessage:u}}}async function mt(e){let t=performance.now(),n="",r=ut(e?.redisTls,$("REDIS_TLS")),o=Number.NaN;try{let s=e?.redisClient;if(!s)throw new Error("Redis client not configured");let l=ye(e?.redisHost??$("REDIS_HOST"),"REDIS_HOST");o=lt(e?.redisPort,$("REDIS_PORT"),"REDIS_PORT"),n=`${r===!1?"redis":"rediss"}://${l}:${o}`,await s.ping();let u=await s.info("server"),c=L(u.match(/redis_version:([^\r\n]+)/)?.[1]),d=null;if(typeof s.dbSize=="function")try{d=await s.dbSize()}catch{d=null}let p=K(t);return{serviceName:"Redis",category:"cache",status:"connected",version:c,endpoint:n,latencyMs:p,details:{totalKeys:d,port:o,tls:r??null,database:0}}}catch(s){let l=K(t),u=s instanceof Error?s.message:String(s);return{serviceName:"Redis",category:"cache",status:"error",version:null,endpoint:n,latencyMs:l,details:{},errorMessage:u}}}function gn(e){let t=e.match(/Microsoft SQL Server \d+ \([^)]+\)/);return L(t===null?e.substring(0,30):t[0].replace("Microsoft SQL Server ",""))}async function gt(e){let t=performance.now(),n="",r=ut(e?.sqlServerTls,$("SQL_SERVER_TLS")),o=Number.NaN;try{let s=e?.sqlServerExecute;if(!s)throw new Error("SQL Server executor not configured");let l=ye(e?.sqlServerHost??$("SQL_SERVER_HOST"),"SQL_SERVER_HOST");o=lt(e?.sqlServerPort,$("SQL_SERVER_PORT"),"SQL_SERVER_PORT"),n=`${l}:${o}`;let u=await s(),c=L(u.db_name),d=L(u.version),p=d===null?null:L(d.split(`
2
+ `)[0]),y=p===null?null:gn(p),A=K(t);return{serviceName:"SQL Server",category:"database",status:"connected",version:y,endpoint:n,latencyMs:A,details:{database:c,port:o,tls:r??null,fullVersion:p}}}catch(s){let l=K(t),u=s instanceof Error?s.message:String(s);return{serviceName:"SQL Server",category:"database",status:"error",version:null,endpoint:n,latencyMs:l,details:{},errorMessage:u}}}async function yt(e){let t=e?.timeoutMs??$e,n=performance.now(),r="";try{r=ye(e?.backendApiHost??$("BACKEND_API_HOST"),"BACKEND_API_HOST");let o=await fetch(`${r}/openapi.json`,{signal:AbortSignal.timeout(t)});if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);let s=await o.json(),l=Object.keys(s.paths??{}).length,u=K(n);return{serviceName:"AI Quant API",category:"api",status:"connected",version:L(s.info?.version),endpoint:r,latencyMs:u,details:{title:L(s.info?.title),endpointsCount:l}}}catch(o){let s=K(n),l=o instanceof Error?o.message:String(o);return{serviceName:"AI Quant API",category:"api",status:"error",version:null,endpoint:r,latencyMs:s,details:{},errorMessage:l}}}async function Ke(e){let[t,n,r,o,s]=await Promise.all([dt(e),pt(e),mt(e),gt(e),yt(e)]),l=t.status==="connected"&&n.status==="connected"&&r.status==="connected"&&o.status==="connected"&&s.status==="connected";return{services:{qdrant:t,neo4j:n,redis:r,sqlServer:o,quantsApi:s},allHealthy:l,checkedAt:new Date().toISOString()}}var yn=C.z.object({templateText:C.z.string(),modelName:C.z.string(),temperature:C.z.number(),maxOutputTokens:C.z.number(),responseSchema:C.z.union([C.z.record(C.z.string(),C.z.unknown()),C.z.string(),C.z.null()]).optional(),endpointBaseUrl:C.z.string().nullable()}).strict(),fn=C.z.discriminatedUnion("mode",[C.z.object({mode:I.IntegrityRunModeSchema.extract(["SCAN"]),basisRunUid:C.z.null()}).strict(),C.z.object({mode:I.IntegrityRunModeSchema.extract(["REPAIR"]),basisRunUid:C.z.string().uuid()}).strict()]),Rn=C.z.object({runUid:C.z.string().uuid()}).strict();function bt(e){return e==="start_integrity_run"?"start":e==="cancel_integrity_run"?"cancel":null}function G(e,t){return e.issues.map(n=>`${n.path.length===0?t:n.path.join(".")}: ${n.message}`).join("; ")}function bn(e,t){if(e==="bool")return t==="true"||t==="false"?null:"paramValue must be 'true' or 'false' for a bool parameter";if(e==="int")return/^[+-]?\d+$/.test(t)&&Number.isSafeInteger(Number(t))?null:"paramValue must be a safe integer for an int parameter";if(e==="float")return t.trim()!==""&&Number.isFinite(Number(t))?null:"paramValue must be a finite number for a float parameter";if(e==="json")try{return JSON.parse(t),null}catch{return"paramValue must be valid JSON for a json parameter"}return null}function Sn(e){let t=I.PipelineRunSummarySchema.array().safeParse(e);if(!t.success)throw new Error(`getRecentPipelineRuns answered something that is not a run summary: ${G(t.error,"getRecentPipelineRuns")}`);return t.data}function hn(e){let t=I.PipelineStepMetricSchema.array().safeParse(e);if(!t.success)throw new Error(`getPipelineStepMetrics answered something that is not a step metric: ${G(t.error,"getPipelineStepMetrics")}`);let n=new Set;for(let r of t.data){let o=`${r.documentKind}/${r.stepKey}`;if(n.has(o))throw new Error(`getPipelineStepMetrics answered more than one metric for (documentKind, stepKey) = (${r.documentKind}, ${r.stepKey})`);n.add(o)}return t.data}function vn(e){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`pipelineStepMetricWindow must be a positive safe integer, got ${String(e)}`);return e}async function In(e,t){let n;try{n=await e.readIntegrityAuditOverview(t)}catch(o){return{ok:!1,status:null,reason:o instanceof Error?o.message:String(o)}}let r=I.IntegrityAuditOverviewSchema.safeParse(n);return r.success?{ok:!0,value:r.data}:{ok:!1,status:null,reason:`readIntegrityAuditOverview answered something that is not an audit overview: ${G(r.error,"readIntegrityAuditOverview")}`}}function wn(e){return!Array.isArray(e)||e.length===0?"orderedRuleIds must be a non-empty array of rule ids":e.every(t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>0)?new Set(e).size!==e.length?"orderedRuleIds must not name a rule twice":null:"orderedRuleIds must contain positive integers only"}function Be(e){let{store:t,healthProbeOptions:n,resourceKey:r="storage_admin",requireUser:o,requirePermission:s,resolveTenantId:l,authorizeIngest:u,canReadIntegrityFindings:c,canUpdateKnowledge:d}=e;async function p(A){let{request:b}=A;if(!await o(b))throw new Response("\u8A8D\u8A3C\u304C\u5FC5\u8981\u3067\u3059\u3002",{status:401});try{await s(b,{resourceKey:r,action:"read"})}catch(ue){throw ue instanceof Ve.AuthzDeniedError?new Response("\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002",{status:403}):ue}let R=await l(b),q=vn(t.pipelineStepMetricWindow),[j,T,_]=await Promise.all([t.getFeatureFlags(R),t.getSystemParameters(R),t.getSyncCounts(R)]),D={featureFlags:j,systemParameters:T,syncCounts:_},[Q,z,J,W,F,P,U,ie,M,X,oe,Re,be,Se,m,Y,he,ae,ve,O,Z]=await Promise.all([t.getConfidentialityPolicies(R),t.getTranscriptionVocabulary(R),t.getTranscriptionReferences(R),t.getUnresolvedReferenceUris(R),t.getPoliciesMissingDestination(R),t.getPromptTemplates(R),t.getClassificationRules(R),t.getFailedSyncItems(R),t.getGraphSchema(R),In(t,R),c(b),d(b),t.getUnresolvedEntities(R),t.getQdrantCollections(R),Ke({...n,tenantId:R}),t.getRecentIngestItems(R),t.getOntologyStatus(R,D),t.getEnrichmentStrategies(R),t.getStrategyVariants(R),t.getPipelineStepMetrics(R),t.getRecentPipelineRuns(R)]),le=t.getCircuitBreakerStatus();return{tenantId:R,featureFlags:D.featureFlags,confidentialityPolicies:Q,transcriptionVocabulary:z,transcriptionReferences:J,unresolvedReferenceUris:W,policiesMissingDestination:F,systemParameters:D.systemParameters,promptTemplates:P,classificationRules:U,classificationRuleConsumer:t.classificationRuleConsumer??null,syncCounts:D.syncCounts.counts,totalFiles:D.syncCounts.total,failedSyncItems:ie,circuitBreakerStatus:le,pipelineStepMetrics:hn(O),pipelineStepMetricWindow:q,recentPipelineRuns:Sn(Z),displayTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,graphSchema:M,enrichmentStrategies:ae,strategyVariants:ve,integrityAudit:X,canReadIntegrityFindings:oe,canUpdateKnowledge:Re,unresolvedEntities:be,qdrantCollections:Se,systemHealth:m,recentIngestItems:Y,ontologyStatus:he}}async function y(A){let{request:b}=A,w=await o(b);if(!w)return Response.json({error:"\u8A8D\u8A3C\u304C\u5FC5\u8981\u3067\u3059\u3002"},{status:401});if(w.email.trim()==="")return Response.json({error:"\u64CD\u4F5C\u8005\u3092\u7279\u5B9A\u3067\u304D\u306A\u3044\u305F\u3081\u8A2D\u5B9A\u3092\u5909\u66F4\u3067\u304D\u307E\u305B\u3093\u3002"},{status:403});if(w.accessToken==="")throw new Error("requireUser resolved an operator whose accessToken is an empty string; answer null when the session holds no token the upstream services accept");let R=w.email,q=w.accessToken===null?void 0:w.accessToken;try{await s(b,{resourceKey:r,action:"update"})}catch(F){if(F instanceof Ve.AuthzDeniedError)return await xn(b);throw F}let j=await l(b),T=await b.formData(),_=String(T.get("intent")??"");if(_==="refresh_health")return Response.json({success:!0,refreshed:!0});let D=await Pn(t,j,_,T,R);if(D)return D;let Q=await Cn(t,j,_,T,R,q);if(Q)return Q;let z=await On(t,j,_,T,R,q,()=>c(b));if(z)return z;let J=await kn(t,j,_,T,q,()=>c(b));if(J)return J;if(_==="resolve_entity"){let F=String(T.get("entityId")??""),P=String(T.get("action")??"");if(!F||P!=="merge"&&P!=="promote")return Response.json({error:"Valid entityId and action ('merge' | 'promote') are required"},{status:400});try{return await t.resolveEntity(j,F,P),Response.json({success:!0,entityId:F,action:P})}catch(U){return Response.json({error:U instanceof Error?U.message:String(U)},{status:400})}}let W=await jn(t,j,_,T,R,b,u,q);return W||Response.json({error:`Unknown intent: ${_}`},{status:400})}return{loader:p,action:y}}function qe(e){let t=String(e??"").trim();return t===""?null:t}function fe(e){let t=String(e??"").trim();if(t==="")return null;let n=Number(t);if(!(!Number.isSafeInteger(n)||n<=0))return n}function An(e){let t=String(e??"").trim();if(t==="")return null;let n=Number(t);if(!(!Number.isFinite(n)||n<=0))return n}async function Pn(e,t,n,r,o){if(n==="update_enrichment_strategy"){let s=String(r.get("stage")??"");if(!(0,I.isEnrichmentStageKey)(s))return Response.json({error:"stage must be a canonical enrichment stage key"},{status:400});let l=fe(r.get("strategyId")),u=fe(r.get("domainId"));if(l==null||u===void 0||u===null)return Response.json({error:"strategyId and domainId must be positive integers naming existing rows"},{status:400});let c=String(r.get("enabled")??"")==="true";try{await e.updateEnrichmentStrategy(t,{strategyId:l,domainId:u,stage:s,enabled:c},o)}catch(d){return Response.json({error:d instanceof Error?d.message:"\u53D6\u308A\u8FBC\u307F\u6226\u7565\u3092\u66F4\u65B0\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},{status:400})}return Response.json({success:!0,strategyId:l,domainId:u,stage:s,enabled:c})}if(n==="toggle_flag"){let s=String(r.get("flagKey")??""),l=String(r.get("enabled")??"")==="true";if(!s)return Response.json({error:"flagKey is required"},{status:400});let u=await e.getFeatureFlags(t);return Object.hasOwn(u,s)?(await e.toggleFeatureFlag(t,s,l,o),Response.json({success:!0,flagKey:s,enabled:l})):Response.json({error:`flagKey names no feature flag of this tenant: ${s}`},{status:400})}if(n==="update_confidentiality_policy"){let s=String(r.get("confidentialityLevel")??""),l=String(r.get("capability")??"");if(!(B.ConfidentialityLevelSchema.safeParse(s).success&&B.GovernedCapabilitySchema.safeParse(l).success))return Response.json({error:"confidentialityLevel and capability must be canonical values"},{status:400});let u=String(r.get("allowCloudProvider")??"")==="true";if(u&&!B.CLOUD_CAPABLE_CAPABILITIES.includes(l))return Response.json({error:`${l} sends nothing outside the deployment, so it has no cloud permission to grant`},{status:400});let c=String(r.get("promptKey")??"");return await e.updateConfidentialityPolicy(t,{confidentialityLevel:s,capability:l,isEnabled:String(r.get("isEnabled")??"")==="true",allowCloudProvider:u,promptKey:c===""?null:c},o),Response.json({success:!0,confidentialityLevel:s,capability:l})}if(n==="save_transcription_term"){let s=String(r.get("term")??"").trim();if(!s)return Response.json({error:"term is required"},{status:400});let l=An(r.get("boost"));if(l===void 0)return Response.json({error:"boost must be a number greater than zero, or absent to let the service decide"},{status:400});let u=fe(r.get("id"));if(u===void 0)return Response.json({error:"id must be a positive integer naming an existing row, or absent for a new one"},{status:400});try{await e.saveTranscriptionTerm(t,{id:u,term:s,reading:qe(r.get("reading")),boost:l,domainKey:qe(r.get("domainKey")),isActive:String(r.get("isActive")??"true")==="true"},o)}catch(c){return Response.json({error:c instanceof Error?c.message:"\u8A9E\u5F59\u3092\u4FDD\u5B58\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},{status:400})}return Response.json({success:!0,term:s})}if(n==="save_transcription_reference"){let s=String(r.get("fileUri")??"").trim();if(!s)return Response.json({error:"fileUri is required"},{status:400});let l=fe(r.get("id"));if(l===void 0)return Response.json({error:"id must be a positive integer naming an existing row, or absent for a new one"},{status:400});try{await e.saveTranscriptionReference(t,{id:l,fileUri:s,domainKey:qe(r.get("domainKey")),isActive:String(r.get("isActive")??"true")==="true"},o)}catch(u){return Response.json({error:u instanceof Error?u.message:"\u53C2\u7167\u8CC7\u6599\u3092\u4FDD\u5B58\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},{status:400})}return Response.json({success:!0,fileUri:s})}if(n==="update_parameter"){let s=String(r.get("paramKey")??""),l=String(r.get("paramValue")??"");if(!s)return Response.json({error:"paramKey is required"},{status:400});let u=(await e.getSystemParameters(t)).find(d=>d.key===s);if(u===void 0)return Response.json({error:`paramKey names no parameter of this tenant: ${s}`},{status:400});let c=bn(u.data_type,l);if(c!==null)return Response.json({error:c},{status:400});try{(0,I.assertSystemParameterInRange)(s,Number(l))}catch(d){return Response.json({error:d.message},{status:400})}return await e.updateSystemParameter(t,s,l,o),Response.json({success:!0,paramKey:s,paramValue:l})}if(n==="update_prompt"){let s=String(r.get("templateKey")??""),l=String(r.get("payload")??"{}"),u;try{u=JSON.parse(l)}catch{return Response.json({error:"Invalid JSON payload"},{status:400})}if(!s)return Response.json({error:"templateKey is required"},{status:400});let c=yn.safeParse(u);if(!c.success)return Response.json({error:`payload does not carry a prompt template update: ${G(c.error,"payload")}`},{status:400});let d=c.data;try{return await e.updatePromptTemplate(t,s,d,o),Response.json({success:!0,templateKey:s})}catch(p){return Response.json({error:p instanceof Error?p.message:String(p)},{status:400})}}if(n==="reorder_rules"){let s=String(r.get("orderedRuleIds")??"[]"),l;try{l=JSON.parse(s)}catch{return Response.json({error:"Invalid orderedRuleIds JSON"},{status:400})}let u=wn(l);if(u!==null)return Response.json({error:u},{status:400});let c=l;return await e.reorderClassificationRules(t,c,o),Response.json({success:!0,orderedRuleIds:c})}return null}async function Cn(e,t,n,r,o,s){if(n==="retry_job"){let l=String(r.get("fileId")??"");if(!l)return Response.json({error:"fileId is required"},{status:400});try{return await e.retrySyncItem(t,l,o,s),Response.json({success:!0,fileId:l})}catch(u){return Response.json({error:u instanceof Error?u.message:String(u)},{status:400})}}if(n==="retry_all_failed")try{let{requeued:l,skipped:u}=await e.retryAllFailedSyncItems(t,o,s);return Response.json({success:!0,requeued:l,skipped:u})}catch(l){return Response.json({error:l instanceof Error?l.message:String(l)},{status:400})}return null}var Nn="resync_findings",En="\u307E\u3068\u3081\u3066\u306E\u518D\u540C\u671F\u306F\u3001\u5168\u3066\u306E\u6587\u66F8\u3092\u95B2\u89A7\u3067\u304D\u308B\u64CD\u4F5C\u8005 (\u30D5\u30A1\u30A4\u30EB\u306E\u95B2\u89A7\u306E\u6A29\u9650\u306B\u884C\u3068\u5217\u306E\u30B9\u30B3\u30FC\u30D7\u304C\u7121\u3044\u64CD\u4F5C\u8005) \u3060\u3051\u304C\u5B9F\u884C\u3067\u304D\u307E\u3059\u3002",Tn=/^[1-9][0-9]*$/;function _n(e){return Object.fromEntries([...e.entries()].filter(([t])=>t!=="intent").map(([t,n])=>[t,t==="after"&&typeof n=="string"&&Tn.test(n)?Number(n):n]))}async function On(e,t,n,r,o,s,l){if(n!==Nn)return null;if(!await l())return Response.json({error:En},{status:403});let u=I.IntegrityCellResyncRequestSchema.safeParse(_n(r));if(!u.success)return Response.json({error:`resync_findings takes runUid (a UUID), store, scopeKey, itemClass UNRECORDED and an optional after (a positive integer): ${G(u.error,"form")}`},{status:400});let c;try{c=await e.resyncIntegrityCell(t,u.data,o,s)}catch(p){return Response.json({error:p instanceof Error?p.message:String(p)},{status:400})}let d=I.IntegrityCellResyncResultSchema.safeParse(c);return d.success?Response.json({success:!0,cellResync:d.data}):Response.json({error:`\u307E\u3068\u3081\u3066\u306E\u518D\u540C\u671F\u306E\u7B54\u3048\u304C\u5951\u7D04\u3068\u7570\u306A\u308A\u307E\u3059 (${G(d.error,"answer")})\u3002\u958B\u767A\u62C5\u5F53\u306B\u9023\u7D61\u3057\u3066\u304F\u3060\u3055\u3044\u3002`},{status:502})}function se(e,t,n){let r=I.IntegrityCommandFailureSchema.parse({command:e,code:t,status:n}),o=I.INTEGRITY_COMMAND_CODES.find(s=>s.code===r.code);return Response.json({failure:r},{status:o===void 0?502:o.status})}async function xn(e){let t=await e.formData().catch(()=>null),n=t===null?null:bt(t.get("intent"));return n===null?Response.json({error:"\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002"},{status:403}):se(n,"FORBIDDEN",null)}async function ft(e,t){let n;try{n=I.IntegrityCommandReplySchema.parse(await t())}catch{return se(e,"UPSTREAM_FAILED",null)}return n.ok?Response.json({success:!0,runUid:n.runUid}):se(e,(0,I.integrityCommandFailureCodeOf)(e,n.status,n.errorCode),n.status)}async function kn(e,t,n,r,o,s){let l=bt(n);if(l==="start"){let u=fn.safeParse({mode:r.get("mode"),basisRunUid:r.get("basisRunUid")});if(!u.success)return Response.json({error:`start_integrity_run takes mode SCAN without basisRunUid, or mode REPAIR with basisRunUid (a UUID): ${G(u.error,"form")}`},{status:400});let{mode:c,basisRunUid:d}=u.data;return o===void 0||c==="REPAIR"&&!await s()?se(l,"FORBIDDEN",null):await ft(l,()=>e.startIntegrityRun(t,c,d,o))}if(l==="cancel"){let u=Rn.safeParse({runUid:r.get("runUid")});return u.success?o===void 0?se(l,"FORBIDDEN",null):await ft(l,()=>e.cancelIntegrityRun(t,u.data.runUid,o)):Response.json({error:`cancel_integrity_run takes runUid (a UUID): ${G(u.error,"form")}`},{status:400})}return null}function Ln(e){if(typeof e!="object"||e===null)return"payload must be an object";let t=e;if(typeof t.fileUri!="string"||t.fileUri.trim()==="")return"payload.fileUri is required";if(!B.ConfidentialityLevelSchema.safeParse(t.confidentialityLevel).success)return`payload.confidentialityLevel must be one of ${B.ConfidentialityLevelSchema.options.join(", ")}`;let r=t.departmentId;return r!=null&&(typeof r!="number"||!Number.isInteger(r))?"payload.departmentId must be an integer or null":null}function Fn(e){try{return(0,Rt.formatCount)(e,pe),null}catch{return`inspectFileUri answered a fileSize that is not a byte count (a non-negative safe integer): ${String(e)}`}}async function jn(e,t,n,r,o,s,l,u){if(n==="ingest_document"){let c=String(r.get("payload")??"");if(!c)return Response.json({error:"payload is required"},{status:400});let d;try{d=JSON.parse(c)}catch{return Response.json({error:"Invalid JSON payload"},{status:400})}let p=Ln(d);if(p)return Response.json({error:p},{status:400});let y=d,A=await l(s,y);if(A!==null)return Response.json({error:A},{status:403});try{let b=u===void 0?await e.ingestDocument(t,y,o):await e.ingestDocument(t,y,o,u);return Response.json({success:!0,result:b})}catch(b){return Response.json({error:b instanceof Error?b.message:String(b)},{status:400})}}if(n==="inspect_uri"){let c=String(r.get("fileUri")??"").trim();if(!c)return Response.json({error:"fileUri is required"},{status:400});if(!e.inspectFileUri)return Response.json({error:"inspectFileUri is not implemented"},{status:501});let d;try{d=u===void 0?await e.inspectFileUri(t,c):await e.inspectFileUri(t,c,u)}catch(y){return Response.json({error:y instanceof Error?y.message:String(y)},{status:400})}let p=Fn(d.fileSize);return p!==null?Response.json({error:p},{status:400}):Response.json({success:!0,inspection:d})}return null}function Dn(e){let t=Be(e);return{loader:t.loader,action:t.action,View:Me,server:t}}0&&(module.exports={StorageAdminConsoleView,checkAllSystemHealth,checkBackendApiHealth,checkNeo4jHealth,checkQdrantHealth,checkRedisHealth,checkSqlServerHealth,createStorageAdminApp,createStorageAdminServer});
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ResourceOutcome } from "@aiquants/console-ui/core";
2
2
  export { CommandOutcome, ResourceOutcome } from "@aiquants/console-ui/core";
3
- import { EnrichmentStageKey, PipelineStepMetric, PipelineRunSummary, IntegrityAuditOverview, IntegrityRunMode, IntegrityCommandReply, PipelineRunRecord, IntegrityCommandFailure } from "@aiquants/enrichment-core";
4
- export { IntegrityAuditOverview, IntegrityCommandFailure, IntegrityCommandReply, IntegrityFindingPage, IntegrityFindingsQuery, IntegrityRunMode, PipelineRunRecord, PipelineRunSummary, PipelineStepMetric, PipelineStepRecord, SearchMode, StageProvenance } from "@aiquants/enrichment-core";
3
+ import { EnrichmentStageKey, PipelineStepMetric, PipelineRunSummary, IntegrityAuditOverview, IntegrityRunMode, IntegrityCommandReply, IntegrityCellResyncRequest, IntegrityCellResyncResult, PipelineRunRecord, IntegrityCommandFailure } from "@aiquants/enrichment-core";
4
+ export { IntegrityAuditOverview, IntegrityCellResyncRequest, IntegrityCellResyncResult, IntegrityCommandFailure, IntegrityCommandReply, IntegrityFindingPage, IntegrityFindingsQuery, IntegrityRunMode, PipelineRunRecord, PipelineRunSummary, PipelineStepMetric, PipelineStepRecord, SearchMode, StageProvenance } from "@aiquants/enrichment-core";
5
5
  import { EnrichmentStrategyRow, FailedSyncItem, QdrantStorageOverview, CircuitBreakerState, DocumentIngestPayload, FileInspectionResult, RecentIngestItem, OntologyStatusData, MetadataSearchWorkbenchProps, ModelComparisonWorkbenchProps } from "@aiquants/enrichment-react";
6
6
  export { ComparisonHit, ComparisonInput, ComparisonOutcome, ComparisonVariantResult, DocumentIngestLabel, DocumentIngestPayload, EnrichmentStrategyRow, FailedSyncItem, FileInspectionResult, FusionStrategy, MetadataSearchHit, MetadataSearchParams, MetadataSearchResult, OntologyStatusData, QdrantCollectionInfo, QdrantStorageOverview, RecentIngestItem, SearchHitGraphRelation, SearchHitScoreBreakdown, StrategyProvenance } from "@aiquants/enrichment-react";
7
7
  import { ConfidentialityPolicyRow, TranscriptionTermRow, TranscriptionReferenceRow, PromptTemplateItem, ClassificationRuleItem, GraphSchemaStats, IntegrityFindingsLoader, PolicyConflictHost, DocumentAuthorityHost, GraphTraversalHost, GraphNodeIndexOutcome, SimulationRunner } from "@aiquants/governance-react";
@@ -180,6 +180,7 @@ interface StorageAdminStore {
180
180
  readIntegrityAuditOverview(tenantId: string): Promise<IntegrityAuditOverview>;
181
181
  startIntegrityRun(tenantId: string, mode: IntegrityRunMode, basisRunUid: string | null, accessToken: string): Promise<IntegrityCommandReply>;
182
182
  cancelIntegrityRun(tenantId: string, runUid: string, accessToken: string): Promise<IntegrityCommandReply>;
183
+ resyncIntegrityCell(tenantId: string, request: IntegrityCellResyncRequest, actor: string, accessToken: string | undefined): Promise<IntegrityCellResyncResult>;
183
184
  getUnresolvedEntities(tenantId: string): Promise<UnresolvedEntity[]>;
184
185
  resolveEntity(tenantId: string, entityId: string, action: "merge" | "promote"): Promise<void>;
185
186
  getQdrantCollections(tenantId: string): Promise<QdrantStorageOverview>;
@@ -248,6 +249,7 @@ interface StorageAdminActionData {
248
249
  skipped?: readonly RetryAllSkippedItem[];
249
250
  failure?: IntegrityCommandFailure;
250
251
  runUid?: string;
252
+ cellResync?: IntegrityCellResyncResult;
251
253
  }
252
254
  interface StorageAdminFetcher {
253
255
  state: "idle" | "submitting" | "loading";
@@ -260,6 +262,7 @@ interface StorageAdminConsoleViewProps {
260
262
  data?: StorageAdminLoaderData;
261
263
  fetcher?: StorageAdminFetcher;
262
264
  integrityFetcher?: StorageAdminFetcher;
265
+ inspectorFetcher?: StorageAdminFetcher;
263
266
  renderHeader?: (props: {
264
267
  title: string;
265
268
  tenantId: string;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ResourceOutcome } from "@aiquants/console-ui/core";
2
2
  export { CommandOutcome, ResourceOutcome } from "@aiquants/console-ui/core";
3
- import { EnrichmentStageKey, PipelineStepMetric, PipelineRunSummary, IntegrityAuditOverview, IntegrityRunMode, IntegrityCommandReply, PipelineRunRecord, IntegrityCommandFailure } from "@aiquants/enrichment-core";
4
- export { IntegrityAuditOverview, IntegrityCommandFailure, IntegrityCommandReply, IntegrityFindingPage, IntegrityFindingsQuery, IntegrityRunMode, PipelineRunRecord, PipelineRunSummary, PipelineStepMetric, PipelineStepRecord, SearchMode, StageProvenance } from "@aiquants/enrichment-core";
3
+ import { EnrichmentStageKey, PipelineStepMetric, PipelineRunSummary, IntegrityAuditOverview, IntegrityRunMode, IntegrityCommandReply, IntegrityCellResyncRequest, IntegrityCellResyncResult, PipelineRunRecord, IntegrityCommandFailure } from "@aiquants/enrichment-core";
4
+ export { IntegrityAuditOverview, IntegrityCellResyncRequest, IntegrityCellResyncResult, IntegrityCommandFailure, IntegrityCommandReply, IntegrityFindingPage, IntegrityFindingsQuery, IntegrityRunMode, PipelineRunRecord, PipelineRunSummary, PipelineStepMetric, PipelineStepRecord, SearchMode, StageProvenance } from "@aiquants/enrichment-core";
5
5
  import { EnrichmentStrategyRow, FailedSyncItem, QdrantStorageOverview, CircuitBreakerState, DocumentIngestPayload, FileInspectionResult, RecentIngestItem, OntologyStatusData, MetadataSearchWorkbenchProps, ModelComparisonWorkbenchProps } from "@aiquants/enrichment-react";
6
6
  export { ComparisonHit, ComparisonInput, ComparisonOutcome, ComparisonVariantResult, DocumentIngestLabel, DocumentIngestPayload, EnrichmentStrategyRow, FailedSyncItem, FileInspectionResult, FusionStrategy, MetadataSearchHit, MetadataSearchParams, MetadataSearchResult, OntologyStatusData, QdrantCollectionInfo, QdrantStorageOverview, RecentIngestItem, SearchHitGraphRelation, SearchHitScoreBreakdown, StrategyProvenance } from "@aiquants/enrichment-react";
7
7
  import { ConfidentialityPolicyRow, TranscriptionTermRow, TranscriptionReferenceRow, PromptTemplateItem, ClassificationRuleItem, GraphSchemaStats, IntegrityFindingsLoader, PolicyConflictHost, DocumentAuthorityHost, GraphTraversalHost, GraphNodeIndexOutcome, SimulationRunner } from "@aiquants/governance-react";
@@ -180,6 +180,7 @@ interface StorageAdminStore {
180
180
  readIntegrityAuditOverview(tenantId: string): Promise<IntegrityAuditOverview>;
181
181
  startIntegrityRun(tenantId: string, mode: IntegrityRunMode, basisRunUid: string | null, accessToken: string): Promise<IntegrityCommandReply>;
182
182
  cancelIntegrityRun(tenantId: string, runUid: string, accessToken: string): Promise<IntegrityCommandReply>;
183
+ resyncIntegrityCell(tenantId: string, request: IntegrityCellResyncRequest, actor: string, accessToken: string | undefined): Promise<IntegrityCellResyncResult>;
183
184
  getUnresolvedEntities(tenantId: string): Promise<UnresolvedEntity[]>;
184
185
  resolveEntity(tenantId: string, entityId: string, action: "merge" | "promote"): Promise<void>;
185
186
  getQdrantCollections(tenantId: string): Promise<QdrantStorageOverview>;
@@ -248,6 +249,7 @@ interface StorageAdminActionData {
248
249
  skipped?: readonly RetryAllSkippedItem[];
249
250
  failure?: IntegrityCommandFailure;
250
251
  runUid?: string;
252
+ cellResync?: IntegrityCellResyncResult;
251
253
  }
252
254
  interface StorageAdminFetcher {
253
255
  state: "idle" | "submitting" | "loading";
@@ -260,6 +262,7 @@ interface StorageAdminConsoleViewProps {
260
262
  data?: StorageAdminLoaderData;
261
263
  fetcher?: StorageAdminFetcher;
262
264
  integrityFetcher?: StorageAdminFetcher;
265
+ inspectorFetcher?: StorageAdminFetcher;
263
266
  renderHeader?: (props: {
264
267
  title: string;
265
268
  tenantId: string;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{Card as Dt,ConsoleUiRoot as Mt,ResourceFailed as Ht,reasonAside as et,resolveConsoleUiLabels as $t,useFocusRescue as Kt}from"@aiquants/console-ui";import{DOCUMENT_KIND_LABELS as qt,EnrichmentSyncStatusSchema as Bt,GRAPH_INDEX_LIMITS as Vt,IntegrityRunModeSchema as Gt,PIPELINE_STEPS as Qt}from"@aiquants/enrichment-core";import{DocumentIngestConsole as zt,EnrichmentStrategyBoard as Jt,FinishedInstant as Wt,InfrastructureHealthMonitor as Yt,MetadataSearchWorkbench as Zt,ModelComparisonWorkbench as Xt,OntologyStatusCard as en,PIPELINE_RUN_STATUS_PRESENTATION as tn,PIPELINE_TRIGGER_LABELS as nn,PipelineFlowViewer as rn,PipelineRunInspector as sn,pipelineRunPresentationKey as an,QdrantStorageCard as on,RecordedInstant as ln,SyncStatusMonitor as un}from"@aiquants/enrichment-react";import{ClassificationRuleEditor as dn,ConfidentialityPolicyBoard as cn,DocumentAuthorityRegistry as pn,FeatureFlagBoard as mn,GovernanceDryRunConsole as gn,integrityFailureNeedsOverviewReread as yn,KnowledgeGraphExplorer as fn,PolicyConflictQueue as bn,PolicyConflictSummaryCard as Sn,PromptTemplateConsole as Rn,SystemParameterTable as hn,TranscriptionAdaptationBoard as vn,TriStoreIntegrityAudit as In}from"@aiquants/governance-react";import{Fragment as wn,useCallback as Z,useEffect as Oe,useMemo as le,useRef as O,useState as L}from"react";import{useFetcher as Ge,useLoaderData as An,useRevalidator as Pn,useSearchParams as Nn}from"react-router";var ae="ja-JP";var Pt=/[^\s\x1c-\x1f\x85\ufeff]/;function oe(e){return Pt.test(e)}function Y(e,t){return new Promise(n=>n(e())).catch(n=>t(n instanceof Error?n.message:String(n)))}import{beginReload as Nt,keepLastGood as Tt}from"@aiquants/console-ui/core";import{isStrictlyEarlier as _t}from"@aiquants/enrichment-core";import{useCallback as he,useEffect as qe,useRef as Ie,useState as Et,useSyncExternalStore as Ct}from"react";var Ot=2e3,xt=1e4;function ve(e,t){return t.ok&&e.kind==="ready"&&_t(t.value.readAt,e.value.readAt)?e:Tt(e,t)}var kt=401;function Lt(e){return e.kind==="failed"||e.refreshFailure!==null&&e.refreshFailure.status===kt?null:e.value.active}function Be(e,t){let[n,r]=Et(()=>({loaded:e,overview:ve({kind:"loading"},e)}));n.loaded!==e&&r({loaded:e,overview:ve(n.overview,e)});let o=Ie(t);o.current=t;let s=Ie(null);qe(()=>()=>s.current?.abort(),[]);let a=he((c,m)=>Y(m,g=>({ok:!1,status:null,reason:g})).then(g=>{c.aborted||r(h=>({loaded:h.loaded,overview:ve(h.overview,g)}))}),[]),l=he(()=>{let c=new AbortController;s.current=c,r(m=>({loaded:m.loaded,overview:Nt(m.overview,"reload")})),a(c.signal,()=>o.current(c.signal))},[a]),d=he(c=>a(c,()=>o.current(c)),[a]);return{overview:n.overview,reload:l,poll:d}}function Ft(e){return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)}function jt(){return document.visibilityState==="visible"}function Ut(){return!0}function Ve(e,t,n){let r=Ct(Ft,jt,Ut),o=t&&r,s=Ie(o),a=e.kind==="ready",l=Lt(e),d=l===null?null:l.run.runUid,c=l===null?!1:l.isStale;qe(()=>{let m=o&&!s.current;if(s.current=o,!o||d===null&&!(m&&a))return;let g=new AbortController,h=c?xt:Ot,f,v=async()=>{await n(g.signal),!g.signal.aborted&&d!==null&&(f=setTimeout(v,h))};return f=setTimeout(v,m?0:h),()=>{g.abort(),clearTimeout(f)}},[o,a,d,c,n])}var we={columns:2,className:"grid-cols-2",spanClassNames:{1:"col-span-1",2:"col-span-2"}},Ae={columns:4,className:"@min-[41.5rem]:grid-cols-4",spanClassNames:{1:"@min-[41.5rem]:col-span-1",2:"@min-[41.5rem]:col-span-2",3:"@min-[41.5rem]:col-span-3",4:"@min-[41.5rem]:col-span-4"}},Pe={className:"@min-[82rem]:grid-flow-col @min-[82rem]:auto-cols-fr @min-[82rem]:grid-cols-none",lastTabClassName:"@min-[82rem]:col-auto"};function Ne(e,t){let n=t%e.columns,r=n===0?1:e.columns-n+1;return e.spanClassNames[r]}import{jsx as u,jsxs as S}from"react/jsx-runtime";var Qe="tab",_e={key:"knowledge-authority",phrases:["\u6A29\u5A01\u53F0\u5E33 & \u898F\u7A0B\u885D\u7A81"]},Ee={key:"pipeline",phrases:["\u30D1\u30A4\u30D7\u30E9\u30A4\u30F3 & \u63A5\u7D9A\u72B6\u614B"]},Ce={key:"parameters",phrases:["\u30E2\u30C7\u30EB & \u30D1\u30E9\u30E1\u30FC\u30BF\u8A2D\u5B9A"]},ze="\u30A8\u30F3\u30EA\u30C3\u30C1\u30E1\u30F3\u30C8\u540C\u671F\u30B9\u30C6\u30FC\u30BF\u30B9",Tn="\u9001\u4FE1\u4E2D\u306E\u64CD\u4F5C (\u540C\u671F\u306E\u518D\u8A66\u884C\u306A\u3069) \u306E\u7D50\u679C\u3092\u5F85\u3063\u3066\u3044\u308B\u305F\u3081\u3001\u9001\u3063\u3066\u3044\u307E\u305B\u3093\u3002\u7D50\u679C\u304C\u51FA\u3066\u304B\u3089\u62BC\u3057\u76F4\u3057\u3066\u304F\u3060\u3055\u3044\u3002",D=[{key:"search",phrases:["\u30E1\u30BF\u30C7\u30FC\u30BF\u691C\u7D22","\u30EF\u30FC\u30AF\u30D9\u30F3\u30C1"]},{key:"ingest",phrases:["\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8","\u53D6\u308A\u8FBC\u307F & \u30E1\u30BF\u751F\u6210"]},Ee,{key:"knowledge-graph",phrases:["\u30CA\u30EC\u30C3\u30B8\u30B0\u30E9\u30D5","\u63A2\u7D22"]},Ce,{key:"prompts",phrases:["\u30D7\u30ED\u30F3\u30D7\u30C8 & \u30C9\u30E9\u30A4\u30E9\u30F3"]},_e,{key:"data-retention",phrases:["\u30C7\u30FC\u30BF\u4FDD\u6301 & \u6574\u5408\u6027\u76E3\u67FB"]}];function Te(e){return e.phrases.join("")}function _n(e){return e!==null&&D.some(t=>t.key===e)}var En="Tri-Store \u30C7\u30FC\u30BF\u6574\u5408\u6027\u76E3\u67FB";function Cn(e){return`\u76E3\u67FB\u306E\u6982\u6CC1\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F${et(e)}\u3002`}var On=$t("ja");function xn(e){return On.failureSentence(e,"\u51E6\u7406\u5C65\u6B74\u3092\u95B2\u89A7\u3059\u308B\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002",t=>`\u51E6\u7406\u5C65\u6B74\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F${et(t)}\u3002`)}var Je={state:"idle",formData:null,data:null,submit:()=>Promise.resolve()};function tt({data:e,fetcher:t,integrityFetcher:n,renderHeader:r,graphTraversal:o,onBrowseGraphNodes:s,onSimulateGovernance:a,onRefreshIngestQueue:l,onSearch:d,onLoadDocumentRuns:c,onCompareVariants:m,loadIntegrityOverview:g,loadIntegrityFindings:h,policyConflicts:f,documentAuthority:v}){let[y,M]=L(null),[U,T]=L(null),[_,E]=L(!1),H=le(()=>{if(s!==void 0)return(i,b)=>{E(!0),Y(()=>s(i,b),R=>({ok:!1,reason:R})).then(R=>{E(!1),T(R.ok?null:R.reason),R.ok&&M(R.page)})}},[s]),[$,K]=Nn(),C=$.get(Qe),I=_n(C)?C:D[0].key,x=i=>{K(b=>{let R=new URLSearchParams(b);return R.set(Qe,i),R},{replace:!1,preventScrollReset:!0})},ee=Ln(e.recentIngestItems,l,I==="ingest"),k=Be(e.integrityAudit,g);Ve(k.overview,I==="data-retention",k.poll);let G=O(null),te=Kt(()=>G.current),[ce,pe]=L(0),me=Z(()=>pe(i=>i+1),[]),p=ee===null?e:{...e,recentIngestItems:[...ee]},q=O({}),ge=Z(()=>q.current[I]??null,[I]),ne=le(()=>Fn(e.enrichmentStrategies),[e.enrichmentStrategies]),ye=le(()=>e.strategyVariants.map(jn),[e.strategyVariants]),A=Mn(c),B=A.open,re=B===void 0?void 0:i=>B(i,null),fe=B===void 0?void 0:i=>B(i.metadataId,i.id),se=(i,b)=>{let R=D.length-1,P;if(i.key==="ArrowRight"||i.key==="ArrowDown")P=b===R?0:b+1;else if(i.key==="ArrowLeft"||i.key==="ArrowUp")P=b===0?R:b-1;else if(i.key==="Home")P=0;else if(i.key==="End")P=R;else return;i.preventDefault();let ie=D[P].key;x(ie),q.current[ie]?.focus()},je={...p.featureFlags};if(t.formData&&t.formData.get("intent")==="toggle_flag"){let i=String(t.formData.get("flagKey")??""),b=String(t.formData.get("enabled")??"")==="true";i&&(je[i]=b)}let pt=t.data&&"inspection"in t.data?t.data.inspection:void 0,Q=t.state==="idle"?null:t.formData?.get("intent"),mt=Q==="inspect_uri",gt=Q==="ingest_document",yt=Q==="retry_job"||Q==="retry_all_failed",ft=Q==="resolve_entity",Ue=n.state==="idle"?null:n.formData?.get("intent"),bt=Ue==="start_integrity_run"?{kind:"starting",mode:Gt.parse(n.formData?.get("mode"))}:Ue==="cancel_integrity_run"?{kind:"cancelling"}:{kind:"idle"},St=Pn(),[Rt,be]=L(null),De=I!=="data-retention";Oe(()=>{De&&be(null)},[De]);let ht=i=>{let b=i?.failure;if(b===void 0){be(null);return}be(R=>({failure:b,occurrence:R===null?1:R.occurrence+1})),yn(b)&&St.revalidate()},[z,J]=L(null),vt=i=>{if(t.state!=="idle"){J({metadataId:i,intent:"retry_job",status:"refused",error:Tn});return}J({metadataId:i,intent:"retry_job",status:"pending",error:null}),t.submit({intent:"retry_job",fileId:String(i)},{method:"post"})},[Me,Se]=L("console"),It=(i,b)=>{if(z!==null&&z.status==="pending"){if(b==="retry_job"){let R=i?.error;J(R===void 0?{...z,status:"accepted",error:null}:{...z,status:"refused",error:R}),Se("inspector");return}J(null)}Se("console")},{settledIntent:wt,submitAndAwait:He}=Ye(t,It);Ye(n,i=>{Se("integrity"),ht(i)});let $e=Me==="inspector"?void 0:(Me==="console"?t:n).data?.error,Re=i=>{x(i),q.current[i]?.focus()},Ke=O(null),At={strategies:{label:Te(Ee),onOpen:()=>Re(Ee.key),closesInspector:!0},projectionPolicy:{label:Te(Ce),onOpen:()=>Re(Ce.key),closesInspector:!0},failedSync:{label:ze,onOpen:()=>Ke.current?.focus(),closesInspector:!1}},W=wt==="retry_all_failed"&&t.data?.skipped!==void 0&&t.data.requeued!==void 0?{requeued:t.data.requeued,skipped:t.data.skipped}:null;return u(Mt,{locale:"ja",formatLocale:ae,timeZone:p.displayTimeZone,testId:"storage-admin-console-ui",children:S("div",{className:"container mx-auto space-y-6 p-6 font-sans text-slate-900","data-testid":"storage-admin-console",children:[$e&&u("div",{className:"rounded-lg border border-red-200 border-solid bg-red-50 p-4 font-medium text-red-700 text-sm shadow-sm",role:"alert","data-testid":"storage-admin-error-alert",children:$e}),r?r({title:"\u30B9\u30C8\u30EC\u30FC\u30B8 AI \u30A8\u30F3\u30EA\u30C3\u30C1\u30E1\u30F3\u30C8 & \u30AC\u30D0\u30CA\u30F3\u30B9\u904B\u7528\u7BA1\u7406",tenantId:p.tenantId}):S("header",{className:"flex flex-col justify-between gap-2 border-slate-200 border-b border-solid pb-4 md:flex-row md:items-center",children:[S("div",{children:[u("h1",{className:"font-bold text-2xl tracking-tight",children:"\u30B9\u30C8\u30EC\u30FC\u30B8 AI \u30A8\u30F3\u30EA\u30C3\u30C1\u30E1\u30F3\u30C8 & \u30AC\u30D0\u30CA\u30F3\u30B9\u904B\u7528\u7BA1\u7406"}),S("p",{className:"mt-1 text-slate-500 text-sm",children:["\u30C6\u30CA\u30F3\u30C8: ",u("code",{className:"font-semibold text-slate-800",children:p.tenantId})," | \u5168\u30B7\u30B9\u30C6\u30E0\u72B6\u614B\u30FB\u30D1\u30E9\u30E1\u30FC\u30BF\u5236\u5FA1\u30FB\u6574\u5408\u6027\u76E3\u67FB"]})]}),u("div",{className:"flex items-center gap-2",children:S("button",{type:"button","data-testid":"header-health-status-button",onClick:()=>x("pipeline"),className:"inline-flex items-center gap-2 rounded-full border border-slate-200 border-solid bg-slate-50 px-3 py-1.5 font-medium text-slate-700 text-xs transition-colors hover:bg-slate-100",children:[u("span",{className:`h-2 w-2 rounded-full ${p.systemHealth.allHealthy?"bg-emerald-500":"bg-amber-500"}`}),S("span",{children:["\u5468\u8FBA\u6A5F\u80FD: ",p.systemHealth.allHealthy?"\u5168\u30B5\u30FC\u30D3\u30B9\u6B63\u5E38":"\u63A5\u7D9A\u8981\u78BA\u8A8D"]})]})})]}),S("div",{className:"w-full space-y-6",children:[u("div",{className:"@container w-full","data-testid":"storage-admin-tablist-frame",children:u("div",{className:`grid w-full ${we.className} ${Ae.className} ${Pe.className} gap-1 rounded-xl bg-slate-100 p-1`,role:"tablist","aria-label":"\u904B\u7528\u7BA1\u7406\u30B3\u30F3\u30BD\u30FC\u30EB\u306E\u753B\u9762",children:D.map((i,b)=>{let R=I===i.key;return u("button",{id:`tab-${i.key}`,type:"button",role:"tab",ref:P=>{q.current[i.key]=P},"aria-selected":R,"aria-controls":`panel-${i.key}`,tabIndex:R?0:-1,"data-testid":`tab-trigger-${i.key}`,onKeyDown:P=>se(P,b),onClick:()=>x(i.key),className:`wrap-anywhere break-keep rounded-lg px-3 py-2.5 text-center font-medium text-sm transition-all ${b===D.length-1?`${Ne(we,D.length)} ${Ne(Ae,D.length)} ${Pe.lastTabClassName}`:""} ${R?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:bg-slate-200/50 hover:text-slate-900"}`,children:i.phrases.map((P,ie)=>S(wn,{children:[ie>0&&u("wbr",{}),P]},P))},i.key)})})}),A.metadataId!==null&&u(sn,{metadataId:A.metadataId,runs:A.runs,selectedRunId:A.selectedRunId,onSelectRun:A.selectRun,isLoading:A.isLoading,failure:A.failure,onClose:A.close,openRequest:A.openRequest,returnFocusFallback:ge}),I==="search"&&S("div",{role:"tabpanel",id:"panel-search","aria-labelledby":"tab-search",className:"space-y-6","data-testid":"tab-content-search",children:[u(Zt,{tenantId:p.tenantId,onSearch:d,circuitBreakerStatus:p.circuitBreakerStatus}),m!==void 0&&u(Xt,{variants:ye,onCompare:m})]}),I==="ingest"&&u("div",{role:"tabpanel",id:"panel-ingest","aria-labelledby":"tab-ingest",className:"space-y-6","data-testid":"tab-content-ingest",children:u(zt,{tenantId:p.tenantId,policies:p.confidentialityPolicies,domainOptions:ne,recentItems:p.recentIngestItems,inspectionResult:pt,isInspecting:mt,isSubmitting:gt,onInspectUri:i=>{t.submit({intent:"inspect_uri",fileUri:i},{method:"post"})},onIngestDocument:i=>{t.submit({intent:"ingest_document",payload:JSON.stringify(i)},{method:"post"})},onRetryItem:i=>{t.submit({intent:"retry_job",fileId:String(i)},{method:"post"})},onShowHistory:re})}),I==="pipeline"&&S("div",{role:"tabpanel",id:"panel-pipeline","aria-labelledby":"tab-pipeline",className:"space-y-6","data-testid":"tab-content-pipeline",children:[u(rn,{featureFlags:p.featureFlags,metrics:p.pipelineStepMetrics,metricSampleWindow:p.pipelineStepMetricWindow}),u(Un,{runs:p.recentPipelineRuns,onOpenRun:fe}),u(Jt,{strategies:p.enrichmentStrategies,featureFlags:p.featureFlags,isUpdating:t.state!=="idle",onToggleStage:(i,b,R)=>t.submit({intent:"update_enrichment_strategy",strategyId:String(i.id),domainId:String(i.domainId),stage:b,enabled:String(R)},{method:"post"})}),u(Yt,{health:p.systemHealth,isRefreshing:t.state!=="idle",onRefresh:()=>t.submit({intent:"refresh_health"},{method:"post"})})]}),I==="knowledge-graph"&&S("div",{role:"tabpanel",id:"panel-knowledge-graph","aria-labelledby":"tab-knowledge-graph",className:"space-y-6","data-testid":"tab-content-knowledge-graph",children:[u(en,{tenantId:p.tenantId,ontologyStatus:p.ontologyStatus}),u(fn,{topologyMaxLabels:Vt.topologyLabels.default,schema:p.graphSchema,tenantId:p.tenantId,unresolvedEntities:p.unresolvedEntities,traversal:o,onBrowseLabel:H,nodeIndexPage:y,nodeIndexFailure:U,isNodeIndexLoading:_,isResolving:ft,onResolveEntity:(i,b)=>{t.submit({intent:"resolve_entity",entityId:i,action:b},{method:"post"})}})]}),I==="parameters"&&S("div",{role:"tabpanel",id:"panel-parameters","aria-labelledby":"tab-parameters",className:"space-y-6","data-testid":"tab-content-parameters",children:[S("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2",children:[u(mn,{flags:je,isUpdating:t.state!=="idle",onToggleFlag:(i,b)=>{t.submit({intent:"toggle_flag",flagKey:i,enabled:String(b)},{method:"post"})}}),u(dn,{rules:p.classificationRules,domainOptions:ne,consultedBy:p.classificationRuleConsumer,onReorderRules:i=>{t.submit({intent:"reorder_rules",orderedRuleIds:JSON.stringify(i)},{method:"post"})}})]}),p.policiesMissingDestination.length>0&&S("div",{"data-testid":"policies-missing-destination",role:"alert",style:{padding:"10px 12px",borderRadius:"6px",backgroundColor:"#fef2f2",color:"#b91c1c",fontSize:"12px"},children:[u("strong",{children:"\u6B21\u306E\u533A\u5206\u30FB\u6A5F\u80FD\u306F\u5B9F\u884C\u6642\u306B\u5931\u6557\u3057\u307E\u3059\u3002"})," \u53C2\u7167\u3059\u308B\u30D7\u30ED\u30F3\u30D7\u30C8\u884C\u306B\u5B9B\u5148\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002",u("ul",{style:{margin:"6px 0 0",paddingInlineStart:"18px"},children:p.policiesMissingDestination.map(i=>S("li",{"data-testid":`missing-destination-${i.confidentialityLevel}-${i.capability}`,children:[i.confidentialityLevel," / ",i.capability," \u2192 ",i.promptKey," (",i.modelProvider,") \u306E ",u("code",{children:"extra_params.base_url"})]},`${i.confidentialityLevel}:${i.capability}`))}),u("span",{style:{display:"block",marginTop:"4px",fontSize:"11px"},children:"\u5B9B\u5148\u3092\u8A2D\u5B9A\u3057\u3066\u3082\u3001\u305D\u306E\u30DB\u30B9\u30C8\u304C\u914D\u5099\u5185\u3068\u3057\u3066\u767B\u9332\u3055\u308C\u3066\u3044\u306A\u3051\u308C\u3070\u62D2\u5426\u3055\u308C\u307E\u3059\u3002"})]}),u(cn,{policies:p.confidentialityPolicies,promptKeys:p.promptTemplates.map(i=>i.template_key),isUpdating:t.state!=="idle",onChangePolicy:i=>{t.submit({intent:"update_confidentiality_policy",confidentialityLevel:i.confidentialityLevel,capability:i.capability,isEnabled:String(i.isEnabled),allowCloudProvider:String(i.allowCloudProvider),promptKey:i.promptKey??""},{method:"post"})}}),u(vn,{vocabulary:p.transcriptionVocabulary,references:p.transcriptionReferences,unresolvedUris:p.unresolvedReferenceUris,isUpdating:t.state!=="idle",onSaveTerm:i=>He({intent:"save_transcription_term",id:i.id===null?"":String(i.id),term:i.term,reading:i.reading??"",boost:i.boost===null?"":String(i.boost),domainKey:i.domainKey??"",isActive:String(i.isActive)},{method:"post"}),onSaveReference:i=>He({intent:"save_transcription_reference",id:i.id===null?"":String(i.id),fileUri:i.fileUri,domainKey:i.domainKey??"",isActive:String(i.isActive)},{method:"post"})}),u(hn,{parameters:p.systemParameters,onSaveParameter:(i,b)=>{t.submit({intent:"update_parameter",paramKey:i,paramValue:String(b)},{method:"post"})}})]}),I==="prompts"&&S("div",{role:"tabpanel",id:"panel-prompts","aria-labelledby":"tab-prompts",className:"space-y-6","data-testid":"tab-content-prompts",children:[u(Rn,{templates:p.promptTemplates,isSaving:t.state!=="idle",onSaveTemplate:i=>{t.submit({intent:"update_prompt",templateKey:i.template_key,payload:JSON.stringify({templateText:i.template_text,modelName:i.model_name,temperature:i.temperature,maxOutputTokens:i.max_output_tokens,responseSchema:i.response_schema,endpointBaseUrl:i.endpoint_base_url??null})},{method:"post"})}}),u(gn,{onSimulate:a})]}),I==="knowledge-authority"&&S("div",{role:"tabpanel",id:"panel-knowledge-authority","aria-labelledby":"tab-knowledge-authority",className:"space-y-6","data-testid":"tab-content-knowledge-authority",children:[u(pn,{host:v,canUpdate:p.canUpdateKnowledge,onPolicyConflictsChanged:me}),u(bn,{host:f,revision:ce})]}),I==="data-retention"&&S("div",{role:"tabpanel",id:"panel-data-retention","aria-labelledby":"tab-data-retention",className:"space-y-6","data-testid":"tab-content-data-retention",children:[k.overview.kind==="ready"?u("div",{ref:te,children:u(In,{overview:k.overview.value,canReadFindings:p.canReadIntegrityFindings,command:bt,commandFailure:Rt,onStartRun:(i,b)=>{n.submit(b===null?{intent:"start_integrity_run",mode:i}:{intent:"start_integrity_run",mode:i,basisRunUid:b},{method:"post"})},onCancelRun:i=>{n.submit({intent:"cancel_integrity_run",runUid:i},{method:"post"})},loadFindings:h,refreshFailure:k.overview.refreshFailure===null?null:k.overview.refreshFailure.reason,headingRef:G,onShowHistory:re,resync:{onResync:vt,onDismiss:()=>J(null),feedback:z},remedyDestinations:At})}):u(Dt,{title:En,testId:"audit-overview-failed",headingRef:G,children:u(Ht,{failure:k.overview,onReload:k.reload,forbiddenMessage:"\u76E3\u67FB\u306E\u6982\u6CC1\u3092\u95B2\u89A7\u3059\u308B\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002",failureMessage:Cn,rescueRef:te,testId:"audit-overview-failed-resource"})}),u(Sn,{host:f,knowledgeTabLabel:Te(_e),onOpenKnowledgeTab:()=>Re(_e.key)}),W!==null&&W.skipped.length>0&&S("div",{role:"status","data-testid":"retry-all-skipped",className:"rounded-lg border border-amber-200 border-solid bg-amber-50 p-4 text-amber-800 text-sm",children:[S("strong",{children:["\u4E00\u62EC\u518D\u8A66\u884C: ",W.requeued," \u4EF6\u3092\u518D\u6295\u5165\u3057\u3001",W.skipped.length," \u4EF6\u3092\u636E\u3048\u7F6E\u304D\u307E\u3057\u305F\u3002"]})," ","\u636E\u3048\u7F6E\u3044\u305F\u884C\u306F\u5931\u6557\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059\u3002",u("ul",{className:"mt-1.5 list-disc ps-5",children:W.skipped.map(i=>S("li",{"data-testid":`retry-all-skipped-${i.metadataId}`,children:["#",i.metadataId,": ",i.reason]},i.metadataId))})]}),S("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2",children:[u("section",{ref:Ke,tabIndex:-1,"aria-label":ze,"data-testid":"sync-status-region",children:u(un,{counts:p.syncCounts,totalFiles:p.totalFiles,failedItems:p.failedSyncItems,isRetrying:yt,onRetryItem:i=>{t.submit({intent:"retry_job",fileId:String(i)},{method:"post"})},onRetryAll:()=>{t.submit({intent:"retry_all_failed"},{method:"post"})}})}),u(on,{overview:p.qdrantCollections,health:{healthy:p.systemHealth.services.qdrant.status==="connected",latency_ms:p.systemHealth.services.qdrant.latencyMs}})]})]})]})]})})}var kn=new Set(Bt.options.filter(e=>e!=="SYNCED"&&!e.startsWith("FAILED"))),We=2e3;function Ln(e,t,n){let[r,o]=L(null),s=O(t);s.current=t;let a=O(e);a.current!==e&&(a.current=e,r!==null&&o(null));let d=(r??e)?.some(c=>kn.has(c.syncStatus))===!0;return Oe(()=>{if(!(n&&d&&s.current))return;let c=!1,m,g=async()=>{let h=s.current;if(h!==void 0){try{let f=await h();if(c)return;o(f)}catch{if(c)return}m=setTimeout(g,We)}};return m=setTimeout(g,We),()=>{c=!0,clearTimeout(m)}},[d,n]),r}function Ye(e,t){let n=O(t);n.current=t;let r=O(null),o=O(!1),s=O(null);if(e.state!=="idle"){o.current=!0;let l=e.formData?.get("intent");typeof l=="string"&&(r.current=l)}Oe(()=>{if(e.state!=="idle"||!o.current)return;o.current=!1,n.current(e.data,r.current);let l=s.current;if(l===null)return;s.current=null;let d=e.data?.error;typeof d=="string"?l.reject(new Error(d)):l.resolve()},[e.state,e.data]);let a=Z((...l)=>new Promise((d,c)=>{s.current?.reject(new Error("\u3053\u306E\u4FDD\u5B58\u306F\u5F8C\u7D9A\u306E\u9001\u4FE1\u306B\u7F6E\u304D\u63DB\u3048\u3089\u308C\u307E\u3057\u305F\u3002")),s.current={resolve:d,reject:c},e.submit(...l)}),[e]);return{settledIntent:e.state==="idle"?r.current:null,submitAndAwait:a}}function Fn(e){let t=new Set,n=[];for(let r of e)t.has(r.domainKey)||(t.add(r.domainKey),n.push({key:r.domainKey,label:r.domainLabel}));return n}function jn(e){return{strategyId:e.strategyId,label:`${e.domainKey} / ${e.variantKey}`,embeddingModel:e.embeddingModel}}function Un({runs:e,onOpenRun:t}){return S("section",{className:"rounded-xl border border-slate-200 border-solid bg-white p-6 shadow-sm","aria-labelledby":"pipeline-recent-runs-heading","data-testid":"pipeline-recent-runs",children:[u("h2",{id:"pipeline-recent-runs-heading",className:"font-bold text-base text-slate-900",children:"\u76F4\u8FD1\u306E\u5B9F\u884C"}),e.length===0?u("p",{className:"mt-4 text-[13px] text-slate-500","data-testid":"pipeline-recent-runs-empty",children:"\u8A18\u9332\u3055\u308C\u305F\u5B9F\u884C\u304C\u3042\u308A\u307E\u305B\u3093\u3002"}):u("div",{className:"relative mt-4 overflow-x-auto","data-testid":"pipeline-recent-runs-scroll",children:S("table",{className:"w-full text-left text-[13px]",children:[u("thead",{children:S("tr",{className:"whitespace-nowrap border-slate-200 border-b border-solid text-[11px] text-slate-500 uppercase",children:[u("th",{scope:"col",className:"px-3 py-2",children:"\u5B9F\u884C"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u6587\u66F8"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u7A2E\u985E"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u304D\u3063\u304B\u3051"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u8A66\u884C"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u72B6\u614B"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u6B62\u307E\u3063\u305F\u6BB5"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u958B\u59CB"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u7D42\u4E86"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u8981\u6C42\u8005"}),t!==void 0&&u("th",{scope:"col",className:"px-3 py-2",children:u("span",{className:"sr-only","data-testid":"pipeline-recent-runs-action-header",children:"\u64CD\u4F5C"})})]})}),u("tbody",{children:e.map(n=>{let r=an(n),o=tn[r];return S("tr",{className:"border-slate-100 border-b border-solid","data-testid":`pipeline-run-row-${n.id}`,"data-status":n.status,children:[S("td",{className:"whitespace-nowrap px-3 py-2 font-mono","data-testid":`pipeline-run-id-${n.id}`,children:["#",n.id]}),S("td",{className:"whitespace-nowrap px-3 py-2 font-mono","data-testid":`pipeline-run-metadata-${n.id}`,children:["#",n.metadataId]}),u("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-kind-${n.id}`,children:qt[n.documentKind]}),u("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-trigger-${n.id}`,"data-trigger":n.trigger,children:nn[n.trigger]}),u("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-attempt-${n.id}`,children:n.attempt}),u("td",{className:"px-3 py-2",children:u("span",{className:`inline-flex whitespace-nowrap rounded-full px-2 py-0.5 font-semibold text-[11px] ${o.className}`,"data-testid":`pipeline-run-status-${n.id}`,"data-status":n.status,"data-presentation":r,children:o.label})}),u("td",{className:"px-3 py-2","data-testid":`pipeline-run-failed-step-${n.id}`,children:n.failedStepKey===null?"\u2014":Qt[n.failedStepKey].label}),u("td",{className:"whitespace-nowrap px-3 py-2 text-slate-500","data-testid":`pipeline-run-started-${n.id}`,children:u(ln,{iso:n.startedAt,testId:`pipeline-run-started-value-${n.id}`})}),u("td",{className:"whitespace-nowrap px-3 py-2 text-slate-500","data-testid":`pipeline-run-finished-${n.id}`,children:u(Wt,{iso:n.finishedAt,testId:`pipeline-run-finished-value-${n.id}`})}),u("td",{className:"wrap-anywhere px-3 py-2","data-testid":`pipeline-run-requested-by-${n.id}`,children:n.requestedBy}),t!==void 0&&u("td",{className:"whitespace-nowrap px-3 py-2 text-right",children:u("button",{type:"button",onClick:()=>t(n),"aria-label":`\u5B9F\u884C #${n.id} (\u6587\u66F8 #${n.metadataId}) \u306E\u8A73\u7D30`,className:"whitespace-nowrap rounded-sm border border-slate-300 border-solid bg-white px-2 py-0.5 font-semibold text-[11px] text-slate-700 hover:bg-slate-50","data-testid":`pipeline-run-open-${n.id}`,children:"\u8A73\u7D30"})})]},n.id)})})]})})]})}var Ze={metadataId:null,runs:[],selectedRunId:null,isLoading:!1,failure:null};function Dn(e){for(let t of e)for(let n of t.steps){let r=n.provenance;if(r!==null){for(let[o,s]of Object.entries(r))if(typeof s=="string"&&!oe(s))return`\u51E6\u7406\u5C65\u6B74\u306E\u8A18\u9332\u306B\u8AAD\u3081\u306A\u3044\u6765\u6B74\u306E\u5024\u304C\u3042\u308A\u307E\u3059 (\u5B9F\u884C ${t.id} \u306E\u6BB5 ${n.sequence} \u306E ${o})\u3002`}}return null}function Mn(e){let[t,n]=L(Ze),[r,o]=L(0),s=O(0),a=O(null),l=le(()=>{if(e!==void 0)return(m,g)=>{s.current+=1;let h=s.current;a.current?.abort();let f=new AbortController;a.current=f,o(v=>v+1),n({metadataId:m,runs:[],selectedRunId:g,isLoading:!0,failure:null}),Y(()=>e(m,f.signal),v=>({ok:!1,status:null,reason:v})).then(v=>{if(s.current!==h)return;let y=v.ok?Dn(v.value):xn(v);if(!v.ok||y!==null){n({metadataId:m,runs:[],selectedRunId:g,isLoading:!1,failure:y});return}n({metadataId:m,runs:v.value,selectedRunId:g===null?Hn(v.value):g,isLoading:!1,failure:null})})}},[e]),d=Z(m=>{n(g=>({...g,selectedRunId:m}))},[]),c=Z(()=>{s.current+=1,a.current?.abort(),a.current=null,n(Ze)},[]);return{...t,openRequest:r,open:l,selectRun:d,close:c}}function Hn(e){return e.length===0?null:e[0].id}function $n(e){let t=An(),n=Ge(),r=Ge(),o=e.data??t,s=e.fetcher??n,a=e.integrityFetcher??r;return o?u(tt,{...e,data:o,fetcher:s,integrityFetcher:a}):u("div",{className:"p-8 text-center text-slate-500","data-testid":"storage-admin-loading",children:"\u30C7\u30FC\u30BF\u8AAD\u307F\u8FBC\u307F\u4E2D..."})}function nt(e){return e.data?u(tt,{...e,data:e.data,fetcher:e.fetcher??Je,integrityFetcher:e.integrityFetcher??Je}):u($n,{...e})}import{AuthzDeniedError as ot}from"@aiquants/authz-core";import{formatCount as Jn}from"@aiquants/console-ui/core";import{assertSystemParameterInRange as Wn,INTEGRITY_COMMAND_CODES as Yn,IntegrityAuditOverviewSchema as Zn,IntegrityCommandFailureSchema as Xn,IntegrityCommandReplySchema as er,IntegrityRunModeSchema as lt,integrityCommandFailureCodeOf as tr,isEnrichmentStageKey as nr,PipelineRunSummarySchema as rr,PipelineStepMetricSchema as sr}from"@aiquants/enrichment-core";import{CLOUD_CAPABLE_CAPABILITIES as ir,ConfidentialityLevelSchema as Fe,GovernedCapabilitySchema as ar}from"@aiquants/governance-core";import{z as w}from"zod";var ke=3e3;function j(e){return Math.round(performance.now()-e)}function N(e){return typeof e=="string"&&oe(e)?e:null}function F(e){let t=globalThis.process;return t===void 0?void 0:t.env[e]}function ue(e,t){let n=e?.trim();if(!n)throw new Error(`${t} is not configured; this probe will not guess an endpoint to send credentials to.`);return n}function rt(e,t,n){let r=e??(t?.trim()?Number(t):Number.NaN);if(!Number.isInteger(r)||r<=0||r>65535)throw new Error(`${n} is not configured with a valid port; this probe will not guess one.`);return r}function st(e,t){if(e!==void 0)return e;let n=t?.trim().toLowerCase();if(!(n===void 0||n===""))return n==="1"||n==="true"||n==="yes"||n==="on"}function it(e){let t=e.trim().split("://",1)[0]?.toLowerCase();if(t&&e.includes("://"))return t.endsWith("s")||t.includes("+s")}function Kn(e){let n=e.split("://").slice(-1)[0].split("/",1)[0],r=n.split(":").pop();if(!r||r===n)return;let o=Number(r);return Number.isInteger(o)&&o>0&&o<=65535?o:void 0}async function xe(e,t){let n;try{return await Promise.race([e,new Promise((r,o)=>{n=setTimeout(()=>o(new Error(`Probe timed out after ${t}ms`)),t)})])}finally{clearTimeout(n)}}async function qn(e){let t=e?.qdrantApiKey??F("QDRANT_API_KEY")??"",n=e?.timeoutMs??ke,r=performance.now(),o="";try{o=ue(e?.qdrantUrl??F("QDRANT_URL"),"QDRANT_URL");let s={};t&&(s["api-key"]=t);let[a,l]=await Promise.all([fetch(`${o}/`,{headers:s,signal:AbortSignal.timeout(n)}),fetch(`${o}/collections`,{headers:s,signal:AbortSignal.timeout(n)})]);if(!a.ok)throw new Error(`HTTP ${a.status}: ${a.statusText}`);if(!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText} (/collections)`);let d=await a.json(),c=j(r),g=(await l.json()).result?.collections?.length??0;return{serviceName:"Qdrant",category:"vector",status:"connected",version:N(d.version),endpoint:o,latencyMs:c,details:{engine:N(d.title),collectionsCount:g,restPort:Kn(o)??null,tls:it(o)??null}}}catch(s){let a=j(r),l=s instanceof Error?s.message:String(s);return{serviceName:"Qdrant",category:"vector",status:"error",version:null,endpoint:o,latencyMs:a,details:{},errorMessage:l}}}async function Bn(e){let t=e?.timeoutMs??ke,n=performance.now(),r=N(e?.neo4jBoltUri??F("NEO4J_URI")),o=r===null?"":r;try{let s=e?.graphReader;if(!s)throw new Error("Graph reader not configured");let a=e?.tenantId,[l,d]=await Promise.all([xe(s("CALL dbms.components() YIELD versions, edition RETURN versions[0] AS version, edition",{}),t),xe(a?s("MATCH (n {tenantId: $tenantId}) RETURN count(n) AS node_count",{tenantId:a}):s("RETURN null AS node_count",{}),t)]);if(!l.ok)throw new Error(l.reason);if(!d.ok)throw new Error(d.reason);let[c,m]=l.rows[0]??[],g=d.rows[0]?.[0],h=j(n);return{serviceName:"Neo4j",category:"graph",status:"connected",version:N(c),endpoint:o,latencyMs:h,details:{edition:N(m),boltUri:r,nodeCount:typeof g=="number"?g:null,tls:r===null?null:it(r)??null}}}catch(s){let a=j(n),l=s instanceof Error?s.message:String(s);return{serviceName:"Neo4j",category:"graph",status:"error",version:null,endpoint:o,latencyMs:a,details:{},errorMessage:l}}}async function Vn(e){let t=performance.now(),n="",r=st(e?.redisTls,F("REDIS_TLS")),o=Number.NaN;try{let s=e?.redisClient;if(!s)throw new Error("Redis client not configured");let a=ue(e?.redisHost??F("REDIS_HOST"),"REDIS_HOST");o=rt(e?.redisPort,F("REDIS_PORT"),"REDIS_PORT"),n=`${r===!1?"redis":"rediss"}://${a}:${o}`,await s.ping();let l=await s.info("server"),d=N(l.match(/redis_version:([^\r\n]+)/)?.[1]),c=null;if(typeof s.dbSize=="function")try{c=await s.dbSize()}catch{c=null}let m=j(t);return{serviceName:"Redis",category:"cache",status:"connected",version:d,endpoint:n,latencyMs:m,details:{totalKeys:c,port:o,tls:r??null,database:0}}}catch(s){let a=j(t),l=s instanceof Error?s.message:String(s);return{serviceName:"Redis",category:"cache",status:"error",version:null,endpoint:n,latencyMs:a,details:{},errorMessage:l}}}function Gn(e){let t=e.match(/Microsoft SQL Server \d+ \([^)]+\)/);return N(t===null?e.substring(0,30):t[0].replace("Microsoft SQL Server ",""))}async function Qn(e){let t=performance.now(),n="",r=st(e?.sqlServerTls,F("SQL_SERVER_TLS")),o=Number.NaN;try{let s=e?.sqlServerExecute;if(!s)throw new Error("SQL Server executor not configured");let a=ue(e?.sqlServerHost??F("SQL_SERVER_HOST"),"SQL_SERVER_HOST");o=rt(e?.sqlServerPort,F("SQL_SERVER_PORT"),"SQL_SERVER_PORT"),n=`${a}:${o}`;let l=await s(),d=N(l.db_name),c=N(l.version),m=c===null?null:N(c.split(`
2
- `)[0]),g=m===null?null:Gn(m),h=j(t);return{serviceName:"SQL Server",category:"database",status:"connected",version:g,endpoint:n,latencyMs:h,details:{database:d,port:o,tls:r??null,fullVersion:m}}}catch(s){let a=j(t),l=s instanceof Error?s.message:String(s);return{serviceName:"SQL Server",category:"database",status:"error",version:null,endpoint:n,latencyMs:a,details:{},errorMessage:l}}}async function zn(e){let t=e?.timeoutMs??ke,n=performance.now(),r="";try{r=ue(e?.backendApiHost??F("BACKEND_API_HOST"),"BACKEND_API_HOST");let o=await fetch(`${r}/openapi.json`,{signal:AbortSignal.timeout(t)});if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);let s=await o.json(),a=Object.keys(s.paths??{}).length,l=j(n);return{serviceName:"AI Quant API",category:"api",status:"connected",version:N(s.info?.version),endpoint:r,latencyMs:l,details:{title:N(s.info?.title),endpointsCount:a}}}catch(o){let s=j(n),a=o instanceof Error?o.message:String(o);return{serviceName:"AI Quant API",category:"api",status:"error",version:null,endpoint:r,latencyMs:s,details:{},errorMessage:a}}}async function at(e){let[t,n,r,o,s]=await Promise.all([qn(e),Bn(e),Vn(e),Qn(e),zn(e)]),a=t.status==="connected"&&n.status==="connected"&&r.status==="connected"&&o.status==="connected"&&s.status==="connected";return{services:{qdrant:t,neo4j:n,redis:r,sqlServer:o,quantsApi:s},allHealthy:a,checkedAt:new Date().toISOString()}}var or=w.object({templateText:w.string(),modelName:w.string(),temperature:w.number(),maxOutputTokens:w.number(),responseSchema:w.union([w.record(w.string(),w.unknown()),w.string(),w.null()]).optional(),endpointBaseUrl:w.string().nullable()}).strict(),lr=w.discriminatedUnion("mode",[w.object({mode:lt.extract(["SCAN"]),basisRunUid:w.null()}).strict(),w.object({mode:lt.extract(["REPAIR"]),basisRunUid:w.string().uuid()}).strict()]),ur=w.object({runUid:w.string().uuid()}).strict();function dt(e){return e==="start_integrity_run"?"start":e==="cancel_integrity_run"?"cancel":null}function V(e,t){return e.issues.map(n=>`${n.path.length===0?t:n.path.join(".")}: ${n.message}`).join("; ")}function dr(e,t){if(e==="bool")return t==="true"||t==="false"?null:"paramValue must be 'true' or 'false' for a bool parameter";if(e==="int")return/^[+-]?\d+$/.test(t)&&Number.isSafeInteger(Number(t))?null:"paramValue must be a safe integer for an int parameter";if(e==="float")return t.trim()!==""&&Number.isFinite(Number(t))?null:"paramValue must be a finite number for a float parameter";if(e==="json")try{return JSON.parse(t),null}catch{return"paramValue must be valid JSON for a json parameter"}return null}function cr(e){let t=rr.array().safeParse(e);if(!t.success)throw new Error(`getRecentPipelineRuns answered something that is not a run summary: ${V(t.error,"getRecentPipelineRuns")}`);return t.data}function pr(e){let t=sr.array().safeParse(e);if(!t.success)throw new Error(`getPipelineStepMetrics answered something that is not a step metric: ${V(t.error,"getPipelineStepMetrics")}`);let n=new Set;for(let r of t.data){let o=`${r.documentKind}/${r.stepKey}`;if(n.has(o))throw new Error(`getPipelineStepMetrics answered more than one metric for (documentKind, stepKey) = (${r.documentKind}, ${r.stepKey})`);n.add(o)}return t.data}function mr(e){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`pipelineStepMetricWindow must be a positive safe integer, got ${String(e)}`);return e}async function gr(e,t){let n;try{n=await e.readIntegrityAuditOverview(t)}catch(o){return{ok:!1,status:null,reason:o instanceof Error?o.message:String(o)}}let r=Zn.safeParse(n);return r.success?{ok:!0,value:r.data}:{ok:!1,status:null,reason:`readIntegrityAuditOverview answered something that is not an audit overview: ${V(r.error,"readIntegrityAuditOverview")}`}}function yr(e){return!Array.isArray(e)||e.length===0?"orderedRuleIds must be a non-empty array of rule ids":e.every(t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>0)?new Set(e).size!==e.length?"orderedRuleIds must not name a rule twice":null:"orderedRuleIds must contain positive integers only"}function ct(e){let{store:t,healthProbeOptions:n,resourceKey:r="storage_admin",requireUser:o,requirePermission:s,resolveTenantId:a,authorizeIngest:l,canReadIntegrityFindings:d,canUpdateKnowledge:c}=e;async function m(h){let{request:f}=h;if(!await o(f))throw new Response("\u8A8D\u8A3C\u304C\u5FC5\u8981\u3067\u3059\u3002",{status:401});try{await s(f,{resourceKey:r,action:"read"})}catch(se){throw se instanceof ot?new Response("\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002",{status:403}):se}let y=await a(f),M=mr(t.pipelineStepMetricWindow),[U,T,_]=await Promise.all([t.getFeatureFlags(y),t.getSystemParameters(y),t.getSyncCounts(y)]),E={featureFlags:U,systemParameters:T,syncCounts:_},[H,$,K,C,I,x,ee,k,G,te,ce,pe,me,p,q,ge,ne,ye,A,B,re]=await Promise.all([t.getConfidentialityPolicies(y),t.getTranscriptionVocabulary(y),t.getTranscriptionReferences(y),t.getUnresolvedReferenceUris(y),t.getPoliciesMissingDestination(y),t.getPromptTemplates(y),t.getClassificationRules(y),t.getFailedSyncItems(y),t.getGraphSchema(y),gr(t,y),d(f),c(f),t.getUnresolvedEntities(y),t.getQdrantCollections(y),at({...n,tenantId:y}),t.getRecentIngestItems(y),t.getOntologyStatus(y,E),t.getEnrichmentStrategies(y),t.getStrategyVariants(y),t.getPipelineStepMetrics(y),t.getRecentPipelineRuns(y)]),fe=t.getCircuitBreakerStatus();return{tenantId:y,featureFlags:E.featureFlags,confidentialityPolicies:H,transcriptionVocabulary:$,transcriptionReferences:K,unresolvedReferenceUris:C,policiesMissingDestination:I,systemParameters:E.systemParameters,promptTemplates:x,classificationRules:ee,classificationRuleConsumer:t.classificationRuleConsumer??null,syncCounts:E.syncCounts.counts,totalFiles:E.syncCounts.total,failedSyncItems:k,circuitBreakerStatus:fe,pipelineStepMetrics:pr(B),pipelineStepMetricWindow:M,recentPipelineRuns:cr(re),displayTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,graphSchema:G,enrichmentStrategies:ye,strategyVariants:A,integrityAudit:te,canReadIntegrityFindings:ce,canUpdateKnowledge:pe,unresolvedEntities:me,qdrantCollections:p,systemHealth:q,recentIngestItems:ge,ontologyStatus:ne}}async function g(h){let{request:f}=h,v=await o(f);if(!v)return Response.json({error:"\u8A8D\u8A3C\u304C\u5FC5\u8981\u3067\u3059\u3002"},{status:401});if(v.email.trim()==="")return Response.json({error:"\u64CD\u4F5C\u8005\u3092\u7279\u5B9A\u3067\u304D\u306A\u3044\u305F\u3081\u8A2D\u5B9A\u3092\u5909\u66F4\u3067\u304D\u307E\u305B\u3093\u3002"},{status:403});if(v.accessToken==="")throw new Error("requireUser resolved an operator whose accessToken is an empty string; answer null when the session holds no token the upstream services accept");let y=v.email,M=v.accessToken===null?void 0:v.accessToken;try{await s(f,{resourceKey:r,action:"update"})}catch(C){if(C instanceof ot)return await Rr(f);throw C}let U=await a(f),T=await f.formData(),_=String(T.get("intent")??"");if(_==="refresh_health")return Response.json({success:!0,refreshed:!0});let E=await br(t,U,_,T,y);if(E)return E;let H=await Sr(t,U,_,T,y,M);if(H)return H;let $=await hr(t,U,_,T,M,()=>d(f));if($)return $;if(_==="resolve_entity"){let C=String(T.get("entityId")??""),I=String(T.get("action")??"");if(!C||I!=="merge"&&I!=="promote")return Response.json({error:"Valid entityId and action ('merge' | 'promote') are required"},{status:400});try{return await t.resolveEntity(U,C,I),Response.json({success:!0,entityId:C,action:I})}catch(x){return Response.json({error:x instanceof Error?x.message:String(x)},{status:400})}}let K=await wr(t,U,_,T,y,f,l,M);return K||Response.json({error:`Unknown intent: ${_}`},{status:400})}return{loader:m,action:g}}function Le(e){let t=String(e??"").trim();return t===""?null:t}function de(e){let t=String(e??"").trim();if(t==="")return null;let n=Number(t);if(!(!Number.isSafeInteger(n)||n<=0))return n}function fr(e){let t=String(e??"").trim();if(t==="")return null;let n=Number(t);if(!(!Number.isFinite(n)||n<=0))return n}async function br(e,t,n,r,o){if(n==="update_enrichment_strategy"){let s=String(r.get("stage")??"");if(!nr(s))return Response.json({error:"stage must be a canonical enrichment stage key"},{status:400});let a=de(r.get("strategyId")),l=de(r.get("domainId"));if(a==null||l===void 0||l===null)return Response.json({error:"strategyId and domainId must be positive integers naming existing rows"},{status:400});let d=String(r.get("enabled")??"")==="true";try{await e.updateEnrichmentStrategy(t,{strategyId:a,domainId:l,stage:s,enabled:d},o)}catch(c){return Response.json({error:c instanceof Error?c.message:"\u53D6\u308A\u8FBC\u307F\u6226\u7565\u3092\u66F4\u65B0\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},{status:400})}return Response.json({success:!0,strategyId:a,domainId:l,stage:s,enabled:d})}if(n==="toggle_flag"){let s=String(r.get("flagKey")??""),a=String(r.get("enabled")??"")==="true";if(!s)return Response.json({error:"flagKey is required"},{status:400});let l=await e.getFeatureFlags(t);return Object.hasOwn(l,s)?(await e.toggleFeatureFlag(t,s,a,o),Response.json({success:!0,flagKey:s,enabled:a})):Response.json({error:`flagKey names no feature flag of this tenant: ${s}`},{status:400})}if(n==="update_confidentiality_policy"){let s=String(r.get("confidentialityLevel")??""),a=String(r.get("capability")??"");if(!(Fe.safeParse(s).success&&ar.safeParse(a).success))return Response.json({error:"confidentialityLevel and capability must be canonical values"},{status:400});let l=String(r.get("allowCloudProvider")??"")==="true";if(l&&!ir.includes(a))return Response.json({error:`${a} sends nothing outside the deployment, so it has no cloud permission to grant`},{status:400});let d=String(r.get("promptKey")??"");return await e.updateConfidentialityPolicy(t,{confidentialityLevel:s,capability:a,isEnabled:String(r.get("isEnabled")??"")==="true",allowCloudProvider:l,promptKey:d===""?null:d},o),Response.json({success:!0,confidentialityLevel:s,capability:a})}if(n==="save_transcription_term"){let s=String(r.get("term")??"").trim();if(!s)return Response.json({error:"term is required"},{status:400});let a=fr(r.get("boost"));if(a===void 0)return Response.json({error:"boost must be a number greater than zero, or absent to let the service decide"},{status:400});let l=de(r.get("id"));if(l===void 0)return Response.json({error:"id must be a positive integer naming an existing row, or absent for a new one"},{status:400});try{await e.saveTranscriptionTerm(t,{id:l,term:s,reading:Le(r.get("reading")),boost:a,domainKey:Le(r.get("domainKey")),isActive:String(r.get("isActive")??"true")==="true"},o)}catch(d){return Response.json({error:d instanceof Error?d.message:"\u8A9E\u5F59\u3092\u4FDD\u5B58\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},{status:400})}return Response.json({success:!0,term:s})}if(n==="save_transcription_reference"){let s=String(r.get("fileUri")??"").trim();if(!s)return Response.json({error:"fileUri is required"},{status:400});let a=de(r.get("id"));if(a===void 0)return Response.json({error:"id must be a positive integer naming an existing row, or absent for a new one"},{status:400});try{await e.saveTranscriptionReference(t,{id:a,fileUri:s,domainKey:Le(r.get("domainKey")),isActive:String(r.get("isActive")??"true")==="true"},o)}catch(l){return Response.json({error:l instanceof Error?l.message:"\u53C2\u7167\u8CC7\u6599\u3092\u4FDD\u5B58\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},{status:400})}return Response.json({success:!0,fileUri:s})}if(n==="update_parameter"){let s=String(r.get("paramKey")??""),a=String(r.get("paramValue")??"");if(!s)return Response.json({error:"paramKey is required"},{status:400});let l=(await e.getSystemParameters(t)).find(c=>c.key===s);if(l===void 0)return Response.json({error:`paramKey names no parameter of this tenant: ${s}`},{status:400});let d=dr(l.data_type,a);if(d!==null)return Response.json({error:d},{status:400});try{Wn(s,Number(a))}catch(c){return Response.json({error:c.message},{status:400})}return await e.updateSystemParameter(t,s,a,o),Response.json({success:!0,paramKey:s,paramValue:a})}if(n==="update_prompt"){let s=String(r.get("templateKey")??""),a=String(r.get("payload")??"{}"),l;try{l=JSON.parse(a)}catch{return Response.json({error:"Invalid JSON payload"},{status:400})}if(!s)return Response.json({error:"templateKey is required"},{status:400});let d=or.safeParse(l);if(!d.success)return Response.json({error:`payload does not carry a prompt template update: ${V(d.error,"payload")}`},{status:400});let c=d.data;try{return await e.updatePromptTemplate(t,s,c,o),Response.json({success:!0,templateKey:s})}catch(m){return Response.json({error:m instanceof Error?m.message:String(m)},{status:400})}}if(n==="reorder_rules"){let s=String(r.get("orderedRuleIds")??"[]"),a;try{a=JSON.parse(s)}catch{return Response.json({error:"Invalid orderedRuleIds JSON"},{status:400})}let l=yr(a);if(l!==null)return Response.json({error:l},{status:400});let d=a;return await e.reorderClassificationRules(t,d,o),Response.json({success:!0,orderedRuleIds:d})}return null}async function Sr(e,t,n,r,o,s){if(n==="retry_job"){let a=String(r.get("fileId")??"");if(!a)return Response.json({error:"fileId is required"},{status:400});try{return await e.retrySyncItem(t,a,o,s),Response.json({success:!0,fileId:a})}catch(l){return Response.json({error:l instanceof Error?l.message:String(l)},{status:400})}}if(n==="retry_all_failed")try{let{requeued:a,skipped:l}=await e.retryAllFailedSyncItems(t,o,s);return Response.json({success:!0,requeued:a,skipped:l})}catch(a){return Response.json({error:a instanceof Error?a.message:String(a)},{status:400})}return null}function X(e,t,n){let r=Xn.parse({command:e,code:t,status:n}),o=Yn.find(s=>s.code===r.code);return Response.json({failure:r},{status:o===void 0?502:o.status})}async function Rr(e){let t=await e.formData().catch(()=>null),n=t===null?null:dt(t.get("intent"));return n===null?Response.json({error:"\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002"},{status:403}):X(n,"FORBIDDEN",null)}async function ut(e,t){let n;try{n=er.parse(await t())}catch{return X(e,"UPSTREAM_FAILED",null)}return n.ok?Response.json({success:!0,runUid:n.runUid}):X(e,tr(e,n.status,n.errorCode),n.status)}async function hr(e,t,n,r,o,s){let a=dt(n);if(a==="start"){let l=lr.safeParse({mode:r.get("mode"),basisRunUid:r.get("basisRunUid")});if(!l.success)return Response.json({error:`start_integrity_run takes mode SCAN without basisRunUid, or mode REPAIR with basisRunUid (a UUID): ${V(l.error,"form")}`},{status:400});let{mode:d,basisRunUid:c}=l.data;return o===void 0||d==="REPAIR"&&!await s()?X(a,"FORBIDDEN",null):await ut(a,()=>e.startIntegrityRun(t,d,c,o))}if(a==="cancel"){let l=ur.safeParse({runUid:r.get("runUid")});return l.success?o===void 0?X(a,"FORBIDDEN",null):await ut(a,()=>e.cancelIntegrityRun(t,l.data.runUid,o)):Response.json({error:`cancel_integrity_run takes runUid (a UUID): ${V(l.error,"form")}`},{status:400})}return null}function vr(e){if(typeof e!="object"||e===null)return"payload must be an object";let t=e;if(typeof t.fileUri!="string"||t.fileUri.trim()==="")return"payload.fileUri is required";if(!Fe.safeParse(t.confidentialityLevel).success)return`payload.confidentialityLevel must be one of ${Fe.options.join(", ")}`;let r=t.departmentId;return r!=null&&(typeof r!="number"||!Number.isInteger(r))?"payload.departmentId must be an integer or null":null}function Ir(e){try{return Jn(e,ae),null}catch{return`inspectFileUri answered a fileSize that is not a byte count (a non-negative safe integer): ${String(e)}`}}async function wr(e,t,n,r,o,s,a,l){if(n==="ingest_document"){let d=String(r.get("payload")??"");if(!d)return Response.json({error:"payload is required"},{status:400});let c;try{c=JSON.parse(d)}catch{return Response.json({error:"Invalid JSON payload"},{status:400})}let m=vr(c);if(m)return Response.json({error:m},{status:400});let g=c,h=await a(s,g);if(h!==null)return Response.json({error:h},{status:403});try{let f=l===void 0?await e.ingestDocument(t,g,o):await e.ingestDocument(t,g,o,l);return Response.json({success:!0,result:f})}catch(f){return Response.json({error:f instanceof Error?f.message:String(f)},{status:400})}}if(n==="inspect_uri"){let d=String(r.get("fileUri")??"").trim();if(!d)return Response.json({error:"fileUri is required"},{status:400});if(!e.inspectFileUri)return Response.json({error:"inspectFileUri is not implemented"},{status:501});let c;try{c=l===void 0?await e.inspectFileUri(t,d):await e.inspectFileUri(t,d,l)}catch(g){return Response.json({error:g instanceof Error?g.message:String(g)},{status:400})}let m=Ir(c.fileSize);return m!==null?Response.json({error:m},{status:400}):Response.json({success:!0,inspection:c})}return null}function ss(e){let t=ct(e);return{loader:t.loader,action:t.action,View:nt,server:t}}export{nt as StorageAdminConsoleView,at as checkAllSystemHealth,zn as checkBackendApiHealth,Bn as checkNeo4jHealth,qn as checkQdrantHealth,Vn as checkRedisHealth,Qn as checkSqlServerHealth,ss as createStorageAdminApp,ct as createStorageAdminServer};
1
+ import{Card as Bt,ConsoleUiRoot as Gt,ResourceFailed as Qt,reasonAside as nt,resolveConsoleUiLabels as zt,useFocusRescue as Jt}from"@aiquants/console-ui";import{DOCUMENT_KIND_LABELS as Wt,EnrichmentSyncStatusSchema as Yt,GRAPH_INDEX_LIMITS as Zt,IntegrityCellResyncResultSchema as Xt,IntegrityRunModeSchema as en,PIPELINE_STEPS as tn}from"@aiquants/enrichment-core";import{DocumentIngestConsole as nn,EnrichmentStrategyBoard as rn,FinishedInstant as sn,InfrastructureHealthMonitor as on,MetadataSearchWorkbench as an,ModelComparisonWorkbench as ln,OntologyStatusCard as un,PIPELINE_RUN_STATUS_PRESENTATION as cn,PIPELINE_TRIGGER_LABELS as dn,PipelineFlowViewer as pn,PipelineRunInspector as mn,pipelineRunPresentationKey as gn,QdrantStorageCard as yn,RecordedInstant as fn,SyncStatusMonitor as Rn}from"@aiquants/enrichment-react";import{ClassificationRuleEditor as bn,ConfidentialityPolicyBoard as Sn,DocumentAuthorityRegistry as hn,FeatureFlagBoard as vn,GovernanceDryRunConsole as In,integrityFailureNeedsOverviewReread as wn,KnowledgeGraphExplorer as An,PolicyConflictQueue as Pn,PolicyConflictSummaryCard as Cn,PromptTemplateConsole as Nn,SystemParameterTable as En,TranscriptionAdaptationBoard as Tn,TriStoreIntegrityAudit as _n}from"@aiquants/governance-react";import{Fragment as On,useCallback as Z,useEffect as je,useMemo as ue,useRef as O,useState as E}from"react";import{useFetcher as Te,useLoaderData as xn,useRevalidator as kn,useSearchParams as Ln}from"react-router";var ae="ja-JP";var xt=/[^\s\x1c-\x1f\x85\ufeff]/;function le(e){return xt.test(e)}function Y(e,t){return new Promise(n=>n(e())).catch(n=>t(n instanceof Error?n.message:String(n)))}import{beginReload as kt,keepLastGood as Lt}from"@aiquants/console-ui/core";import{isStrictlyEarlier as Ft}from"@aiquants/enrichment-core";import{useCallback as Ie,useEffect as ze,useRef as Ae,useState as jt,useSyncExternalStore as Dt}from"react";var Ut=2e3,Mt=1e4;function we(e,t){return t.ok&&e.kind==="ready"&&Ft(t.value.readAt,e.value.readAt)?e:Lt(e,t)}var Ht=401;function $t(e){return e.kind==="failed"||e.refreshFailure!==null&&e.refreshFailure.status===Ht?null:e.value.active}function Je(e,t){let[n,r]=jt(()=>({loaded:e,overview:we({kind:"loading"},e)}));n.loaded!==e&&r({loaded:e,overview:we(n.overview,e)});let a=Ae(t);a.current=t;let s=Ae(null);ze(()=>()=>s.current?.abort(),[]);let o=Ie((d,p)=>Y(p,g=>({ok:!1,status:null,reason:g})).then(g=>{d.aborted||r(v=>({loaded:v.loaded,overview:we(v.overview,g)}))}),[]),l=Ie(()=>{let d=new AbortController;s.current=d,r(p=>({loaded:p.loaded,overview:kt(p.overview,"reload")})),o(d.signal,()=>a.current(d.signal))},[o]),c=Ie(d=>o(d,()=>a.current(d)),[o]);return{overview:n.overview,reload:l,poll:c}}function Kt(e){return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)}function qt(){return document.visibilityState==="visible"}function Vt(){return!0}function We(e,t,n){let r=Dt(Kt,qt,Vt),a=t&&r,s=Ae(a),o=e.kind==="ready",l=$t(e),c=l===null?null:l.run.runUid,d=l===null?!1:l.isStale;ze(()=>{let p=a&&!s.current;if(s.current=a,!a||c===null&&!(p&&o))return;let g=new AbortController,v=d?Mt:Ut,R,h=async()=>{await n(g.signal),!g.signal.aborted&&c!==null&&(R=setTimeout(h,v))};return R=setTimeout(h,p?0:v),()=>{g.abort(),clearTimeout(R)}},[a,o,c,d,n])}var Pe={columns:2,className:"grid-cols-2",spanClassNames:{1:"col-span-1",2:"col-span-2"}},Ce={columns:4,className:"@min-[41.5rem]:grid-cols-4",spanClassNames:{1:"@min-[41.5rem]:col-span-1",2:"@min-[41.5rem]:col-span-2",3:"@min-[41.5rem]:col-span-3",4:"@min-[41.5rem]:col-span-4"}},Ne={className:"@min-[82rem]:grid-flow-col @min-[82rem]:auto-cols-fr @min-[82rem]:grid-cols-none",lastTabClassName:"@min-[82rem]:col-auto"};function Ee(e,t){let n=t%e.columns,r=n===0?1:e.columns-n+1;return e.spanClassNames[r]}import{jsx as u,jsxs as S}from"react/jsx-runtime";var Ye="tab",ke={key:"knowledge-authority",phrases:["\u6A29\u5A01\u53F0\u5E33 & \u898F\u7A0B\u885D\u7A81"]},Le={key:"pipeline",phrases:["\u30D1\u30A4\u30D7\u30E9\u30A4\u30F3 & \u63A5\u7D9A\u72B6\u614B"]},Fe={key:"parameters",phrases:["\u30E2\u30C7\u30EB & \u30D1\u30E9\u30E1\u30FC\u30BF\u8A2D\u5B9A"]},Ze="\u30A8\u30F3\u30EA\u30C3\u30C1\u30E1\u30F3\u30C8\u540C\u671F\u30B9\u30C6\u30FC\u30BF\u30B9";function Fn(e,t){let n=e.settled+1,r=t?.error;if(r!==void 0)return{...e,settled:n,status:"refused",nextAfter:null,error:r};let a=Xt.safeParse(t?.cellResync);if(!a.success)return{...e,settled:n,status:"refused",nextAfter:null,error:"\u307E\u3068\u3081\u3066\u306E\u518D\u540C\u671F\u306E\u7B54\u3048\u306E\u5F62\u304C\u60F3\u5B9A\u3068\u7570\u306A\u308A\u307E\u3059\u3002\u958B\u767A\u62C5\u5F53\u306B\u9023\u7D61\u3057\u3066\u304F\u3060\u3055\u3044\u3002"};let{requeued:s,skipped:o,nextAfter:l}=a.data;return{settled:n,status:l===null?"done":"pending",requeued:e.requeued+s,skipped:[...e.skipped,...o],nextAfter:l,error:null}}var M=[{key:"search",phrases:["\u30E1\u30BF\u30C7\u30FC\u30BF\u691C\u7D22","\u30EF\u30FC\u30AF\u30D9\u30F3\u30C1"]},{key:"ingest",phrases:["\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8","\u53D6\u308A\u8FBC\u307F & \u30E1\u30BF\u751F\u6210"]},Le,{key:"knowledge-graph",phrases:["\u30CA\u30EC\u30C3\u30B8\u30B0\u30E9\u30D5","\u63A2\u7D22"]},Fe,{key:"prompts",phrases:["\u30D7\u30ED\u30F3\u30D7\u30C8 & \u30C9\u30E9\u30A4\u30E9\u30F3"]},ke,{key:"data-retention",phrases:["\u30C7\u30FC\u30BF\u4FDD\u6301 & \u6574\u5408\u6027\u76E3\u67FB"]}];function _e(e){return e.phrases.join("")}function jn(e){return e!==null&&M.some(t=>t.key===e)}var Dn="Tri-Store \u30C7\u30FC\u30BF\u6574\u5408\u6027\u76E3\u67FB";function Un(e){return`\u76E3\u67FB\u306E\u6982\u6CC1\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F${nt(e)}\u3002`}var Mn=zt("ja");function Hn(e){return Mn.failureSentence(e,"\u51E6\u7406\u5C65\u6B74\u3092\u95B2\u89A7\u3059\u308B\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002",t=>`\u51E6\u7406\u5C65\u6B74\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F${nt(t)}\u3002`)}var Oe={state:"idle",formData:null,data:null,submit:()=>Promise.resolve()};function rt({data:e,fetcher:t,integrityFetcher:n,inspectorFetcher:r,renderHeader:a,graphTraversal:s,onBrowseGraphNodes:o,onSimulateGovernance:l,onRefreshIngestQueue:c,onSearch:d,onLoadDocumentRuns:p,onCompareVariants:g,loadIntegrityOverview:v,loadIntegrityFindings:R,policyConflicts:h,documentAuthority:f}){let[U,x]=E(null),[A,P]=E(null),[k,$]=E(!1),K=ue(()=>{if(o!==void 0)return(i,y)=>{$(!0),Y(()=>o(i,y),b=>({ok:!1,reason:b})).then(b=>{$(!1),P(b.ok?null:b.reason),b.ok&&x(b.page)})}},[o]),[q,V]=Ln(),_=q.get(Ye),I=jn(_)?_:M[0].key,L=i=>{V(y=>{let b=new URLSearchParams(y);return b.set(Ye,i),b},{replace:!1,preventScrollReset:!0})},ee=Kn(e.recentIngestItems,c,I==="ingest"),F=Je(e.integrityAudit,v);We(F.overview,I==="data-retention",F.poll);let Q=O(null),te=Jt(()=>Q.current),[pe,me]=E(0),ge=Z(()=>me(i=>i+1),[]),m=ee===null?e:{...e,recentIngestItems:[...ee]},B=O({}),ye=Z(()=>B.current[I]??null,[I]),ne=ue(()=>qn(e.enrichmentStrategies),[e.enrichmentStrategies]),fe=ue(()=>e.strategyVariants.map(Vn),[e.strategyVariants]),C=Qn(p),G=C.open,re=G===void 0?void 0:i=>G(i,null),se=G===void 0?void 0:i=>G(i.metadataId,i.id),gt=(i,y)=>{let b=M.length-1,N;if(i.key==="ArrowRight"||i.key==="ArrowDown")N=y===b?0:y+1;else if(i.key==="ArrowLeft"||i.key==="ArrowUp")N=y===0?b:y-1;else if(i.key==="Home")N=0;else if(i.key==="End")N=b;else return;i.preventDefault();let oe=M[N].key;L(oe),B.current[oe]?.focus()},$e={...m.featureFlags};if(t.formData&&t.formData.get("intent")==="toggle_flag"){let i=String(t.formData.get("flagKey")??""),y=String(t.formData.get("enabled")??"")==="true";i&&($e[i]=y)}let yt=t.data&&"inspection"in t.data?t.data.inspection:void 0,z=t.state==="idle"?null:t.formData?.get("intent"),ft=z==="inspect_uri",Rt=z==="ingest_document",bt=z==="retry_job"||z==="retry_all_failed",St=z==="resolve_entity",Ke=n.state==="idle"?null:n.formData?.get("intent"),ht=Ke==="start_integrity_run"?{kind:"starting",mode:en.parse(n.formData?.get("mode"))}:Ke==="cancel_integrity_run"?{kind:"cancelling"}:{kind:"idle"},vt=kn(),[It,Re]=E(null),qe=I!=="data-retention";je(()=>{qe&&Re(null)},[qe]);let wt=i=>{let y=i?.failure;if(y===void 0){Re(null);return}Re(b=>({failure:y,occurrence:b===null?1:b.occurrence+1})),wn(y)&&vt.revalidate()},[J,be]=E(null),[ie,Se]=E(null),At=i=>{be({metadataId:i,intent:"retry_job",status:"pending",error:null}),r.submit({intent:"retry_job",fileId:String(i)},{method:"post"})},Pt=i=>{i.after===void 0&&Se({settled:0,status:"pending",requeued:0,skipped:[],nextAfter:null,error:null});let{after:y,...b}=i;r.submit(y===void 0?{intent:"resync_findings",...b}:{intent:"resync_findings",...b,after:String(y)},{method:"post"})},Ct=()=>{be(null),Se(null)},[Ve,he]=E("console"),[Nt,Et]=E(void 0),Tt=(i,y)=>{if(y==="retry_job"&&J!==null&&J.status==="pending"){let b=i?.error;be(b===void 0?{...J,status:"accepted",error:null}:{...J,status:"refused",error:b});return}if(y==="resync_findings"&&ie!==null&&ie.status==="pending"){Se(Fn(ie,i));return}Et(i?.error),he("inspector")},{settledIntent:_t,submitAndAwait:Be}=xe(t,()=>he("console"));xe(n,i=>{he("integrity"),wt(i)}),xe(r,Tt);let Ge=Ve==="inspector"?Nt:(Ve==="console"?t:n).data?.error,ve=i=>{L(i),B.current[i]?.focus()},Qe=O(null),Ot={strategies:{label:_e(Le),onOpen:()=>ve(Le.key),closesInspector:!0},projectionPolicy:{label:_e(Fe),onOpen:()=>ve(Fe.key),closesInspector:!0},failedSync:{label:Ze,onOpen:()=>Qe.current?.focus(),closesInspector:!1}},W=_t==="retry_all_failed"&&t.data?.skipped!==void 0&&t.data.requeued!==void 0?{requeued:t.data.requeued,skipped:t.data.skipped}:null;return u(Gt,{locale:"ja",formatLocale:ae,timeZone:m.displayTimeZone,testId:"storage-admin-console-ui",children:S("div",{className:"container mx-auto space-y-6 p-6 font-sans text-slate-900","data-testid":"storage-admin-console",children:[Ge&&u("div",{className:"rounded-lg border border-red-200 border-solid bg-red-50 p-4 font-medium text-red-700 text-sm shadow-sm",role:"alert","data-testid":"storage-admin-error-alert",children:Ge}),a?a({title:"\u30B9\u30C8\u30EC\u30FC\u30B8 AI \u30A8\u30F3\u30EA\u30C3\u30C1\u30E1\u30F3\u30C8 & \u30AC\u30D0\u30CA\u30F3\u30B9\u904B\u7528\u7BA1\u7406",tenantId:m.tenantId}):S("header",{className:"flex flex-col justify-between gap-2 border-slate-200 border-b border-solid pb-4 md:flex-row md:items-center",children:[S("div",{children:[u("h1",{className:"font-bold text-2xl tracking-tight",children:"\u30B9\u30C8\u30EC\u30FC\u30B8 AI \u30A8\u30F3\u30EA\u30C3\u30C1\u30E1\u30F3\u30C8 & \u30AC\u30D0\u30CA\u30F3\u30B9\u904B\u7528\u7BA1\u7406"}),S("p",{className:"mt-1 text-slate-500 text-sm",children:["\u30C6\u30CA\u30F3\u30C8: ",u("code",{className:"font-semibold text-slate-800",children:m.tenantId})," | \u5168\u30B7\u30B9\u30C6\u30E0\u72B6\u614B\u30FB\u30D1\u30E9\u30E1\u30FC\u30BF\u5236\u5FA1\u30FB\u6574\u5408\u6027\u76E3\u67FB"]})]}),u("div",{className:"flex items-center gap-2",children:S("button",{type:"button","data-testid":"header-health-status-button",onClick:()=>L("pipeline"),className:"inline-flex items-center gap-2 rounded-full border border-slate-200 border-solid bg-slate-50 px-3 py-1.5 font-medium text-slate-700 text-xs transition-colors hover:bg-slate-100",children:[u("span",{className:`h-2 w-2 rounded-full ${m.systemHealth.allHealthy?"bg-emerald-500":"bg-amber-500"}`}),S("span",{children:["\u5468\u8FBA\u6A5F\u80FD: ",m.systemHealth.allHealthy?"\u5168\u30B5\u30FC\u30D3\u30B9\u6B63\u5E38":"\u63A5\u7D9A\u8981\u78BA\u8A8D"]})]})})]}),S("div",{className:"w-full space-y-6",children:[u("div",{className:"@container w-full","data-testid":"storage-admin-tablist-frame",children:u("div",{className:`grid w-full ${Pe.className} ${Ce.className} ${Ne.className} gap-1 rounded-xl bg-slate-100 p-1`,role:"tablist","aria-label":"\u904B\u7528\u7BA1\u7406\u30B3\u30F3\u30BD\u30FC\u30EB\u306E\u753B\u9762",children:M.map((i,y)=>{let b=I===i.key;return u("button",{id:`tab-${i.key}`,type:"button",role:"tab",ref:N=>{B.current[i.key]=N},"aria-selected":b,"aria-controls":`panel-${i.key}`,tabIndex:b?0:-1,"data-testid":`tab-trigger-${i.key}`,onKeyDown:N=>gt(N,y),onClick:()=>L(i.key),className:`wrap-anywhere break-keep rounded-lg px-3 py-2.5 text-center font-medium text-sm transition-all ${y===M.length-1?`${Ee(Pe,M.length)} ${Ee(Ce,M.length)} ${Ne.lastTabClassName}`:""} ${b?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:bg-slate-200/50 hover:text-slate-900"}`,children:i.phrases.map((N,oe)=>S(On,{children:[oe>0&&u("wbr",{}),N]},N))},i.key)})})}),C.metadataId!==null&&u(mn,{metadataId:C.metadataId,runs:C.runs,selectedRunId:C.selectedRunId,onSelectRun:C.selectRun,isLoading:C.isLoading,failure:C.failure,onClose:C.close,openRequest:C.openRequest,returnFocusFallback:ye}),I==="search"&&S("div",{role:"tabpanel",id:"panel-search","aria-labelledby":"tab-search",className:"space-y-6","data-testid":"tab-content-search",children:[u(an,{tenantId:m.tenantId,onSearch:d,circuitBreakerStatus:m.circuitBreakerStatus}),g!==void 0&&u(ln,{variants:fe,onCompare:g})]}),I==="ingest"&&u("div",{role:"tabpanel",id:"panel-ingest","aria-labelledby":"tab-ingest",className:"space-y-6","data-testid":"tab-content-ingest",children:u(nn,{tenantId:m.tenantId,policies:m.confidentialityPolicies,domainOptions:ne,recentItems:m.recentIngestItems,inspectionResult:yt,isInspecting:ft,isSubmitting:Rt,onInspectUri:i=>{t.submit({intent:"inspect_uri",fileUri:i},{method:"post"})},onIngestDocument:i=>{t.submit({intent:"ingest_document",payload:JSON.stringify(i)},{method:"post"})},onRetryItem:i=>{t.submit({intent:"retry_job",fileId:String(i)},{method:"post"})},onShowHistory:re})}),I==="pipeline"&&S("div",{role:"tabpanel",id:"panel-pipeline","aria-labelledby":"tab-pipeline",className:"space-y-6","data-testid":"tab-content-pipeline",children:[u(pn,{featureFlags:m.featureFlags,metrics:m.pipelineStepMetrics,metricSampleWindow:m.pipelineStepMetricWindow}),u(Bn,{runs:m.recentPipelineRuns,onOpenRun:se}),u(rn,{strategies:m.enrichmentStrategies,featureFlags:m.featureFlags,isUpdating:t.state!=="idle",onToggleStage:(i,y,b)=>t.submit({intent:"update_enrichment_strategy",strategyId:String(i.id),domainId:String(i.domainId),stage:y,enabled:String(b)},{method:"post"})}),u(on,{health:m.systemHealth,isRefreshing:t.state!=="idle",onRefresh:()=>t.submit({intent:"refresh_health"},{method:"post"})})]}),I==="knowledge-graph"&&S("div",{role:"tabpanel",id:"panel-knowledge-graph","aria-labelledby":"tab-knowledge-graph",className:"space-y-6","data-testid":"tab-content-knowledge-graph",children:[u(un,{tenantId:m.tenantId,ontologyStatus:m.ontologyStatus}),u(An,{topologyMaxLabels:Zt.topologyLabels.default,schema:m.graphSchema,tenantId:m.tenantId,unresolvedEntities:m.unresolvedEntities,traversal:s,onBrowseLabel:K,nodeIndexPage:U,nodeIndexFailure:A,isNodeIndexLoading:k,isResolving:St,onResolveEntity:(i,y)=>{t.submit({intent:"resolve_entity",entityId:i,action:y},{method:"post"})}})]}),I==="parameters"&&S("div",{role:"tabpanel",id:"panel-parameters","aria-labelledby":"tab-parameters",className:"space-y-6","data-testid":"tab-content-parameters",children:[S("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2",children:[u(vn,{flags:$e,isUpdating:t.state!=="idle",onToggleFlag:(i,y)=>{t.submit({intent:"toggle_flag",flagKey:i,enabled:String(y)},{method:"post"})}}),u(bn,{rules:m.classificationRules,domainOptions:ne,consultedBy:m.classificationRuleConsumer,onReorderRules:i=>{t.submit({intent:"reorder_rules",orderedRuleIds:JSON.stringify(i)},{method:"post"})}})]}),m.policiesMissingDestination.length>0&&S("div",{"data-testid":"policies-missing-destination",role:"alert",style:{padding:"10px 12px",borderRadius:"6px",backgroundColor:"#fef2f2",color:"#b91c1c",fontSize:"12px"},children:[u("strong",{children:"\u6B21\u306E\u533A\u5206\u30FB\u6A5F\u80FD\u306F\u5B9F\u884C\u6642\u306B\u5931\u6557\u3057\u307E\u3059\u3002"})," \u53C2\u7167\u3059\u308B\u30D7\u30ED\u30F3\u30D7\u30C8\u884C\u306B\u5B9B\u5148\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002",u("ul",{style:{margin:"6px 0 0",paddingInlineStart:"18px"},children:m.policiesMissingDestination.map(i=>S("li",{"data-testid":`missing-destination-${i.confidentialityLevel}-${i.capability}`,children:[i.confidentialityLevel," / ",i.capability," \u2192 ",i.promptKey," (",i.modelProvider,") \u306E ",u("code",{children:"extra_params.base_url"})]},`${i.confidentialityLevel}:${i.capability}`))}),u("span",{style:{display:"block",marginTop:"4px",fontSize:"11px"},children:"\u5B9B\u5148\u3092\u8A2D\u5B9A\u3057\u3066\u3082\u3001\u305D\u306E\u30DB\u30B9\u30C8\u304C\u914D\u5099\u5185\u3068\u3057\u3066\u767B\u9332\u3055\u308C\u3066\u3044\u306A\u3051\u308C\u3070\u62D2\u5426\u3055\u308C\u307E\u3059\u3002"})]}),u(Sn,{policies:m.confidentialityPolicies,promptKeys:m.promptTemplates.map(i=>i.template_key),isUpdating:t.state!=="idle",onChangePolicy:i=>{t.submit({intent:"update_confidentiality_policy",confidentialityLevel:i.confidentialityLevel,capability:i.capability,isEnabled:String(i.isEnabled),allowCloudProvider:String(i.allowCloudProvider),promptKey:i.promptKey??""},{method:"post"})}}),u(Tn,{vocabulary:m.transcriptionVocabulary,references:m.transcriptionReferences,unresolvedUris:m.unresolvedReferenceUris,isUpdating:t.state!=="idle",onSaveTerm:i=>Be({intent:"save_transcription_term",id:i.id===null?"":String(i.id),term:i.term,reading:i.reading??"",boost:i.boost===null?"":String(i.boost),domainKey:i.domainKey??"",isActive:String(i.isActive)},{method:"post"}),onSaveReference:i=>Be({intent:"save_transcription_reference",id:i.id===null?"":String(i.id),fileUri:i.fileUri,domainKey:i.domainKey??"",isActive:String(i.isActive)},{method:"post"})}),u(En,{parameters:m.systemParameters,onSaveParameter:(i,y)=>{t.submit({intent:"update_parameter",paramKey:i,paramValue:String(y)},{method:"post"})}})]}),I==="prompts"&&S("div",{role:"tabpanel",id:"panel-prompts","aria-labelledby":"tab-prompts",className:"space-y-6","data-testid":"tab-content-prompts",children:[u(Nn,{templates:m.promptTemplates,isSaving:t.state!=="idle",onSaveTemplate:i=>{t.submit({intent:"update_prompt",templateKey:i.template_key,payload:JSON.stringify({templateText:i.template_text,modelName:i.model_name,temperature:i.temperature,maxOutputTokens:i.max_output_tokens,responseSchema:i.response_schema,endpointBaseUrl:i.endpoint_base_url??null})},{method:"post"})}}),u(In,{onSimulate:l})]}),I==="knowledge-authority"&&S("div",{role:"tabpanel",id:"panel-knowledge-authority","aria-labelledby":"tab-knowledge-authority",className:"space-y-6","data-testid":"tab-content-knowledge-authority",children:[u(hn,{host:f,canUpdate:m.canUpdateKnowledge,onPolicyConflictsChanged:ge}),u(Pn,{host:h,revision:pe})]}),I==="data-retention"&&S("div",{role:"tabpanel",id:"panel-data-retention","aria-labelledby":"tab-data-retention",className:"space-y-6","data-testid":"tab-content-data-retention",children:[F.overview.kind==="ready"?u("div",{ref:te,children:u(_n,{overview:F.overview.value,canReadFindings:m.canReadIntegrityFindings,command:ht,commandFailure:It,onStartRun:(i,y)=>{n.submit(y===null?{intent:"start_integrity_run",mode:i}:{intent:"start_integrity_run",mode:i,basisRunUid:y},{method:"post"})},onCancelRun:i=>{n.submit({intent:"cancel_integrity_run",runUid:i},{method:"post"})},loadFindings:R,refreshFailure:F.overview.refreshFailure===null?null:F.overview.refreshFailure.reason,headingRef:Q,onShowHistory:re,resync:{onResync:At,onDismiss:Ct,feedback:J,sending:r.state!=="idle",cellResync:{onResyncCell:Pt,feedback:ie}},remedyDestinations:Ot})}):u(Bt,{title:Dn,testId:"audit-overview-failed",headingRef:Q,children:u(Qt,{failure:F.overview,onReload:F.reload,forbiddenMessage:"\u76E3\u67FB\u306E\u6982\u6CC1\u3092\u95B2\u89A7\u3059\u308B\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002",failureMessage:Un,rescueRef:te,testId:"audit-overview-failed-resource"})}),u(Cn,{host:h,knowledgeTabLabel:_e(ke),onOpenKnowledgeTab:()=>ve(ke.key)}),W!==null&&W.skipped.length>0&&S("div",{role:"status","data-testid":"retry-all-skipped",className:"rounded-lg border border-amber-200 border-solid bg-amber-50 p-4 text-amber-800 text-sm",children:[S("strong",{children:["\u4E00\u62EC\u518D\u8A66\u884C: ",W.requeued," \u4EF6\u3092\u518D\u6295\u5165\u3057\u3001",W.skipped.length," \u4EF6\u3092\u636E\u3048\u7F6E\u304D\u307E\u3057\u305F\u3002"]})," ","\u636E\u3048\u7F6E\u3044\u305F\u884C\u306F\u5931\u6557\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059\u3002",u("ul",{className:"mt-1.5 list-disc ps-5",children:W.skipped.map(i=>S("li",{"data-testid":`retry-all-skipped-${i.metadataId}`,children:["#",i.metadataId,": ",i.reason]},i.metadataId))})]}),S("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2",children:[u("section",{ref:Qe,tabIndex:-1,"aria-label":Ze,"data-testid":"sync-status-region",children:u(Rn,{counts:m.syncCounts,totalFiles:m.totalFiles,failedItems:m.failedSyncItems,isRetrying:bt,onRetryItem:i=>{t.submit({intent:"retry_job",fileId:String(i)},{method:"post"})},onRetryAll:()=>{t.submit({intent:"retry_all_failed"},{method:"post"})}})}),u(yn,{overview:m.qdrantCollections,health:{healthy:m.systemHealth.services.qdrant.status==="connected",latency_ms:m.systemHealth.services.qdrant.latencyMs}})]})]})]})]})})}var $n=new Set(Yt.options.filter(e=>e!=="SYNCED"&&!e.startsWith("FAILED"))),Xe=2e3;function Kn(e,t,n){let[r,a]=E(null),s=O(t);s.current=t;let o=O(e);o.current!==e&&(o.current=e,r!==null&&a(null));let c=(r??e)?.some(d=>$n.has(d.syncStatus))===!0;return je(()=>{if(!(n&&c&&s.current))return;let d=!1,p,g=async()=>{let v=s.current;if(v!==void 0){try{let R=await v();if(d)return;a(R)}catch{if(d)return}p=setTimeout(g,Xe)}};return p=setTimeout(g,Xe),()=>{d=!0,clearTimeout(p)}},[c,n]),r}function xe(e,t){let n=O(t);n.current=t;let r=O(null),a=O(!1),s=O(null);if(e.state!=="idle"){a.current=!0;let l=e.formData?.get("intent");typeof l=="string"&&(r.current=l)}je(()=>{if(e.state!=="idle"||!a.current)return;a.current=!1,n.current(e.data,r.current);let l=s.current;if(l===null)return;s.current=null;let c=e.data?.error;typeof c=="string"?l.reject(new Error(c)):l.resolve()},[e.state,e.data]);let o=Z((...l)=>new Promise((c,d)=>{s.current?.reject(new Error("\u3053\u306E\u4FDD\u5B58\u306F\u5F8C\u7D9A\u306E\u9001\u4FE1\u306B\u7F6E\u304D\u63DB\u3048\u3089\u308C\u307E\u3057\u305F\u3002")),s.current={resolve:c,reject:d},e.submit(...l)}),[e]);return{settledIntent:e.state==="idle"?r.current:null,submitAndAwait:o}}function qn(e){let t=new Set,n=[];for(let r of e)t.has(r.domainKey)||(t.add(r.domainKey),n.push({key:r.domainKey,label:r.domainLabel}));return n}function Vn(e){return{strategyId:e.strategyId,label:`${e.domainKey} / ${e.variantKey}`,embeddingModel:e.embeddingModel}}function Bn({runs:e,onOpenRun:t}){return S("section",{className:"rounded-xl border border-slate-200 border-solid bg-white p-6 shadow-sm","aria-labelledby":"pipeline-recent-runs-heading","data-testid":"pipeline-recent-runs",children:[u("h2",{id:"pipeline-recent-runs-heading",className:"font-bold text-base text-slate-900",children:"\u76F4\u8FD1\u306E\u5B9F\u884C"}),e.length===0?u("p",{className:"mt-4 text-[13px] text-slate-500","data-testid":"pipeline-recent-runs-empty",children:"\u8A18\u9332\u3055\u308C\u305F\u5B9F\u884C\u304C\u3042\u308A\u307E\u305B\u3093\u3002"}):u("div",{className:"relative mt-4 overflow-x-auto","data-testid":"pipeline-recent-runs-scroll",children:S("table",{className:"w-full text-left text-[13px]",children:[u("thead",{children:S("tr",{className:"whitespace-nowrap border-slate-200 border-b border-solid text-[11px] text-slate-500 uppercase",children:[u("th",{scope:"col",className:"px-3 py-2",children:"\u5B9F\u884C"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u6587\u66F8"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u7A2E\u985E"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u304D\u3063\u304B\u3051"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u8A66\u884C"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u72B6\u614B"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u6B62\u307E\u3063\u305F\u6BB5"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u958B\u59CB"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u7D42\u4E86"}),u("th",{scope:"col",className:"px-3 py-2",children:"\u8981\u6C42\u8005"}),t!==void 0&&u("th",{scope:"col",className:"px-3 py-2",children:u("span",{className:"sr-only","data-testid":"pipeline-recent-runs-action-header",children:"\u64CD\u4F5C"})})]})}),u("tbody",{children:e.map(n=>{let r=gn(n),a=cn[r];return S("tr",{className:"border-slate-100 border-b border-solid","data-testid":`pipeline-run-row-${n.id}`,"data-status":n.status,children:[S("td",{className:"whitespace-nowrap px-3 py-2 font-mono","data-testid":`pipeline-run-id-${n.id}`,children:["#",n.id]}),S("td",{className:"whitespace-nowrap px-3 py-2 font-mono","data-testid":`pipeline-run-metadata-${n.id}`,children:["#",n.metadataId]}),u("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-kind-${n.id}`,children:Wt[n.documentKind]}),u("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-trigger-${n.id}`,"data-trigger":n.trigger,children:dn[n.trigger]}),u("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-attempt-${n.id}`,children:n.attempt}),u("td",{className:"px-3 py-2",children:u("span",{className:`inline-flex whitespace-nowrap rounded-full px-2 py-0.5 font-semibold text-[11px] ${a.className}`,"data-testid":`pipeline-run-status-${n.id}`,"data-status":n.status,"data-presentation":r,children:a.label})}),u("td",{className:"px-3 py-2","data-testid":`pipeline-run-failed-step-${n.id}`,children:n.failedStepKey===null?"\u2014":tn[n.failedStepKey].label}),u("td",{className:"whitespace-nowrap px-3 py-2 text-slate-500","data-testid":`pipeline-run-started-${n.id}`,children:u(fn,{iso:n.startedAt,testId:`pipeline-run-started-value-${n.id}`})}),u("td",{className:"whitespace-nowrap px-3 py-2 text-slate-500","data-testid":`pipeline-run-finished-${n.id}`,children:u(sn,{iso:n.finishedAt,testId:`pipeline-run-finished-value-${n.id}`})}),u("td",{className:"wrap-anywhere px-3 py-2","data-testid":`pipeline-run-requested-by-${n.id}`,children:n.requestedBy}),t!==void 0&&u("td",{className:"whitespace-nowrap px-3 py-2 text-right",children:u("button",{type:"button",onClick:()=>t(n),"aria-label":`\u5B9F\u884C #${n.id} (\u6587\u66F8 #${n.metadataId}) \u306E\u8A73\u7D30`,className:"whitespace-nowrap rounded-sm border border-slate-300 border-solid bg-white px-2 py-0.5 font-semibold text-[11px] text-slate-700 hover:bg-slate-50","data-testid":`pipeline-run-open-${n.id}`,children:"\u8A73\u7D30"})})]},n.id)})})]})})]})}var et={metadataId:null,runs:[],selectedRunId:null,isLoading:!1,failure:null};function Gn(e){for(let t of e)for(let n of t.steps){let r=n.provenance;if(r!==null){for(let[a,s]of Object.entries(r))if(typeof s=="string"&&!le(s))return`\u51E6\u7406\u5C65\u6B74\u306E\u8A18\u9332\u306B\u8AAD\u3081\u306A\u3044\u6765\u6B74\u306E\u5024\u304C\u3042\u308A\u307E\u3059 (\u5B9F\u884C ${t.id} \u306E\u6BB5 ${n.sequence} \u306E ${a})\u3002`}}return null}function Qn(e){let[t,n]=E(et),[r,a]=E(0),s=O(0),o=O(null),l=ue(()=>{if(e!==void 0)return(p,g)=>{s.current+=1;let v=s.current;o.current?.abort();let R=new AbortController;o.current=R,a(h=>h+1),n({metadataId:p,runs:[],selectedRunId:g,isLoading:!0,failure:null}),Y(()=>e(p,R.signal),h=>({ok:!1,status:null,reason:h})).then(h=>{if(s.current!==v)return;let f=h.ok?Gn(h.value):Hn(h);if(!h.ok||f!==null){n({metadataId:p,runs:[],selectedRunId:g,isLoading:!1,failure:f});return}n({metadataId:p,runs:h.value,selectedRunId:g===null?zn(h.value):g,isLoading:!1,failure:null})})}},[e]),c=Z(p=>{n(g=>({...g,selectedRunId:p}))},[]),d=Z(()=>{s.current+=1,o.current?.abort(),o.current=null,n(et)},[]);return{...t,openRequest:r,open:l,selectRun:c,close:d}}function zn(e){return e.length===0?null:e[0].id}function Jn(e){let t=xn(),n=Te(),r=Te(),a=Te(),s=e.data??t,o=e.fetcher??n,l=e.integrityFetcher??r,c=e.inspectorFetcher??a;return s?u(rt,{...e,data:s,fetcher:o,integrityFetcher:l,inspectorFetcher:c}):u("div",{className:"p-8 text-center text-slate-500","data-testid":"storage-admin-loading",children:"\u30C7\u30FC\u30BF\u8AAD\u307F\u8FBC\u307F\u4E2D..."})}function st(e){return e.data?u(rt,{...e,data:e.data,fetcher:e.fetcher??Oe,integrityFetcher:e.integrityFetcher??Oe,inspectorFetcher:e.inspectorFetcher??Oe}):u(Jn,{...e})}import{AuthzDeniedError as ut}from"@aiquants/authz-core";import{formatCount as rr}from"@aiquants/console-ui/core";import{assertSystemParameterInRange as sr,INTEGRITY_COMMAND_CODES as ir,IntegrityAuditOverviewSchema as or,IntegrityCellResyncRequestSchema as ar,IntegrityCellResyncResultSchema as lr,IntegrityCommandFailureSchema as ur,IntegrityCommandReplySchema as cr,IntegrityRunModeSchema as ct,integrityCommandFailureCodeOf as dr,isEnrichmentStageKey as pr,PipelineRunSummarySchema as mr,PipelineStepMetricSchema as gr}from"@aiquants/enrichment-core";import{CLOUD_CAPABLE_CAPABILITIES as yr,ConfidentialityLevelSchema as He,GovernedCapabilitySchema as fr}from"@aiquants/governance-core";import{z as w}from"zod";var Ue=3e3;function D(e){return Math.round(performance.now()-e)}function T(e){return typeof e=="string"&&le(e)?e:null}function j(e){let t=globalThis.process;return t===void 0?void 0:t.env[e]}function ce(e,t){let n=e?.trim();if(!n)throw new Error(`${t} is not configured; this probe will not guess an endpoint to send credentials to.`);return n}function it(e,t,n){let r=e??(t?.trim()?Number(t):Number.NaN);if(!Number.isInteger(r)||r<=0||r>65535)throw new Error(`${n} is not configured with a valid port; this probe will not guess one.`);return r}function ot(e,t){if(e!==void 0)return e;let n=t?.trim().toLowerCase();if(!(n===void 0||n===""))return n==="1"||n==="true"||n==="yes"||n==="on"}function at(e){let t=e.trim().split("://",1)[0]?.toLowerCase();if(t&&e.includes("://"))return t.endsWith("s")||t.includes("+s")}function Wn(e){let n=e.split("://").slice(-1)[0].split("/",1)[0],r=n.split(":").pop();if(!r||r===n)return;let a=Number(r);return Number.isInteger(a)&&a>0&&a<=65535?a:void 0}async function De(e,t){let n;try{return await Promise.race([e,new Promise((r,a)=>{n=setTimeout(()=>a(new Error(`Probe timed out after ${t}ms`)),t)})])}finally{clearTimeout(n)}}async function Yn(e){let t=e?.qdrantApiKey??j("QDRANT_API_KEY")??"",n=e?.timeoutMs??Ue,r=performance.now(),a="";try{a=ce(e?.qdrantUrl??j("QDRANT_URL"),"QDRANT_URL");let s={};t&&(s["api-key"]=t);let[o,l]=await Promise.all([fetch(`${a}/`,{headers:s,signal:AbortSignal.timeout(n)}),fetch(`${a}/collections`,{headers:s,signal:AbortSignal.timeout(n)})]);if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);if(!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText} (/collections)`);let c=await o.json(),d=D(r),g=(await l.json()).result?.collections?.length??0;return{serviceName:"Qdrant",category:"vector",status:"connected",version:T(c.version),endpoint:a,latencyMs:d,details:{engine:T(c.title),collectionsCount:g,restPort:Wn(a)??null,tls:at(a)??null}}}catch(s){let o=D(r),l=s instanceof Error?s.message:String(s);return{serviceName:"Qdrant",category:"vector",status:"error",version:null,endpoint:a,latencyMs:o,details:{},errorMessage:l}}}async function Zn(e){let t=e?.timeoutMs??Ue,n=performance.now(),r=T(e?.neo4jBoltUri??j("NEO4J_URI")),a=r===null?"":r;try{let s=e?.graphReader;if(!s)throw new Error("Graph reader not configured");let o=e?.tenantId,[l,c]=await Promise.all([De(s("CALL dbms.components() YIELD versions, edition RETURN versions[0] AS version, edition",{}),t),De(o?s("MATCH (n {tenantId: $tenantId}) RETURN count(n) AS node_count",{tenantId:o}):s("RETURN null AS node_count",{}),t)]);if(!l.ok)throw new Error(l.reason);if(!c.ok)throw new Error(c.reason);let[d,p]=l.rows[0]??[],g=c.rows[0]?.[0],v=D(n);return{serviceName:"Neo4j",category:"graph",status:"connected",version:T(d),endpoint:a,latencyMs:v,details:{edition:T(p),boltUri:r,nodeCount:typeof g=="number"?g:null,tls:r===null?null:at(r)??null}}}catch(s){let o=D(n),l=s instanceof Error?s.message:String(s);return{serviceName:"Neo4j",category:"graph",status:"error",version:null,endpoint:a,latencyMs:o,details:{},errorMessage:l}}}async function Xn(e){let t=performance.now(),n="",r=ot(e?.redisTls,j("REDIS_TLS")),a=Number.NaN;try{let s=e?.redisClient;if(!s)throw new Error("Redis client not configured");let o=ce(e?.redisHost??j("REDIS_HOST"),"REDIS_HOST");a=it(e?.redisPort,j("REDIS_PORT"),"REDIS_PORT"),n=`${r===!1?"redis":"rediss"}://${o}:${a}`,await s.ping();let l=await s.info("server"),c=T(l.match(/redis_version:([^\r\n]+)/)?.[1]),d=null;if(typeof s.dbSize=="function")try{d=await s.dbSize()}catch{d=null}let p=D(t);return{serviceName:"Redis",category:"cache",status:"connected",version:c,endpoint:n,latencyMs:p,details:{totalKeys:d,port:a,tls:r??null,database:0}}}catch(s){let o=D(t),l=s instanceof Error?s.message:String(s);return{serviceName:"Redis",category:"cache",status:"error",version:null,endpoint:n,latencyMs:o,details:{},errorMessage:l}}}function er(e){let t=e.match(/Microsoft SQL Server \d+ \([^)]+\)/);return T(t===null?e.substring(0,30):t[0].replace("Microsoft SQL Server ",""))}async function tr(e){let t=performance.now(),n="",r=ot(e?.sqlServerTls,j("SQL_SERVER_TLS")),a=Number.NaN;try{let s=e?.sqlServerExecute;if(!s)throw new Error("SQL Server executor not configured");let o=ce(e?.sqlServerHost??j("SQL_SERVER_HOST"),"SQL_SERVER_HOST");a=it(e?.sqlServerPort,j("SQL_SERVER_PORT"),"SQL_SERVER_PORT"),n=`${o}:${a}`;let l=await s(),c=T(l.db_name),d=T(l.version),p=d===null?null:T(d.split(`
2
+ `)[0]),g=p===null?null:er(p),v=D(t);return{serviceName:"SQL Server",category:"database",status:"connected",version:g,endpoint:n,latencyMs:v,details:{database:c,port:a,tls:r??null,fullVersion:p}}}catch(s){let o=D(t),l=s instanceof Error?s.message:String(s);return{serviceName:"SQL Server",category:"database",status:"error",version:null,endpoint:n,latencyMs:o,details:{},errorMessage:l}}}async function nr(e){let t=e?.timeoutMs??Ue,n=performance.now(),r="";try{r=ce(e?.backendApiHost??j("BACKEND_API_HOST"),"BACKEND_API_HOST");let a=await fetch(`${r}/openapi.json`,{signal:AbortSignal.timeout(t)});if(!a.ok)throw new Error(`HTTP ${a.status}: ${a.statusText}`);let s=await a.json(),o=Object.keys(s.paths??{}).length,l=D(n);return{serviceName:"AI Quant API",category:"api",status:"connected",version:T(s.info?.version),endpoint:r,latencyMs:l,details:{title:T(s.info?.title),endpointsCount:o}}}catch(a){let s=D(n),o=a instanceof Error?a.message:String(a);return{serviceName:"AI Quant API",category:"api",status:"error",version:null,endpoint:r,latencyMs:s,details:{},errorMessage:o}}}async function lt(e){let[t,n,r,a,s]=await Promise.all([Yn(e),Zn(e),Xn(e),tr(e),nr(e)]),o=t.status==="connected"&&n.status==="connected"&&r.status==="connected"&&a.status==="connected"&&s.status==="connected";return{services:{qdrant:t,neo4j:n,redis:r,sqlServer:a,quantsApi:s},allHealthy:o,checkedAt:new Date().toISOString()}}var Rr=w.object({templateText:w.string(),modelName:w.string(),temperature:w.number(),maxOutputTokens:w.number(),responseSchema:w.union([w.record(w.string(),w.unknown()),w.string(),w.null()]).optional(),endpointBaseUrl:w.string().nullable()}).strict(),br=w.discriminatedUnion("mode",[w.object({mode:ct.extract(["SCAN"]),basisRunUid:w.null()}).strict(),w.object({mode:ct.extract(["REPAIR"]),basisRunUid:w.string().uuid()}).strict()]),Sr=w.object({runUid:w.string().uuid()}).strict();function pt(e){return e==="start_integrity_run"?"start":e==="cancel_integrity_run"?"cancel":null}function H(e,t){return e.issues.map(n=>`${n.path.length===0?t:n.path.join(".")}: ${n.message}`).join("; ")}function hr(e,t){if(e==="bool")return t==="true"||t==="false"?null:"paramValue must be 'true' or 'false' for a bool parameter";if(e==="int")return/^[+-]?\d+$/.test(t)&&Number.isSafeInteger(Number(t))?null:"paramValue must be a safe integer for an int parameter";if(e==="float")return t.trim()!==""&&Number.isFinite(Number(t))?null:"paramValue must be a finite number for a float parameter";if(e==="json")try{return JSON.parse(t),null}catch{return"paramValue must be valid JSON for a json parameter"}return null}function vr(e){let t=mr.array().safeParse(e);if(!t.success)throw new Error(`getRecentPipelineRuns answered something that is not a run summary: ${H(t.error,"getRecentPipelineRuns")}`);return t.data}function Ir(e){let t=gr.array().safeParse(e);if(!t.success)throw new Error(`getPipelineStepMetrics answered something that is not a step metric: ${H(t.error,"getPipelineStepMetrics")}`);let n=new Set;for(let r of t.data){let a=`${r.documentKind}/${r.stepKey}`;if(n.has(a))throw new Error(`getPipelineStepMetrics answered more than one metric for (documentKind, stepKey) = (${r.documentKind}, ${r.stepKey})`);n.add(a)}return t.data}function wr(e){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`pipelineStepMetricWindow must be a positive safe integer, got ${String(e)}`);return e}async function Ar(e,t){let n;try{n=await e.readIntegrityAuditOverview(t)}catch(a){return{ok:!1,status:null,reason:a instanceof Error?a.message:String(a)}}let r=or.safeParse(n);return r.success?{ok:!0,value:r.data}:{ok:!1,status:null,reason:`readIntegrityAuditOverview answered something that is not an audit overview: ${H(r.error,"readIntegrityAuditOverview")}`}}function Pr(e){return!Array.isArray(e)||e.length===0?"orderedRuleIds must be a non-empty array of rule ids":e.every(t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>0)?new Set(e).size!==e.length?"orderedRuleIds must not name a rule twice":null:"orderedRuleIds must contain positive integers only"}function mt(e){let{store:t,healthProbeOptions:n,resourceKey:r="storage_admin",requireUser:a,requirePermission:s,resolveTenantId:o,authorizeIngest:l,canReadIntegrityFindings:c,canUpdateKnowledge:d}=e;async function p(v){let{request:R}=v;if(!await a(R))throw new Response("\u8A8D\u8A3C\u304C\u5FC5\u8981\u3067\u3059\u3002",{status:401});try{await s(R,{resourceKey:r,action:"read"})}catch(se){throw se instanceof ut?new Response("\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002",{status:403}):se}let f=await o(R),U=wr(t.pipelineStepMetricWindow),[x,A,P]=await Promise.all([t.getFeatureFlags(f),t.getSystemParameters(f),t.getSyncCounts(f)]),k={featureFlags:x,systemParameters:A,syncCounts:P},[$,K,q,V,_,I,L,ee,F,Q,te,pe,me,ge,m,B,ye,ne,fe,C,G]=await Promise.all([t.getConfidentialityPolicies(f),t.getTranscriptionVocabulary(f),t.getTranscriptionReferences(f),t.getUnresolvedReferenceUris(f),t.getPoliciesMissingDestination(f),t.getPromptTemplates(f),t.getClassificationRules(f),t.getFailedSyncItems(f),t.getGraphSchema(f),Ar(t,f),c(R),d(R),t.getUnresolvedEntities(f),t.getQdrantCollections(f),lt({...n,tenantId:f}),t.getRecentIngestItems(f),t.getOntologyStatus(f,k),t.getEnrichmentStrategies(f),t.getStrategyVariants(f),t.getPipelineStepMetrics(f),t.getRecentPipelineRuns(f)]),re=t.getCircuitBreakerStatus();return{tenantId:f,featureFlags:k.featureFlags,confidentialityPolicies:$,transcriptionVocabulary:K,transcriptionReferences:q,unresolvedReferenceUris:V,policiesMissingDestination:_,systemParameters:k.systemParameters,promptTemplates:I,classificationRules:L,classificationRuleConsumer:t.classificationRuleConsumer??null,syncCounts:k.syncCounts.counts,totalFiles:k.syncCounts.total,failedSyncItems:ee,circuitBreakerStatus:re,pipelineStepMetrics:Ir(C),pipelineStepMetricWindow:U,recentPipelineRuns:vr(G),displayTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,graphSchema:F,enrichmentStrategies:ne,strategyVariants:fe,integrityAudit:Q,canReadIntegrityFindings:te,canUpdateKnowledge:pe,unresolvedEntities:me,qdrantCollections:ge,systemHealth:m,recentIngestItems:B,ontologyStatus:ye}}async function g(v){let{request:R}=v,h=await a(R);if(!h)return Response.json({error:"\u8A8D\u8A3C\u304C\u5FC5\u8981\u3067\u3059\u3002"},{status:401});if(h.email.trim()==="")return Response.json({error:"\u64CD\u4F5C\u8005\u3092\u7279\u5B9A\u3067\u304D\u306A\u3044\u305F\u3081\u8A2D\u5B9A\u3092\u5909\u66F4\u3067\u304D\u307E\u305B\u3093\u3002"},{status:403});if(h.accessToken==="")throw new Error("requireUser resolved an operator whose accessToken is an empty string; answer null when the session holds no token the upstream services accept");let f=h.email,U=h.accessToken===null?void 0:h.accessToken;try{await s(R,{resourceKey:r,action:"update"})}catch(_){if(_ instanceof ut)return await Lr(R);throw _}let x=await o(R),A=await R.formData(),P=String(A.get("intent")??"");if(P==="refresh_health")return Response.json({success:!0,refreshed:!0});let k=await Nr(t,x,P,A,f);if(k)return k;let $=await Er(t,x,P,A,f,U);if($)return $;let K=await kr(t,x,P,A,f,U,()=>c(R));if(K)return K;let q=await Fr(t,x,P,A,U,()=>c(R));if(q)return q;if(P==="resolve_entity"){let _=String(A.get("entityId")??""),I=String(A.get("action")??"");if(!_||I!=="merge"&&I!=="promote")return Response.json({error:"Valid entityId and action ('merge' | 'promote') are required"},{status:400});try{return await t.resolveEntity(x,_,I),Response.json({success:!0,entityId:_,action:I})}catch(L){return Response.json({error:L instanceof Error?L.message:String(L)},{status:400})}}let V=await Ur(t,x,P,A,f,R,l,U);return V||Response.json({error:`Unknown intent: ${P}`},{status:400})}return{loader:p,action:g}}function Me(e){let t=String(e??"").trim();return t===""?null:t}function de(e){let t=String(e??"").trim();if(t==="")return null;let n=Number(t);if(!(!Number.isSafeInteger(n)||n<=0))return n}function Cr(e){let t=String(e??"").trim();if(t==="")return null;let n=Number(t);if(!(!Number.isFinite(n)||n<=0))return n}async function Nr(e,t,n,r,a){if(n==="update_enrichment_strategy"){let s=String(r.get("stage")??"");if(!pr(s))return Response.json({error:"stage must be a canonical enrichment stage key"},{status:400});let o=de(r.get("strategyId")),l=de(r.get("domainId"));if(o==null||l===void 0||l===null)return Response.json({error:"strategyId and domainId must be positive integers naming existing rows"},{status:400});let c=String(r.get("enabled")??"")==="true";try{await e.updateEnrichmentStrategy(t,{strategyId:o,domainId:l,stage:s,enabled:c},a)}catch(d){return Response.json({error:d instanceof Error?d.message:"\u53D6\u308A\u8FBC\u307F\u6226\u7565\u3092\u66F4\u65B0\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},{status:400})}return Response.json({success:!0,strategyId:o,domainId:l,stage:s,enabled:c})}if(n==="toggle_flag"){let s=String(r.get("flagKey")??""),o=String(r.get("enabled")??"")==="true";if(!s)return Response.json({error:"flagKey is required"},{status:400});let l=await e.getFeatureFlags(t);return Object.hasOwn(l,s)?(await e.toggleFeatureFlag(t,s,o,a),Response.json({success:!0,flagKey:s,enabled:o})):Response.json({error:`flagKey names no feature flag of this tenant: ${s}`},{status:400})}if(n==="update_confidentiality_policy"){let s=String(r.get("confidentialityLevel")??""),o=String(r.get("capability")??"");if(!(He.safeParse(s).success&&fr.safeParse(o).success))return Response.json({error:"confidentialityLevel and capability must be canonical values"},{status:400});let l=String(r.get("allowCloudProvider")??"")==="true";if(l&&!yr.includes(o))return Response.json({error:`${o} sends nothing outside the deployment, so it has no cloud permission to grant`},{status:400});let c=String(r.get("promptKey")??"");return await e.updateConfidentialityPolicy(t,{confidentialityLevel:s,capability:o,isEnabled:String(r.get("isEnabled")??"")==="true",allowCloudProvider:l,promptKey:c===""?null:c},a),Response.json({success:!0,confidentialityLevel:s,capability:o})}if(n==="save_transcription_term"){let s=String(r.get("term")??"").trim();if(!s)return Response.json({error:"term is required"},{status:400});let o=Cr(r.get("boost"));if(o===void 0)return Response.json({error:"boost must be a number greater than zero, or absent to let the service decide"},{status:400});let l=de(r.get("id"));if(l===void 0)return Response.json({error:"id must be a positive integer naming an existing row, or absent for a new one"},{status:400});try{await e.saveTranscriptionTerm(t,{id:l,term:s,reading:Me(r.get("reading")),boost:o,domainKey:Me(r.get("domainKey")),isActive:String(r.get("isActive")??"true")==="true"},a)}catch(c){return Response.json({error:c instanceof Error?c.message:"\u8A9E\u5F59\u3092\u4FDD\u5B58\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},{status:400})}return Response.json({success:!0,term:s})}if(n==="save_transcription_reference"){let s=String(r.get("fileUri")??"").trim();if(!s)return Response.json({error:"fileUri is required"},{status:400});let o=de(r.get("id"));if(o===void 0)return Response.json({error:"id must be a positive integer naming an existing row, or absent for a new one"},{status:400});try{await e.saveTranscriptionReference(t,{id:o,fileUri:s,domainKey:Me(r.get("domainKey")),isActive:String(r.get("isActive")??"true")==="true"},a)}catch(l){return Response.json({error:l instanceof Error?l.message:"\u53C2\u7167\u8CC7\u6599\u3092\u4FDD\u5B58\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},{status:400})}return Response.json({success:!0,fileUri:s})}if(n==="update_parameter"){let s=String(r.get("paramKey")??""),o=String(r.get("paramValue")??"");if(!s)return Response.json({error:"paramKey is required"},{status:400});let l=(await e.getSystemParameters(t)).find(d=>d.key===s);if(l===void 0)return Response.json({error:`paramKey names no parameter of this tenant: ${s}`},{status:400});let c=hr(l.data_type,o);if(c!==null)return Response.json({error:c},{status:400});try{sr(s,Number(o))}catch(d){return Response.json({error:d.message},{status:400})}return await e.updateSystemParameter(t,s,o,a),Response.json({success:!0,paramKey:s,paramValue:o})}if(n==="update_prompt"){let s=String(r.get("templateKey")??""),o=String(r.get("payload")??"{}"),l;try{l=JSON.parse(o)}catch{return Response.json({error:"Invalid JSON payload"},{status:400})}if(!s)return Response.json({error:"templateKey is required"},{status:400});let c=Rr.safeParse(l);if(!c.success)return Response.json({error:`payload does not carry a prompt template update: ${H(c.error,"payload")}`},{status:400});let d=c.data;try{return await e.updatePromptTemplate(t,s,d,a),Response.json({success:!0,templateKey:s})}catch(p){return Response.json({error:p instanceof Error?p.message:String(p)},{status:400})}}if(n==="reorder_rules"){let s=String(r.get("orderedRuleIds")??"[]"),o;try{o=JSON.parse(s)}catch{return Response.json({error:"Invalid orderedRuleIds JSON"},{status:400})}let l=Pr(o);if(l!==null)return Response.json({error:l},{status:400});let c=o;return await e.reorderClassificationRules(t,c,a),Response.json({success:!0,orderedRuleIds:c})}return null}async function Er(e,t,n,r,a,s){if(n==="retry_job"){let o=String(r.get("fileId")??"");if(!o)return Response.json({error:"fileId is required"},{status:400});try{return await e.retrySyncItem(t,o,a,s),Response.json({success:!0,fileId:o})}catch(l){return Response.json({error:l instanceof Error?l.message:String(l)},{status:400})}}if(n==="retry_all_failed")try{let{requeued:o,skipped:l}=await e.retryAllFailedSyncItems(t,a,s);return Response.json({success:!0,requeued:o,skipped:l})}catch(o){return Response.json({error:o instanceof Error?o.message:String(o)},{status:400})}return null}var Tr="resync_findings",_r="\u307E\u3068\u3081\u3066\u306E\u518D\u540C\u671F\u306F\u3001\u5168\u3066\u306E\u6587\u66F8\u3092\u95B2\u89A7\u3067\u304D\u308B\u64CD\u4F5C\u8005 (\u30D5\u30A1\u30A4\u30EB\u306E\u95B2\u89A7\u306E\u6A29\u9650\u306B\u884C\u3068\u5217\u306E\u30B9\u30B3\u30FC\u30D7\u304C\u7121\u3044\u64CD\u4F5C\u8005) \u3060\u3051\u304C\u5B9F\u884C\u3067\u304D\u307E\u3059\u3002",Or=/^[1-9][0-9]*$/;function xr(e){return Object.fromEntries([...e.entries()].filter(([t])=>t!=="intent").map(([t,n])=>[t,t==="after"&&typeof n=="string"&&Or.test(n)?Number(n):n]))}async function kr(e,t,n,r,a,s,o){if(n!==Tr)return null;if(!await o())return Response.json({error:_r},{status:403});let l=ar.safeParse(xr(r));if(!l.success)return Response.json({error:`resync_findings takes runUid (a UUID), store, scopeKey, itemClass UNRECORDED and an optional after (a positive integer): ${H(l.error,"form")}`},{status:400});let c;try{c=await e.resyncIntegrityCell(t,l.data,a,s)}catch(p){return Response.json({error:p instanceof Error?p.message:String(p)},{status:400})}let d=lr.safeParse(c);return d.success?Response.json({success:!0,cellResync:d.data}):Response.json({error:`\u307E\u3068\u3081\u3066\u306E\u518D\u540C\u671F\u306E\u7B54\u3048\u304C\u5951\u7D04\u3068\u7570\u306A\u308A\u307E\u3059 (${H(d.error,"answer")})\u3002\u958B\u767A\u62C5\u5F53\u306B\u9023\u7D61\u3057\u3066\u304F\u3060\u3055\u3044\u3002`},{status:502})}function X(e,t,n){let r=ur.parse({command:e,code:t,status:n}),a=ir.find(s=>s.code===r.code);return Response.json({failure:r},{status:a===void 0?502:a.status})}async function Lr(e){let t=await e.formData().catch(()=>null),n=t===null?null:pt(t.get("intent"));return n===null?Response.json({error:"\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002"},{status:403}):X(n,"FORBIDDEN",null)}async function dt(e,t){let n;try{n=cr.parse(await t())}catch{return X(e,"UPSTREAM_FAILED",null)}return n.ok?Response.json({success:!0,runUid:n.runUid}):X(e,dr(e,n.status,n.errorCode),n.status)}async function Fr(e,t,n,r,a,s){let o=pt(n);if(o==="start"){let l=br.safeParse({mode:r.get("mode"),basisRunUid:r.get("basisRunUid")});if(!l.success)return Response.json({error:`start_integrity_run takes mode SCAN without basisRunUid, or mode REPAIR with basisRunUid (a UUID): ${H(l.error,"form")}`},{status:400});let{mode:c,basisRunUid:d}=l.data;return a===void 0||c==="REPAIR"&&!await s()?X(o,"FORBIDDEN",null):await dt(o,()=>e.startIntegrityRun(t,c,d,a))}if(o==="cancel"){let l=Sr.safeParse({runUid:r.get("runUid")});return l.success?a===void 0?X(o,"FORBIDDEN",null):await dt(o,()=>e.cancelIntegrityRun(t,l.data.runUid,a)):Response.json({error:`cancel_integrity_run takes runUid (a UUID): ${H(l.error,"form")}`},{status:400})}return null}function jr(e){if(typeof e!="object"||e===null)return"payload must be an object";let t=e;if(typeof t.fileUri!="string"||t.fileUri.trim()==="")return"payload.fileUri is required";if(!He.safeParse(t.confidentialityLevel).success)return`payload.confidentialityLevel must be one of ${He.options.join(", ")}`;let r=t.departmentId;return r!=null&&(typeof r!="number"||!Number.isInteger(r))?"payload.departmentId must be an integer or null":null}function Dr(e){try{return rr(e,ae),null}catch{return`inspectFileUri answered a fileSize that is not a byte count (a non-negative safe integer): ${String(e)}`}}async function Ur(e,t,n,r,a,s,o,l){if(n==="ingest_document"){let c=String(r.get("payload")??"");if(!c)return Response.json({error:"payload is required"},{status:400});let d;try{d=JSON.parse(c)}catch{return Response.json({error:"Invalid JSON payload"},{status:400})}let p=jr(d);if(p)return Response.json({error:p},{status:400});let g=d,v=await o(s,g);if(v!==null)return Response.json({error:v},{status:403});try{let R=l===void 0?await e.ingestDocument(t,g,a):await e.ingestDocument(t,g,a,l);return Response.json({success:!0,result:R})}catch(R){return Response.json({error:R instanceof Error?R.message:String(R)},{status:400})}}if(n==="inspect_uri"){let c=String(r.get("fileUri")??"").trim();if(!c)return Response.json({error:"fileUri is required"},{status:400});if(!e.inspectFileUri)return Response.json({error:"inspectFileUri is not implemented"},{status:501});let d;try{d=l===void 0?await e.inspectFileUri(t,c):await e.inspectFileUri(t,c,l)}catch(g){return Response.json({error:g instanceof Error?g.message:String(g)},{status:400})}let p=Dr(d.fileSize);return p!==null?Response.json({error:p},{status:400}):Response.json({success:!0,inspection:d})}return null}function Ss(e){let t=mt(e);return{loader:t.loader,action:t.action,View:st,server:t}}export{st as StorageAdminConsoleView,lt as checkAllSystemHealth,nr as checkBackendApiHealth,Zn as checkNeo4jHealth,Yn as checkQdrantHealth,Xn as checkRedisHealth,tr as checkSqlServerHealth,Ss as createStorageAdminApp,mt as createStorageAdminServer};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiquants/enrichment-react-router",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "React Router (v7 / v8) adapter for storage AI enrichment & knowledge governance admin console.",
5
5
  "sideEffects": false,
6
6
  "type": "module",
@@ -37,10 +37,10 @@
37
37
  "peerDependencies": {
38
38
  "@aiquants/authz-core": "^0.6.1",
39
39
  "@aiquants/console-ui": "^0.2.0",
40
- "@aiquants/enrichment-core": "^0.3.2",
40
+ "@aiquants/enrichment-core": "^0.3.3",
41
41
  "@aiquants/enrichment-react": "^0.3.0",
42
42
  "@aiquants/governance-core": "^0.2.1",
43
- "@aiquants/governance-react": "^0.3.0",
43
+ "@aiquants/governance-react": "^0.4.0",
44
44
  "react": ">=19",
45
45
  "react-dom": ">=19",
46
46
  "react-router": "^7.0.0 || ^8.0.0",
@@ -49,10 +49,10 @@
49
49
  "devDependencies": {
50
50
  "@aiquants/authz-core": "0.6.1",
51
51
  "@aiquants/console-ui": "0.2.0",
52
- "@aiquants/enrichment-core": "0.3.2",
52
+ "@aiquants/enrichment-core": "0.3.3",
53
53
  "@aiquants/enrichment-react": "0.3.0",
54
54
  "@aiquants/governance-core": "0.2.1",
55
- "@aiquants/governance-react": "0.3.0",
55
+ "@aiquants/governance-react": "0.4.0",
56
56
  "@testing-library/jest-dom": "^6.9.1",
57
57
  "@testing-library/react": "^16.3.2",
58
58
  "@testing-library/user-event": "^14.6.1",