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