@aiquants/enrichment-react-router 0.4.0 → 0.5.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
@@ -27,7 +27,7 @@ React, React DOM and React Router come from the host application. `zod` carries
27
27
  ```tsx
28
28
  import { createStorageAdminApp } from "@aiquants/enrichment-react-router"
29
29
 
30
- const app = createStorageAdminApp({ store, requireUser, requirePermission, resolveTenantId, authorizeIngest, canReadIntegrityFindings, canUpdateKnowledge })
30
+ const app = createStorageAdminApp({ store, requireUser, requirePermission, resolveTenantId, authorizeIngest, authorizeHistoryCapture, canReadIntegrityFindings, canUpdateKnowledge })
31
31
 
32
32
  export const loader = app.loader
33
33
  export const action = app.action
@@ -41,7 +41,7 @@ export default function StorageAdminRoute() {
41
41
  policyConflicts={POLICY_CONFLICT_HOST}
42
42
  documentAuthority={DOCUMENT_AUTHORITY_HOST}
43
43
  onRefreshIngestQueue={refreshIngestQueue}
44
- onLoadDocumentRuns={loadDocumentRuns}
44
+ documentHistory={DOCUMENT_HISTORY_HOST}
45
45
  onCompareVariants={compareVariants}
46
46
  />
47
47
  )
@@ -63,6 +63,7 @@ Every port below except the two optional settings of the last row is required, s
63
63
  | `canReadIntegrityFindings(request)` | `Promise<boolean>` | Whether the operator may read every document (a file read scoped to no rows and no columns). The integrity audit's findings name documents, so the findings cells and the repair are offered only when it is `true`; the action refuses a `REPAIR` start with `FORBIDDEN` before calling the store when it is `false`. The host's findings route should use the same judgment. |
64
64
  | `canUpdateKnowledge(request)` | `Promise<boolean>` | Whether the operator may write the document-authority ledger and decide policy conflicts: `true` exactly when the host would answer this operator's policy conflict summary with `viewer.canDecide` `true` (compute both from one function, so the ledger and the conflict queue never disagree). It is a permission, not a deployment state: a deployment that disables knowledge writes still answers `true`, and its write routes refuse with `DEPLOYMENT_DISABLED`, which the cards state. The loader answers it, so the ledger's first render (and a server render) already knows it. |
65
65
  | `authorizeIngest(request, payload)` | `Promise<string \| null>` | The ingest refusal in the operator's words, or `null` to allow. |
66
+ | `authorizeHistoryCapture(request, metadataId)` | `Promise<HistoryCaptureRefusal \| null>` | Whether the operator may record the named document's current state (`capture_document_state`), decided before the store is called, in this order: the deployment's recording switch (`503` when off or misconfigured), the operator's document reading (`403` without `file:read` or with a column-scoped one), the named document's current row (`404` when missing or unreadable). A refusal `{ status, error }` is the action's answer and the store is not called. `error` is shown by the history panel after its own sentence: a 403's is the cause only (`文書の状態を記録する権限がありません。<error>。`), any other a phrase without a final 。 (`文書の状態を記録できませんでした (<error>)。`); `""` leaves the panel's sentence alone. A throw propagates. |
66
67
  | `healthProbeOptions?` / `resourceKey?` | | Optional probe settings and the permission resource key. |
67
68
 
68
69
  ## The store contract (`StorageAdminStore`)
@@ -73,7 +74,12 @@ The host implements one object and injects it through `createStorageAdminApp`. B
73
74
  | --- | --- | --- |
74
75
  | `getPipelineStepMetrics(tenantId)` | `readonly PipelineStepMetric[]` | One aggregate per (`documentKind`, `stepKey`) over the newest `pipelineStepMetricWindow` records of that pair (`@aiquants/enrichment-core`); `documentKind` is the kind of the run the records belong to. Read from the step table, never measured in process. The loader checks every entry against `PipelineStepMetricSchema` and throws (naming the method and each issue) when one is not a metric — one without `documentKind` included — or when a pair appears twice, because the flow figure shows the first match and would silently drop the second. |
75
76
  | `pipelineStepMetricWindow` (property) | `number` | How many of the newest records per (`documentKind`, `stepKey`) each metric aggregates: the same constant the aggregation query uses. The loader throws, before it queries anything, when it is not a positive safe integer. |
76
- | `getRecentPipelineRuns(tenantId)` | `readonly PipelineRunSummary[]` | The tenant's most recent runs, newest first, **without their steps**. The loader checks every entry against `PipelineRunSummarySchema` and throws (naming the method and each issue) when one is not a summary — a `steps` key included, because a full `PipelineRunRecord` is assignable to the summary type and would otherwise ship every step to the browser on each load. |
77
+ | `getRecentPipelineRuns(tenantId, request)` | `readonly RecentPipelineRunEntry[]` | The tenant's most recent runs, newest first, **without their steps**, for the operator `request` acts for: each entry is a readable run (`{ kind: "readable", item: PipelineRunSummary }`) or the restricted mark of a run the quarantine (`RESTRICTED`) withholds (`RestrictedRunMark`: `startedAt`, `finishedAt`, `status` only). A run the operator's row scope alone hides is left out; the readability and mark predicates are applied inside the query, and its row limit counts runs and marks together after them. The loader checks every entry against `RecentPipelineRunEntrySchema` and throws (naming the method and each issue) when one is neither — a `steps` key included, because a full `PipelineRunRecord` is assignable to the summary type and would otherwise ship every step to the browser on each load, and any key a mark does not carry. |
78
+ | `getRecentIngestItems(tenantId, request)` | `readonly RecentIngestEntry[]` | The ingest list for the operator `request` acts for: readable rows (`{ kind: "readable", item: RecentIngestItem }`, whose `lastRun` is the latest readable run, that run's `RestrictedRunMark`, or `null`) and the `RestrictedIngestMark` of each row the quarantine withholds (the document's current row `RESTRICTED`, or a readable document's `RESTRICTED` revision row, an older one included; a mark carries no latest run). The host's ingest-queue route answers the same list through the same judgment (`IngestQueueRefresher`). |
79
+ | `getFailedSyncItems(tenantId, request)` | `readonly FailedSyncEntry[]` | The failed rows for the operator `request` acts for: readable rows (`{ kind: "readable", item: FailedSyncItem }`) and the `RestrictedFailureMark` (`failedAt`, `syncStatus` only) of each row the quarantine withholds. |
80
+ | `getDocumentReadRefusal(tenantId, request)` | `string \| null` | Why the operator may read no document of the three lists (no `file:read`, or a column-scoped one), as a full sentence, or `null`. The loader reads it in the same wave as the lists and ships it as `documentReadRefusal`; such an operator's lists are empty (no mark either). |
81
+ | `ingestDocument(tenantId, payload, actor, accessToken?)` | `DocumentIngestOutcome` | `{ kind: "ingested", result }`, or `{ kind: "refused", status: 403 \| 500 \| 503, error }` for a refusal decided inside the host's own transaction after `authorizeIngest` passed (the revision writer's scope refusal, the pre-write history capture's lock timeout, any other failure of that capture); `error` is shown as given, never a driver message. A throw is answered `400` with its message. |
82
+ | `captureDocumentState(tenantId, metadataId, actor)` | `DocumentStateCaptureOutcome` | Records the named document's current state after `authorizeHistoryCapture` admitted it: `{ kind: "recorded" }`, `{ kind: "unchanged" }`, or `{ kind: "failed", status: 404 \| 500 \| 503, error }` (`error` a phrase without a final 。, or `""`). A throw is answered as a `500` without a reason and its cause is discarded, so the store logs a failure before it throws for it. |
77
83
  | `getStrategyVariants(tenantId)` | `readonly StrategyVariant[]` | `{ strategyId, variantKey, label, embeddingModel, domainKey }`, one per `tm_enrichment_strategy` row the tenant can see (its own rows and the `SYSTEM` rows). `strategyId` is the identity: every domain has its own `default` row, so a variant key repeats across domains. |
78
84
  | `getEnrichmentStrategies(tenantId)` | `EnrichmentStrategyRow[]` | The per-domain strategies. Also the one source of the domain list the ingest console and the classification-rule editor offer (`{ key: domainKey, label: domainLabel }`, distinct, in board order). |
79
85
  | `retryAllFailedSyncItems(tenantId, actor?, accessToken?)` | `RetryAllFailedResult` | `{ requeued, skipped: { metadataId, reason }[] }` — every row the retry left where it was is named, so the console never reports an all-clear over skipped rows. |
@@ -84,7 +90,7 @@ The host implements one object and injects it through `createStorageAdminApp`. B
84
90
  | `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. |
85
91
  | `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. |
86
92
 
87
- The store reads no single run and no document history: the history panel reads through the injected `onLoadDocumentRuns` (below), whose route and authorization belong to the host.
93
+ The store reads no single run and no document history: the history panel and the recent changes card read through the injected `documentHistory` host (below), whose routes and authorization belong to the host.
88
94
 
89
95
  ## The operator (`StorageAdminOperator`)
90
96
 
@@ -114,17 +120,19 @@ const requireUser = async (request: Request): Promise<StorageAdminOperator | nul
114
120
  - `pipelineStepMetrics` — the step aggregates above, one per (`documentKind`, `stepKey`); the pipeline flow viewer draws its per-step figures from these and from nothing else, showing only the selected kind's own entry (a kind without one reads 未測定, never another kind's numbers).
115
121
  - `pipelineStepMetricWindow` — the store's `pipelineStepMetricWindow`, passed to `PipelineFlowViewer` as `metricSampleWindow` so the figure states the window its numbers cover.
116
122
  - `circuitBreakerStatus` — the search breakers above, passed to `MetadataSearchWorkbench` only.
117
- - `recentPipelineRuns` — the run summaries above, listed under the flow viewer.
123
+ - `recentPipelineRuns` — the readable runs and run marks above, listed under the flow viewer.
124
+ - `recentIngestItems` / `failedSyncItems` — the readable rows and marks of the ingest list and the failed rows above.
125
+ - `documentReadRefusal` — the store's `getDocumentReadRefusal`: `null`, or the sentence shown in place of each of the three lists (no row, no empty-list sentence).
118
126
  - `displayTimeZone` — the IANA time zone every recorded instant is written in, resolved on the server (`Intl.DateTimeFormat().resolvedOptions().timeZone`).
119
127
  The view sets the console root's time zone from it (`ConsoleUiRoot` of `@aiquants/console-ui`, `locale="ja"`, `formatLocale="ja-JP"`, test id `storage-admin-console-ui`, its announcer `storage-admin-console-ui-announcer`), and every card reads the zone from the root — no card takes it as a prop — so the server-rendered page and the hydrated one print the same string.
120
- `SyncStatusMonitor`'s `failedSyncItems[].failed_at` must therefore be ISO 8601 instants with an explicit offset, or `null`.
128
+ `SyncStatusMonitor`'s `failedSyncItems[].item.failed_at` (and a mark's `failedAt`) must therefore be ISO 8601 instants with an explicit offset, or `null`.
121
129
  - `integrityAudit` — `ResourceOutcome<IntegrityAuditOverview>` (`@aiquants/console-ui/core`): the store's overview, or `{ ok: false, status: null, reason }` when that one read failed.
122
130
  - `canReadIntegrityFindings` / `canUpdateKnowledge` — the two host judgments above, answered per request.
123
131
  - `strategyVariants` — the variants above, offered by the model-comparison workbench.
124
132
  - `enrichmentStrategies` — the strategies above; the domain options are derived from them in the view.
125
133
  - `systemParameters` — the typed parameters above.
126
134
 
127
- Every timestamp the host ships in loader data or in `onLoadDocumentRuns` (`startedAt`, `finishedAt`, `createdAt`, `lastStartedAt`, `checkedAt`, and `failedSyncItems[].failed_at` when not `null`) must be an ISO 8601 instant with an explicit offset (`Z` or `±hh:mm`), as `Date.prototype.toISOString()` writes it: `@aiquants/enrichment-react`'s `RecordedInstant` throws `RangeError` for anything else rather than guess the zone. The integrity audit's instants are checked by the core's contract where the loader reads them.
135
+ Every timestamp the host ships in loader data or through `documentHistory` (`startedAt`, `finishedAt`, `createdAt`, `settledAt`, `lastStartedAt`, `checkedAt`, and a failed row's `failed_at` or a mark's `failedAt` when not `null`) must be an ISO 8601 instant with an explicit offset (`Z` or `±hh:mm`), as `Date.prototype.toISOString()` writes it: `@aiquants/enrichment-react`'s `RecordedInstant` throws `RangeError` for anything else rather than guess the zone. The integrity audit's instants are checked by the core's contract where the loader reads them.
128
136
 
129
137
  ## Route action validation
130
138
 
@@ -135,7 +143,7 @@ Before any intent is acted on, the action refuses the request as a whole:
135
143
  | `requireUser` resolves `null` | `401 { error: "認証が必要です。" }` |
136
144
  | The operator's `email` is empty or only whitespace | `403 { error: "操作者を特定できないため設定を変更できません。" }` |
137
145
  | The operator's `accessToken` is `""` | Throws `Error` (a host error: answer `null` for a session without a usable token); it propagates to the route's error boundary and nothing is written. |
138
- | `requirePermission` throws `AuthzDeniedError` for `update` | `403 { error: "権限がありません。" }`, except that a `start_integrity_run` / `cancel_integrity_run` is refused on the audit card: `403 { failure }` with `FORBIDDEN` and no status (below). Only this refusal reads the form, to choose the answer; a request the gate admits is read after the gate. A refused body that is not a form (JSON, or none) names no intent and gets the same `403 { error }`. Any other error `requirePermission` throws propagates. |
146
+ | `requirePermission` throws `AuthzDeniedError` for `update` | `403 { error: "権限がありません。" }`, except that a `start_integrity_run` / `cancel_integrity_run` is refused on the audit card: `403 { failure }` with `FORBIDDEN` and no status (below), and a `capture_document_state` in the history panel: `403 { captureFailure: { status: 403, reason: "" } }`. Only this refusal reads the form, to choose the answer; a request the gate admits is read after the gate. A refused body that is not a form (JSON, or none) names no intent and gets the same `403 { error }`. Any other error `requirePermission` throws propagates. |
139
147
 
140
148
  The loader throws `Response` `401` (`認証が必要です。`) when `requireUser` resolves `null`, and `403` (`権限がありません。`) when `requirePermission` throws `AuthzDeniedError` for `read`.
141
149
 
@@ -158,7 +166,8 @@ Each intent then answers `{ success: true, ... }` or refuses with `{ error }`:
158
166
  | `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). |
159
167
  | `cancel_integrity_run` | `400` / failure | `400 { error }` unless `runUid` is a UUID. Success answers `{ success, runUid }`. A failure answers `{ failure }` (below). |
160
168
  | `resolve_entity` | `400` | `entityId` is empty or `action` is neither `merge` nor `promote`; the store throws. |
161
- | `ingest_document` | `400` / `403` | `400` when `payload` is absent or empty, is not valid JSON, or is refused (not an object; `fileUri` absent, not a string, or blank; `confidentialityLevel` absent or not one of `PUBLIC`, `INTERNAL`, `DEPARTMENT`, `CONFIDENTIAL`, `RESTRICTED`; `departmentId` present but neither an integer nor `null` — an absent `departmentId` is accepted), and when the store throws. `403` when the host's `authorizeIngest(request, payload)` returns a refusal (the refusal is the `error`). Success answers `{ success, result }`. |
169
+ | `ingest_document` | `400` / `403` / `500` / `503` | `400` when `payload` is absent or empty, is not valid JSON, or is refused (not an object; `fileUri` absent, not a string, or blank; `confidentialityLevel` absent or not one of `PUBLIC`, `INTERNAL`, `DEPARTMENT`, `CONFIDENTIAL`, `RESTRICTED`; `departmentId` present but neither an integer nor `null` — an absent `departmentId` is accepted), and when the store throws. `403` when the host's `authorizeIngest(request, payload)` returns a refusal (the refusal is the `error`). The store's `{ kind: "refused", status, error }` is answered with its status (`403`, `500`, `503`) and `{ error }`. Success answers `{ success, result }`. |
170
+ | `capture_document_state` | `400` / `403` / `404` / `500` / `503` | `400 { error }` unless `metadataId` is written as a positive decimal integer within the safe range (neither the judgment nor the store is called). A refusal of `authorizeHistoryCapture` (`403` / `404` / `503`) is answered with its status and `{ captureFailure: { status, reason: error } }`, and the store is not called. The store's `failed` is answered the same way with its status (`404` / `500` / `503`); a throw, or an outcome of no known kind (only a store breaking its type can answer one; the mapping is an exhaustive `switch`, so a new kind fails to compile), is `500` with `reason` `""`. Success answers `{ outcome: "RECORDED" }` or `{ outcome: "UNCHANGED" }` and nothing else (no state id, sequence or facet). |
162
171
  | `inspect_uri` | `400` / `501` | `400` when `fileUri` is blank, the store throws, or the inspection's `fileSize` is not a non-negative safe integer (the count rule the ingest console draws it with; the `error` names `fileSize`, so a broken size never reaches the console as a value); `501` when the store implements no `inspectFileUri`. Success answers `{ success, inspection }`. |
163
172
  | any other value | `400` | `Unknown intent: <intent>`. |
164
173
 
@@ -179,7 +188,7 @@ Store failures are caught and answered as `400 { error }` only where the table s
179
188
 
180
189
  ## View props (`StorageAdminConsoleViewProps`)
181
190
 
182
- A host read answers every failure it can describe as an outcome. The reads whose failure the view itself shows (`loadIntegrityOverview`, `onLoadDocumentRuns`, `onBrowseGraphNodes`) settle even when the function breaks that contract: a rejection or a synchronous throw is shown as a failed read whose reason is the error's message, so no control stays busy and no panel stays loading. The ingest queue's refresh shows no failure: a failed round keeps the rows and the next round reads again.
191
+ A host read answers every failure it can describe as an outcome. The reads whose failure the view itself shows (`loadIntegrityOverview`, the four reads of `documentHistory`, `onBrowseGraphNodes`) settle even when the function breaks that contract: a rejection or a synchronous throw is shown as a failed read whose reason is the error's message, so no control stays busy and no panel stays loading. The ingest queue's refresh shows no failure: a failed round keeps the rows and the next round reads again.
183
192
 
184
193
  | Prop | Required | Purpose |
185
194
  | --- | --- | --- |
@@ -188,13 +197,13 @@ A host read answers every failure it can describe as an outcome. The reads whose
188
197
  | `loadIntegrityFindings: IntegrityFindingsLoader` | yes | `(query, signal) => Promise<ResourceOutcome<IntegrityFindingPage>>` — a page of one cell's findings, for the audit card's findings inspector. |
189
198
  | `policyConflicts: PolicyConflictHost` | yes | The summary, the list's pages, a pair's detail, the decision and the detection (`@aiquants/governance-react`); reads answer `ResourceOutcome`, the decision and the detection `CommandOutcome` with the core's rejection body. |
190
199
  | `documentAuthority: DocumentAuthorityHost` | yes | The ledger's pages, the unregistered candidates, the replaceable rows and the command (`CommandOutcome` with the core's rejection body). |
