@jini-ai/db 0.3.0 → 0.3.2

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.
Files changed (63) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/core/artifact-naming.d.ts +4 -1
  3. package/dist/core/artifact-naming.js +3 -4
  4. package/dist/core/index.d.ts +1 -0
  5. package/dist/core/messages.d.ts +1 -1
  6. package/dist/core/pg-types.d.ts +52 -0
  7. package/dist/core/pg-types.js +8 -0
  8. package/dist/core/transfer-naming.d.ts +10 -0
  9. package/dist/core/transfer-naming.js +2 -0
  10. package/dist/kernel/postgres/driver.d.ts +1 -1
  11. package/dist/kernel/postgres/driver.js +1 -1
  12. package/dist/kernel/postgres/pglite-socket.d.ts +1 -1
  13. package/dist/kernel/postgres/pglite-socket.js +1 -1
  14. package/dist/pg-fixture.d.ts +50 -0
  15. package/dist/pg-fixture.js +84 -0
  16. package/dist/pglite/owner.js +7 -0
  17. package/dist/postgres/index.d.ts +1 -1
  18. package/dist/postgres/index.js +1 -1
  19. package/dist/postgres/types.d.ts +1 -52
  20. package/dist/postgres/types.js +2 -13
  21. package/dist/recovery/deep-link.d.ts +60 -0
  22. package/dist/recovery/deep-link.js +16 -0
  23. package/dist/recovery/degraded-banners.d.ts +40 -0
  24. package/dist/recovery/degraded-banners.js +69 -0
  25. package/dist/recovery/disclosure.d.ts +58 -0
  26. package/dist/recovery/disclosure.js +55 -0
  27. package/dist/recovery/evaluate-boot-migration-policy.d.ts +41 -0
  28. package/dist/recovery/evaluate-boot-migration-policy.js +50 -0
  29. package/dist/recovery/hook-policy.d.ts +9 -0
  30. package/dist/recovery/hook-policy.js +2 -0
  31. package/dist/recovery/index.d.ts +15 -0
  32. package/dist/recovery/index.js +13 -0
  33. package/dist/recovery/lookup-adapters.d.ts +40 -0
  34. package/dist/recovery/lookup-adapters.js +44 -0
  35. package/dist/recovery/migrate-forward-execute.d.ts +65 -0
  36. package/dist/recovery/migrate-forward-execute.js +68 -0
  37. package/dist/recovery/migrate-forward-hooks.d.ts +118 -0
  38. package/dist/recovery/migrate-forward-hooks.js +85 -0
  39. package/dist/recovery/operation-lock.d.ts +78 -0
  40. package/dist/recovery/operation-lock.js +58 -0
  41. package/dist/recovery/reconcile-interrupted-migration.d.ts +73 -0
  42. package/dist/recovery/reconcile-interrupted-migration.js +47 -0
  43. package/dist/recovery/recovery-orchestrator.d.ts +204 -0
  44. package/dist/recovery/recovery-orchestrator.js +96 -0
  45. package/dist/recovery/restore-hooks.d.ts +105 -0
  46. package/dist/recovery/restore-hooks.js +154 -0
  47. package/dist/recovery/restore-point-create.d.ts +80 -0
  48. package/dist/recovery/restore-point-create.js +37 -0
  49. package/dist/secrets-vault/index.d.ts +2 -0
  50. package/dist/secrets-vault/index.js +2 -0
  51. package/dist/secrets-vault/repo.sql.d.ts +82 -0
  52. package/dist/secrets-vault/repo.sql.js +176 -0
  53. package/dist/sqlite/inspect.d.ts +5 -1
  54. package/dist/sqlite/inspect.js +47 -18
  55. package/dist/sqlite/open.d.ts +1 -1
  56. package/dist/sqlite/open.js +3 -3
  57. package/dist/sqlite/restore-types.d.ts +7 -3
  58. package/dist/tools/surface-port.d.ts +11 -35
  59. package/dist/tools/transfer-tools.js +36 -37
  60. package/dist/transfer/internal-ddl.d.ts +3 -0
  61. package/dist/transfer/internal-ddl.js +6 -2
  62. package/dist/transfer/types.d.ts +6 -9
  63. package/package.json +57 -6