191
- | `onRefreshIngestQueue?: IngestQueueRefresher` | no | Refetches the ingest queue while an ingestion runs. Forwarded on both the connected and the `data`-prop path. |
200
+ | `onRefreshIngestQueue?: IngestQueueRefresher` | no | `() => Promise<IngestQueueRefresh>` — refetches the ingest queue while an entry is being processed (a readable row by its sync status or by a `RUNNING` run mark standing in for its latest run, a mark by its own sync status; a mark whose `syncStatus` is `null`, a document with no enrichment record, is not in progress). `{ kind: "rows", rows }` replaces the rows shown (readable rows and marks, the loader's list's shape); `{ kind: "refused", reason }` (the host route's 403 and its `{ error }`) withdraws the rows shown, states `reason` where the loader's refusal stands (the ingest console's `listRefusal`) and stops refreshing until the loader delivers again; a rejection keeps the rows and tries again on the next round. Rows the loader delivers restart the rounds and drop the answer of a refresh still in flight, so a refresh that began before a revalidation never replaces its newer rows. Never started for an operator the loader refused. Forwarded on both the connected and the `data`-prop path. |
192
201
  | `graphTraversal?: GraphTraversalHost` | no | `{ run: GraphTraversalRunner; listRelationshipTypes: GraphRelationshipTypesReader }` — graph traversal and the relationship types it may follow, supplied together; the traversal form is absent without it. `listRelationshipTypes` answers the deployment's offer (`{ ok: true, relationshipTypes }`, e.g. from the governance backend's `POST /ai/governance/admin/kg/relationship-types`, or `{ ok: false, reason }`); the form offers exactly those types, says why nothing can be traversed when the offer is empty, and re-reads when the function changes — keep the object stable (a module constant). A traversal that names no type follows the whole offer. `run` hands the backend's rows over unchanged (`label`, `from_label`, `to_label` included): the result map names each node by label and identifier, so an `Entity` and a `File` with the same identifier stay two nodes, and offers only `Entity` nodes as the next start. |
193
202
  | `onBrowseGraphNodes?` | no | Reads one page of a label's nodes; the index is absent without it. |
194
203
  | `onSimulateGovernance?: SimulationRunner` | no | Governance dry run; the dry-run console is absent without it. |
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. |
204
+ | `documentHistory?: DocumentHistoryHost` | no | `{ loadHistory(metadataId, signal), compare(query, signal), readLines(query, signal), loadChanges(cursor, signal) }` (`@aiquants/enrichment-react`'s host type, re-exported here), each resolving to a `ResourceOutcome`; pass a module constant. Without it the history panel, the recent changes card and every entry point (詳細, 履歴, 開く) are absent. A failed read's `reason` is a short phrase without a final 。 and a 403's names only the cause the route declared (`""` when none). Every read settles even when the function rejects or throws (a failure without a status whose reason is the error's message), and a history whose run step carries a report string with nothing to read (empty, or only white space of JavaScript's and Python's `\s`) is answered to the panel as a failed read naming the run, the step and the field, since the panel's step timeline would refuse it while rendering. |
196
205
  | `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. |
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. |
206
+ | `data?` / `fetcher?` / `integrityFetcher?` / `inspectorFetcher?` / `captureFetcher?` / `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`; `captureFetcher` the history panel's `capture_document_state` 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. |
198
207
 
199
208
  ## Tabs
200
209
 
@@ -214,17 +223,21 @@ Only the selected panel is mounted, so leaving a tab discards what was typed the
214
223
  - It writes the status badge (`PIPELINE_RUN_STATUS_PRESENTATION[pipelineRunPresentationKey(run)]`, so a failed run with a scheduled retry reads 失敗 (再試行予定)), the trigger (`PIPELINE_TRIGGER_LABELS`, the raw value kept in `data-trigger`) and the times (`@aiquants/enrichment-react`'s `RecordedInstant` / `FinishedInstant`, written in the console root's time zone, which the view sets from `displayTimeZone`) exactly as the history panel and the ingest queue do.
215
224
  - Its horizontal scroller is a containing block (`relative`), so the visually hidden header of the button column cannot widen the page at narrow widths.
216
225
  - Headers, run / document ids, kind, trigger, attempt, times and the 詳細 button never wrap (`whitespace-nowrap`); only the failed step and the requester (`wrap-anywhere`) wrap, so a squeezed table breaks long values instead of splitting 詳細 or きっかけ mid-word.
217
- - The document history panel (`PipelineRunInspector`) opens above the panels and stays open across tabs.
218
- - A recent run's 詳細 opens that run's document with that run selected. An ingest row's 履歴 opens the document's whole history and selects the newest run once it is read — also for a row with no recorded run, which the panel then states as a neutral `role="status"` note.
219
- - The panel reads through `onLoadDocumentRuns`, shows `処理履歴を読めませんでした (<reason>)。` when the read fails, rejects or throws (for a rejection or a throw the reason is the error's message; a `""` reason leaves out the parentheses), and ignores a read that settles after it was closed or another document was opened.
220
- - A 403 is not wrapped in that sentence: the panel states the refusal, `処理履歴を閲覧する権限がありません。`, followed by the declared cause as a second sentence (`…ありません。<reason>。`, by the console foundation's `failureSentence`, the rule `ResourceFailed` draws with), or that sentence alone for `""`.
221
- - An entry point's run stays selected even when the history does not list it (the panel says so); the newest run is never substituted for it.
222
- - Re-targeting keeps the one panel mounted. Every open from outside the panel (a 詳細 or 履歴 press, including one that names the run already shown) bumps the panel's `openRequest`, so focus moves to its heading each time; a load settling on the newest run does not move focus.
223
- - On 閉じる or Escape focus returns to the entry point that opened the panel most recently; when that element has left the page (its tab panel was switched away), the panel's `returnFocusFallback` hands focus to the active tab's button.
224
- - A history holding a provenance string with nothing to read (any string a step's report carries, such as `provider` or `model`) — empty, or only white space of JavaScript's and Python's `\s` — is shown as a failure naming the run, the step and the field (`処理履歴の記録に読めない来歴の値があります (実行 <id> の段 <sequence> の <field>)。`, not wrapped in the failed-read sentence), and its runs are not handed to the panel (the panel's measured text slot would refuse it while rendering and take the console with it).
226
+ - A restricted run mark is one row of the same table (`pipeline-run-mark-<position>`, `data-restricted-mark="run"`): its start and finish times, `隔離 (RESTRICTED) の文書` in the document column and its status, the other cells empty — no run id, kind, trigger, attempt, failed step, requester or 詳細. Its React key is its position in the answer (`restricted:<position>`), a readable run's its id (`readable:<id>`).
227
+ - With a non-`null` `documentReadRefusal` the table states it in place of its body (`document-read-refusal-pipeline`, a warning `Notice`): no run and no empty-table sentence, since the operator cannot read the runs, which is not the same as there being none.
228
+ - The document history panel (`@aiquants/enrichment-react`'s `DocumentHistoryInspector`) opens above the panels and stays open across tabs.
229
+ The panel owns the selection; the view passes the document, what the entry point selects (`DocumentHistoryTarget`) and an `openRequest` that advances on every open from outside, a press naming what is already shown included (the panel then re-reads the history and moves focus to its heading).
230
+ - A recent run's 詳細 opens that run's document selecting that run (`{ kind: "run", runId }`); an ingest row's or an audit finding's 履歴 opens the document selecting its newest readable state (`{ kind: "latest_state" }`); the recent changes card's 開く opens the change's document selecting its arriving state (`{ kind: "state", stateId }`).
231
+ - Re-targeting keeps the one panel mounted. On 閉じる or Escape focus returns to the entry point that opened the panel most recently; when that element has left the page (its tab panel was switched away), `returnFocusFallback` hands focus to the active tab's button.
232
+ - The panel reads through `documentHistory` as described under View props; its failures, its 403 withdrawal and its restricted-mark group are the panel's own.
233
+ - Its 今の状態を記録 submits `capture_document_state` with the document's metadata id on a fetcher of its own (`captureFetcher`), so no other submission aborts it; the answer settles the panel's command.
234
+ `{ outcome }` is announced (`記録しました` / `前の記録から変化はありません`) and the history read again; `{ captureFailure }` is stated by the panel from its status and reason; any other answer (the action's refusals before it reads the intent: no session, a blank `email`, a malformed `metadataId`) is a failure without a status whose reason is that `error` with exactly one final 。 removed, so the panel's sentence does not end in `。)。`.
235
+ A capture submitted before the previous one settled settles the previous one as replaced. Neither reaches the console's alert.
236
+ - `ingest` (ドキュメント取り込み & メタ生成) draws `DocumentIngestConsole` with `recentItems` = the loader's `recentIngestItems` (readable rows and ingest marks), replaced by the refresh's rows while an entry is being processed. A non-`null` `documentReadRefusal`, or a refresh's refusal, is passed as its `listRefusal`, so the list is replaced by that sentence (`recent-items-refused`): no row, no empty-list sentence, no row action.
225
237
  - `search` draws `MetadataSearchWorkbench` and, when `onCompareVariants` is supplied, `ModelComparisonWorkbench`, keyed by `strategyId`, with each variant labelled `<domainKey> / <variantKey> (<embeddingModel>)`.
226
238
  - `knowledge-authority` (権威台帳 & 規程衝突) draws `DocumentAuthorityRegistry` (its `canUpdate` is the loader's `canUpdateKnowledge`) and then `PolicyConflictQueue`. The view keeps a policy conflict revision: the ledger's `onPolicyConflictsChanged` advances it, and the queue re-reads its summary, its first page and the open detail in place when it changes.
227
- - `data-retention` (データ保持 & 整合性監査) draws `TriStoreIntegrityAudit`, then `PolicyConflictSummaryCard` (its `knowledgeTabLabel` is the knowledge-authority tab's label, and its link switches to that tab and moves focus to it), then the bulk-retry notice and the `SyncStatusMonitor` / `QdrantStorageCard` grid. `SyncStatusMonitor` sits in a `<section tabIndex={-1}>` (`sync-status-region`) named `エンリッチメント同期ステータス`, its card's own heading.
239
+ - `data-retention` (データ保持 & 整合性監査) draws `TriStoreIntegrityAudit`, then `PolicyConflictSummaryCard` (its `knowledgeTabLabel` is the knowledge-authority tab's label, and its link switches to that tab and moves focus to it),
240
+ then, with a `documentHistory` host, `DocumentChangeFeed` (直近の文書の変化, read through `loadChanges`, its 開く opening the history panel), then the bulk-retry notice and the `SyncStatusMonitor` / `QdrantStorageCard` grid; a non-`null` `documentReadRefusal` is `SyncStatusMonitor`'s `listRefusal`, so its failed list is replaced by that sentence (`failed-items-refused`). `SyncStatusMonitor` sits in a `<section tabIndex={-1}>` (`sync-status-region`) named `エンリッチメント同期ステータス`, its card's own heading.
228
241
  - The overview is kept last-good: the loader's answer, every poll and the reload are applied in arrival order through the console foundation's `keepLastGood`, so an overview once shown stays through later failures, which show only `更新に失敗しました (<reason>)。`. A success whose `readAt` is strictly earlier than the shown one (the core's `isStrictlyEarlier`, which compares every fractional digit across offsets) is dropped.
229
242
  - A 403 is the exception: `keepLastGood` withdraws a shown overview, since the operator may no longer read it and the card's refresh note carries no status to say so. The overview is then drawn as a first read answered 403 is (below), it stays so through every later answer that carries no value (a 503 after it changes nothing and is not announced again) until an overview is read again, and focus that was inside the audit card moves to the heading of the card drawn in its place.
230
243
  - Until an overview has been shown, and after a 403 withdrew it, a card titled `Tri-Store データ整合性監査` (`audit-overview-failed`) holds the console foundation's `ResourceFailed` (`audit-overview-failed-resource`).
@@ -236,7 +249,7 @@ Only the selected panel is mounted, so leaving a tab discards what was typed the
236
249
  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).
237
250
  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.
238
251
  - The card's findings inspector gets the console's document controls and remedy places:
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.
252
+ - `onShowHistory` is the ingest rows' history entry: a row's `履歴` opens the document history panel on the row's document and selects its newest readable state. Without `documentHistory` the rows offer no `履歴` and no remedy names it.
240
253
  - 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
254
  `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