@@ -0,0 +1,85 @@
1
+ import { nowIso as clockNowIso } from "@jini-ai/core/primitives";
2
+ /**
3
+ * SPEC-017 C-103/C-105 — the Database `migrate-forward` ceremony's `GatedMutationHooks`.
4
+ *
5
+ * `computePlan()` reads live `dbOps.getCapabilities()` every call (never cached) — a site whose
6
+ * capability changes between plan and execute (e.g. `cheap` -> `unavailable`) correctly produces a
7
+ * different plan hash.
8
+ *
9
+ * `executeMutation()` performs the two safe, real, ADR-041 §2/§3-mandated actions this composition
10
+ * root can perform without inventing an unreviewed live-schema-swap mechanism: it captures a real
11
+ * restore point (`dbOps.captureRestorePoint` — an online-backup file copy in the real SQLite
12
+ * composition, a deterministic double in the hermetic one) and appends a `core.migration`
13
+ * `database_ledger` row anchored to it. It deliberately does NOT re-run `drizzle-orm`'s migrator
14
+ * directly against `content.db` — every composition root already runs `migrate()` unconditionally
15
+ * at `openContentDb()` boot time (`db/sqlite/content-db.ts`), so by the time any ceremony could
16
+ * run, the schema is already at head; re-invoking the migrator here would be a no-op in every
17
+ * environment this dispatch can actually exercise, and this file has no reachable seam into the
18
+ * hermetic (`server/app.ts`) composition's non-existent `content.db` at all. Persisting a
19
+ * `migration_runs` row (the former state machine's attempt ledger) is likewise
20
+ * out of this pass's scope — no composition root wires `SqliteMigrationRunsRepo`/an in-memory
21
+ * counterpart into `RouteDeps` yet; disclosed, not silently skipped.
22
+ *
23
+ * `scopeKind: "instance"` (internal audit, 2026-08-12): `executeMutation()`'s only real side
24
+ * effects are `dbOps.captureRestorePoint` (a whole-file online-backup COPY of `content.db` — the
25
+ * same "never a partial/logical export" mechanism `db/sqlite/db-ops.ts` documents for restore,
26
+ * so the resulting artifact carries every workspace's data, not just the caller's) plus one
27
+ * `restorePointsRepo`/`databaseLedgerRepo` write each. The restore-points subsystem this feeds is
28
+ * itself not workspace-partitioned in practice: the real SQLite repo is nominally `siteId`-scoped
29
+ * but bound to exactly one `siteId` for a whole process's lifetime (`server/deps.ts`), the
30
+ * in-memory test double has no partitioning field at all (`features/database/repo.memory.ts`),
31
+ * and `features/recovery/gated-hooks.ts`'s `buildRestoreHooks` reads `restorePointsRepo.list()`
32
+ * completely unfiltered — so a restore point this ceremony captures is exactly as instance-wide
33
+ * as the one `backup.restore` (`features/recovery/gated-hooks.ts`, same `scopeKind` reasoning)
34
+ * consumes. A workspace-scoped admin should not be able to trigger a whole-instance backup capture
35
+ * that a single workspace's RBAC grant was never meant to cover.
36
+ *
37
+ * @complexity O(1) plus one `captureRestorePoint()` call and two persistence writes.
38
+ * state-machine.ts (features/database/migrate-forward/state-machine.ts) was deleted 2026-10-03: unused; see development/DELETED-CODE.md.
39
+ */
40
+ export function buildMigrateForwardHooks(input, _optional = {}) {
41
+ return {
42
+ domain: "database.migrate",
43
+ readPermission: "database.read",
44
+ mutatePermission: "database.migrate",
45
+ scopeId: input.workspaceId,
46
+ scopeKind: "instance",
47
+ computePlan: async () => {
48
+ const capabilities = await input.dbOps.getCapabilities();
49
+ const details = { costClass: capabilities.restorePoint.costClass, siteId: input.workspaceId };
50
+ return { planHash: input.planHashOf({ details }, {}), details };
51
+ },
52
+ executeMutation: async () => {
53
+ // Read fresh, not the `computePlan()` value — CIC U-003: a capability check cached across the
54
+ // plan/execute boundary can go stale, and the saved row must reflect what was ACTUALLY captured.
55
+ const capabilities = await input.dbOps.getCapabilities();
56
+ const captured = await input.dbOps.captureRestorePoint({ scopeId: input.workspaceId });
57
+ const restorePointId = input.idGen.newId();
58
+ const now = clockNowIso({ clock: input.clock });
59
+ await input.restorePointsRepo.save({
60
+ restorePointId,
61
+ idempotencyKey: restorePointId,
62
+ trigger: "migrate-forward",
63
+ createdAt: now,
64
+ createdBy: input.actorId,
65
+ costClass: capabilities.restorePoint.costClass,
66
+ kind: capabilities.restorePoint.kind,
67
+ watermarkAtCapture: captured.watermarkAtCapture,
68
+ artifactRef: captured.artifactRef,
69
+ });
70
+ await input.databaseLedgerRepo.append({
71
+ id: input.idGen.newId(),
72
+ kind: "core.migration",
73
+ restorePointId,
74
+ outcome: "success",
75
+ detailJson: JSON.stringify({ artifactRef: captured.artifactRef }),
76
+ actorWorkspaceId: input.workspaceId,
77
+ actorId: input.actorId,
78
+ createdAt: now,
79
+ });
80
+ return { migrated: true };
81
+ },
82
+ resolveActorClassIdentity: input.resolveActorClassIdentity,
83
+ };
84
+ }
85
+ //# sourceMappingURL=migrate-forward-hooks.js.map
@@ -0,0 +1,78 @@
1
+ import { type Clock as ClockPort } from "@jini-ai/core/primitives";
2
+ /**
3
+ * @file CIC U-001 (SPEC-019 `critical-internal-constraints.md`) — site-wide gated-operation
4
+ * mutual exclusion (C-309; REQ-13, INV-03; GOV-ADR-002).
5
+ *
6
+ * Purpose:
7
+ * The single, shared primitive both `features/database` (SPEC-017, migrate-forward) and
8
+ * `features/recovery` (SPEC-019, restore) MUST consult before starting a gated operation. Two
9
+ * domains racing to mutate the same site's `content.db` must never both be "in flight" — the
10
+ * primitive tracks in-flight state per `siteId` only, never per-domain, so it cannot be defeated
11
+ * by two domain-local checks that happen to look similar (U-001-B1).
12
+ *
13
+ * How it relates to the project:
14
+ * `executeMigrateForward` and `executeRestore` both call `acquireOperationLock` as the provably
15
+ * first side-effecting step of their own orchestration (U-001-ORD1), and `releaseOperationLock`
16
+ * once the operation concludes (success or failure).
17
+ *
18
+ * Architectural role:
19
+ * Core primitive. In-process only (host-shared instance registry) — a site's operations are already
20
+ * serialized to a single process by `content.db`'s own single-writer model; this primitive adds
21
+ * the cross-domain intent-level guard on top of that.
22
+ *
23
+ * ADR-041/043/044/045 re-audit (2026-07-16, TM-adr041-043-044-045-audit-001, Finding 3):
24
+ * the internal verifier's original claim — "never wired into any composition root" — is false,
25
+ * disproven by direct evidence: `server/routes/admin/database/migrate-forward.ts` and
26
+ * `server/routes/admin/recovery/restore.ts` both import `acquireOperationLock`/
27
+ * `releaseOperationLock` from this file directly and pass them into `executeMigrateForward`/
28
+ * `executeRestore` (their `execute` endpoints only). The mutual-exclusion guarantee (U-001) is
29
+ * real and live for both gated ceremonies today. The actual, narrower gap the re-audit surfaced:
30
+ * this module had no read-only query, so `routes/admin/recovery/status.ts`'s capability bar
31
+ * could not reflect live lock state and stubbed `operationInFlight: false` unconditionally.
32
+ * `isOperationInFlight` below closes that display gap without changing the mutual-exclusion
33
+ * mechanism itself.
34
+ */
35
+ export interface OperationLockHandle {
36
+ siteId: string;
37
+ operationKind: string;
38
+ /** ISO-8601 UTC. */
39
+ acquiredAt: string;
40
+ }
41
+ export interface OperationLockError {
42
+ code: "OPERATION_IN_FLIGHT";
43
+ message: string;
44
+ }
45
+ export type AcquireOperationLockResult = {
46
+ ok: true;
47
+ value: OperationLockHandle;
48
+ } | {
49
+ ok: false;
50
+ error: OperationLockError;
51
+ };
52
+ /** One host-owned registry shared by migration, restore and display-only status readers. */
53
+ export interface SharedOperationLockPort {
54
+ acquireOperationLock(required: {
55
+ deps: {
56
+ clock: ClockPort;
57
+ };
58
+ input: {
59
+ siteId: string;
60
+ operationKind: string;
61
+ };
62
+ }, optional?: Record<string, never>): Promise<AcquireOperationLockResult>;
63
+ releaseOperationLock(required: {
64
+ deps: {
65
+ clock: ClockPort;
66
+ };
67
+ input: {
68
+ siteId: string;
69
+ handle: OperationLockHandle;
70
+ };
71
+ }, optional?: Record<string, never>): Promise<void>;
72
+ isOperationInFlight(required: {
73
+ siteId: string;
74
+ }, optional?: Record<string, never>): boolean;
75
+ }
76
+ /** Create one shared lock for all gated-operation domains in a host; separate hosts get isolated state. */
77
+ export declare function createOperationLock(_required: Record<string, never>, _optional?: Record<string, never>): SharedOperationLockPort;
78
+ //# sourceMappingURL=operation-lock.d.ts.map
@@ -0,0 +1,58 @@
1
+ import { nowIso as readNowIso } from "@jini-ai/core/primitives";
2
+ /** Create one shared lock for all gated-operation domains in a host; separate hosts get isolated state. */
3
+ export function createOperationLock(_required, _optional = {}) {
4
+ /** Instance-owned in-flight registry — one entry per `siteId` (CIC U-001-B1). */
5
+ const activeLocksBySiteId = new Map();
6
+ /**
7
+ * Atomic check-and-set (U-001-B2): the presence check and the registry write happen in the same
8
+ * synchronous span with no intervening `await`, so concurrent callers on Node's single-threaded
9
+ * event loop (see the cross-domain property tests) cannot race a read-then-write gap — exactly
10
+ * one caller ever observes an empty slot for a given `siteId`.
11
+ *
12
+ * @complexity O(1).
13
+ */
14
+ async function acquireOperationLock(required, _optional = {}) {
15
+ const { deps, input } = required;
16
+ if (activeLocksBySiteId.has(input.siteId)) {
17
+ return {
18
+ ok: false,
19
+ error: {
20
+ code: "OPERATION_IN_FLIGHT",
21
+ message: `an operation is already in flight for site '${input.siteId}'`,
22
+ },
23
+ };
24
+ }
25
+ const handle = {
26
+ siteId: input.siteId,
27
+ operationKind: input.operationKind,
28
+ acquiredAt: readNowIso({ clock: deps.clock }),
29
+ };
30
+ activeLocksBySiteId.set(input.siteId, handle);
31
+ return { ok: true, value: handle };
32
+ }
33
+ /**
34
+ * Frees `input.siteId`'s lock. Idempotent — releasing a site with no held lock is a no-op, never
35
+ * an error. A stale holder cannot release a later acquisition for the same site.
36
+ *
37
+ * @complexity O(1).
38
+ */
39
+ async function releaseOperationLock(required, _optional = {}) {
40
+ const { siteId, handle } = required.input;
41
+ if (activeLocksBySiteId.get(siteId) === handle)
42
+ activeLocksBySiteId.delete(siteId);
43
+ }
44
+ /**
45
+ * Read-only peek at whether `siteId` currently holds a lock — never acquires, never mutates the
46
+ * registry. For display/status surfaces only (e.g. Recovery's capability bar); gated ceremonies
47
+ * must keep using `acquireOperationLock`'s atomic check-and-set, never this function, to decide
48
+ * whether they may proceed (a peek-then-acquire pair would reintroduce the TOCTOU gap U-001-B2
49
+ * exists to prevent).
50
+ *
51
+ * @complexity O(1).
52
+ */
53
+ function isOperationInFlight({ siteId }, _optional = {}) {
54
+ return activeLocksBySiteId.has(siteId);
55
+ }
56
+ return { acquireOperationLock, releaseOperationLock, isOperationInFlight };
57
+ }
58
+ //# sourceMappingURL=operation-lock.js.map
@@ -0,0 +1,73 @@
1
+ /**
2
+ * @file SPEC-017 C-106 / CIC U-004 / REQ-15 / AC-17 — boot-time crash reconciliation
3
+ * (ADR-041 §3).
4
+ *
5
+ * Purpose:
6
+ * A boot scanner that converts any non-terminal `migration_runs` row (read from the sidecar ops
7
+ * journal — the only place guaranteed to survive a mid-crash restore of `content.db`, ADR-041 §2)
8
+ * into a `migration.interrupted` ledger row, and blocks normal site open until an operator
9
+ * resolves it via Recovery. This is a real, accepted downtime vector, traded deliberately for
10
+ * "never boot into a half-migrated schema" (ADR-041 §3).
11
+ *
12
+ * How it relates to the project:
13
+ * The boot composition root calls this BEFORE `evaluate-boot-migration-policy.ts`'s
14
+ * `evaluateBootMigrationPolicy` (C-107) every boot cycle (U-004-ORD1) — that ordering is a
15
+ * composition-root wiring concern this module cannot itself enforce; the sibling `defensive`
16
+ * precondition check lives in `evaluate-boot-migration-policy.ts` instead.
17
+ *
18
+ * ADR-041/043/044/045 re-audit (2026-07-16, TM-adr041-043-044-045-audit-001, Finding 2 — hard
19
+ * blocker fix): this function is now actually invoked, by `server/runtime/boot/bootstrap.ts`'s
20
+ * `database-migration-reconciliation` boot module (a CRITICAL ADR-046 Phase 2 boot module, runs
21
+ * first), before the real server accepts any traffic. It was previously fully built and
22
+ * unit-tested but never called by any composition root — a real, live gap (not just a "seams
23
+ * only" v1 disclosure) this fix closes. `evaluate-boot-migration-policy.ts`'s
24
+ * `evaluateBootMigrationPolicy` (C-107) itself remains NOT wired into any composition root —
25
+ * that is `SERVE_SITE` cost-gated auto-migration, a separate, larger, still-deferred capability
26
+ * this fix does not build; only the crash-detection half above is now live.
27
+ *
28
+ * Architectural role:
29
+ * `features/database` domain logic. Depends only on the injected ports.
30
+ */
31
+ export interface MigrationRunsRepoPort {
32
+ findNonTerminalForSite(siteId: string): Promise<{
33
+ id: string;
34
+ status: string;
35
+ } | null>;
36
+ /**
37
+ * Round-5 re-audit (2026-07-16, TM-adr041-043-044-045-audit-001, codex `R5-F1-BLOCKED-RECOVERY-
38
+ * NOT-RESTART-SAFE` / Fable `R5-F2-BLOCK-HAS-NO-EXIT`, both independently confirmed): before this
39
+ * fix, no production code path ever terminalized a non-terminal `migration_runs` row, so a
40
+ * successful Recovery restore left `BLOCKED_PENDING_RECOVERY` in place forever — the block had no
41
+ * exit. Marks the run terminal (`RESTORED`) so the next boot's `findNonTerminalForSite` no longer
42
+ * re-detects it.
43
+ */
44
+ markResolved(params: {
45
+ id: string;
46
+ }): Promise<void>;
47
+ }
48
+ export interface BootLedgerPort {
49
+ appendInterruptedRow(params: {
50
+ siteId: string;
51
+ migrationRunId: string;
52
+ }): Promise<void>;
53
+ }
54
+ export type SiteServeStatus = "SERVING" | "PENDING_MIGRATION" | "BLOCKED_PENDING_RECOVERY";
55
+ export interface SiteStatusPort {
56
+ get(siteId: string): Promise<SiteServeStatus>;
57
+ set(siteId: string, status: SiteServeStatus): Promise<void>;
58
+ }
59
+ /**
60
+ * Reconciles any crashed-mid-migration state found for `siteId` on boot.
61
+ *
62
+ * @complexity O(1) plus one repo read and, when a non-terminal row exists, one ledger append and
63
+ * one status write.
64
+ */
65
+ export declare function reconcileInterruptedMigrationOnBoot(required: {
66
+ siteId: string;
67
+ migrationRuns: MigrationRunsRepoPort;
68
+ ledger: BootLedgerPort;
69
+ siteStatus: SiteStatusPort;
70
+ }, _optional?: Record<string, never>): Promise<{
71
+ blocked: boolean;
72
+ }>;
73
+ //# sourceMappingURL=reconcile-interrupted-migration.d.ts.map
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @file SPEC-017 C-106 / CIC U-004 / REQ-15 / AC-17 — boot-time crash reconciliation
3
+ * (ADR-041 §3).
4
+ *
5
+ * Purpose:
6
+ * A boot scanner that converts any non-terminal `migration_runs` row (read from the sidecar ops
7
+ * journal — the only place guaranteed to survive a mid-crash restore of `content.db`, ADR-041 §2)
8
+ * into a `migration.interrupted` ledger row, and blocks normal site open until an operator
9
+ * resolves it via Recovery. This is a real, accepted downtime vector, traded deliberately for
10
+ * "never boot into a half-migrated schema" (ADR-041 §3).
11
+ *
12
+ * How it relates to the project:
13
+ * The boot composition root calls this BEFORE `evaluate-boot-migration-policy.ts`'s
14
+ * `evaluateBootMigrationPolicy` (C-107) every boot cycle (U-004-ORD1) — that ordering is a
15
+ * composition-root wiring concern this module cannot itself enforce; the sibling `defensive`
16
+ * precondition check lives in `evaluate-boot-migration-policy.ts` instead.
17
+ *
18
+ * ADR-041/043/044/045 re-audit (2026-07-16, TM-adr041-043-044-045-audit-001, Finding 2 — hard
19
+ * blocker fix): this function is now actually invoked, by `server/runtime/boot/bootstrap.ts`'s
20
+ * `database-migration-reconciliation` boot module (a CRITICAL ADR-046 Phase 2 boot module, runs
21
+ * first), before the real server accepts any traffic. It was previously fully built and
22
+ * unit-tested but never called by any composition root — a real, live gap (not just a "seams
23
+ * only" v1 disclosure) this fix closes. `evaluate-boot-migration-policy.ts`'s
24
+ * `evaluateBootMigrationPolicy` (C-107) itself remains NOT wired into any composition root —
25
+ * that is `SERVE_SITE` cost-gated auto-migration, a separate, larger, still-deferred capability
26
+ * this fix does not build; only the crash-detection half above is now live.
27
+ *
28
+ * Architectural role:
29
+ * `features/database` domain logic. Depends only on the injected ports.
30
+ */
31
+ /**
32
+ * Reconciles any crashed-mid-migration state found for `siteId` on boot.
33
+ *
34
+ * @complexity O(1) plus one repo read and, when a non-terminal row exists, one ledger append and
35
+ * one status write.
36
+ */
37
+ export async function reconcileInterruptedMigrationOnBoot(required, _optional = {}) {
38
+ const { siteId, migrationRuns, ledger, siteStatus } = required;
39
+ const nonTerminal = await migrationRuns.findNonTerminalForSite(siteId);
40
+ if (!nonTerminal) {
41
+ return { blocked: false };
42
+ }
43
+ await ledger.appendInterruptedRow({ siteId, migrationRunId: nonTerminal.id });
44
+ await siteStatus.set(siteId, "BLOCKED_PENDING_RECOVERY");
45
+ return { blocked: true };
46
+ }
47
+ //# sourceMappingURL=reconcile-interrupted-migration.js.map
@@ -0,0 +1,204 @@
1
+ import type { Clock } from "@jini-ai/core/primitives";
2
+ /**
3
+ * @file SPEC-019 C-301/C-302/C-303 — the Recovery restore ceremony (ADR-045 §3, CIC U-001/U-002/
4
+ * U-003).
5
+ *
6
+ * Purpose:
7
+ * `planRestore` / `confirmRestore` / `executeRestore` — three separate exports, never a combined
8
+ * single-call restore endpoint (AC-12, REQ-06). Each is a thin orchestration wrapper around the
9
+ * SPEC-016 `core/gated-mutations` gateway (injected here as `deps.gateway`, since that module's
10
+ * real binding is a composition-root concern outside this domain's own certified test suite) plus
11
+ * this domain's own binding constraints:
12
+ *
13
+ * - `planRestore` (CIC U-003): re-checks `costClass` FRESH at call time via `db-ops.getCapabilities()`
14
+ * — never a cached value — and refuses to reach the gateway at all once `costClass==='unavailable'`
15
+ * is freshly confirmed (U-003-ORD1, REQ-12).
16
+ * - `confirmRestore` (CIC U-002): rejects (mints no token) unless `disclosureAcknowledged===true`
17
+ * STRICTLY (not merely truthy) — the composite of "the client claims acknowledgment" AND "the
18
+ * `planId` resolves to a plan the server's own `planRestore` actually minted," the latter half
19
+ * delegated entirely to the injected gateway's own plan-provenance verification.
20
+ * - `executeRestore` (CIC U-001-ORD1): acquires the shared, cross-domain `core/operation-lock`
21
+ * BEFORE the gateway's own `execute()` runs — the same primitive `features/database`'s
22
+ * `executeMigrateForward` acquires, never an independent Recovery-local check (GOV-ADR-002) —
23
+ * and always releases it afterward, success or failure. Never itself clears `PENDING_MIGRATION`
24
+ * (REQ-18/EC-07 — restoring to an older snapshot does not resolve schema drift against the
25
+ * current runtime, ADR-045 §4). A successful `RESTORED` completion attaches a deep-link back to
26
+ * the Database Timeline (REQ-16/AC-26) — the incident thread's closing hop (ADR-041 §7).
27
+ *
28
+ * How it relates to the project:
29
+ * `deps.gateway` stands in for a composition root's binding over the real
30
+ * `core/gated-mutations.plan/confirm/execute` (SPEC-016) plus this domain's own hooks
31
+ * (`domain="backup.restore"`); this file owns none of that gateway's own fixed check-sequence
32
+ * (authorize -> token state -> actor-class -> plan-hash -> redeem), only this domain's binding
33
+ * constraints layered around it.
34
+ */
35
+ export type PrincipalKind = "user" | "agent" | "api_key";
36
+ export type Result<TValue, TError> = {
37
+ ok: true;
38
+ value: TValue;
39
+ } | {
40
+ ok: false;
41
+ error: TError;
42
+ };
43
+ export interface RecoveryErrorPayload {
44
+ code: string;
45
+ message?: string;
46
+ }
47
+ interface RestoreCapabilities {
48
+ costClass: "cheap" | "expensive" | "unavailable";
49
+ restorePointKind: string;
50
+ }
51
+ export interface PlanRestoreDbOpsPort {
52
+ getCapabilities(): Promise<RestoreCapabilities>;
53
+ }
54
+ export interface PlanRestoreGatewayPort {
55
+ plan(input: {
56
+ principalId: string;
57
+ principalKind: PrincipalKind;
58
+ restorePointId: string;
59
+ costClass: RestoreCapabilities["costClass"];
60
+ }): Promise<Result<unknown, RecoveryErrorPayload>>;
61
+ }
62
+ export interface PlanRestoreRequired {
63
+ deps: {
64
+ dbOps: PlanRestoreDbOpsPort;
65
+ gateway: PlanRestoreGatewayPort;
66
+ };
67
+ input: {
68
+ principalId: string;
69
+ principalKind: PrincipalKind;
70
+ restorePointId: string;
71
+ };
72
+ }
73
+ /**
74
+ * C-301/CIC U-003 — `plan()` step. Never reaches the gateway when a fresh `costClass` recheck
75
+ * reports `'unavailable'` (U-003-ORD1); `'expensive'` still reaches it (only `'unavailable'`
76
+ * short-circuits, per ADR-041 §2's "no attestation override" carried into this domain).
77
+ *
78
+ * @complexity O(1) plus one `getCapabilities()` call and, when not short-circuited, one
79
+ * `gateway.plan()` call.
80
+ */
81
+ export declare function planRestore(required: PlanRestoreRequired, _optional?: Record<string, never>): Promise<Result<unknown, RecoveryErrorPayload>>;
82
+ export interface ConfirmRestoreGatewayPort {
83
+ confirm(input: {
84
+ planId: string;
85
+ planHash: string;
86
+ }): Promise<Result<unknown, RecoveryErrorPayload>>;
87
+ }
88
+ export interface ConfirmRestoreRequired {
89
+ deps: {
90
+ gateway: ConfirmRestoreGatewayPort;
91
+ };
92
+ input: {
93
+ principalId: string;
94
+ principalKind: PrincipalKind;
95
+ planId: string;
96
+ planHash: string;
97
+ disclosureAcknowledged: boolean;
98
+ };
99
+ }
100
+ /**
101
+ * C-302/CIC U-002 — `confirm()` step. `disclosureAcknowledged` must be exactly `true` (a truthy
102
+ * non-boolean, e.g. the string `"true"`, is rejected — U-002-B1's exact wording) before the
103
+ * gateway is ever consulted; plan provenance (whether `planId` was actually minted by this
104
+ * server's own `planRestore`) is verified entirely by the injected gateway, never re-derived or
105
+ * short-circuit-trusted here (U-002-ORD1).
106
+ *
107
+ * @complexity O(1) plus, when the acknowledgment gate passes, one `gateway.confirm()` call.
108
+ */
109
+ export declare function confirmRestore(required: ConfirmRestoreRequired, _optional?: Record<string, never>): Promise<Result<unknown, RecoveryErrorPayload>>;
110
+ export interface ExecuteRestoreGatewayPort {
111
+ execute(input: {
112
+ confirmationToken: string;
113
+ confirmerPrincipalId?: string;
114
+ }): Promise<Result<{
115
+ restoreRunId: string;
116
+ state: string;
117
+ restartRequired?: boolean;
118
+ }, RecoveryErrorPayload>>;
119
+ }
120
+ interface OperationLockHandle {
121
+ siteId: string;
122
+ operationKind: string;
123
+ acquiredAt: string;
124
+ }
125
+ export interface ExecuteRestoreOperationLockPort {
126
+ acquireOperationLock(params: {
127
+ deps: {
128
+ clock: Clock;
129
+ };
130
+ input: {
131
+ siteId: string;
132
+ operationKind: "migration" | "restore";
133
+ };
134
+ }): Promise<{
135
+ ok: true;
136
+ value: OperationLockHandle;
137
+ } | {
138
+ ok: false;
139
+ error: {
140
+ code: string;
141
+ message?: string;
142
+ };
143
+ }>;
144
+ releaseOperationLock(params: {
145
+ deps: {
146
+ clock: Clock;
147
+ };
148
+ input: {
149
+ siteId: string;
150
+ handle: OperationLockHandle;
151
+ };
152
+ }): Promise<void>;
153
+ }
154
+ export interface ExecuteRestorePendingMigrationTrackerPort {
155
+ clearPendingMigration(): Promise<void>;
156
+ }
157
+ export interface ExecuteRestoreRequired {
158
+ deps: {
159
+ gateway: ExecuteRestoreGatewayPort;
160
+ operationLock: ExecuteRestoreOperationLockPort;
161
+ clock: Clock;
162
+ /** Never invoked by this function (REQ-18/EC-07) — accepted only so a caller cannot be
163
+ * tempted to wire an implicit clear-on-success elsewhere; kept in the seam to make the
164
+ * "never called" property directly testable. */
165
+ pendingMigrationTracker?: ExecuteRestorePendingMigrationTrackerPort;
166
+ };
167
+ input: {
168
+ principalId: string;
169
+ principalKind: PrincipalKind;
170
+ confirmationToken: string;
171
+ siteId: string;
172
+ /** Required only for `principalKind==='agent'` — the agent's current delegator, used as the
173
+ * confirmer identity the gateway's own actor-class rule compares against (SPEC-016 REQ-13). */
174
+ delegatedByPrincipalId?: string;
175
+ };
176
+ }
177
+ export interface ExecuteRestoreValue {
178
+ restoreRunId: string;
179
+ state: string;
180
+ /** Attached only on `state==='RESTORED'` (REQ-16/AC-26) — the deep-link back to the Database
181
+ * Timeline that closes the incident thread ADR-041 §7 describes. */
182
+ databaseTimelineDeepLink?: {
183
+ v: 1;
184
+ siteId: string;
185
+ intent: "view";
186
+ };
187
+ /** 2026-07-16: `true` when the physical content.db file was actually swapped (real SQLite
188
+ * composition) — the running process keeps serving the pre-restore data from its already-open
189
+ * file handle until an operator restarts it. `false`/absent for the hermetic in-memory
190
+ * composition, which has no real file to restore into. */
191
+ restartRequired?: boolean;
192
+ }
193
+ /**
194
+ * C-303/CIC U-001-ORD1 — `execute()` step. Acquires the shared cross-domain operation lock BEFORE
195
+ * the gateway's own `execute()` runs, and releases it in a `finally` regardless of outcome (never
196
+ * leaks a held lock). Never calls `pendingMigrationTracker.clearPendingMigration()` — a restore to
197
+ * an older snapshot does not, by itself, resolve schema drift against the current runtime
198
+ * (ADR-045 §4).
199
+ *
200
+ * @complexity O(1) plus one lock acquire/release pair and one `gateway.execute()` call.
201
+ */
202
+ export declare function executeRestore(required: ExecuteRestoreRequired, _optional?: Record<string, never>): Promise<Result<ExecuteRestoreValue, RecoveryErrorPayload>>;
203
+ export {};
204
+ //# sourceMappingURL=recovery-orchestrator.d.ts.map
@@ -0,0 +1,96 @@
1
+ /**
2
+ * C-301/CIC U-003 — `plan()` step. Never reaches the gateway when a fresh `costClass` recheck
3
+ * reports `'unavailable'` (U-003-ORD1); `'expensive'` still reaches it (only `'unavailable'`
4
+ * short-circuits, per ADR-041 §2's "no attestation override" carried into this domain).
5
+ *
6
+ * @complexity O(1) plus one `getCapabilities()` call and, when not short-circuited, one
7
+ * `gateway.plan()` call.
8
+ */
9
+ export async function planRestore(required, _optional = {}) {
10
+ const { deps, input } = required;
11
+ const capabilities = await deps.dbOps.getCapabilities();
12
+ if (capabilities.costClass === "unavailable") {
13
+ return {
14
+ ok: false,
15
+ error: {
16
+ code: "COST_CLASS_UNAVAILABLE",
17
+ message: `restore point '${input.restorePointId}' has no available restore mechanism for this site (no attestation override)`,
18
+ },
19
+ };
20
+ }
21
+ return deps.gateway.plan({
22
+ principalId: input.principalId,
23
+ principalKind: input.principalKind,
24
+ restorePointId: input.restorePointId,
25
+ costClass: capabilities.costClass,
26
+ });
27
+ }
28
+ /**
29
+ * C-302/CIC U-002 — `confirm()` step. `disclosureAcknowledged` must be exactly `true` (a truthy
30
+ * non-boolean, e.g. the string `"true"`, is rejected — U-002-B1's exact wording) before the
31
+ * gateway is ever consulted; plan provenance (whether `planId` was actually minted by this
32
+ * server's own `planRestore`) is verified entirely by the injected gateway, never re-derived or
33
+ * short-circuit-trusted here (U-002-ORD1).
34
+ *
35
+ * @complexity O(1) plus, when the acknowledgment gate passes, one `gateway.confirm()` call.
36
+ */
37
+ export async function confirmRestore(required, _optional = {}) {
38
+ const { deps, input } = required;
39
+ if (input.disclosureAcknowledged !== true) {
40
+ return {
41
+ ok: false,
42
+ error: {
43
+ code: "VALIDATION_ERROR",
44
+ message: "disclosureAcknowledged must be exactly true before a restore confirmation token may be minted",
45
+ },
46
+ };
47
+ }
48
+ return deps.gateway.confirm({ planId: input.planId, planHash: input.planHash });
49
+ }
50
+ /**
51
+ * C-303/CIC U-001-ORD1 — `execute()` step. Acquires the shared cross-domain operation lock BEFORE
52
+ * the gateway's own `execute()` runs, and releases it in a `finally` regardless of outcome (never
53
+ * leaks a held lock). Never calls `pendingMigrationTracker.clearPendingMigration()` — a restore to
54
+ * an older snapshot does not, by itself, resolve schema drift against the current runtime
55
+ * (ADR-045 §4).
56
+ *
57
+ * @complexity O(1) plus one lock acquire/release pair and one `gateway.execute()` call.
58
+ */
59
+ export async function executeRestore(required, _optional = {}) {
60
+ const { deps, input } = required;
61
+ const acquireResult = await deps.operationLock.acquireOperationLock({
62
+ deps: { clock: deps.clock },
63
+ input: { siteId: input.siteId, operationKind: "restore" },
64
+ });
65
+ if (!acquireResult.ok) {
66
+ return {
67
+ ok: false,
68
+ error: {
69
+ code: "RESTORE_OPERATION_IN_FLIGHT",
70
+ message: acquireResult.error.message ?? `an operation is already in flight for site '${input.siteId}'`,
71
+ },
72
+ };
73
+ }
74
+ try {
75
+ const confirmerPrincipalId = input.principalKind === "agent" ? input.delegatedByPrincipalId : input.principalId;
76
+ const executeResult = await deps.gateway.execute({
77
+ confirmationToken: input.confirmationToken,
78
+ ...(confirmerPrincipalId !== undefined ? { confirmerPrincipalId } : {}),
79
+ });
80
+ if (!executeResult.ok) {
81
+ return executeResult;
82
+ }
83
+ const value = { ...executeResult.value };
84
+ if (value.state === "RESTORED") {
85
+ value.databaseTimelineDeepLink = { v: 1, siteId: input.siteId, intent: "view" };
86
+ }
87
+ return { ok: true, value };
88
+ }
89
+ finally {
90
+ await deps.operationLock.releaseOperationLock({
91
+ deps: { clock: deps.clock },
92
+ input: { siteId: input.siteId, handle: acquireResult.value },
93
+ });
94
+ }
95
+ }
96
+ //# sourceMappingURL=recovery-orchestrator.js.map