255
  - `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`.
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
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});
1
+ "use strict";var Fe=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var en=Object.getOwnPropertyNames;var tn=Object.prototype.hasOwnProperty;var nn=(e,t)=>{for(var n in t)Fe(e,n,{get:t[n],enumerable:!0})},rn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of en(t))!tn.call(e,a)&&a!==n&&Fe(e,a,{get:()=>t[a],enumerable:!(r=Xt(t,a))||r.enumerable});return e};var sn=e=>rn(Fe({},"__esModule",{value:!0}),e);var nr={};nn(nr,{StorageAdminConsoleView:()=>Be,checkAllSystemHealth:()=>ze,checkBackendApiHealth:()=>wt,checkNeo4jHealth:()=>ht,checkQdrantHealth:()=>bt,checkRedisHealth:()=>vt,checkSqlServerHealth:()=>It,createStorageAdminApp:()=>tr,createStorageAdminServer:()=>Ye});module.exports=sn(nr);var k=require("@aiquants/console-ui"),P=require("@aiquants/enrichment-core"),y=require("@aiquants/enrichment-react"),h=require("@aiquants/governance-react"),p=require("react"),D=require("react-router");var ye="ja-JP";var an=/[^\s\x1c-\x1f\x85\ufeff]/;function fe(e){return an.test(e)}function B(e,t){return new Promise(n=>n(e())).catch(n=>t(n instanceof Error?n.message:String(n)))}var Re=require("@aiquants/console-ui/core"),ot=require("@aiquants/enrichment-core"),N=require("react");var on=2e3,ln=1e4;function De(e,t){return t.ok&&e.kind==="ready"&&(0,ot.isStrictlyEarlier)(t.value.readAt,e.value.readAt)?e:(0,Re.keepLastGood)(e,t)}var un=401;function cn(e){return e.kind==="failed"||e.refreshFailure!==null&&e.refreshFailure.status===un?null:e.value.active}function lt(e,t){let[n,r]=(0,N.useState)(()=>({loaded:e,overview:De({kind:"loading"},e)}));n.loaded!==e&&r({loaded:e,overview:De(n.overview,e)});let a=(0,N.useRef)(t);a.current=t;let s=(0,N.useRef)(null);(0,N.useEffect)(()=>()=>s.current?.abort(),[]);let l=(0,N.useCallback)((d,m)=>B(m,R=>({ok:!1,status:null,reason:R})).then(R=>{d.aborted||r(w=>({loaded:w.loaded,overview:De(w.overview,R)}))}),[]),u=(0,N.useCallback)(()=>{let d=new AbortController;s.current=d,r(m=>({loaded:m.loaded,overview:(0,Re.beginReload)(m.overview,"reload")})),l(d.signal,()=>a.current(d.signal))},[l]),c=(0,N.useCallback)(d=>l(d,()=>a.current(d)),[l]);return{overview:n.overview,reload:u,poll:c}}function dn(e){return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)}function pn(){return document.visibilityState==="visible"}function mn(){return!0}function ut(e,t,n){let r=(0,N.useSyncExternalStore)(dn,pn,mn),a=t&&r,s=(0,N.useRef)(a),l=e.kind==="ready",u=cn(e),c=u===null?null:u.run.runUid,d=u===null?!1:u.isStale;(0,N.useEffect)(()=>{let m=a&&!s.current;if(s.current=a,!a||c===null&&!(m&&l))return;let R=new AbortController,w=d?ln:on,C,b=async()=>{await n(R.signal),!R.signal.aborted&&c!==null&&(C=setTimeout(b,w))};return C=setTimeout(b,m?0:w),()=>{R.abort(),clearTimeout(C)}},[a,l,c,d,n])}var Le={columns:2,className:"grid-cols-2",spanClassNames:{1:"col-span-1",2:"col-span-2"}},je={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"}},Ue={className:"@min-[82rem]:grid-flow-col @min-[82rem]:auto-cols-fr @min-[82rem]:grid-cols-none",lastTabClassName:"@min-[82rem]:col-auto"};function He(e,t){let n=t%e.columns,r=n===0?1:e.columns-n+1;return e.spanClassNames[r]}var i=require("react/jsx-runtime"),ct="tab",Ke={key:"knowledge-authority",phrases:["\u6A29\u5A01\u53F0\u5E33 & \u898F\u7A0B\u885D\u7A81"]},qe={key:"pipeline",phrases:["\u30D1\u30A4\u30D7\u30E9\u30A4\u30F3 & \u63A5\u7D9A\u72B6\u614B"]},Ve={key:"parameters",phrases:["\u30E2\u30C7\u30EB & \u30D1\u30E9\u30E1\u30FC\u30BF\u8A2D\u5B9A"]},dt="\u30A8\u30F3\u30EA\u30C3\u30C1\u30E1\u30F3\u30C8\u540C\u671F\u30B9\u30C6\u30FC\u30BF\u30B9";function yn(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=P.IntegrityCellResyncResultSchema.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:l,nextAfter:u}=a.data;return{settled:n,status:u===null?"done":"pending",requeued:e.requeued+s,skipped:[...e.skipped,...l],nextAfter:u,error:null}}var 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"]},qe,{key:"knowledge-graph",phrases:["\u30CA\u30EC\u30C3\u30B8\u30B0\u30E9\u30D5","\u63A2\u7D22"]},Ve,{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 fn(e){return e!==null&&Q.some(t=>t.key===e)}var Rn="Tri-Store \u30C7\u30FC\u30BF\u6574\u5408\u6027\u76E3\u67FB";function Sn(e){return`\u76E3\u67FB\u306E\u6982\u6CC1\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F${(0,k.reasonAside)(e)}\u3002`}var bn={kind:"latest_state"},gt=[];function hn(e){for(let t of e.runs)if(t.kind==="readable")for(let n of t.item.steps){let r=n.provenance;if(r!==null){for(let[a,s]of Object.entries(r))if(typeof s=="string"&&!fe(s))return`\u5B9F\u884C #${t.item.id} \u306E\u6BB5 ${n.sequence} \u306E\u5831\u544A\u306E ${a} \u306B\u8AAD\u3081\u308B\u6587\u5B57\u304C\u3042\u308A\u307E\u305B\u3093`}}return null}function ae(e){return{ok:!1,status:null,reason:e}}function vn(e){return{loadHistory:async(t,n)=>{let r=await B(()=>e.loadHistory(t,n),ae);if(!r.ok)return r;let a=hn(r.value);return a===null?r:ae(a)},compare:(t,n)=>B(()=>e.compare(t,n),ae),readLines:(t,n)=>B(()=>e.readLines(t,n),ae),loadChanges:(t,n)=>B(()=>e.loadChanges(t,n),ae)}}function In(e){let t=P.DocumentCaptureAnswerSchema.safeParse(e);if(t.success)return{ok:!0,value:t.data};let n=e?.captureFailure;if(n!==void 0)return{ok:!1,status:n.status,reason:n.reason};let r=e?.error;return r===void 0?{ok:!1,status:null,reason:"\u8A18\u9332\u306E\u7B54\u3048\u306E\u5F62\u304C\u60F3\u5B9A\u3068\u7570\u306A\u308A\u307E\u3059"}:{ok:!1,status:null,reason:r.endsWith("\u3002")?r.slice(0,-1):r}}var Se={state:"idle",formData:null,data:null,submit:()=>Promise.resolve()};function yt({data:e,fetcher:t,integrityFetcher:n,inspectorFetcher:r,captureFetcher:a,renderHeader:s,graphTraversal:l,onBrowseGraphNodes:u,onSimulateGovernance:c,onRefreshIngestQueue:d,onSearch:m,documentHistory:R,onCompareVariants:w,loadIntegrityOverview:C,loadIntegrityFindings:b,policyConflicts:L,documentAuthority:f}){let[K,x]=(0,p.useState)(null),[E,T]=(0,p.useState)(null),[j,W]=(0,p.useState)(!1),J=(0,p.useMemo)(()=>{if(u!==void 0)return(o,g)=>{W(!0),B(()=>u(o,g),S=>({ok:!1,reason:S})).then(S=>{W(!1),T(S.ok?null:S.reason),S.ok&&x(S.page)})}},[u]),[Y,Z]=(0,D.useSearchParams)(),F=Y.get(ct),I=fn(F)?F:Q[0].key,U=o=>{Z(g=>{let S=new URLSearchParams(g);return S.set(ct,o),S},{replace:!1,preventScrollReset:!0})},q=e.documentReadRefusal,ue=q===null?e.recentIngestItems:gt,te=Cn(ue,d,I==="ingest"),H=lt(e.integrityAudit,C);ut(H.overview,I==="data-retention",H.poll);let ne=(0,p.useRef)(null),ce=(0,k.useFocusRescue)(()=>ne.current),[Ie,we]=(0,p.useState)(0),Ae=(0,p.useCallback)(()=>we(o=>o+1),[]),Ce=te.rows===null?ue:te.rows,de=q===null?te.refusal:q,X=(0,p.useRef)({}),Pe=(0,p.useCallback)(()=>X.current[I]??null,[I]),pe=(0,p.useMemo)(()=>Nn(e.enrichmentStrategies),[e.enrichmentStrategies]),Ne=(0,p.useMemo)(()=>e.strategyVariants.map(En),[e.strategyVariants]),V=(0,p.useMemo)(()=>R===void 0?void 0:vn(R),[R]),[ee,Ze]=(0,p.useState)(null),[Tt,_t]=(0,p.useState)(0),Ee=(0,p.useCallback)((o,g)=>{Ze({metadataId:o,target:g}),_t(S=>S+1)},[]),kt=(0,p.useCallback)(()=>Ze(null),[]),Ot=Pn(a),Xe=V===void 0?void 0:o=>Ee(o,bn),xt=V===void 0?void 0:o=>Ee(o.metadataId,{kind:"run",runId:o.id}),Ft=(o,g)=>Ee(o,{kind:"state",stateId:g}),Dt=(o,g)=>{let S=Q.length-1,_;if(o.key==="ArrowRight"||o.key==="ArrowDown")_=g===S?0:g+1;else if(o.key==="ArrowLeft"||o.key==="ArrowUp")_=g===0?S:g-1;else if(o.key==="Home")_=0;else if(o.key==="End")_=S;else return;o.preventDefault();let ge=Q[_].key;U(ge),X.current[ge]?.focus()},et={...e.featureFlags};if(t.formData&&t.formData.get("intent")==="toggle_flag"){let o=String(t.formData.get("flagKey")??""),g=String(t.formData.get("enabled")??"")==="true";o&&(et[o]=g)}let Lt=t.data&&"inspection"in t.data?t.data.inspection:void 0,re=t.state==="idle"?null:t.formData?.get("intent"),jt=re==="inspect_uri",Ut=re==="ingest_document",Ht=re==="retry_job"||re==="retry_all_failed",$t=re==="resolve_entity",tt=n.state==="idle"?null:n.formData?.get("intent"),Mt=tt==="start_integrity_run"?{kind:"starting",mode:P.IntegrityRunModeSchema.parse(n.formData?.get("mode"))}:tt==="cancel_integrity_run"?{kind:"cancelling"}:{kind:"idle"},Kt=(0,D.useRevalidator)(),[qt,Te]=(0,p.useState)(null),nt=I!=="data-retention";(0,p.useEffect)(()=>{nt&&Te(null)},[nt]);let Vt=o=>{let g=o?.failure;if(g===void 0){Te(null);return}Te(S=>({failure:g,occurrence:S===null?1:S.occurrence+1})),(0,h.integrityFailureNeedsOverviewReread)(g)&&Kt.revalidate()},[se,_e]=(0,p.useState)(null),[me,ke]=(0,p.useState)(null),Bt=o=>{_e({metadataId:o,intent:"retry_job",status:"pending",error:null}),r.submit({intent:"retry_job",fileId:String(o)},{method:"post"})},Qt=o=>{o.after===void 0&&ke({settled:0,status:"pending",requeued:0,skipped:[],nextAfter:null,error:null});let{after:g,...S}=o;r.submit(g===void 0?{intent:"resync_findings",...S}:{intent:"resync_findings",...S,after:String(g)},{method:"post"})},Gt=()=>{_e(null),ke(null)},[rt,Oe]=(0,p.useState)("console"),[zt,Wt]=(0,p.useState)(void 0),Jt=(o,g)=>{if(g==="retry_job"&&se!==null&&se.status==="pending"){let S=o?.error;_e(S===void 0?{...se,status:"accepted",error:null}:{...se,status:"refused",error:S});return}if(g==="resync_findings"&&me!==null&&me.status==="pending"){ke(yn(me,o));return}Wt(o?.error),Oe("inspector")},{settledIntent:Yt,submitAndAwait:st}=be(t,()=>Oe("console"));be(n,o=>{Oe("integrity"),Vt(o)}),be(r,Jt);let it=rt==="inspector"?zt:(rt==="console"?t:n).data?.error,xe=o=>{U(o),X.current[o]?.focus()},at=(0,p.useRef)(null),Zt={strategies:{label:$e(qe),onOpen:()=>xe(qe.key),closesInspector:!0},projectionPolicy:{label:$e(Ve),onOpen:()=>xe(Ve.key),closesInspector:!0},failedSync:{label:dt,onOpen:()=>at.current?.focus(),closesInspector:!1}},ie=Yt==="retry_all_failed"&&t.data?.skipped!==void 0&&t.data.requeued!==void 0?{requeued:t.data.requeued,skipped:t.data.skipped}:null;return(0,i.jsx)(k.ConsoleUiRoot,{locale:"ja",formatLocale:ye,timeZone:e.displayTimeZone,testId:"storage-admin-console-ui",children:(0,i.jsxs)("div",{className:"container mx-auto space-y-6 p-6 font-sans text-slate-900","data-testid":"storage-admin-console",children:[it&&(0,i.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:it}),s?s({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:e.tenantId}):(0,i.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,i.jsxs)("div",{children:[(0,i.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,i.jsxs)("p",{className:"mt-1 text-slate-500 text-sm",children:["\u30C6\u30CA\u30F3\u30C8: ",(0,i.jsx)("code",{className:"font-semibold text-slate-800",children:e.tenantId})," | \u5168\u30B7\u30B9\u30C6\u30E0\u72B6\u614B\u30FB\u30D1\u30E9\u30E1\u30FC\u30BF\u5236\u5FA1\u30FB\u6574\u5408\u6027\u76E3\u67FB"]})]}),(0,i.jsx)("div",{className:"flex items-center gap-2",children:(0,i.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,i.jsx)("span",{className:`h-2 w-2 rounded-full ${e.systemHealth.allHealthy?"bg-emerald-500":"bg-amber-500"}`}),(0,i.jsxs)("span",{children:["\u5468\u8FBA\u6A5F\u80FD: ",e.systemHealth.allHealthy?"\u5168\u30B5\u30FC\u30D3\u30B9\u6B63\u5E38":"\u63A5\u7D9A\u8981\u78BA\u8A8D"]})]})})]}),(0,i.jsxs)("div",{className:"w-full space-y-6",children:[(0,i.jsx)("div",{className:"@container w-full","data-testid":"storage-admin-tablist-frame",children:(0,i.jsx)("div",{className:`grid w-full ${Le.className} ${je.className} ${Ue.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((o,g)=>{let S=I===o.key;return(0,i.jsx)("button",{id:`tab-${o.key}`,type:"button",role:"tab",ref:_=>{X.current[o.key]=_},"aria-selected":S,"aria-controls":`panel-${o.key}`,tabIndex:S?0:-1,"data-testid":`tab-trigger-${o.key}`,onKeyDown:_=>Dt(_,g),onClick:()=>U(o.key),className:`wrap-anywhere break-keep rounded-lg px-3 py-2.5 text-center font-medium text-sm transition-all ${g===Q.length-1?`${He(Le,Q.length)} ${He(je,Q.length)} ${Ue.lastTabClassName}`:""} ${S?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:bg-slate-200/50 hover:text-slate-900"}`,children:o.phrases.map((_,ge)=>(0,i.jsxs)(p.Fragment,{children:[ge>0&&(0,i.jsx)("wbr",{}),_]},_))},o.key)})})}),V!==void 0&&ee!==null&&(0,i.jsx)(y.DocumentHistoryInspector,{host:V,metadataId:ee.metadataId,target:ee.target,openRequest:Tt,onClose:kt,returnFocusFallback:Pe,captureState:Ot}),I==="search"&&(0,i.jsxs)("div",{role:"tabpanel",id:"panel-search","aria-labelledby":"tab-search",className:"space-y-6","data-testid":"tab-content-search",children:[(0,i.jsx)(y.MetadataSearchWorkbench,{tenantId:e.tenantId,onSearch:m,circuitBreakerStatus:e.circuitBreakerStatus}),w!==void 0&&(0,i.jsx)(y.ModelComparisonWorkbench,{variants:Ne,onCompare:w})]}),I==="ingest"&&(0,i.jsx)("div",{role:"tabpanel",id:"panel-ingest","aria-labelledby":"tab-ingest",className:"space-y-6","data-testid":"tab-content-ingest",children:(0,i.jsx)(y.DocumentIngestConsole,{tenantId:e.tenantId,policies:e.confidentialityPolicies,domainOptions:pe,recentItems:Ce,listRefusal:de===null?void 0:de,inspectionResult:Lt,isInspecting:jt,isSubmitting:Ut,onInspectUri:o=>{t.submit({intent:"inspect_uri",fileUri:o},{method:"post"})},onIngestDocument:o=>{t.submit({intent:"ingest_document",payload:JSON.stringify(o)},{method:"post"})},onRetryItem:o=>{t.submit({intent:"retry_job",fileId:String(o)},{method:"post"})},onShowHistory:Xe})}),I==="pipeline"&&(0,i.jsxs)("div",{role:"tabpanel",id:"panel-pipeline","aria-labelledby":"tab-pipeline",className:"space-y-6","data-testid":"tab-content-pipeline",children:[(0,i.jsx)(y.PipelineFlowViewer,{featureFlags:e.featureFlags,metrics:e.pipelineStepMetrics,metricSampleWindow:e.pipelineStepMetricWindow}),(0,i.jsx)(Tn,{runs:e.recentPipelineRuns,refusal:q,onOpenRun:xt}),(0,i.jsx)(y.EnrichmentStrategyBoard,{strategies:e.enrichmentStrategies,featureFlags:e.featureFlags,isUpdating:t.state!=="idle",onToggleStage:(o,g,S)=>t.submit({intent:"update_enrichment_strategy",strategyId:String(o.id),domainId:String(o.domainId),stage:g,enabled:String(S)},{method:"post"})}),(0,i.jsx)(y.InfrastructureHealthMonitor,{health:e.systemHealth,isRefreshing:t.state!=="idle",onRefresh:()=>t.submit({intent:"refresh_health"},{method:"post"})})]}),I==="knowledge-graph"&&(0,i.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,i.jsx)(y.OntologyStatusCard,{tenantId:e.tenantId,ontologyStatus:e.ontologyStatus}),(0,i.jsx)(h.KnowledgeGraphExplorer,{topologyMaxLabels:P.GRAPH_INDEX_LIMITS.topologyLabels.default,schema:e.graphSchema,tenantId:e.tenantId,unresolvedEntities:e.unresolvedEntities,traversal:l,onBrowseLabel:J,nodeIndexPage:K,nodeIndexFailure:E,isNodeIndexLoading:j,isResolving:$t,onResolveEntity:(o,g)=>{t.submit({intent:"resolve_entity",entityId:o,action:g},{method:"post"})}})]}),I==="parameters"&&(0,i.jsxs)("div",{role:"tabpanel",id:"panel-parameters","aria-labelledby":"tab-parameters",className:"space-y-6","data-testid":"tab-content-parameters",children:[(0,i.jsxs)("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2",children:[(0,i.jsx)(h.FeatureFlagBoard,{flags:et,isUpdating:t.state!=="idle",onToggleFlag:(o,g)=>{t.submit({intent:"toggle_flag",flagKey:o,enabled:String(g)},{method:"post"})}}),(0,i.jsx)(h.ClassificationRuleEditor,{rules:e.classificationRules,domainOptions:pe,consultedBy:e.classificationRuleConsumer,onReorderRules:o=>{t.submit({intent:"reorder_rules",orderedRuleIds:JSON.stringify(o)},{method:"post"})}})]}),e.policiesMissingDestination.length>0&&(0,i.jsxs)("div",{"data-testid":"policies-missing-destination",role:"alert",style:{padding:"10px 12px",borderRadius:"6px",backgroundColor:"#fef2f2",color:"#b91c1c",fontSize:"12px"},children:[(0,i.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,i.jsx)("ul",{style:{margin:"6px 0 0",paddingInlineStart:"18px"},children:e.policiesMissingDestination.map(o=>(0,i.jsxs)("li",{"data-testid":`missing-destination-${o.confidentialityLevel}-${o.capability}`,children:[o.confidentialityLevel," / ",o.capability," \u2192 ",o.promptKey," (",o.modelProvider,") \u306E ",(0,i.jsx)("code",{children:"extra_params.base_url"})]},`${o.confidentialityLevel}:${o.capability}`))}),(0,i.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,i.jsx)(h.ConfidentialityPolicyBoard,{policies:e.confidentialityPolicies,promptKeys:e.promptTemplates.map(o=>o.template_key),isUpdating:t.state!=="idle",onChangePolicy:o=>{t.submit({intent:"update_confidentiality_policy",confidentialityLevel:o.confidentialityLevel,capability:o.capability,isEnabled:String(o.isEnabled),allowCloudProvider:String(o.allowCloudProvider),promptKey:o.promptKey??""},{method:"post"})}}),(0,i.jsx)(h.TranscriptionAdaptationBoard,{vocabulary:e.transcriptionVocabulary,references:e.transcriptionReferences,unresolvedUris:e.unresolvedReferenceUris,isUpdating:t.state!=="idle",onSaveTerm:o=>st({intent:"save_transcription_term",id:o.id===null?"":String(o.id),term:o.term,reading:o.reading??"",boost:o.boost===null?"":String(o.boost),domainKey:o.domainKey??"",isActive:String(o.isActive)},{method:"post"}),onSaveReference:o=>st({intent:"save_transcription_reference",id:o.id===null?"":String(o.id),fileUri:o.fileUri,domainKey:o.domainKey??"",isActive:String(o.isActive)},{method:"post"})}),(0,i.jsx)(h.SystemParameterTable,{parameters:e.systemParameters,onSaveParameter:(o,g)=>{t.submit({intent:"update_parameter",paramKey:o,paramValue:String(g)},{method:"post"})}})]}),I==="prompts"&&(0,i.jsxs)("div",{role:"tabpanel",id:"panel-prompts","aria-labelledby":"tab-prompts",className:"space-y-6","data-testid":"tab-content-prompts",children:[(0,i.jsx)(h.PromptTemplateConsole,{templates:e.promptTemplates,isSaving:t.state!=="idle",onSaveTemplate:o=>{t.submit({intent:"update_prompt",templateKey:o.template_key,payload:JSON.stringify({templateText:o.template_text,modelName:o.model_name,temperature:o.temperature,maxOutputTokens:o.max_output_tokens,responseSchema:o.response_schema,endpointBaseUrl:o.endpoint_base_url??null})},{method:"post"})}}),(0,i.jsx)(h.GovernanceDryRunConsole,{onSimulate:c})]}),I==="knowledge-authority"&&(0,i.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,i.jsx)(h.DocumentAuthorityRegistry,{host:f,canUpdate:e.canUpdateKnowledge,onPolicyConflictsChanged:Ae}),(0,i.jsx)(h.PolicyConflictQueue,{host:L,revision:Ie})]}),I==="data-retention"&&(0,i.jsxs)("div",{role:"tabpanel",id:"panel-data-retention","aria-labelledby":"tab-data-retention",className:"space-y-6","data-testid":"tab-content-data-retention",children:[H.overview.kind==="ready"?(0,i.jsx)("div",{ref:ce,children:(0,i.jsx)(h.TriStoreIntegrityAudit,{overview:H.overview.value,canReadFindings:e.canReadIntegrityFindings,command:Mt,commandFailure:qt,onStartRun:(o,g)=>{n.submit(g===null?{intent:"start_integrity_run",mode:o}:{intent:"start_integrity_run",mode:o,basisRunUid:g},{method:"post"})},onCancelRun:o=>{n.submit({intent:"cancel_integrity_run",runUid:o},{method:"post"})},loadFindings:b,refreshFailure:H.overview.refreshFailure===null?null:H.overview.refreshFailure.reason,headingRef:ne,onShowHistory:Xe,resync:{onResync:Bt,onDismiss:Gt,feedback:se,sending:r.state!=="idle",cellResync:{onResyncCell:Qt,feedback:me}},remedyDestinations:Zt})}):(0,i.jsx)(k.Card,{title:Rn,testId:"audit-overview-failed",headingRef:ne,children:(0,i.jsx)(k.ResourceFailed,{failure:H.overview,onReload:H.reload,forbiddenMessage:"\u76E3\u67FB\u306E\u6982\u6CC1\u3092\u95B2\u89A7\u3059\u308B\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002",failureMessage:Sn,rescueRef:ce,testId:"audit-overview-failed-resource"})}),(0,i.jsx)(h.PolicyConflictSummaryCard,{host:L,knowledgeTabLabel:$e(Ke),onOpenKnowledgeTab:()=>xe(Ke.key)}),V!==void 0&&(0,i.jsx)(y.DocumentChangeFeed,{host:V,onOpen:Ft}),ie!==null&&ie.skipped.length>0&&(0,i.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,i.jsxs)("strong",{children:["\u4E00\u62EC\u518D\u8A66\u884C: ",ie.requeued," \u4EF6\u3092\u518D\u6295\u5165\u3057\u3001",ie.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,i.jsx)("ul",{className:"mt-1.5 list-disc ps-5",children:ie.skipped.map(o=>(0,i.jsxs)("li",{"data-testid":`retry-all-skipped-${o.metadataId}`,children:["#",o.metadataId,": ",o.reason]},o.metadataId))})]}),(0,i.jsxs)("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2",children:[(0,i.jsx)("section",{ref:at,tabIndex:-1,"aria-label":dt,"data-testid":"sync-status-region",children:(0,i.jsx)(y.SyncStatusMonitor,{counts:e.syncCounts,totalFiles:e.totalFiles,failedItems:e.failedSyncItems,listRefusal:q===null?void 0:q,isRetrying:Ht,onRetryItem:o=>{t.submit({intent:"retry_job",fileId:String(o)},{method:"post"})},onRetryAll:()=>{t.submit({intent:"retry_all_failed"},{method:"post"})}})}),(0,i.jsx)(y.QdrantStorageCard,{overview:e.qdrantCollections,health:{healthy:e.systemHealth.services.qdrant.status==="connected",latency_ms:e.systemHealth.services.qdrant.latencyMs}})]})]})]})]})})}var pt=new Set(P.EnrichmentSyncStatusSchema.options.filter(e=>e!=="SYNCED"&&!e.startsWith("FAILED"))),wn=new Set(P.PipelineRunStatusSchema.options.filter(e=>e!=="SUCCEEDED"&&!e.startsWith("FAILED"))),mt=2e3;function An(e){if(e.kind==="restricted")return e.syncStatus!==null&&pt.has(e.syncStatus);let t=e.item.lastRun;return pt.has(e.item.syncStatus)||t!==null&&t.kind==="restricted"&&wn.has(t.status)}var Me={rows:null,refusal:null};function Cn(e,t,n){let[r,a]=(0,p.useState)(Me),s=(0,p.useRef)(t);s.current=t;let l=(0,p.useRef)(e);l.current!==e&&(l.current=e,r!==Me&&a(Me));let c=(r.rows===null?e:r.rows)?.some(An)===!0;return(0,p.useEffect)(()=>{if(!(n&&c&&s.current))return;let d=!1,m,R=async()=>{let w=s.current;if(w!==void 0){try{let C=await w();if(d)return;a(C.kind==="rows"?{rows:C.rows,refusal:null}:{rows:gt,refusal:C.reason})}catch{if(d)return}m=setTimeout(R,mt)}};return m=setTimeout(R,mt),()=>{d=!0,clearTimeout(m)}},[c,n,e]),r}function Pn(e){let t=(0,p.useRef)(e);t.current=e;let n=(0,p.useRef)(null);return be(e,r=>{let a=n.current;n.current=null,a?.(In(r))}),(0,p.useCallback)(r=>new Promise(a=>{n.current?.({ok:!1,status:null,reason:"\u5F8C\u306E\u8A18\u9332\u306B\u7F6E\u304D\u63DB\u3048\u3089\u308C\u307E\u3057\u305F"}),n.current=a,t.current.submit({intent:"capture_document_state",metadataId:String(r)},{method:"post"})}),[])}function be(e,t){let n=(0,p.useRef)(t);n.current=t;let r=(0,p.useRef)(null),a=(0,p.useRef)(!1),s=(0,p.useRef)(null);if(e.state!=="idle"){a.current=!0;let u=e.formData?.get("intent");typeof u=="string"&&(r.current=u)}(0,p.useEffect)(()=>{if(e.state!=="idle"||!a.current)return;a.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,p.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 Nn(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 En(e){return{strategyId:e.strategyId,label:`${e.domainKey} / ${e.variantKey}`,embeddingModel:e.embeddingModel}}function Tn({runs:e,refusal:t,onOpenRun:n}){return(0,i.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,i.jsx)("h2",{id:"pipeline-recent-runs-heading",className:"font-bold text-base text-slate-900",children:"\u76F4\u8FD1\u306E\u5B9F\u884C"}),t!==null?(0,i.jsx)("div",{className:"mt-4",children:(0,i.jsx)(k.Notice,{tone:"warning",testId:"document-read-refusal-pipeline",children:t})}):e.length===0?(0,i.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,i.jsx)("div",{className:"relative mt-4 overflow-x-auto","data-testid":"pipeline-recent-runs-scroll",children:(0,i.jsxs)("table",{className:"w-full text-left text-[13px]",children:[(0,i.jsx)("thead",{children:(0,i.jsxs)("tr",{className:"whitespace-nowrap border-slate-200 border-b border-solid text-[11px] text-slate-500 uppercase",children:[(0,i.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u5B9F\u884C"}),(0,i.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u6587\u66F8"}),(0,i.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u7A2E\u985E"}),(0,i.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u304D\u3063\u304B\u3051"}),(0,i.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u8A66\u884C"}),(0,i.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u72B6\u614B"}),(0,i.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u6B62\u307E\u3063\u305F\u6BB5"}),(0,i.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u958B\u59CB"}),(0,i.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u7D42\u4E86"}),(0,i.jsx)("th",{scope:"col",className:"px-3 py-2",children:"\u8981\u6C42\u8005"}),n!==void 0&&(0,i.jsx)("th",{scope:"col",className:"px-3 py-2",children:(0,i.jsx)("span",{className:"sr-only","data-testid":"pipeline-recent-runs-action-header",children:"\u64CD\u4F5C"})})]})}),(0,i.jsx)("tbody",{children:e.map((r,a)=>{if(r.kind==="restricted"){let c=y.PIPELINE_RUN_STATUS_PRESENTATION[r.status];return(0,i.jsxs)("tr",{className:"border-slate-100 border-b border-solid","data-testid":`pipeline-run-mark-${a}`,"data-restricted-mark":"run","data-status":r.status,children:[(0,i.jsx)("td",{className:"px-3 py-2"}),(0,i.jsx)("td",{className:"px-3 py-2","data-testid":`pipeline-run-mark-document-${a}`,children:y.RESTRICTED_DOCUMENT_TEXT}),(0,i.jsx)("td",{className:"px-3 py-2"}),(0,i.jsx)("td",{className:"px-3 py-2"}),(0,i.jsx)("td",{className:"px-3 py-2"}),(0,i.jsx)("td",{className:"px-3 py-2",children:(0,i.jsx)("span",{className:`inline-flex whitespace-nowrap rounded-full px-2 py-0.5 font-semibold text-[11px] ${c.className}`,"data-testid":`pipeline-run-mark-status-${a}`,"data-status":r.status,children:c.label})}),(0,i.jsx)("td",{className:"px-3 py-2"}),(0,i.jsx)("td",{className:"whitespace-nowrap px-3 py-2 text-slate-500","data-testid":`pipeline-run-mark-started-${a}`,children:(0,i.jsx)(y.RecordedInstant,{iso:r.startedAt,testId:`pipeline-run-mark-started-value-${a}`})}),(0,i.jsx)("td",{className:"whitespace-nowrap px-3 py-2 text-slate-500","data-testid":`pipeline-run-mark-finished-${a}`,children:(0,i.jsx)(y.FinishedInstant,{iso:r.finishedAt,testId:`pipeline-run-mark-finished-value-${a}`})}),(0,i.jsx)("td",{className:"px-3 py-2"}),n!==void 0&&(0,i.jsx)("td",{className:"px-3 py-2"})]},`restricted:${a}`)}let s=r.item,l=(0,y.pipelineRunPresentationKey)(s),u=y.PIPELINE_RUN_STATUS_PRESENTATION[l];return(0,i.jsxs)("tr",{className:"border-slate-100 border-b border-solid","data-testid":`pipeline-run-row-${s.id}`,"data-status":s.status,children:[(0,i.jsxs)("td",{className:"whitespace-nowrap px-3 py-2 font-mono","data-testid":`pipeline-run-id-${s.id}`,children:["#",s.id]}),(0,i.jsxs)("td",{className:"whitespace-nowrap px-3 py-2 font-mono","data-testid":`pipeline-run-metadata-${s.id}`,children:["#",s.metadataId]}),(0,i.jsx)("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-kind-${s.id}`,children:P.DOCUMENT_KIND_LABELS[s.documentKind]}),(0,i.jsx)("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-trigger-${s.id}`,"data-trigger":s.trigger,children:y.PIPELINE_TRIGGER_LABELS[s.trigger]}),(0,i.jsx)("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-attempt-${s.id}`,children:s.attempt}),(0,i.jsx)("td",{className:"px-3 py-2",children:(0,i.jsx)("span",{className:`inline-flex whitespace-nowrap rounded-full px-2 py-0.5 font-semibold text-[11px] ${u.className}`,"data-testid":`pipeline-run-status-${s.id}`,"data-status":s.status,"data-presentation":l,children:u.label})}),(0,i.jsx)("td",{className:"px-3 py-2","data-testid":`pipeline-run-failed-step-${s.id}`,children:s.failedStepKey===null?"\u2014":P.PIPELINE_STEPS[s.failedStepKey].label}),(0,i.jsx)("td",{className:"whitespace-nowrap px-3 py-2 text-slate-500","data-testid":`pipeline-run-started-${s.id}`,children:(0,i.jsx)(y.RecordedInstant,{iso:s.startedAt,testId:`pipeline-run-started-value-${s.id}`})}),(0,i.jsx)("td",{className:"whitespace-nowrap px-3 py-2 text-slate-500","data-testid":`pipeline-run-finished-${s.id}`,children:(0,i.jsx)(y.FinishedInstant,{iso:s.finishedAt,testId:`pipeline-run-finished-value-${s.id}`})}),(0,i.jsx)("td",{className:"wrap-anywhere px-3 py-2","data-testid":`pipeline-run-requested-by-${s.id}`,children:s.requestedBy}),n!==void 0&&(0,i.jsx)("td",{className:"whitespace-nowrap px-3 py-2 text-right",children:(0,i.jsx)("button",{type:"button",onClick:()=>n(s),"aria-label":`\u5B9F\u884C #${s.id} (\u6587\u66F8 #${s.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-${s.id}`,children:"\u8A73\u7D30"})})]},`readable:${s.id}`)})})]})})]})}function _n(e){let t=(0,D.useLoaderData)(),n=(0,D.useFetcher)(),r=(0,D.useFetcher)(),a=(0,D.useFetcher)(),s=(0,D.useFetcher)(),l=e.data??t,u=e.fetcher??n,c=e.integrityFetcher??r,d=e.inspectorFetcher??a,m=e.captureFetcher??s;return l?(0,i.jsx)(yt,{...e,data:l,fetcher:u,integrityFetcher:c,inspectorFetcher:d,captureFetcher:m}):(0,i.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 Be(e){return e.data?(0,i.jsx)(yt,{...e,data:e.data,fetcher:e.fetcher??Se,integrityFetcher:e.integrityFetcher??Se,inspectorFetcher:e.inspectorFetcher??Se,captureFetcher:e.captureFetcher??Se}):(0,i.jsx)(_n,{...e})}var Je=require("@aiquants/authz-core"),Ct=require("@aiquants/console-ui/core"),v=require("@aiquants/enrichment-core"),G=require("@aiquants/governance-core"),A=require("zod");var Ge=3e3;function M(e){return Math.round(performance.now()-e)}function O(e){return typeof e=="string"&&fe(e)?e:null}function $(e){let t=globalThis.process;return t===void 0?void 0:t.env[e]}function he(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 ft(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 Rt(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 St(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 a=Number(r);return Number.isInteger(a)&&a>0&&a<=65535?a:void 0}async function Qe(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 bt(e){let t=e?.qdrantApiKey??$("QDRANT_API_KEY")??"",n=e?.timeoutMs??Ge,r=performance.now(),a="";try{a=he(e?.qdrantUrl??$("QDRANT_URL"),"QDRANT_URL");let s={};t&&(s["api-key"]=t);let[l,u]=await Promise.all([fetch(`${a}/`,{headers:s,signal:AbortSignal.timeout(n)}),fetch(`${a}/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=M(r),R=(await u.json()).result?.collections?.length??0;return{serviceName:"Qdrant",category:"vector",status:"connected",version:O(c.version),endpoint:a,latencyMs:d,details:{engine:O(c.title),collectionsCount:R,restPort:kn(a)??null,tls:St(a)??null}}}catch(s){let l=M(r),u=s instanceof Error?s.message:String(s);return{serviceName:"Qdrant",category:"vector",status:"error",version:null,endpoint:a,latencyMs:l,details:{},errorMessage:u}}}async function ht(e){let t=e?.timeoutMs??Ge,n=performance.now(),r=O(e?.neo4jBoltUri??$("NEO4J_URI")),a=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([Qe(s("CALL dbms.components() YIELD versions, edition RETURN versions[0] AS version, edition",{}),t),Qe(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,m]=u.rows[0]??[],R=c.rows[0]?.[0],w=M(n);return{serviceName:"Neo4j",category:"graph",status:"connected",version:O(d),endpoint:a,latencyMs:w,details:{edition:O(m),boltUri:r,nodeCount:typeof R=="number"?R:null,tls:r===null?null:St(r)??null}}}catch(s){let l=M(n),u=s instanceof Error?s.message:String(s);return{serviceName:"Neo4j",category:"graph",status:"error",version:null,endpoint:a,latencyMs:l,details:{},errorMessage:u}}}async function vt(e){let t=performance.now(),n="",r=Rt(e?.redisTls,$("REDIS_TLS")),a=Number.NaN;try{let s=e?.redisClient;if(!s)throw new Error("Redis client not configured");let l=he(e?.redisHost??$("REDIS_HOST"),"REDIS_HOST");a=ft(e?.redisPort,$("REDIS_PORT"),"REDIS_PORT"),n=`${r===!1?"redis":"rediss"}://${l}:${a}`,await s.ping();let u=await s.info("server"),c=O(u.match(/redis_version:([^\r\n]+)/)?.[1]),d=null;if(typeof s.dbSize=="function")try{d=await s.dbSize()}catch{d=null}let m=M(t);return{serviceName:"Redis",category:"cache",status:"connected",version:c,endpoint:n,latencyMs:m,details:{totalKeys:d,port:a,tls:r??null,database:0}}}catch(s){let l=M(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 It(e){let t=performance.now(),n="",r=Rt(e?.sqlServerTls,$("SQL_SERVER_TLS")),a=Number.NaN;try{let s=e?.sqlServerExecute;if(!s)throw new Error("SQL Server executor not configured");let l=he(e?.sqlServerHost??$("SQL_SERVER_HOST"),"SQL_SERVER_HOST");a=ft(e?.sqlServerPort,$("SQL_SERVER_PORT"),"SQL_SERVER_PORT"),n=`${l}:${a}`;let u=await s(),c=O(u.db_name),d=O(u.version),m=d===null?null:O(d.split(`
2
+ `)[0]),R=m===null?null:On(m),w=M(t);return{serviceName:"SQL Server",category:"database",status:"connected",version:R,endpoint:n,latencyMs:w,details:{database:c,port:a,tls:r??null,fullVersion:m}}}catch(s){let l=M(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 wt(e){let t=e?.timeoutMs??Ge,n=performance.now(),r="";try{r=he(e?.backendApiHost??$("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(),l=Object.keys(s.paths??{}).length,u=M(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(a){let s=M(n),l=a instanceof Error?a.message:String(a);return{serviceName:"AI Quant API",category:"api",status:"error",version:null,endpoint:r,latencyMs:s,details:{},errorMessage:l}}}async function ze(e){let[t,n,r,a,s]=await Promise.all([bt(e),ht(e),vt(e),It(e),wt(e)]),l=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:l,checkedAt:new Date().toISOString()}}var xn=A.z.object({templateText:A.z.string(),modelName:A.z.string(),temperature:A.z.number(),maxOutputTokens:A.z.number(),responseSchema:A.z.union([A.z.record(A.z.string(),A.z.unknown()),A.z.string(),A.z.null()]).optional(),endpointBaseUrl:A.z.string().nullable()}).strict(),Fn=A.z.discriminatedUnion("mode",[A.z.object({mode:v.IntegrityRunModeSchema.extract(["SCAN"]),basisRunUid:A.z.null()}).strict(),A.z.object({mode:v.IntegrityRunModeSchema.extract(["REPAIR"]),basisRunUid:A.z.string().uuid()}).strict()]),Dn=A.z.object({runUid:A.z.string().uuid()}).strict();function Pt(e){return e==="start_integrity_run"?"start":e==="cancel_integrity_run"?"cancel":null}function z(e,t){return e.issues.map(n=>`${n.path.length===0?t:n.path.join(".")}: ${n.message}`).join("; ")}function Ln(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 jn(e){let t=v.RecentPipelineRunEntrySchema.array().safeParse(e);if(!t.success)throw new Error(`getRecentPipelineRuns answered something that is neither a readable run summary nor a restricted run mark: ${z(t.error,"getRecentPipelineRuns")}`);return t.data}function Un(e){let t=v.PipelineStepMetricSchema.array().safeParse(e);if(!t.success)throw new Error(`getPipelineStepMetrics answered something that is not a step metric: ${z(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 Hn(e){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`pipelineStepMetricWindow must be a positive safe integer, got ${String(e)}`);return e}async function $n(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=v.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: ${z(r.error,"readIntegrityAuditOverview")}`}}function Mn(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 Ye(e){let{store:t,healthProbeOptions:n,resourceKey:r="storage_admin",requireUser:a,requirePermission:s,resolveTenantId:l,authorizeIngest:u,authorizeHistoryCapture:c,canReadIntegrityFindings:d,canUpdateKnowledge:m}=e;async function R(C){let{request:b}=C;if(!await a(b))throw new Response("\u8A8D\u8A3C\u304C\u5FC5\u8981\u3067\u3059\u3002",{status:401});try{await s(b,{resourceKey:r,action:"read"})}catch(ee){throw ee instanceof Je.AuthzDeniedError?new Response("\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002",{status:403}):ee}let f=await l(b),K=Hn(t.pipelineStepMetricWindow),[x,E,T]=await Promise.all([t.getFeatureFlags(f),t.getSystemParameters(f),t.getSyncCounts(f)]),j={featureFlags:x,systemParameters:E,syncCounts:T},[W,J,Y,Z,F,I,U,q,ue,te,H,ne,ce,Ie,we,Ae,Ce,de,X,Pe,pe,Ne]=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,b),t.getGraphSchema(f),$n(t,f),d(b),m(b),t.getUnresolvedEntities(f),t.getQdrantCollections(f),ze({...n,tenantId:f}),t.getRecentIngestItems(f,b),t.getOntologyStatus(f,j),t.getEnrichmentStrategies(f),t.getStrategyVariants(f),t.getPipelineStepMetrics(f),t.getRecentPipelineRuns(f,b),t.getDocumentReadRefusal(f,b)]),V=t.getCircuitBreakerStatus();return{tenantId:f,featureFlags:j.featureFlags,confidentialityPolicies:W,transcriptionVocabulary:J,transcriptionReferences:Y,unresolvedReferenceUris:Z,policiesMissingDestination:F,systemParameters:j.systemParameters,promptTemplates:I,classificationRules:U,classificationRuleConsumer:t.classificationRuleConsumer??null,syncCounts:j.syncCounts.counts,totalFiles:j.syncCounts.total,failedSyncItems:q,circuitBreakerStatus:V,pipelineStepMetrics:Un(Pe),pipelineStepMetricWindow:K,recentPipelineRuns:jn(pe),displayTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,graphSchema:ue,enrichmentStrategies:de,strategyVariants:X,integrityAudit:te,canReadIntegrityFindings:H,canUpdateKnowledge:ne,unresolvedEntities:ce,qdrantCollections:Ie,systemHealth:we,recentIngestItems:Ae,documentReadRefusal:Ne,ontologyStatus:Ce}}async function w(C){let{request:b}=C,L=await a(b);if(!L)return Response.json({error:"\u8A8D\u8A3C\u304C\u5FC5\u8981\u3067\u3059\u3002"},{status:401});if(L.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(L.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=L.email,K=L.accessToken===null?void 0:L.accessToken;try{await s(b,{resourceKey:r,action:"update"})}catch(F){if(F instanceof Je.AuthzDeniedError)return await Wn(b);throw F}let x=await l(b),E=await b.formData(),T=String(E.get("intent")??"");if(T==="refresh_health")return Response.json({success:!0,refreshed:!0});let j=await qn(t,x,T,E,f);if(j)return j;let W=await Vn(t,x,T,E,f,K);if(W)return W;let J=await zn(t,x,T,E,f,K,()=>d(b));if(J)return J;let Y=await Yn(t,x,T,E,K,()=>d(b));if(Y)return Y;if(T==="resolve_entity"){let F=String(E.get("entityId")??""),I=String(E.get("action")??"");if(!F||I!=="merge"&&I!=="promote")return Response.json({error:"Valid entityId and action ('merge' | 'promote') are required"},{status:400});try{return await t.resolveEntity(x,F,I),Response.json({success:!0,entityId:F,action:I})}catch(U){return Response.json({error:U instanceof Error?U.message:String(U)},{status:400})}}let Z=await er(t,x,T,E,f,b,u,K);return Z||(T===Et?await Jn(t,x,E,f,b,c):Response.json({error:`Unknown intent: ${T}`},{status:400}))}return{loader:R,action:w}}function We(e){let t=String(e??"").trim();return t===""?null:t}function ve(e){let t=String(e??"").trim();if(t==="")return null;let n=Number(t);if(!(!Number.isSafeInteger(n)||n<=0))return n}function Kn(e){let t=String(e??"").trim();if(t==="")return null;let n=Number(t);if(!(!Number.isFinite(n)||n<=0))return n}async function qn(e,t,n,r,a){if(n==="update_enrichment_strategy"){let s=String(r.get("stage")??"");if(!(0,v.isEnrichmentStageKey)(s))return Response.json({error:"stage must be a canonical enrichment stage key"},{status:400});let l=ve(r.get("strategyId")),u=ve(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},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: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,a),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(!(G.ConfidentialityLevelSchema.safeParse(s).success&&G.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&&!G.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},a),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=Kn(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=ve(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:We(r.get("reading")),boost:l,domainKey:We(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 l=ve(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:We(r.get("domainKey")),isActive:String(r.get("isActive")??"true")==="true"},a)}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=Ln(u.data_type,l);if(c!==null)return Response.json({error:c},{status:400});try{(0,v.assertSystemParameterInRange)(s,Number(l))}catch(d){return Response.json({error:d.message},{status:400})}return await e.updateSystemParameter(t,s,l,a),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=xn.safeParse(u);if(!c.success)return Response.json({error:`payload does not carry a prompt template update: ${z(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(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=Mn(l);if(u!==null)return Response.json({error:u},{status:400});let c=l;return await e.reorderClassificationRules(t,c,a),Response.json({success:!0,orderedRuleIds:c})}return null}async function Vn(e,t,n,r,a,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,a,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,a,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 Bn="resync_findings",Qn="\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",Nt=/^[1-9][0-9]*$/;function Gn(e){return Object.fromEntries([...e.entries()].filter(([t])=>t!=="intent").map(([t,n])=>[t,t==="after"&&typeof n=="string"&&Nt.test(n)?Number(n):n]))}async function zn(e,t,n,r,a,s,l){if(n!==Bn)return null;if(!await l())return Response.json({error:Qn},{status:403});let u=v.IntegrityCellResyncRequestSchema.safeParse(Gn(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): ${z(u.error,"form")}`},{status:400});let c;try{c=await e.resyncIntegrityCell(t,u.data,a,s)}catch(m){return Response.json({error:m instanceof Error?m.message:String(m)},{status:400})}let d=v.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 (${z(d.error,"answer")})\u3002\u958B\u767A\u62C5\u5F53\u306B\u9023\u7D61\u3057\u3066\u304F\u3060\u3055\u3044\u3002`},{status:502})}function le(e,t,n){let r=v.IntegrityCommandFailureSchema.parse({command:e,code:t,status:n}),a=v.INTEGRITY_COMMAND_CODES.find(s=>s.code===r.code);return Response.json({failure:r},{status:a===void 0?502:a.status})}async function Wn(e){let t=await e.formData().catch(()=>null),n=t===null?null:t.get("intent");if(n===Et)return oe({status:403,reason:""});let r=Pt(n);return r===null?Response.json({error:"\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002"},{status:403}):le(r,"FORBIDDEN",null)}var Et="capture_document_state";function oe(e){return Response.json({captureFailure:e},{status:e.status})}async function Jn(e,t,n,r,a,s){let l=n.get("metadataId"),u=typeof l=="string"&&Nt.test(l)?Number(l):null;if(u===null||!Number.isSafeInteger(u))return Response.json({error:"capture_document_state takes metadataId (a positive integer)"},{status:400});let c=await s(a,u);if(c!==null)return oe({status:c.status,reason:c.error});let d;try{d=await e.captureDocumentState(t,u,r)}catch{return oe({status:500,reason:""})}switch(d.kind){case"recorded":return Response.json({outcome:"RECORDED"});case"unchanged":return Response.json({outcome:"UNCHANGED"});case"failed":return oe({status:d.status,reason:d.error});default:return oe({status:500,reason:""})}}async function At(e,t){let n;try{n=v.IntegrityCommandReplySchema.parse(await t())}catch{return le(e,"UPSTREAM_FAILED",null)}return n.ok?Response.json({success:!0,runUid:n.runUid}):le(e,(0,v.integrityCommandFailureCodeOf)(e,n.status,n.errorCode),n.status)}async function Yn(e,t,n,r,a,s){let l=Pt(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): ${z(u.error,"form")}`},{status:400});let{mode:c,basisRunUid:d}=u.data;return a===void 0||c==="REPAIR"&&!await s()?le(l,"FORBIDDEN",null):await At(l,()=>e.startIntegrityRun(t,c,d,a))}if(l==="cancel"){let u=Dn.safeParse({runUid:r.get("runUid")});return u.success?a===void 0?le(l,"FORBIDDEN",null):await At(l,()=>e.cancelIntegrityRun(t,u.data.runUid,a)):Response.json({error:`cancel_integrity_run takes runUid (a UUID): ${z(u.error,"form")}`},{status:400})}return null}function Zn(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(!G.ConfidentialityLevelSchema.safeParse(t.confidentialityLevel).success)return`payload.confidentialityLevel must be one of ${G.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 Xn(e){try{return(0,Ct.formatCount)(e,ye),null}catch{return`inspectFileUri answered a fileSize that is not a byte count (a non-negative safe integer): ${String(e)}`}}async function er(e,t,n,r,a,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 m=Zn(d);if(m)return Response.json({error:m},{status:400});let R=d,w=await l(s,R);if(w!==null)return Response.json({error:w},{status:403});let C;try{C=await(u===void 0?e.ingestDocument(t,R,a):e.ingestDocument(t,R,a,u))}catch(b){return Response.json({error:b instanceof Error?b.message:String(b)},{status:400})}return C.kind==="refused"?Response.json({error:C.error},{status:C.status}):Response.json({success:!0,result:C.result})}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(R){return Response.json({error:R instanceof Error?R.message:String(R)},{status:400})}let m=Xn(d.fileSize);return m!==null?Response.json({error:m},{status:400}):Response.json({success:!0,inspection:d})}return null}function tr(e){let t=Ye(e);return{loader:t.loader,action:t.action,View:Be,server:t}}0&&(module.exports={StorageAdminConsoleView,checkAllSystemHealth,checkBackendApiHealth,checkNeo4jHealth,checkQdrantHealth,checkRedisHealth,checkSqlServerHealth,createStorageAdminApp,createStorageAdminServer});
package/dist/index.d.cts CHANGED
@@ -1,9 +1,9 @@
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, 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
- import { EnrichmentStrategyRow, FailedSyncItem, QdrantStorageOverview, CircuitBreakerState, DocumentIngestPayload, FileInspectionResult, RecentIngestItem, OntologyStatusData, MetadataSearchWorkbenchProps, ModelComparisonWorkbenchProps } from "@aiquants/enrichment-react";
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";
3
+ import { EnrichmentStageKey, PipelineStepMetric, RecentPipelineRunEntry, IntegrityAuditOverview, IntegrityRunMode, IntegrityCommandReply, IntegrityCellResyncRequest, IntegrityCellResyncResult, IntegrityCommandFailure, DocumentCaptureAnswer } from "@aiquants/enrichment-core";
4
+ export { DiffLinePage, DocumentCaptureAnswer, DocumentChangeFeedPage, DocumentComparison, DocumentHistory, IntegrityAuditOverview, IntegrityCellResyncRequest, IntegrityCellResyncResult, IntegrityCommandFailure, IntegrityCommandReply, IntegrityFindingPage, IntegrityFindingsQuery, IntegrityRunMode, PipelineRunRecord, PipelineRunSummary, PipelineStepMetric, PipelineStepRecord, ReadableEntry, RecentPipelineRunEntry, RestrictedFailureMark, RestrictedIngestMark, RestrictedRunMark, SearchMode, StageProvenance } from "@aiquants/enrichment-core";
5
+ import { EnrichmentStrategyRow, FailedSyncEntry, QdrantStorageOverview, CircuitBreakerState, DocumentIngestPayload, FileInspectionResult, RecentIngestEntry, OntologyStatusData, MetadataSearchWorkbenchProps, ModelComparisonWorkbenchProps, DocumentHistoryHost } from "@aiquants/enrichment-react";
6
+ export { ComparisonHit, ComparisonInput, ComparisonOutcome, ComparisonVariantResult, DiffLinePageQuery, DiffLinePageReader, DiffLineTarget, DocumentComparisonQuery, DocumentHistoryHost, DocumentHistoryTarget, DocumentIngestLabel, DocumentIngestPayload, DocumentStateCapture, EnrichmentStrategyRow, FailedSyncEntry, FailedSyncItem, FileInspectionResult, FusionStrategy, MetadataSearchHit, MetadataSearchParams, MetadataSearchResult, OntologyStatusData, QdrantCollectionInfo, QdrantStorageOverview, RecentIngestEntry, RecentIngestItem, RecentIngestLastRun, 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";
8
8
  export { ClassificationRuleItem as ClassificationRule, DocumentAuthorityHost, GraphNodeIndexOutcome, GraphNodeIndexPage, GraphNodeSummary, GraphRelationshipTypesOutcome, GraphRelationshipTypesReader, GraphSchemaStats, GraphTraversalHost, GraphTraversalInput, GraphTraversalOutcome, GraphTraversalRunner, IntegrityFindingsLoader, PolicyConflictHost, PromptTemplateItem, SimulationOutcome, SimulationRunInput, SimulationRunResult, SimulationRunner, SimulationScoreSet, SimulationVerdictFlip } from "@aiquants/governance-react";
9
9
  import * as react from "react";
@@ -20,7 +20,39 @@ interface StrategyVariant {
20
20
  readonly embeddingModel: string;
21
21
  readonly domainKey: string;
22
22
  }
23
- type DocumentRunsLoader = (metadataId: number, signal: AbortSignal) => Promise<ResourceOutcome<readonly PipelineRunRecord[]>>;
23
+ type IngestQueueRefresh = {
24
+ readonly kind: "rows";
25
+ readonly rows: readonly RecentIngestEntry[];
26
+ } | {
27
+ readonly kind: "refused";
28
+ readonly reason: string;
29
+ };
30
+ type IngestQueueRefresher = () => Promise<IngestQueueRefresh>;
31
+ type DocumentIngestOutcome = {
32
+ readonly kind: "ingested";
33
+ readonly result: DocumentIngestResult;
34
+ } | {
35
+ readonly kind: "refused";
36
+ readonly status: 403 | 500 | 503;
37
+ readonly error: string;
38
+ };
39
+ type DocumentStateCaptureOutcome = {
40
+ readonly kind: "recorded";
41
+ } | {
42
+ readonly kind: "unchanged";
43
+ } | {
44
+ readonly kind: "failed";
45
+ readonly status: 404 | 500 | 503;
46
+ readonly error: string;
47
+ };
48
+ interface HistoryCaptureRefusal {
49
+ readonly status: 403 | 404 | 503;
50
+ readonly error: string;
51
+ }
52
+ interface DocumentCaptureFailure {
53
+ readonly status: 403 | 404 | 500 | 503;
54
+ readonly reason: string;
55
+ }
24
56
  interface RetryAllSkippedItem {
25
57
  metadataId: number;
26
58
  reason: string;
@@ -104,11 +136,11 @@ interface StorageAdminLoaderData {
104
136
  classificationRuleConsumer: string | null;
105
137
  syncCounts: Record<string, number>;
106
138
  totalFiles: number;
107
- failedSyncItems: FailedSyncItem[];
139
+ failedSyncItems: readonly FailedSyncEntry[];
108
140
  circuitBreakerStatus: Record<string, CircuitBreakerState>;
109
141
  pipelineStepMetrics: readonly PipelineStepMetric[];
110
142
  pipelineStepMetricWindow: number;
111
- recentPipelineRuns: readonly PipelineRunSummary[];
143
+ recentPipelineRuns: readonly RecentPipelineRunEntry[];
112
144
  displayTimeZone: string;
113
145
  graphSchema: GraphSchemaStats;
114
146
  enrichmentStrategies: EnrichmentStrategyRow[];
@@ -119,7 +151,8 @@ interface StorageAdminLoaderData {
119
151
  unresolvedEntities: UnresolvedEntity[];
120
152
  qdrantCollections: QdrantStorageOverview;
121
153
  systemHealth: SystemInfrastructureHealth;
122
- recentIngestItems?: RecentIngestItem[];
154
+ recentIngestItems?: readonly RecentIngestEntry[];
155
+ documentReadRefusal: string | null;
123
156
  ontologyStatus: OntologyStatusData;
124
157
  confidentialityPolicies: ConfidentialityPolicyRow[];
125
158
  transcriptionVocabulary: TranscriptionTermRow[];
@@ -169,12 +202,13 @@ interface StorageAdminStore {
169
202
  counts: Record<string, number>;
170
203
  total: number;
171
204
  }>;
172
- getFailedSyncItems(tenantId: string): Promise<FailedSyncItem[]>;
205
+ getFailedSyncItems(tenantId: string, request: Request): Promise<readonly FailedSyncEntry[]>;
206
+ getDocumentReadRefusal(tenantId: string, request: Request): Promise<string | null>;
173
207
  retrySyncItem(tenantId: string, fileId: string, actor?: string, accessToken?: string): Promise<void>;
174
208
  retryAllFailedSyncItems(tenantId: string, actor?: string, accessToken?: string): Promise<RetryAllFailedResult>;
175
209
  getPipelineStepMetrics(tenantId: string): Promise<readonly PipelineStepMetric[]>;
176
210
  readonly pipelineStepMetricWindow: number;
177
- getRecentPipelineRuns(tenantId: string): Promise<readonly PipelineRunSummary[]>;
211
+ getRecentPipelineRuns(tenantId: string, request: Request): Promise<readonly RecentPipelineRunEntry[]>;
178
212
  getStrategyVariants(tenantId: string): Promise<readonly StrategyVariant[]>;
179
213
  getGraphSchema(tenantId: string): Promise<GraphSchemaStats>;
180
214
  readIntegrityAuditOverview(tenantId: string): Promise<IntegrityAuditOverview>;
@@ -185,9 +219,10 @@ interface StorageAdminStore {
185
219
  resolveEntity(tenantId: string, entityId: string, action: "merge" | "promote"): Promise<void>;
186
220
  getQdrantCollections(tenantId: string): Promise<QdrantStorageOverview>;
187
221
  getCircuitBreakerStatus(): Record<string, CircuitBreakerState>;
188
- ingestDocument(tenantId: string, payload: DocumentIngestPayload, actor: string, accessToken?: string): Promise<DocumentIngestResult>;
222
+ ingestDocument(tenantId: string, payload: DocumentIngestPayload, actor: string, accessToken?: string): Promise<DocumentIngestOutcome>;
189
223
  inspectFileUri?(tenantId: string, fileUri: string, accessToken?: string): Promise<FileInspectionResult>;
190
- getRecentIngestItems(tenantId: string): Promise<RecentIngestItem[]>;
224
+ getRecentIngestItems(tenantId: string, request: Request): Promise<readonly RecentIngestEntry[]>;
225
+ captureDocumentState(tenantId: string, metadataId: number, actor: string): Promise<DocumentStateCaptureOutcome>;
191
226
  getOntologyStatus(tenantId: string, snapshot: ConsoleConfigSnapshot): Promise<OntologyStatusData>;
192
227
  }
193
228
  type GraphReadOutcome = {
@@ -239,6 +274,7 @@ interface CreateStorageAdminAppOptions {
239
274
  canReadIntegrityFindings: (request: Request) => Promise<boolean>;
240
275
  canUpdateKnowledge: (request: Request) => Promise<boolean>;
241
276
  authorizeIngest: (request: Request, payload: DocumentIngestPayload) => Promise<string | null>;
277
+ authorizeHistoryCapture: (request: Request, metadataId: number) => Promise<HistoryCaptureRefusal | null>;
242
278
  }
243
279
  interface StorageAdminActionData {
244
280
  success?: boolean;
@@ -250,6 +286,8 @@ interface StorageAdminActionData {
250
286
  failure?: IntegrityCommandFailure;
251
287
  runUid?: string;
252
288
  cellResync?: IntegrityCellResyncResult;
289
+ outcome?: DocumentCaptureAnswer["outcome"];
290
+ captureFailure?: DocumentCaptureFailure;
253
291
  }
254
292
  interface StorageAdminFetcher {
255
293
  state: "idle" | "submitting" | "loading";
@@ -263,6 +301,7 @@ interface StorageAdminConsoleViewProps {
263
301
  fetcher?: StorageAdminFetcher;
264
302
  integrityFetcher?: StorageAdminFetcher;
265
303
  inspectorFetcher?: StorageAdminFetcher;
304
+ captureFetcher?: StorageAdminFetcher;
266
305
  renderHeader?: (props: {
267
306
  title: string;
268
307
  tenantId: string;
@@ -272,14 +311,13 @@ interface StorageAdminConsoleViewProps {
272
311
  loadIntegrityFindings: IntegrityFindingsLoader;
273
312
  policyConflicts: PolicyConflictHost;
274
313
  documentAuthority: DocumentAuthorityHost;
275
- onLoadDocumentRuns?: DocumentRunsLoader;
314
+ documentHistory?: DocumentHistoryHost;
276
315
  onCompareVariants?: ModelComparisonRunner;
277
316
  graphTraversal?: GraphTraversalHost;
278
317
  onBrowseGraphNodes?: (label: string, pageIndex: number) => Promise<GraphNodeIndexOutcome>;
279
318
  onSimulateGovernance?: SimulationRunner;
280
319
  onRefreshIngestQueue?: IngestQueueRefresher;
281
320
  }
282
- type IngestQueueRefresher = () => Promise<readonly RecentIngestItem[]>;
283
321
  declare function StorageAdminConsoleView(props: StorageAdminConsoleViewProps): react.JSX.Element;
284
322
  declare function createStorageAdminApp(options: CreateStorageAdminAppOptions): {
285
323
  loader: (args: {
@@ -312,4 +350,4 @@ declare function createStorageAdminServer(options: CreateStorageAdminAppOptions)
312
350
  request: Request;
313
351
  }) => Promise<Response>;
314
352
  };
315
- export { type AwaitableSubmit, type ConsoleConfigSnapshot, type CreateStorageAdminAppOptions, type DocumentIngestResult, type DocumentRunsLoader, type EnrichmentStrategyUpdate, type GraphReadOutcome, type GraphReader, type HealthProbeOptions, type IngestQueueRefresher, type IntegrityOverviewLoader, type MetadataSearchRunner, type ModelComparisonRunner, type PolicyWithoutDestination, type PromptTemplateUpdate, type RetryAllFailedResult, type RetryAllSkippedItem, type ServiceHealthStatus, type StorageAdminActionData, StorageAdminConsoleView, type StorageAdminConsoleViewProps, type StorageAdminFetcher, type StorageAdminLoaderData, type StorageAdminOperator, type StorageAdminStore, type StrategyVariant, type SystemInfrastructureHealth, type SystemParameter, type SystemParameterDataType, type UnresolvedEntity, checkAllSystemHealth, checkBackendApiHealth, checkNeo4jHealth, checkQdrantHealth, checkRedisHealth, checkSqlServerHealth, createStorageAdminApp, createStorageAdminServer };
353
+ export { type AwaitableSubmit, type ConsoleConfigSnapshot, type CreateStorageAdminAppOptions, type DocumentCaptureFailure, type DocumentIngestOutcome, type DocumentIngestResult, type DocumentStateCaptureOutcome, type EnrichmentStrategyUpdate, type GraphReadOutcome, type GraphReader, type HealthProbeOptions, type HistoryCaptureRefusal, type IngestQueueRefresh, type IngestQueueRefresher, type IntegrityOverviewLoader, type MetadataSearchRunner, type ModelComparisonRunner, type PolicyWithoutDestination, type PromptTemplateUpdate, type RetryAllFailedResult, type RetryAllSkippedItem, type ServiceHealthStatus, type StorageAdminActionData, StorageAdminConsoleView, type StorageAdminConsoleViewProps, type StorageAdminFetcher, type StorageAdminLoaderData, type StorageAdminOperator, type StorageAdminStore, type StrategyVariant, type SystemInfrastructureHealth, type SystemParameter, type SystemParameterDataType, type UnresolvedEntity, checkAllSystemHealth, checkBackendApiHealth, checkNeo4jHealth, checkQdrantHealth, checkRedisHealth, checkSqlServerHealth, createStorageAdminApp, createStorageAdminServer };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
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, 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
- import { EnrichmentStrategyRow, FailedSyncItem, QdrantStorageOverview, CircuitBreakerState, DocumentIngestPayload, FileInspectionResult, RecentIngestItem, OntologyStatusData, MetadataSearchWorkbenchProps, ModelComparisonWorkbenchProps } from "@aiquants/enrichment-react";
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";
3
+ import { EnrichmentStageKey, PipelineStepMetric, RecentPipelineRunEntry, IntegrityAuditOverview, IntegrityRunMode, IntegrityCommandReply, IntegrityCellResyncRequest, IntegrityCellResyncResult, IntegrityCommandFailure, DocumentCaptureAnswer } from "@aiquants/enrichment-core";
4
+ export { DiffLinePage, DocumentCaptureAnswer, DocumentChangeFeedPage, DocumentComparison, DocumentHistory, IntegrityAuditOverview, IntegrityCellResyncRequest, IntegrityCellResyncResult, IntegrityCommandFailure, IntegrityCommandReply, IntegrityFindingPage, IntegrityFindingsQuery, IntegrityRunMode, PipelineRunRecord, PipelineRunSummary, PipelineStepMetric, PipelineStepRecord, ReadableEntry, RecentPipelineRunEntry, RestrictedFailureMark, RestrictedIngestMark, RestrictedRunMark, SearchMode, StageProvenance } from "@aiquants/enrichment-core";
5
+ import { EnrichmentStrategyRow, FailedSyncEntry, QdrantStorageOverview, CircuitBreakerState, DocumentIngestPayload, FileInspectionResult, RecentIngestEntry, OntologyStatusData, MetadataSearchWorkbenchProps, ModelComparisonWorkbenchProps, DocumentHistoryHost } from "@aiquants/enrichment-react";
6
+ export { ComparisonHit, ComparisonInput, ComparisonOutcome, ComparisonVariantResult, DiffLinePageQuery, DiffLinePageReader, DiffLineTarget, DocumentComparisonQuery, DocumentHistoryHost, DocumentHistoryTarget, DocumentIngestLabel, DocumentIngestPayload, DocumentStateCapture, EnrichmentStrategyRow, FailedSyncEntry, FailedSyncItem, FileInspectionResult, FusionStrategy, MetadataSearchHit, MetadataSearchParams, MetadataSearchResult, OntologyStatusData, QdrantCollectionInfo, QdrantStorageOverview, RecentIngestEntry, RecentIngestItem, RecentIngestLastRun, 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";
8
8
  export { ClassificationRuleItem as ClassificationRule, DocumentAuthorityHost, GraphNodeIndexOutcome, GraphNodeIndexPage, GraphNodeSummary, GraphRelationshipTypesOutcome, GraphRelationshipTypesReader, GraphSchemaStats, GraphTraversalHost, GraphTraversalInput, GraphTraversalOutcome, GraphTraversalRunner, IntegrityFindingsLoader, PolicyConflictHost, PromptTemplateItem, SimulationOutcome, SimulationRunInput, SimulationRunResult, SimulationRunner, SimulationScoreSet, SimulationVerdictFlip } from "@aiquants/governance-react";
9
9
  import * as react from "react";
@@ -20,7 +20,39 @@ interface StrategyVariant {
20
20
  readonly embeddingModel: string;
21
21
  readonly domainKey: string;
22
22
  }
23
- type DocumentRunsLoader = (metadataId: number, signal: AbortSignal) => Promise<ResourceOutcome<readonly PipelineRunRecord[]>>;
23
+ type IngestQueueRefresh = {
24
+ readonly kind: "rows";
25
+ readonly rows: readonly RecentIngestEntry[];
26
+ } | {
27
+ readonly kind: "refused";
28
+ readonly reason: string;
29
+ };
30
+ type IngestQueueRefresher = () => Promise<IngestQueueRefresh>;
31
+ type DocumentIngestOutcome = {
32
+ readonly kind: "ingested";
33
+ readonly result: DocumentIngestResult;
34
+ } | {
35
+ readonly kind: "refused";
36
+ readonly status: 403 | 500 | 503;
37
+ readonly error: string;
38
+ };
39
+ type DocumentStateCaptureOutcome = {
40
+ readonly kind: "recorded";
41
+ } | {
42
+ readonly kind: "unchanged";
43
+ } | {
44
+ readonly kind: "failed";
45
+ readonly status: 404 | 500 | 503;
46
+ readonly error: string;
47
+ };
48
+ interface HistoryCaptureRefusal {
49
+ readonly status: 403 | 404 | 503;
50
+ readonly error: string;
51
+ }
52
+ interface DocumentCaptureFailure {
53
+ readonly status: 403 | 404 | 500 | 503;
54
+ readonly reason: string;
55
+ }
24
56
  interface RetryAllSkippedItem {
25
57
  metadataId: number;
26
58
  reason: string;
@@ -104,11 +136,11 @@ interface StorageAdminLoaderData {
104
136
  classificationRuleConsumer: string | null;
105
137
  syncCounts: Record<string, number>;
106
138
  totalFiles: number;
107
- failedSyncItems: FailedSyncItem[];
139
+ failedSyncItems: readonly FailedSyncEntry[];
108
140
  circuitBreakerStatus: Record<string, CircuitBreakerState>;
109
141
  pipelineStepMetrics: readonly PipelineStepMetric[];
110
142
  pipelineStepMetricWindow: number;
111
- recentPipelineRuns: readonly PipelineRunSummary[];
143
+ recentPipelineRuns: readonly RecentPipelineRunEntry[];
112
144
  displayTimeZone: string;
113
145
  graphSchema: GraphSchemaStats;
114
146
  enrichmentStrategies: EnrichmentStrategyRow[];
@@ -119,7 +151,8 @@ interface StorageAdminLoaderData {
119
151
  unresolvedEntities: UnresolvedEntity[];
120
152
  qdrantCollections: QdrantStorageOverview;
121
153
  systemHealth: SystemInfrastructureHealth;
122
- recentIngestItems?: RecentIngestItem[];
154
+ recentIngestItems?: readonly RecentIngestEntry[];
155
+ documentReadRefusal: string | null;
123
156
  ontologyStatus: OntologyStatusData;
124
157
  confidentialityPolicies: ConfidentialityPolicyRow[];
125
158
  transcriptionVocabulary: TranscriptionTermRow[];
@@ -169,12 +202,13 @@ interface StorageAdminStore {
169
202
  counts: Record<string, number>;
170
203
  total: number;
171
204
  }>;
172
- getFailedSyncItems(tenantId: string): Promise<FailedSyncItem[]>;
205
+ getFailedSyncItems(tenantId: string, request: Request): Promise<readonly FailedSyncEntry[]>;
206
+ getDocumentReadRefusal(tenantId: string, request: Request): Promise<string | null>;
173
207
  retrySyncItem(tenantId: string, fileId: string, actor?: string, accessToken?: string): Promise<void>;
174
208
  retryAllFailedSyncItems(tenantId: string, actor?: string, accessToken?: string): Promise<RetryAllFailedResult>;
175
209
  getPipelineStepMetrics(tenantId: string): Promise<readonly PipelineStepMetric[]>;
176
210
  readonly pipelineStepMetricWindow: number;
177
- getRecentPipelineRuns(tenantId: string): Promise<readonly PipelineRunSummary[]>;
211
+ getRecentPipelineRuns(tenantId: string, request: Request): Promise<readonly RecentPipelineRunEntry[]>;
178
212
  getStrategyVariants(tenantId: string): Promise<readonly StrategyVariant[]>;
179
213
  getGraphSchema(tenantId: string): Promise<GraphSchemaStats>;
180
214
  readIntegrityAuditOverview(tenantId: string): Promise<IntegrityAuditOverview>;
@@ -185,9 +219,10 @@ interface StorageAdminStore {
185
219
  resolveEntity(tenantId: string, entityId: string, action: "merge" | "promote"): Promise<void>;
186
220
  getQdrantCollections(tenantId: string): Promise<QdrantStorageOverview>;
187
221
  getCircuitBreakerStatus(): Record<string, CircuitBreakerState>;
188
- ingestDocument(tenantId: string, payload: DocumentIngestPayload, actor: string, accessToken?: string): Promise<DocumentIngestResult>;
222
+ ingestDocument(tenantId: string, payload: DocumentIngestPayload, actor: string, accessToken?: string): Promise<DocumentIngestOutcome>;
189
223
  inspectFileUri?(tenantId: string, fileUri: string, accessToken?: string): Promise<FileInspectionResult>;
190
- getRecentIngestItems(tenantId: string): Promise<RecentIngestItem[]>;
224
+ getRecentIngestItems(tenantId: string, request: Request): Promise<readonly RecentIngestEntry[]>;
225
+ captureDocumentState(tenantId: string, metadataId: number, actor: string): Promise<DocumentStateCaptureOutcome>;
191
226
  getOntologyStatus(tenantId: string, snapshot: ConsoleConfigSnapshot): Promise<OntologyStatusData>;
192
227
  }
193
228
  type GraphReadOutcome = {
@@ -239,6 +274,7 @@ interface CreateStorageAdminAppOptions {
239
274
  canReadIntegrityFindings: (request: Request) => Promise<boolean>;
240
275
  canUpdateKnowledge: (request: Request) => Promise<boolean>;
241
276
  authorizeIngest: (request: Request, payload: DocumentIngestPayload) => Promise<string | null>;
277
+ authorizeHistoryCapture: (request: Request, metadataId: number) => Promise<HistoryCaptureRefusal | null>;
242
278
  }
243
279
  interface StorageAdminActionData {
244
280
  success?: boolean;
@@ -250,6 +286,8 @@ interface StorageAdminActionData {
250
286
  failure?: IntegrityCommandFailure;
251
287
  runUid?: string;
252
288
  cellResync?: IntegrityCellResyncResult;
289
+ outcome?: DocumentCaptureAnswer["outcome"];
290
+ captureFailure?: DocumentCaptureFailure;
253
291
  }
254
292
  interface StorageAdminFetcher {
255
293
  state: "idle" | "submitting" | "loading";
@@ -263,6 +301,7 @@ interface StorageAdminConsoleViewProps {
263
301
  fetcher?: StorageAdminFetcher;
264
302
  integrityFetcher?: StorageAdminFetcher;
265
303
  inspectorFetcher?: StorageAdminFetcher;
304
+ captureFetcher?: StorageAdminFetcher;
266
305
  renderHeader?: (props: {
267
306
  title: string;
268
307
  tenantId: string;
@@ -272,14 +311,13 @@ interface StorageAdminConsoleViewProps {
272
311
  loadIntegrityFindings: IntegrityFindingsLoader;
273
312
  policyConflicts: PolicyConflictHost;
274
313
  documentAuthority: DocumentAuthorityHost;
275
- onLoadDocumentRuns?: DocumentRunsLoader;
314
+ documentHistory?: DocumentHistoryHost;
276
315
  onCompareVariants?: ModelComparisonRunner;
277
316
  graphTraversal?: GraphTraversalHost;
278
317
  onBrowseGraphNodes?: (label: string, pageIndex: number) => Promise<GraphNodeIndexOutcome>;
279
318
  onSimulateGovernance?: SimulationRunner;
280
319
  onRefreshIngestQueue?: IngestQueueRefresher;
281
320
  }
282
- type IngestQueueRefresher = () => Promise<readonly RecentIngestItem[]>;
283
321
  declare function StorageAdminConsoleView(props: StorageAdminConsoleViewProps): react.JSX.Element;
284
322
  declare function createStorageAdminApp(options: CreateStorageAdminAppOptions): {
285
323
  loader: (args: {
@@ -312,4 +350,4 @@ declare function createStorageAdminServer(options: CreateStorageAdminAppOptions)
312
350
  request: Request;
313
351
  }) => Promise<Response>;
314
352
  };
315
- export { type AwaitableSubmit, type ConsoleConfigSnapshot, type CreateStorageAdminAppOptions, type DocumentIngestResult, type DocumentRunsLoader, type EnrichmentStrategyUpdate, type GraphReadOutcome, type GraphReader, type HealthProbeOptions, type IngestQueueRefresher, type IntegrityOverviewLoader, type MetadataSearchRunner, type ModelComparisonRunner, type PolicyWithoutDestination, type PromptTemplateUpdate, type RetryAllFailedResult, type RetryAllSkippedItem, type ServiceHealthStatus, type StorageAdminActionData, StorageAdminConsoleView, type StorageAdminConsoleViewProps, type StorageAdminFetcher, type StorageAdminLoaderData, type StorageAdminOperator, type StorageAdminStore, type StrategyVariant, type SystemInfrastructureHealth, type SystemParameter, type SystemParameterDataType, type UnresolvedEntity, checkAllSystemHealth, checkBackendApiHealth, checkNeo4jHealth, checkQdrantHealth, checkRedisHealth, checkSqlServerHealth, createStorageAdminApp, createStorageAdminServer };
353
+ export { type AwaitableSubmit, type ConsoleConfigSnapshot, type CreateStorageAdminAppOptions, type DocumentCaptureFailure, type DocumentIngestOutcome, type DocumentIngestResult, type DocumentStateCaptureOutcome, type EnrichmentStrategyUpdate, type GraphReadOutcome, type GraphReader, type HealthProbeOptions, type HistoryCaptureRefusal, type IngestQueueRefresh, type IngestQueueRefresher, type IntegrityOverviewLoader, type MetadataSearchRunner, type ModelComparisonRunner, type PolicyWithoutDestination, type PromptTemplateUpdate, type RetryAllFailedResult, type RetryAllSkippedItem, type ServiceHealthStatus, type StorageAdminActionData, StorageAdminConsoleView, type StorageAdminConsoleViewProps, type StorageAdminFetcher, type StorageAdminLoaderData, type StorageAdminOperator, type StorageAdminStore, type StrategyVariant, type SystemInfrastructureHealth, type SystemParameter, type SystemParameterDataType, type UnresolvedEntity, checkAllSystemHealth, checkBackendApiHealth, checkNeo4jHealth, checkQdrantHealth, checkRedisHealth, checkSqlServerHealth, createStorageAdminApp, createStorageAdminServer };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
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};
1
+ import{Card as dn,ConsoleUiRoot as pn,Notice as mn,ResourceFailed as gn,reasonAside as yn,useFocusRescue as fn}from"@aiquants/console-ui";import{DOCUMENT_KIND_LABELS as Rn,DocumentCaptureAnswerSchema as Sn,EnrichmentSyncStatusSchema as bn,GRAPH_INDEX_LIMITS as hn,IntegrityCellResyncResultSchema as vn,IntegrityRunModeSchema as In,PIPELINE_STEPS as wn,PipelineRunStatusSchema as An}from"@aiquants/enrichment-core";import{DocumentChangeFeed as Cn,DocumentHistoryInspector as Pn,DocumentIngestConsole as Nn,EnrichmentStrategyBoard as En,FinishedInstant as it,InfrastructureHealthMonitor as Tn,MetadataSearchWorkbench as _n,ModelComparisonWorkbench as kn,OntologyStatusCard as On,PIPELINE_RUN_STATUS_PRESENTATION as at,PIPELINE_TRIGGER_LABELS as xn,PipelineFlowViewer as Fn,pipelineRunPresentationKey as Dn,QdrantStorageCard as Ln,RESTRICTED_DOCUMENT_TEXT as jn,RecordedInstant as ot,SyncStatusMonitor as Un}from"@aiquants/enrichment-react";import{ClassificationRuleEditor as Hn,ConfidentialityPolicyBoard as $n,DocumentAuthorityRegistry as Mn,FeatureFlagBoard as Kn,GovernanceDryRunConsole as qn,integrityFailureNeedsOverviewReread as Vn,KnowledgeGraphExplorer as Bn,PolicyConflictQueue as Qn,PolicyConflictSummaryCard as Gn,PromptTemplateConsole as zn,SystemParameterTable as Wn,TranscriptionAdaptationBoard as Jn,TriStoreIntegrityAudit as Yn}from"@aiquants/governance-react";import{Fragment as Zn,useCallback as W,useEffect as Ke,useMemo as pe,useRef as _,useState as P}from"react";import{useFetcher as me,useLoaderData as Xn,useRevalidator as er,useSearchParams as tr}from"react-router";var ce="ja-JP";var Jt=/[^\s\x1c-\x1f\x85\ufeff]/;function de(e){return Jt.test(e)}function $(e,t){return new Promise(n=>n(e())).catch(n=>t(n instanceof Error?n.message:String(n)))}import{beginReload as Yt,keepLastGood as Zt}from"@aiquants/console-ui/core";import{isStrictlyEarlier as Xt}from"@aiquants/enrichment-core";import{useCallback as _e,useEffect as nt,useRef as Oe,useState as en,useSyncExternalStore as tn}from"react";var nn=2e3,rn=1e4;function ke(e,t){return t.ok&&e.kind==="ready"&&Xt(t.value.readAt,e.value.readAt)?e:Zt(e,t)}var sn=401;function an(e){return e.kind==="failed"||e.refreshFailure!==null&&e.refreshFailure.status===sn?null:e.value.active}function rt(e,t){let[n,r]=en(()=>({loaded:e,overview:ke({kind:"loading"},e)}));n.loaded!==e&&r({loaded:e,overview:ke(n.overview,e)});let a=Oe(t);a.current=t;let s=Oe(null);nt(()=>()=>s.current?.abort(),[]);let o=_e((d,p)=>$(p,y=>({ok:!1,status:null,reason:y})).then(y=>{d.aborted||r(h=>({loaded:h.loaded,overview:ke(h.overview,y)}))}),[]),l=_e(()=>{let d=new AbortController;s.current=d,r(p=>({loaded:p.loaded,overview:Yt(p.overview,"reload")})),o(d.signal,()=>a.current(d.signal))},[o]),c=_e(d=>o(d,()=>a.current(d)),[o]);return{overview:n.overview,reload:l,poll:c}}function on(e){return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)}function ln(){return document.visibilityState==="visible"}function un(){return!0}function st(e,t,n){let r=tn(on,ln,un),a=t&&r,s=Oe(a),o=e.kind==="ready",l=an(e),c=l===null?null:l.run.runUid,d=l===null?!1:l.isStale;nt(()=>{let p=a&&!s.current;if(s.current=a,!a||c===null&&!(p&&o))return;let y=new AbortController,h=d?rn:nn,v,S=async()=>{await n(y.signal),!y.signal.aborted&&c!==null&&(v=setTimeout(S,h))};return v=setTimeout(S,p?0:h),()=>{y.abort(),clearTimeout(v)}},[a,o,c,d,n])}var xe={columns:2,className:"grid-cols-2",spanClassNames:{1:"col-span-1",2:"col-span-2"}},Fe={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"}},De={className:"@min-[82rem]:grid-flow-col @min-[82rem]:auto-cols-fr @min-[82rem]:grid-cols-none",lastTabClassName:"@min-[82rem]:col-auto"};function Le(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 R}from"react/jsx-runtime";var lt="tab",He={key:"knowledge-authority",phrases:["\u6A29\u5A01\u53F0\u5E33 & \u898F\u7A0B\u885D\u7A81"]},$e={key:"pipeline",phrases:["\u30D1\u30A4\u30D7\u30E9\u30A4\u30F3 & \u63A5\u7D9A\u72B6\u614B"]},Me={key:"parameters",phrases:["\u30E2\u30C7\u30EB & \u30D1\u30E9\u30E1\u30FC\u30BF\u8A2D\u5B9A"]},ut="\u30A8\u30F3\u30EA\u30C3\u30C1\u30E1\u30F3\u30C8\u540C\u671F\u30B9\u30C6\u30FC\u30BF\u30B9";function nr(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=vn.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"]},$e,{key:"knowledge-graph",phrases:["\u30CA\u30EC\u30C3\u30B8\u30B0\u30E9\u30D5","\u63A2\u7D22"]},Me,{key:"prompts",phrases:["\u30D7\u30ED\u30F3\u30D7\u30C8 & \u30C9\u30E9\u30A4\u30E9\u30F3"]},He,{key:"data-retention",phrases:["\u30C7\u30FC\u30BF\u4FDD\u6301 & \u6574\u5408\u6027\u76E3\u67FB"]}];function je(e){return e.phrases.join("")}function rr(e){return e!==null&&M.some(t=>t.key===e)}var sr="Tri-Store \u30C7\u30FC\u30BF\u6574\u5408\u6027\u76E3\u67FB";function ir(e){return`\u76E3\u67FB\u306E\u6982\u6CC1\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F${yn(e)}\u3002`}var ar={kind:"latest_state"},pt=[];function or(e){for(let t of e.runs)if(t.kind==="readable")for(let n of t.item.steps){let r=n.provenance;if(r!==null){for(let[a,s]of Object.entries(r))if(typeof s=="string"&&!de(s))return`\u5B9F\u884C #${t.item.id} \u306E\u6BB5 ${n.sequence} \u306E\u5831\u544A\u306E ${a} \u306B\u8AAD\u3081\u308B\u6587\u5B57\u304C\u3042\u308A\u307E\u305B\u3093`}}return null}function te(e){return{ok:!1,status:null,reason:e}}function lr(e){return{loadHistory:async(t,n)=>{let r=await $(()=>e.loadHistory(t,n),te);if(!r.ok)return r;let a=or(r.value);return a===null?r:te(a)},compare:(t,n)=>$(()=>e.compare(t,n),te),readLines:(t,n)=>$(()=>e.readLines(t,n),te),loadChanges:(t,n)=>$(()=>e.loadChanges(t,n),te)}}function ur(e){let t=Sn.safeParse(e);if(t.success)return{ok:!0,value:t.data};let n=e?.captureFailure;if(n!==void 0)return{ok:!1,status:n.status,reason:n.reason};let r=e?.error;return r===void 0?{ok:!1,status:null,reason:"\u8A18\u9332\u306E\u7B54\u3048\u306E\u5F62\u304C\u60F3\u5B9A\u3068\u7570\u306A\u308A\u307E\u3059"}:{ok:!1,status:null,reason:r.endsWith("\u3002")?r.slice(0,-1):r}}var ge={state:"idle",formData:null,data:null,submit:()=>Promise.resolve()};function mt({data:e,fetcher:t,integrityFetcher:n,inspectorFetcher:r,captureFetcher:a,renderHeader:s,graphTraversal:o,onBrowseGraphNodes:l,onSimulateGovernance:c,onRefreshIngestQueue:d,onSearch:p,documentHistory:y,onCompareVariants:h,loadIntegrityOverview:v,loadIntegrityFindings:S,policyConflicts:k,documentAuthority:g}){let[j,E]=P(null),[w,A]=P(null),[O,q]=P(!1),V=pe(()=>{if(l!==void 0)return(i,m)=>{q(!0),$(()=>l(i,m),f=>({ok:!1,reason:f})).then(f=>{q(!1),A(f.ok?null:f.reason),f.ok&&E(f.page)})}},[l]),[B,Q]=tr(),T=B.get(lt),b=rr(T)?T:M[0].key,x=i=>{Q(m=>{let f=new URLSearchParams(m);return f.set(lt,i),f},{replace:!1,preventScrollReset:!0})},U=e.documentReadRefusal,se=U===null?e.recentIngestItems:pt,J=pr(se,d,b==="ingest"),F=rt(e.integrityAudit,v);st(F.overview,b==="data-retention",F.poll);let Y=_(null),ie=fn(()=>Y.current),[Se,be]=P(0),he=W(()=>be(i=>i+1),[]),ve=J.rows===null?se:J.rows,ae=U===null?J.refusal:U,G=_({}),Ie=W(()=>G.current[b]??null,[b]),oe=pe(()=>gr(e.enrichmentStrategies),[e.enrichmentStrategies]),we=pe(()=>e.strategyVariants.map(yr),[e.strategyVariants]),H=pe(()=>y===void 0?void 0:lr(y),[y]),[z,Ge]=P(null),[Pt,Nt]=P(0),Ae=W((i,m)=>{Ge({metadataId:i,target:m}),Nt(f=>f+1)},[]),Et=W(()=>Ge(null),[]),Tt=mr(a),ze=H===void 0?void 0:i=>Ae(i,ar),_t=H===void 0?void 0:i=>Ae(i.metadataId,{kind:"run",runId:i.id}),kt=(i,m)=>Ae(i,{kind:"state",stateId:m}),Ot=(i,m)=>{let f=M.length-1,C;if(i.key==="ArrowRight"||i.key==="ArrowDown")C=m===f?0:m+1;else if(i.key==="ArrowLeft"||i.key==="ArrowUp")C=m===0?f:m-1;else if(i.key==="Home")C=0;else if(i.key==="End")C=f;else return;i.preventDefault();let ue=M[C].key;x(ue),G.current[ue]?.focus()},We={...e.featureFlags};if(t.formData&&t.formData.get("intent")==="toggle_flag"){let i=String(t.formData.get("flagKey")??""),m=String(t.formData.get("enabled")??"")==="true";i&&(We[i]=m)}let xt=t.data&&"inspection"in t.data?t.data.inspection:void 0,Z=t.state==="idle"?null:t.formData?.get("intent"),Ft=Z==="inspect_uri",Dt=Z==="ingest_document",Lt=Z==="retry_job"||Z==="retry_all_failed",jt=Z==="resolve_entity",Je=n.state==="idle"?null:n.formData?.get("intent"),Ut=Je==="start_integrity_run"?{kind:"starting",mode:In.parse(n.formData?.get("mode"))}:Je==="cancel_integrity_run"?{kind:"cancelling"}:{kind:"idle"},Ht=er(),[$t,Ce]=P(null),Ye=b!=="data-retention";Ke(()=>{Ye&&Ce(null)},[Ye]);let Mt=i=>{let m=i?.failure;if(m===void 0){Ce(null);return}Ce(f=>({failure:m,occurrence:f===null?1:f.occurrence+1})),Vn(m)&&Ht.revalidate()},[X,Pe]=P(null),[le,Ne]=P(null),Kt=i=>{Pe({metadataId:i,intent:"retry_job",status:"pending",error:null}),r.submit({intent:"retry_job",fileId:String(i)},{method:"post"})},qt=i=>{i.after===void 0&&Ne({settled:0,status:"pending",requeued:0,skipped:[],nextAfter:null,error:null});let{after:m,...f}=i;r.submit(m===void 0?{intent:"resync_findings",...f}:{intent:"resync_findings",...f,after:String(m)},{method:"post"})},Vt=()=>{Pe(null),Ne(null)},[Ze,Ee]=P("console"),[Bt,Qt]=P(void 0),Gt=(i,m)=>{if(m==="retry_job"&&X!==null&&X.status==="pending"){let f=i?.error;Pe(f===void 0?{...X,status:"accepted",error:null}:{...X,status:"refused",error:f});return}if(m==="resync_findings"&&le!==null&&le.status==="pending"){Ne(nr(le,i));return}Qt(i?.error),Ee("inspector")},{settledIntent:zt,submitAndAwait:Xe}=ye(t,()=>Ee("console"));ye(n,i=>{Ee("integrity"),Mt(i)}),ye(r,Gt);let et=Ze==="inspector"?Bt:(Ze==="console"?t:n).data?.error,Te=i=>{x(i),G.current[i]?.focus()},tt=_(null),Wt={strategies:{label:je($e),onOpen:()=>Te($e.key),closesInspector:!0},projectionPolicy:{label:je(Me),onOpen:()=>Te(Me.key),closesInspector:!0},failedSync:{label:ut,onOpen:()=>tt.current?.focus(),closesInspector:!1}},ee=zt==="retry_all_failed"&&t.data?.skipped!==void 0&&t.data.requeued!==void 0?{requeued:t.data.requeued,skipped:t.data.skipped}:null;return u(pn,{locale:"ja",formatLocale:ce,timeZone:e.displayTimeZone,testId:"storage-admin-console-ui",children:R("div",{className:"container mx-auto space-y-6 p-6 font-sans text-slate-900","data-testid":"storage-admin-console",children:[et&&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:et}),s?s({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:e.tenantId}):R("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:[R("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"}),R("p",{className:"mt-1 text-slate-500 text-sm",children:["\u30C6\u30CA\u30F3\u30C8: ",u("code",{className:"font-semibold text-slate-800",children:e.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:R("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 ${e.systemHealth.allHealthy?"bg-emerald-500":"bg-amber-500"}`}),R("span",{children:["\u5468\u8FBA\u6A5F\u80FD: ",e.systemHealth.allHealthy?"\u5168\u30B5\u30FC\u30D3\u30B9\u6B63\u5E38":"\u63A5\u7D9A\u8981\u78BA\u8A8D"]})]})})]}),R("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 ${xe.className} ${Fe.className} ${De.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,m)=>{let f=b===i.key;return u("button",{id:`tab-${i.key}`,type:"button",role:"tab",ref:C=>{G.current[i.key]=C},"aria-selected":f,"aria-controls":`panel-${i.key}`,tabIndex:f?0:-1,"data-testid":`tab-trigger-${i.key}`,onKeyDown:C=>Ot(C,m),onClick:()=>x(i.key),className:`wrap-anywhere break-keep rounded-lg px-3 py-2.5 text-center font-medium text-sm transition-all ${m===M.length-1?`${Le(xe,M.length)} ${Le(Fe,M.length)} ${De.lastTabClassName}`:""} ${f?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:bg-slate-200/50 hover:text-slate-900"}`,children:i.phrases.map((C,ue)=>R(Zn,{children:[ue>0&&u("wbr",{}),C]},C))},i.key)})})}),H!==void 0&&z!==null&&u(Pn,{host:H,metadataId:z.metadataId,target:z.target,openRequest:Pt,onClose:Et,returnFocusFallback:Ie,captureState:Tt}),b==="search"&&R("div",{role:"tabpanel",id:"panel-search","aria-labelledby":"tab-search",className:"space-y-6","data-testid":"tab-content-search",children:[u(_n,{tenantId:e.tenantId,onSearch:p,circuitBreakerStatus:e.circuitBreakerStatus}),h!==void 0&&u(kn,{variants:we,onCompare:h})]}),b==="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:e.tenantId,policies:e.confidentialityPolicies,domainOptions:oe,recentItems:ve,listRefusal:ae===null?void 0:ae,inspectionResult:xt,isInspecting:Ft,isSubmitting:Dt,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:ze})}),b==="pipeline"&&R("div",{role:"tabpanel",id:"panel-pipeline","aria-labelledby":"tab-pipeline",className:"space-y-6","data-testid":"tab-content-pipeline",children:[u(Fn,{featureFlags:e.featureFlags,metrics:e.pipelineStepMetrics,metricSampleWindow:e.pipelineStepMetricWindow}),u(fr,{runs:e.recentPipelineRuns,refusal:U,onOpenRun:_t}),u(En,{strategies:e.enrichmentStrategies,featureFlags:e.featureFlags,isUpdating:t.state!=="idle",onToggleStage:(i,m,f)=>t.submit({intent:"update_enrichment_strategy",strategyId:String(i.id),domainId:String(i.domainId),stage:m,enabled:String(f)},{method:"post"})}),u(Tn,{health:e.systemHealth,isRefreshing:t.state!=="idle",onRefresh:()=>t.submit({intent:"refresh_health"},{method:"post"})})]}),b==="knowledge-graph"&&R("div",{role:"tabpanel",id:"panel-knowledge-graph","aria-labelledby":"tab-knowledge-graph",className:"space-y-6","data-testid":"tab-content-knowledge-graph",children:[u(On,{tenantId:e.tenantId,ontologyStatus:e.ontologyStatus}),u(Bn,{topologyMaxLabels:hn.topologyLabels.default,schema:e.graphSchema,tenantId:e.tenantId,unresolvedEntities:e.unresolvedEntities,traversal:o,onBrowseLabel:V,nodeIndexPage:j,nodeIndexFailure:w,isNodeIndexLoading:O,isResolving:jt,onResolveEntity:(i,m)=>{t.submit({intent:"resolve_entity",entityId:i,action:m},{method:"post"})}})]}),b==="parameters"&&R("div",{role:"tabpanel",id:"panel-parameters","aria-labelledby":"tab-parameters",className:"space-y-6","data-testid":"tab-content-parameters",children:[R("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2",children:[u(Kn,{flags:We,isUpdating:t.state!=="idle",onToggleFlag:(i,m)=>{t.submit({intent:"toggle_flag",flagKey:i,enabled:String(m)},{method:"post"})}}),u(Hn,{rules:e.classificationRules,domainOptions:oe,consultedBy:e.classificationRuleConsumer,onReorderRules:i=>{t.submit({intent:"reorder_rules",orderedRuleIds:JSON.stringify(i)},{method:"post"})}})]}),e.policiesMissingDestination.length>0&&R("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:e.policiesMissingDestination.map(i=>R("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($n,{policies:e.confidentialityPolicies,promptKeys:e.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(Jn,{vocabulary:e.transcriptionVocabulary,references:e.transcriptionReferences,unresolvedUris:e.unresolvedReferenceUris,isUpdating:t.state!=="idle",onSaveTerm:i=>Xe({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=>Xe({intent:"save_transcription_reference",id:i.id===null?"":String(i.id),fileUri:i.fileUri,domainKey:i.domainKey??"",isActive:String(i.isActive)},{method:"post"})}),u(Wn,{parameters:e.systemParameters,onSaveParameter:(i,m)=>{t.submit({intent:"update_parameter",paramKey:i,paramValue:String(m)},{method:"post"})}})]}),b==="prompts"&&R("div",{role:"tabpanel",id:"panel-prompts","aria-labelledby":"tab-prompts",className:"space-y-6","data-testid":"tab-content-prompts",children:[u(zn,{templates:e.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(qn,{onSimulate:c})]}),b==="knowledge-authority"&&R("div",{role:"tabpanel",id:"panel-knowledge-authority","aria-labelledby":"tab-knowledge-authority",className:"space-y-6","data-testid":"tab-content-knowledge-authority",children:[u(Mn,{host:g,canUpdate:e.canUpdateKnowledge,onPolicyConflictsChanged:he}),u(Qn,{host:k,revision:Se})]}),b==="data-retention"&&R("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:ie,children:u(Yn,{overview:F.overview.value,canReadFindings:e.canReadIntegrityFindings,command:Ut,commandFailure:$t,onStartRun:(i,m)=>{n.submit(m===null?{intent:"start_integrity_run",mode:i}:{intent:"start_integrity_run",mode:i,basisRunUid:m},{method:"post"})},onCancelRun:i=>{n.submit({intent:"cancel_integrity_run",runUid:i},{method:"post"})},loadFindings:S,refreshFailure:F.overview.refreshFailure===null?null:F.overview.refreshFailure.reason,headingRef:Y,onShowHistory:ze,resync:{onResync:Kt,onDismiss:Vt,feedback:X,sending:r.state!=="idle",cellResync:{onResyncCell:qt,feedback:le}},remedyDestinations:Wt})}):u(dn,{title:sr,testId:"audit-overview-failed",headingRef:Y,children:u(gn,{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:ir,rescueRef:ie,testId:"audit-overview-failed-resource"})}),u(Gn,{host:k,knowledgeTabLabel:je(He),onOpenKnowledgeTab:()=>Te(He.key)}),H!==void 0&&u(Cn,{host:H,onOpen:kt}),ee!==null&&ee.skipped.length>0&&R("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:[R("strong",{children:["\u4E00\u62EC\u518D\u8A66\u884C: ",ee.requeued," \u4EF6\u3092\u518D\u6295\u5165\u3057\u3001",ee.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:ee.skipped.map(i=>R("li",{"data-testid":`retry-all-skipped-${i.metadataId}`,children:["#",i.metadataId,": ",i.reason]},i.metadataId))})]}),R("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2",children:[u("section",{ref:tt,tabIndex:-1,"aria-label":ut,"data-testid":"sync-status-region",children:u(Un,{counts:e.syncCounts,totalFiles:e.totalFiles,failedItems:e.failedSyncItems,listRefusal:U===null?void 0:U,isRetrying:Lt,onRetryItem:i=>{t.submit({intent:"retry_job",fileId:String(i)},{method:"post"})},onRetryAll:()=>{t.submit({intent:"retry_all_failed"},{method:"post"})}})}),u(Ln,{overview:e.qdrantCollections,health:{healthy:e.systemHealth.services.qdrant.status==="connected",latency_ms:e.systemHealth.services.qdrant.latencyMs}})]})]})]})]})})}var ct=new Set(bn.options.filter(e=>e!=="SYNCED"&&!e.startsWith("FAILED"))),cr=new Set(An.options.filter(e=>e!=="SUCCEEDED"&&!e.startsWith("FAILED"))),dt=2e3;function dr(e){if(e.kind==="restricted")return e.syncStatus!==null&&ct.has(e.syncStatus);let t=e.item.lastRun;return ct.has(e.item.syncStatus)||t!==null&&t.kind==="restricted"&&cr.has(t.status)}var Ue={rows:null,refusal:null};function pr(e,t,n){let[r,a]=P(Ue),s=_(t);s.current=t;let o=_(e);o.current!==e&&(o.current=e,r!==Ue&&a(Ue));let c=(r.rows===null?e:r.rows)?.some(dr)===!0;return Ke(()=>{if(!(n&&c&&s.current))return;let d=!1,p,y=async()=>{let h=s.current;if(h!==void 0){try{let v=await h();if(d)return;a(v.kind==="rows"?{rows:v.rows,refusal:null}:{rows:pt,refusal:v.reason})}catch{if(d)return}p=setTimeout(y,dt)}};return p=setTimeout(y,dt),()=>{d=!0,clearTimeout(p)}},[c,n,e]),r}function mr(e){let t=_(e);t.current=e;let n=_(null);return ye(e,r=>{let a=n.current;n.current=null,a?.(ur(r))}),W(r=>new Promise(a=>{n.current?.({ok:!1,status:null,reason:"\u5F8C\u306E\u8A18\u9332\u306B\u7F6E\u304D\u63DB\u3048\u3089\u308C\u307E\u3057\u305F"}),n.current=a,t.current.submit({intent:"capture_document_state",metadataId:String(r)},{method:"post"})}),[])}function ye(e,t){let n=_(t);n.current=t;let r=_(null),a=_(!1),s=_(null);if(e.state!=="idle"){a.current=!0;let l=e.formData?.get("intent");typeof l=="string"&&(r.current=l)}Ke(()=>{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=W((...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 gr(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 yr(e){return{strategyId:e.strategyId,label:`${e.domainKey} / ${e.variantKey}`,embeddingModel:e.embeddingModel}}function fr({runs:e,refusal:t,onOpenRun:n}){return R("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"}),t!==null?u("div",{className:"mt-4",children:u(mn,{tone:"warning",testId:"document-read-refusal-pipeline",children:t})}):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:R("table",{className:"w-full text-left text-[13px]",children:[u("thead",{children:R("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"}),n!==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((r,a)=>{if(r.kind==="restricted"){let c=at[r.status];return R("tr",{className:"border-slate-100 border-b border-solid","data-testid":`pipeline-run-mark-${a}`,"data-restricted-mark":"run","data-status":r.status,children:[u("td",{className:"px-3 py-2"}),u("td",{className:"px-3 py-2","data-testid":`pipeline-run-mark-document-${a}`,children:jn}),u("td",{className:"px-3 py-2"}),u("td",{className:"px-3 py-2"}),u("td",{className:"px-3 py-2"}),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] ${c.className}`,"data-testid":`pipeline-run-mark-status-${a}`,"data-status":r.status,children:c.label})}),u("td",{className:"px-3 py-2"}),u("td",{className:"whitespace-nowrap px-3 py-2 text-slate-500","data-testid":`pipeline-run-mark-started-${a}`,children:u(ot,{iso:r.startedAt,testId:`pipeline-run-mark-started-value-${a}`})}),u("td",{className:"whitespace-nowrap px-3 py-2 text-slate-500","data-testid":`pipeline-run-mark-finished-${a}`,children:u(it,{iso:r.finishedAt,testId:`pipeline-run-mark-finished-value-${a}`})}),u("td",{className:"px-3 py-2"}),n!==void 0&&u("td",{className:"px-3 py-2"})]},`restricted:${a}`)}let s=r.item,o=Dn(s),l=at[o];return R("tr",{className:"border-slate-100 border-b border-solid","data-testid":`pipeline-run-row-${s.id}`,"data-status":s.status,children:[R("td",{className:"whitespace-nowrap px-3 py-2 font-mono","data-testid":`pipeline-run-id-${s.id}`,children:["#",s.id]}),R("td",{className:"whitespace-nowrap px-3 py-2 font-mono","data-testid":`pipeline-run-metadata-${s.id}`,children:["#",s.metadataId]}),u("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-kind-${s.id}`,children:Rn[s.documentKind]}),u("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-trigger-${s.id}`,"data-trigger":s.trigger,children:xn[s.trigger]}),u("td",{className:"whitespace-nowrap px-3 py-2","data-testid":`pipeline-run-attempt-${s.id}`,children:s.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] ${l.className}`,"data-testid":`pipeline-run-status-${s.id}`,"data-status":s.status,"data-presentation":o,children:l.label})}),u("td",{className:"px-3 py-2","data-testid":`pipeline-run-failed-step-${s.id}`,children:s.failedStepKey===null?"\u2014":wn[s.failedStepKey].label}),u("td",{className:"whitespace-nowrap px-3 py-2 text-slate-500","data-testid":`pipeline-run-started-${s.id}`,children:u(ot,{iso:s.startedAt,testId:`pipeline-run-started-value-${s.id}`})}),u("td",{className:"whitespace-nowrap px-3 py-2 text-slate-500","data-testid":`pipeline-run-finished-${s.id}`,children:u(it,{iso:s.finishedAt,testId:`pipeline-run-finished-value-${s.id}`})}),u("td",{className:"wrap-anywhere px-3 py-2","data-testid":`pipeline-run-requested-by-${s.id}`,children:s.requestedBy}),n!==void 0&&u("td",{className:"whitespace-nowrap px-3 py-2 text-right",children:u("button",{type:"button",onClick:()=>n(s),"aria-label":`\u5B9F\u884C #${s.id} (\u6587\u66F8 #${s.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-${s.id}`,children:"\u8A73\u7D30"})})]},`readable:${s.id}`)})})]})})]})}function Rr(e){let t=Xn(),n=me(),r=me(),a=me(),s=me(),o=e.data??t,l=e.fetcher??n,c=e.integrityFetcher??r,d=e.inspectorFetcher??a,p=e.captureFetcher??s;return o?u(mt,{...e,data:o,fetcher:l,integrityFetcher:c,inspectorFetcher:d,captureFetcher:p}):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 gt(e){return e.data?u(mt,{...e,data:e.data,fetcher:e.fetcher??ge,integrityFetcher:e.integrityFetcher??ge,inspectorFetcher:e.inspectorFetcher??ge,captureFetcher:e.captureFetcher??ge}):u(Rr,{...e})}import{AuthzDeniedError as bt}from"@aiquants/authz-core";import{formatCount as Cr}from"@aiquants/console-ui/core";import{assertSystemParameterInRange as Pr,INTEGRITY_COMMAND_CODES as Nr,IntegrityAuditOverviewSchema as Er,IntegrityCellResyncRequestSchema as Tr,IntegrityCellResyncResultSchema as _r,IntegrityCommandFailureSchema as kr,IntegrityCommandReplySchema as Or,IntegrityRunModeSchema as ht,integrityCommandFailureCodeOf as xr,isEnrichmentStageKey as Fr,PipelineStepMetricSchema as Dr,RecentPipelineRunEntrySchema as Lr}from"@aiquants/enrichment-core";import{CLOUD_CAPABLE_CAPABILITIES as jr,ConfidentialityLevelSchema as Qe,GovernedCapabilitySchema as Ur}from"@aiquants/governance-core";import{z as I}from"zod";var Ve=3e3;function L(e){return Math.round(performance.now()-e)}function N(e){return typeof e=="string"&&de(e)?e:null}function D(e){let t=globalThis.process;return t===void 0?void 0:t.env[e]}function fe(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 yt(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 ft(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 Rt(e){let t=e.trim().split("://",1)[0]?.toLowerCase();if(t&&e.includes("://"))return t.endsWith("s")||t.includes("+s")}function Sr(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 qe(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 br(e){let t=e?.qdrantApiKey??D("QDRANT_API_KEY")??"",n=e?.timeoutMs??Ve,r=performance.now(),a="";try{a=fe(e?.qdrantUrl??D("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=L(r),y=(await l.json()).result?.collections?.length??0;return{serviceName:"Qdrant",category:"vector",status:"connected",version:N(c.version),endpoint:a,latencyMs:d,details:{engine:N(c.title),collectionsCount:y,restPort:Sr(a)??null,tls:Rt(a)??null}}}catch(s){let o=L(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 hr(e){let t=e?.timeoutMs??Ve,n=performance.now(),r=N(e?.neo4jBoltUri??D("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([qe(s("CALL dbms.components() YIELD versions, edition RETURN versions[0] AS version, edition",{}),t),qe(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]??[],y=c.rows[0]?.[0],h=L(n);return{serviceName:"Neo4j",category:"graph",status:"connected",version:N(d),endpoint:a,latencyMs:h,details:{edition:N(p),boltUri:r,nodeCount:typeof y=="number"?y:null,tls:r===null?null:Rt(r)??null}}}catch(s){let o=L(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 vr(e){let t=performance.now(),n="",r=ft(e?.redisTls,D("REDIS_TLS")),a=Number.NaN;try{let s=e?.redisClient;if(!s)throw new Error("Redis client not configured");let o=fe(e?.redisHost??D("REDIS_HOST"),"REDIS_HOST");a=yt(e?.redisPort,D("REDIS_PORT"),"REDIS_PORT"),n=`${r===!1?"redis":"rediss"}://${o}:${a}`,await s.ping();let l=await s.info("server"),c=N(l.match(/redis_version:([^\r\n]+)/)?.[1]),d=null;if(typeof s.dbSize=="function")try{d=await s.dbSize()}catch{d=null}let p=L(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=L(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 Ir(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 wr(e){let t=performance.now(),n="",r=ft(e?.sqlServerTls,D("SQL_SERVER_TLS")),a=Number.NaN;try{let s=e?.sqlServerExecute;if(!s)throw new Error("SQL Server executor not configured");let o=fe(e?.sqlServerHost??D("SQL_SERVER_HOST"),"SQL_SERVER_HOST");a=yt(e?.sqlServerPort,D("SQL_SERVER_PORT"),"SQL_SERVER_PORT"),n=`${o}:${a}`;let l=await s(),c=N(l.db_name),d=N(l.version),p=d===null?null:N(d.split(`
2
+ `)[0]),y=p===null?null:Ir(p),h=L(t);return{serviceName:"SQL Server",category:"database",status:"connected",version:y,endpoint:n,latencyMs:h,details:{database:c,port:a,tls:r??null,fullVersion:p}}}catch(s){let o=L(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 Ar(e){let t=e?.timeoutMs??Ve,n=performance.now(),r="";try{r=fe(e?.backendApiHost??D("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=L(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:o}}}catch(a){let s=L(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 St(e){let[t,n,r,a,s]=await Promise.all([br(e),hr(e),vr(e),wr(e),Ar(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 Hr=I.object({templateText:I.string(),modelName:I.string(),temperature:I.number(),maxOutputTokens:I.number(),responseSchema:I.union([I.record(I.string(),I.unknown()),I.string(),I.null()]).optional(),endpointBaseUrl:I.string().nullable()}).strict(),$r=I.discriminatedUnion("mode",[I.object({mode:ht.extract(["SCAN"]),basisRunUid:I.null()}).strict(),I.object({mode:ht.extract(["REPAIR"]),basisRunUid:I.string().uuid()}).strict()]),Mr=I.object({runUid:I.string().uuid()}).strict();function It(e){return e==="start_integrity_run"?"start":e==="cancel_integrity_run"?"cancel":null}function K(e,t){return e.issues.map(n=>`${n.path.length===0?t:n.path.join(".")}: ${n.message}`).join("; ")}function Kr(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 qr(e){let t=Lr.array().safeParse(e);if(!t.success)throw new Error(`getRecentPipelineRuns answered something that is neither a readable run summary nor a restricted run mark: ${K(t.error,"getRecentPipelineRuns")}`);return t.data}function Vr(e){let t=Dr.array().safeParse(e);if(!t.success)throw new Error(`getPipelineStepMetrics answered something that is not a step metric: ${K(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 Br(e){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`pipelineStepMetricWindow must be a positive safe integer, got ${String(e)}`);return e}async function Qr(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=Er.safeParse(n);return r.success?{ok:!0,value:r.data}:{ok:!1,status:null,reason:`readIntegrityAuditOverview answered something that is not an audit overview: ${K(r.error,"readIntegrityAuditOverview")}`}}function Gr(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 wt(e){let{store:t,healthProbeOptions:n,resourceKey:r="storage_admin",requireUser:a,requirePermission:s,resolveTenantId:o,authorizeIngest:l,authorizeHistoryCapture:c,canReadIntegrityFindings:d,canUpdateKnowledge:p}=e;async function y(v){let{request:S}=v;if(!await a(S))throw new Response("\u8A8D\u8A3C\u304C\u5FC5\u8981\u3067\u3059\u3002",{status:401});try{await s(S,{resourceKey:r,action:"read"})}catch(z){throw z instanceof bt?new Response("\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002",{status:403}):z}let g=await o(S),j=Br(t.pipelineStepMetricWindow),[E,w,A]=await Promise.all([t.getFeatureFlags(g),t.getSystemParameters(g),t.getSyncCounts(g)]),O={featureFlags:E,systemParameters:w,syncCounts:A},[q,V,B,Q,T,b,x,U,se,J,F,Y,ie,Se,be,he,ve,ae,G,Ie,oe,we]=await Promise.all([t.getConfidentialityPolicies(g),t.getTranscriptionVocabulary(g),t.getTranscriptionReferences(g),t.getUnresolvedReferenceUris(g),t.getPoliciesMissingDestination(g),t.getPromptTemplates(g),t.getClassificationRules(g),t.getFailedSyncItems(g,S),t.getGraphSchema(g),Qr(t,g),d(S),p(S),t.getUnresolvedEntities(g),t.getQdrantCollections(g),St({...n,tenantId:g}),t.getRecentIngestItems(g,S),t.getOntologyStatus(g,O),t.getEnrichmentStrategies(g),t.getStrategyVariants(g),t.getPipelineStepMetrics(g),t.getRecentPipelineRuns(g,S),t.getDocumentReadRefusal(g,S)]),H=t.getCircuitBreakerStatus();return{tenantId:g,featureFlags:O.featureFlags,confidentialityPolicies:q,transcriptionVocabulary:V,transcriptionReferences:B,unresolvedReferenceUris:Q,policiesMissingDestination:T,systemParameters:O.systemParameters,promptTemplates:b,classificationRules:x,classificationRuleConsumer:t.classificationRuleConsumer??null,syncCounts:O.syncCounts.counts,totalFiles:O.syncCounts.total,failedSyncItems:U,circuitBreakerStatus:H,pipelineStepMetrics:Vr(Ie),pipelineStepMetricWindow:j,recentPipelineRuns:qr(oe),displayTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,graphSchema:se,enrichmentStrategies:ae,strategyVariants:G,integrityAudit:J,canReadIntegrityFindings:F,canUpdateKnowledge:Y,unresolvedEntities:ie,qdrantCollections:Se,systemHealth:be,recentIngestItems:he,documentReadRefusal:we,ontologyStatus:ve}}async function h(v){let{request:S}=v,k=await a(S);if(!k)return Response.json({error:"\u8A8D\u8A3C\u304C\u5FC5\u8981\u3067\u3059\u3002"},{status:401});if(k.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(k.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 g=k.email,j=k.accessToken===null?void 0:k.accessToken;try{await s(S,{resourceKey:r,action:"update"})}catch(T){if(T instanceof bt)return await ts(S);throw T}let E=await o(S),w=await S.formData(),A=String(w.get("intent")??"");if(A==="refresh_health")return Response.json({success:!0,refreshed:!0});let O=await Wr(t,E,A,w,g);if(O)return O;let q=await Jr(t,E,A,w,g,j);if(q)return q;let V=await es(t,E,A,w,g,j,()=>d(S));if(V)return V;let B=await rs(t,E,A,w,j,()=>d(S));if(B)return B;if(A==="resolve_entity"){let T=String(w.get("entityId")??""),b=String(w.get("action")??"");if(!T||b!=="merge"&&b!=="promote")return Response.json({error:"Valid entityId and action ('merge' | 'promote') are required"},{status:400});try{return await t.resolveEntity(E,T,b),Response.json({success:!0,entityId:T,action:b})}catch(x){return Response.json({error:x instanceof Error?x.message:String(x)},{status:400})}}let Q=await as(t,E,A,w,g,S,l,j);return Q||(A===Ct?await ns(t,E,w,g,S,c):Response.json({error:`Unknown intent: ${A}`},{status:400}))}return{loader:y,action:h}}function Be(e){let t=String(e??"").trim();return t===""?null:t}function Re(e){let t=String(e??"").trim();if(t==="")return null;let n=Number(t);if(!(!Number.isSafeInteger(n)||n<=0))return n}function zr(e){let t=String(e??"").trim();if(t==="")return null;let n=Number(t);if(!(!Number.isFinite(n)||n<=0))return n}async function Wr(e,t,n,r,a){if(n==="update_enrichment_strategy"){let s=String(r.get("stage")??"");if(!Fr(s))return Response.json({error:"stage must be a canonical enrichment stage key"},{status:400});let o=Re(r.get("strategyId")),l=Re(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(!(Qe.safeParse(s).success&&Ur.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&&!jr.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=zr(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=Re(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:Be(r.get("reading")),boost:o,domainKey:Be(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=Re(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:Be(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=Kr(l.data_type,o);if(c!==null)return Response.json({error:c},{status:400});try{Pr(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=Hr.safeParse(l);if(!c.success)return Response.json({error:`payload does not carry a prompt template update: ${K(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=Gr(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 Jr(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 Yr="resync_findings",Zr="\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",At=/^[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"&&At.test(n)?Number(n):n]))}async function es(e,t,n,r,a,s,o){if(n!==Yr)return null;if(!await o())return Response.json({error:Zr},{status:403});let l=Tr.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): ${K(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=_r.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 (${K(d.error,"answer")})\u3002\u958B\u767A\u62C5\u5F53\u306B\u9023\u7D61\u3057\u3066\u304F\u3060\u3055\u3044\u3002`},{status:502})}function re(e,t,n){let r=kr.parse({command:e,code:t,status:n}),a=Nr.find(s=>s.code===r.code);return Response.json({failure:r},{status:a===void 0?502:a.status})}async function ts(e){let t=await e.formData().catch(()=>null),n=t===null?null:t.get("intent");if(n===Ct)return ne({status:403,reason:""});let r=It(n);return r===null?Response.json({error:"\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002"},{status:403}):re(r,"FORBIDDEN",null)}var Ct="capture_document_state";function ne(e){return Response.json({captureFailure:e},{status:e.status})}async function ns(e,t,n,r,a,s){let o=n.get("metadataId"),l=typeof o=="string"&&At.test(o)?Number(o):null;if(l===null||!Number.isSafeInteger(l))return Response.json({error:"capture_document_state takes metadataId (a positive integer)"},{status:400});let c=await s(a,l);if(c!==null)return ne({status:c.status,reason:c.error});let d;try{d=await e.captureDocumentState(t,l,r)}catch{return ne({status:500,reason:""})}switch(d.kind){case"recorded":return Response.json({outcome:"RECORDED"});case"unchanged":return Response.json({outcome:"UNCHANGED"});case"failed":return ne({status:d.status,reason:d.error});default:return ne({status:500,reason:""})}}async function vt(e,t){let n;try{n=Or.parse(await t())}catch{return re(e,"UPSTREAM_FAILED",null)}return n.ok?Response.json({success:!0,runUid:n.runUid}):re(e,xr(e,n.status,n.errorCode),n.status)}async function rs(e,t,n,r,a,s){let o=It(n);if(o==="start"){let l=$r.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): ${K(l.error,"form")}`},{status:400});let{mode:c,basisRunUid:d}=l.data;return a===void 0||c==="REPAIR"&&!await s()?re(o,"FORBIDDEN",null):await vt(o,()=>e.startIntegrityRun(t,c,d,a))}if(o==="cancel"){let l=Mr.safeParse({runUid:r.get("runUid")});return l.success?a===void 0?re(o,"FORBIDDEN",null):await vt(o,()=>e.cancelIntegrityRun(t,l.data.runUid,a)):Response.json({error:`cancel_integrity_run takes runUid (a UUID): ${K(l.error,"form")}`},{status:400})}return null}function ss(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(!Qe.safeParse(t.confidentialityLevel).success)return`payload.confidentialityLevel must be one of ${Qe.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 is(e){try{return Cr(e,ce),null}catch{return`inspectFileUri answered a fileSize that is not a byte count (a non-negative safe integer): ${String(e)}`}}async function as(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=ss(d);if(p)return Response.json({error:p},{status:400});let y=d,h=await o(s,y);if(h!==null)return Response.json({error:h},{status:403});let v;try{v=await(l===void 0?e.ingestDocument(t,y,a):e.ingestDocument(t,y,a,l))}catch(S){return Response.json({error:S instanceof Error?S.message:String(S)},{status:400})}return v.kind==="refused"?Response.json({error:v.error},{status:v.status}):Response.json({success:!0,result:v.result})}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(y){return Response.json({error:y instanceof Error?y.message:String(y)},{status:400})}let p=is(d.fileSize);return p!==null?Response.json({error:p},{status:400}):Response.json({success:!0,inspection:d})}return null}function Ms(e){let t=wt(e);return{loader:t.loader,action:t.action,View:gt,server:t}}export{gt as StorageAdminConsoleView,St as checkAllSystemHealth,Ar as checkBackendApiHealth,hr as checkNeo4jHealth,br as checkQdrantHealth,vr as checkRedisHealth,wr as checkSqlServerHealth,Ms as createStorageAdminApp,wt as createStorageAdminServer};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiquants/enrichment-react-router",
3
- "version": "0.4.0",
3
+ "version": "0.5.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.3",
41
- "@aiquants/enrichment-react": "^0.3.0",
42
- "@aiquants/governance-core": "^0.2.1",
43
- "@aiquants/governance-react": "^0.4.0",
40
+ "@aiquants/enrichment-core": "^0.4.0",
41
+ "@aiquants/enrichment-react": "^0.4.0",
42
+ "@aiquants/governance-core": "^0.3.0",
43
+ "@aiquants/governance-react": "^0.5.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.3",
53
- "@aiquants/enrichment-react": "0.3.0",
54
- "@aiquants/governance-core": "0.2.1",
55
- "@aiquants/governance-react": "0.4.0",
52
+ "@aiquants/enrichment-core": "0.4.0",
53
+ "@aiquants/enrichment-react": "0.4.0",
54
+ "@aiquants/governance-core": "0.3.0",
55
+ "@aiquants/governance-react": "0.5.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",