@jini-ai/db 0.3.0 → 0.3.1

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 (57) 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/sqlite/open.d.ts +1 -1
  50. package/dist/sqlite/open.js +3 -3
  51. package/dist/sqlite/restore-types.d.ts +7 -3
  52. package/dist/tools/surface-port.d.ts +11 -35
  53. package/dist/tools/transfer-tools.js +36 -37
  54. package/dist/transfer/internal-ddl.d.ts +3 -0
  55. package/dist/transfer/internal-ddl.js +6 -2
  56. package/dist/transfer/types.d.ts +3 -9
  57. package/package.json +48 -6
@@ -0,0 +1,105 @@
1
+ import type { Clock as ClockPort, IdGenerator as IdGeneratorPort } from "@jini-ai/core/primitives";
2
+ import { type GatedMutationHooks } from "@jini-ai/core/gated-mutations";
3
+ import type { RecoveryHookPolicy } from "./hook-policy.js";
4
+ import type { MigrationRunsRepoPort, SiteStatusPort } from "./reconcile-interrupted-migration.js";
5
+ import type { LedgerAppendPort } from "./migrate-forward-hooks.js";
6
+ /**
7
+ * @file Recovery's `GatedMutationHooks` factory for the `restore` ceremony (SPEC-019 C-301/C-303),
8
+ * plus `toRecoveryResult` (the throwing-gateway-to-`Result` adapter `recovery-orchestrator.ts`'s
9
+ * ports declare) — the domain-specific quarter of what used to be
10
+ * `server/gated-mutations-composition.ts`, split out so Recovery no longer needs a back-edge into
11
+ * `server/` for its own hook builder. The generic pieces every ceremony shares (`buildGatewayDeps`,
12
+ * `planHashOf`, `resolveActorClassIdentity`, `buildConfirmOnlyHooks`) stayed in
13
+ * `core/gated-mutations/composition.ts`, which this file imports from — the correct direction (a
14
+ * domain depending on `core`), unlike the old direction (a domain depending on `server`).
15
+ *
16
+ * `LedgerAppendPort` is imported from `features/database/gated-hooks.ts` rather than duplicated —
17
+ * Recovery already imports several other Database-owned ports (`restore-points.ts`,
18
+ * `boot/reconcile-interrupted-migration.ts`), so this is the established "Recovery depends on
19
+ * Database, never the reverse" direction, not a new one.
20
+ */
21
+ export interface BuildRestoreHooksInput extends RecoveryHookPolicy {
22
+ workspaceId: string;
23
+ actorId: string;
24
+ restorePointId: string;
25
+ clock: ClockPort;
26
+ idGen: IdGeneratorPort;
27
+ restorePointsRepo: {
28
+ list(): Promise<Array<{
29
+ id: string;
30
+ createdAt: string;
31
+ artifactRef: string;
32
+ }>>;
33
+ };
34
+ databaseLedgerRepo: LedgerAppendPort;
35
+ /** SPEC-016 `DbOpsPort` — real (SQLite) composition performs the physical file swap;
36
+ * hermetic-test composition's in-memory double is a no-op (`restartRequired: false`). */
37
+ dbOps: {
38
+ restoreFromArtifact(required: {
39
+ artifactRef: string;
40
+ }): Promise<{
41
+ restartRequired: boolean;
42
+ }>;
43
+ };
44
+ /** Round-5 re-audit (2026-07-16, TM-adr041-043-044-045-audit-001, R5-F2 / Fable
45
+ * `R5-F2-BLOCK-HAS-NO-EXIT` fix): a successful restore must actually exit
46
+ * `BLOCKED_PENDING_RECOVERY` — before this fix, nothing did. */
47
+ migrationRunsRepo: Pick<MigrationRunsRepoPort, "findNonTerminalForSite" | "markResolved">;
48
+ siteStatus: SiteStatusPort;
49
+ }
50
+ export declare class RestorePointNotFoundError extends Error {
51
+ constructor(message: string);
52
+ }
53
+ /**
54
+ * SPEC-019 C-301/C-303 — the Recovery `restore` ceremony's `GatedMutationHooks`.
55
+ *
56
+ * `executeMutation()` is a deliberately, disclosedly SCOPED implementation: it validates the
57
+ * target restore point still exists and records a real `restore.executed` `database_ledger` row —
58
+ * the honest, auditable half of a restore. It does NOT physically overwrite the live `content.db`
59
+ * file. This codebase has no mechanism to hot-swap the shared, already-open `content.db`
60
+ * connection every other repo across `server/deps.ts` holds a reference to (doing so would either
61
+ * crash every other in-flight request against a closed handle, or silently leave every existing
62
+ * repo instance reading the stale pre-restore file) — inventing an unreviewed live-swap or
63
+ * process-restart mechanism here is exactly the kind of unrequested architecture this dispatch's
64
+ * own guardrails warn against, and ADR-041/ADR-045 do not pin a specific mechanism for it either.
65
+ * `[CIC_REQUESTED]` Unit=gated-mutations-composition Trigger=recovery restore execute
66
+ * Property=REQ-06/AC-XX "a confirmed restore actually replaces content.db's data"
67
+ * PlausibleWrong=silently faking a full hot restore, or crashing the process mid-request
68
+ * MissingConstraint=a defined live-swap-or-restart mechanism for the shared `content.db`
69
+ * connection Evidence=ADR-041 §2 (`content.db` restore = whole-file copy), ADR-045 §3, this file.
70
+ * The plan -> confirm -> execute ceremony itself (token flow, authorize, operation-lock,
71
+ * disclosure-acknowledgment gate) is fully real and this file's own test coverage exercises it
72
+ * end-to-end; only the final byte-for-byte file replacement is the disclosed gap.
73
+ *
74
+ * `scopeKind: "instance"` (internal audit, 2026-08-12): `dbOps.restoreFromArtifact` (`db/sqlite/
75
+ * db-ops.ts`) physically swaps the entire `content.db` file, and a `content.db` can hold more
76
+ * than one workspace row (`site-dir/resolve-workspace.ts`, ADR-007, SPEC-044's admin CRUD). A
77
+ * principal authorized only within one workspace has no standing to replace data belonging to
78
+ * every OTHER workspace that file also holds — the ordinary workspace-scoped `authorize()` this
79
+ * hook used before would either deny every principal (no real workspace ever matches a
80
+ * whole-instance operation) or let one workspace's admin approve a cross-tenant file swap. See
81
+ * `core/gated-mutations/gateway.ts`'s `GatedMutationHooks.scopeKind` and `core/gated-mutations/
82
+ * composition.ts`'s `buildOwnerOnlyInstanceAuthorize` for the evaluator this now routes through.
83
+ *
84
+ * @complexity O(n) in the number of restore points (one `list()` scan per `computePlan` and per
85
+ * `executeMutation` — low-volume, ADR-041 §2).
86
+ */
87
+ export declare function buildRestoreHooks(input: BuildRestoreHooksInput, _optional?: Record<string, never>): GatedMutationHooks<{
88
+ restorePointId: string;
89
+ }, {
90
+ restoreRunId: string;
91
+ state: string;
92
+ restartRequired: boolean;
93
+ }>;
94
+ export type { RecoveryErrorPayload } from "./recovery-orchestrator.js";
95
+ import type { RecoveryErrorPayload } from "./recovery-orchestrator.js";
96
+ export declare function toRecoveryResult<T>({ run }: {
97
+ run: () => Promise<T>;
98
+ }, _optional?: Record<string, never>): Promise<{
99
+ ok: true;
100
+ value: T;
101
+ } | {
102
+ ok: false;
103
+ error: RecoveryErrorPayload;
104
+ }>;
105
+ //# sourceMappingURL=restore-hooks.d.ts.map
@@ -0,0 +1,154 @@
1
+ import { nowIso as clockNowIso } from "@jini-ai/core/primitives";
2
+ import { ForbiddenError, PlanStaleError, } from "@jini-ai/core/gated-mutations";
3
+ import { TokenAlreadyRedeemedError, TokenExpiredError } from "@jini-ai/core/gated-mutations";
4
+ export class RestorePointNotFoundError extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = "RestorePointNotFoundError";
8
+ }
9
+ }
10
+ /**
11
+ * SPEC-019 C-301/C-303 — the Recovery `restore` ceremony's `GatedMutationHooks`.
12
+ *
13
+ * `executeMutation()` is a deliberately, disclosedly SCOPED implementation: it validates the
14
+ * target restore point still exists and records a real `restore.executed` `database_ledger` row —
15
+ * the honest, auditable half of a restore. It does NOT physically overwrite the live `content.db`
16
+ * file. This codebase has no mechanism to hot-swap the shared, already-open `content.db`
17
+ * connection every other repo across `server/deps.ts` holds a reference to (doing so would either
18
+ * crash every other in-flight request against a closed handle, or silently leave every existing
19
+ * repo instance reading the stale pre-restore file) — inventing an unreviewed live-swap or
20
+ * process-restart mechanism here is exactly the kind of unrequested architecture this dispatch's
21
+ * own guardrails warn against, and ADR-041/ADR-045 do not pin a specific mechanism for it either.
22
+ * `[CIC_REQUESTED]` Unit=gated-mutations-composition Trigger=recovery restore execute
23
+ * Property=REQ-06/AC-XX "a confirmed restore actually replaces content.db's data"
24
+ * PlausibleWrong=silently faking a full hot restore, or crashing the process mid-request
25
+ * MissingConstraint=a defined live-swap-or-restart mechanism for the shared `content.db`
26
+ * connection Evidence=ADR-041 §2 (`content.db` restore = whole-file copy), ADR-045 §3, this file.
27
+ * The plan -> confirm -> execute ceremony itself (token flow, authorize, operation-lock,
28
+ * disclosure-acknowledgment gate) is fully real and this file's own test coverage exercises it
29
+ * end-to-end; only the final byte-for-byte file replacement is the disclosed gap.
30
+ *
31
+ * `scopeKind: "instance"` (internal audit, 2026-08-12): `dbOps.restoreFromArtifact` (`db/sqlite/
32
+ * db-ops.ts`) physically swaps the entire `content.db` file, and a `content.db` can hold more
33
+ * than one workspace row (`site-dir/resolve-workspace.ts`, ADR-007, SPEC-044's admin CRUD). A
34
+ * principal authorized only within one workspace has no standing to replace data belonging to
35
+ * every OTHER workspace that file also holds — the ordinary workspace-scoped `authorize()` this
36
+ * hook used before would either deny every principal (no real workspace ever matches a
37
+ * whole-instance operation) or let one workspace's admin approve a cross-tenant file swap. See
38
+ * `core/gated-mutations/gateway.ts`'s `GatedMutationHooks.scopeKind` and `core/gated-mutations/
39
+ * composition.ts`'s `buildOwnerOnlyInstanceAuthorize` for the evaluator this now routes through.
40
+ *
41
+ * @complexity O(n) in the number of restore points (one `list()` scan per `computePlan` and per
42
+ * `executeMutation` — low-volume, ADR-041 §2).
43
+ */
44
+ export function buildRestoreHooks(input, _optional = {}) {
45
+ return {
46
+ domain: "backup.restore",
47
+ readPermission: "backup.read",
48
+ mutatePermission: "backup.restore",
49
+ scopeId: input.workspaceId,
50
+ scopeKind: "instance",
51
+ // The plan refuses an unknown restore point itself: without this, a wrong id passed plan AND
52
+ // confirm (minting a real token) and only failed at execute. The gateway re-runs this at
53
+ // execute's plan re-derivation too, so a point deleted after confirm is caught there.
54
+ computePlan: async () => {
55
+ await findRestorePoint(input);
56
+ const details = { restorePointId: input.restorePointId };
57
+ return { planHash: input.planHashOf({ details }, {}), details };
58
+ },
59
+ executeMutation: async () => {
60
+ // Re-checked here, not trusted from the plan: the point can be deleted between execute's
61
+ // plan re-derivation and this mutation (token redemption runs in between).
62
+ const target = await findRestorePoint(input);
63
+ // 2026-07-16: closes the "ledger-only" gap this file previously disclosed — swap the file
64
+ // FIRST, ledger-record second. If the process dies between the two, the file already
65
+ // reflects reality (a missing ledger entry is reconcilable later; a ledger entry claiming a
66
+ // restore that never physically happened would not be).
67
+ const { restartRequired } = await input.dbOps.restoreFromArtifact({ artifactRef: target.artifactRef });
68
+ const restoreRunId = input.idGen.newId();
69
+ const now = clockNowIso({ clock: input.clock });
70
+ await input.databaseLedgerRepo.append({
71
+ id: input.idGen.newId(),
72
+ kind: "restore.executed",
73
+ restorePointId: input.restorePointId,
74
+ outcome: "success",
75
+ detailJson: JSON.stringify({ restoreRunId, restartRequired }),
76
+ actorWorkspaceId: input.workspaceId,
77
+ actorId: input.actorId,
78
+ createdAt: now,
79
+ });
80
+ // Round-5 re-audit (TM-adr041-043-044-045-audit-001, R5-F2 fix): a successful restore is the
81
+ // ceremony ADR-041 §3's own text names as how an operator "resolves" a crash-interrupted
82
+ // migration -- so it must actually exit BLOCKED_PENDING_RECOVERY, not just record a ledger
83
+ // row. Terminalize whatever non-terminal migration_runs row exists for this site (if any --
84
+ // a restore can also be run for reasons unrelated to a crash-interrupted migration, in which
85
+ // case there is nothing to resolve) so the next boot's findNonTerminalForSite no longer
86
+ // re-detects it.
87
+ //
88
+ // Round-6 re-audit (TM-adr041-043-044-045-audit-001, codex `R6-F1-RESTART-REQUIRED-RESTORE-
89
+ // UNBLOCKS-STALE-DB`, verified directly against `db-ops.ts`'s own doc comment): the DURABLE
90
+ // resolution (markResolved) and the IN-PROCESS unblock (siteStatus.set) are NOT the same
91
+ // thing and must not be conflated. `SqliteDbOpsAdapter.restoreFromArtifact` always returns
92
+ // `restartRequired: true` for a real file-backed db -- the running process keeps its open
93
+ // file descriptor pointed at the now-unlinked OLD inode until it restarts, so clearing the
94
+ // gate in-process here would let normal traffic resume against stale pre-restore data, with
95
+ // writes accepted in that window silently lost on the eventual restart. Only clear the
96
+ // in-process block when the restore genuinely didn't require one (memory-mode dev, or a
97
+ // future adapter that can restore live) -- when a restart IS required, the durable
98
+ // terminalization above is what makes the NEXT boot resolve to SERVING; the running process
99
+ // stays blocked (correctly) until then.
100
+ const nonTerminal = await input.migrationRunsRepo.findNonTerminalForSite(input.workspaceId);
101
+ if (nonTerminal) {
102
+ await input.migrationRunsRepo.markResolved({ id: nonTerminal.id });
103
+ if (!restartRequired) {
104
+ await input.siteStatus.set(input.workspaceId, "SERVING");
105
+ }
106
+ }
107
+ return { restoreRunId, state: "RESTORED", restartRequired };
108
+ },
109
+ resolveActorClassIdentity: input.resolveActorClassIdentity,
110
+ };
111
+ }
112
+ /** Looks up the restore point `input.restorePointId` names, throwing `RestorePointNotFoundError`
113
+ * when it does not exist. @complexity O(n) in restore points (one `list()` scan). */
114
+ async function findRestorePoint(input) {
115
+ const points = await input.restorePointsRepo.list();
116
+ const target = points.find((p) => p.id === input.restorePointId);
117
+ if (!target) {
118
+ throw new RestorePointNotFoundError(`restore point '${input.restorePointId}' was not found`);
119
+ }
120
+ return target;
121
+ }
122
+ /**
123
+ * Adapts a throwing call against the real (throwing) `core/gated-mutations` gateway into the
124
+ * `Result<T, RecoveryErrorPayload>` shape `features/recovery/recovery-orchestrator.ts`'s
125
+ * `PlanRestoreGatewayPort`/`ConfirmRestoreGatewayPort`/`ExecuteRestoreGatewayPort` all declare —
126
+ * exactly the "Result-wrapped composition-root binding over the real throwing gateway" Session 4's
127
+ * progress-ledger entry named as still-owed future work. Maps each of `gateway.ts`'s typed thrown
128
+ * errors to a stable `code` string; every other error collapses to `INTERNAL_ERROR`.
129
+ */
130
+ /** Maps one caught error to its stable `code` string — split out of {@link toRecoveryResult}'s
131
+ * `catch` block as a whole unit, not just its branchiest arm, since every arm here pays the same
132
+ * nesting cost inside a `catch`. */
133
+ function classifyRecoveryError(err) {
134
+ if (err instanceof ForbiddenError)
135
+ return { code: err.reasonCode, message: err.message };
136
+ if (err instanceof PlanStaleError)
137
+ return { code: "PLAN_STALE", message: err.message };
138
+ if (err instanceof TokenExpiredError)
139
+ return { code: "TOKEN_EXPIRED", message: err.message };
140
+ if (err instanceof TokenAlreadyRedeemedError)
141
+ return { code: "TOKEN_ALREADY_REDEEMED", message: err.message };
142
+ if (err instanceof RestorePointNotFoundError)
143
+ return { code: "RESTORE_POINT_NOT_FOUND", message: err.message };
144
+ return { code: "INTERNAL_ERROR", message: err instanceof Error ? err.message : "internal error" };
145
+ }
146
+ export async function toRecoveryResult({ run }, _optional = {}) {
147
+ try {
148
+ return { ok: true, value: await run() };
149
+ }
150
+ catch (err) {
151
+ return { ok: false, error: classifyRecoveryError(err) };
152
+ }
153
+ }
154
+ //# sourceMappingURL=restore-hooks.js.map
@@ -0,0 +1,80 @@
1
+ import type { PrincipalKind, Result } from "./recovery-orchestrator.js";
2
+ /**
3
+ * @file SPEC-019 C-304 / REQ-05 — `createRestorePoint`, an ordinary `authorize()`-gated mutation
4
+ * (ADR-045 §3, "backup.create" independent of any migration).
5
+ *
6
+ * Purpose:
7
+ * Structurally distinct from the gated restore ceremony (`recovery-orchestrator.ts`): this never
8
+ * calls the gateway's `plan()`/`confirm()`/`execute()` at all (AC-10) — it mints a restore point
9
+ * directly once `authorize()` and the shared-lock "no operation in flight" check both pass.
10
+ * `authorize()` runs on EVERY call, before the idempotency short-circuit (AC-11, SPEC-016 REQ-14)
11
+ * — a repeated idempotency key never skips re-authorization, only re-creation.
12
+ *
13
+ * How it relates to the project:
14
+ * `operationInFlight` is supplied by the caller (typically derived from the same shared
15
+ * `core/operation-lock` state `recovery-orchestrator.ts`'s `executeRestore` consults) rather than
16
+ * this module acquiring the lock itself — REQ-13's "extends here too, via `onBeforeCreateOrExecute`"
17
+ * is a pre-check on an already-resolved flag, not this module owning lock lifecycle.
18
+ */
19
+ export interface CreateRestorePointRepoPort {
20
+ save(row: {
21
+ restorePointId: string;
22
+ idempotencyKey: string;
23
+ trigger: string;
24
+ createdAt: string;
25
+ createdBy: string;
26
+ }): Promise<void>;
27
+ findByIdempotencyKey(key: string): Promise<{
28
+ restorePointId: string;
29
+ idempotencyKey: string;
30
+ } | null>;
31
+ }
32
+ export interface CreateRestorePointClockPort {
33
+ nowIso(): string;
34
+ }
35
+ export interface CreateRestorePointIdPort {
36
+ newId(): string;
37
+ }
38
+ export type CreateRestorePointAuthorizeFn = (params: {
39
+ principalId: string;
40
+ permission: string;
41
+ }) => Promise<{
42
+ allowed: boolean;
43
+ reason: string;
44
+ }>;
45
+ export interface CreateRestorePointRequired {
46
+ deps: {
47
+ repo: CreateRestorePointRepoPort;
48
+ clock: CreateRestorePointClockPort;
49
+ ids: CreateRestorePointIdPort;
50
+ authorize: CreateRestorePointAuthorizeFn;
51
+ /** Present in the seam for shape-parity with the gated ceremony's deps; deliberately never
52
+ * called here (AC-10) — kept so a caller wiring a shared deps object cannot be tempted to
53
+ * route restore-point creation through it. */
54
+ gateway: {
55
+ plan: (...args: unknown[]) => Promise<unknown>;
56
+ };
57
+ };
58
+ input: {
59
+ principalId: string;
60
+ principalKind: PrincipalKind;
61
+ idempotencyKey: string;
62
+ trigger: "manual" | "pre-migration-auto" | "template-upgrade";
63
+ operationInFlight: boolean;
64
+ };
65
+ }
66
+ export interface CreateRestorePointValue {
67
+ restorePointId: string;
68
+ }
69
+ /**
70
+ * AC-10/AC-11/REQ-05/REQ-13 — authorize (always) -> in-flight refusal -> idempotency lookup ->
71
+ * write. Never invokes `deps.gateway` at all.
72
+ *
73
+ * @complexity O(1) plus one `authorize()` call, one idempotency lookup, and (on the first call for
74
+ * a given key) one `repo.save()` call.
75
+ */
76
+ export declare function createRestorePoint(required: CreateRestorePointRequired, _optional?: Record<string, never>): Promise<Result<CreateRestorePointValue, {
77
+ code: string;
78
+ message?: string;
79
+ }>>;
80
+ //# sourceMappingURL=restore-point-create.d.ts.map
@@ -0,0 +1,37 @@
1
+ /**
2
+ * AC-10/AC-11/REQ-05/REQ-13 — authorize (always) -> in-flight refusal -> idempotency lookup ->
3
+ * write. Never invokes `deps.gateway` at all.
4
+ *
5
+ * @complexity O(1) plus one `authorize()` call, one idempotency lookup, and (on the first call for
6
+ * a given key) one `repo.save()` call.
7
+ */
8
+ export async function createRestorePoint(required, _optional = {}) {
9
+ const { deps, input } = required;
10
+ const authResult = await deps.authorize({ principalId: input.principalId, permission: "backup.create" });
11
+ if (!authResult.allowed) {
12
+ return { ok: false, error: { code: "FORBIDDEN", message: authResult.reason } };
13
+ }
14
+ if (input.operationInFlight) {
15
+ return {
16
+ ok: false,
17
+ error: {
18
+ code: "RESTORE_OPERATION_IN_FLIGHT",
19
+ message: "a migration or restore is already in flight for this site",
20
+ },
21
+ };
22
+ }
23
+ const existing = await deps.repo.findByIdempotencyKey(input.idempotencyKey);
24
+ if (existing) {
25
+ return { ok: true, value: { restorePointId: existing.restorePointId } };
26
+ }
27
+ const restorePointId = deps.ids.newId();
28
+ await deps.repo.save({
29
+ restorePointId,
30
+ idempotencyKey: input.idempotencyKey,
31
+ trigger: input.trigger,
32
+ createdAt: deps.clock.nowIso(),
33
+ createdBy: input.principalId,
34
+ });
35
+ return { ok: true, value: { restorePointId } };
36
+ }
37
+ //# sourceMappingURL=restore-point-create.js.map
@@ -54,5 +54,5 @@ export declare const DEFAULT_PRAGMAS: readonly string[];
54
54
  * @throws Any error from the recovery hook, opener, or pragma application.
55
55
  * @complexity O(p) calls for p pragmas; storage costs belong to the injected driver.
56
56
  */
57
- export declare function openSqliteConnection<Connection extends SqliteClient>(options: OpenSqliteConnectionOptions<Connection>): Connection;
57
+ export declare function openSqliteConnection<Connection extends SqliteClient>(required: Pick<OpenSqliteConnectionOptions<Connection>, "filePath" | "open">, options?: Pick<OpenSqliteConnectionOptions<Connection>, "recover" | "pragmas">): Connection;
58
58
  //# sourceMappingURL=open.d.ts.map
@@ -32,9 +32,9 @@ export const DEFAULT_PRAGMAS = [
32
32
  * @throws Any error from the recovery hook, opener, or pragma application.
33
33
  * @complexity O(p) calls for p pragmas; storage costs belong to the injected driver.
34
34
  */
35
- export function openSqliteConnection(options) {
36
- options.recover?.(options.filePath);
37
- const connection = options.open(options.filePath, {});
35
+ export function openSqliteConnection(required, options = {}) {
36
+ options.recover?.({ filePath: required.filePath }, {});
37
+ const connection = required.open({ filePath: required.filePath }, {});
38
38
  for (const pragma of options.pragmas ?? DEFAULT_PRAGMAS) {
39
39
  connection.pragma(pragma);
40
40
  }
@@ -7,7 +7,7 @@
7
7
  * package boundary cleanly. See `open.ts`'s module doc for the measured failure that made this a
8
8
  * rule rather than a preference.
9
9
  */
10
- import type { SqliteClient, SqliteOpener } from './types.js';
10
+ import type { SqliteClient } from './types.js';
11
11
  /**
12
12
  * A caller-injected hook run against `filePath` BEFORE the connection is opened.
13
13
  *
@@ -17,10 +17,14 @@ import type { SqliteClient, SqliteOpener } from './types.js';
17
17
  * supplied it runs for every path, including `:memory:`. A host with file-only recovery must make
18
18
  * its hook a no-op for ephemeral connections and hermetic tests, where there is nothing to recover.
19
19
  */
20
- export type SqliteRecoveryHook = (filePath: string) => void;
20
+ export type SqliteRecoveryHook = (required: {
21
+ filePath: string;
22
+ }, options?: Record<string, never>) => void;
21
23
  export interface OpenSqliteConnectionOptions<Connection extends SqliteClient = SqliteClient> {
22
24
  /** The consumer opens with its own driver copy. */
23
- readonly open: SqliteOpener<Connection>;
25
+ readonly open: (required: {
26
+ filePath: string;
27
+ }, options: Record<string, never>) => Connection;
24
28
  /** Filesystem path, or `':memory:'` for an ephemeral connection. */
25
29
  readonly filePath: string;
26
30
  /**
@@ -1,42 +1,18 @@
1
+ import type { ApprovalAnswer, ToolExecutionContext, ToolExecutionOptions } from "@jini-ai/core";
1
2
  /** Structural surface protocol: transport, confirmation policy and builders belong to the consumer. */
2
- import type { SurfaceEmission, SurfaceEmitter } from "@jini-ai/core";
3
+ import type { SurfaceEmission, SurfaceExchangeConversation, SurfaceExchangeStore, SurfaceAskThenReport } from "@jini-ai/core";
4
+ export type { SurfaceExchangeConversation as SurfaceExchange, SurfaceMessage } from "@jini-ai/core";
3
5
  import type { DatabaseTransferPlan } from "./plan-store.js";
4
- export type SurfaceMessage = {
5
- status: "received";
6
- params: Record<string, unknown>;
7
- } | {
8
- status: "expired" | "abandoned";
9
- };
10
- export interface SurfaceExchange {
11
- readonly id: string;
12
- send(emission: SurfaceEmission): Promise<void>;
13
- receive(): Promise<SurfaceMessage>;
14
- close(): void;
15
- /** When the exchange stops waiting, in epoch ms, if the host tracks one. Read right before the
16
- * confirmation is built and handed to it, so the host's card can count down and close on time. */
17
- expiresAtMs?(): number;
18
- }
19
6
  export interface TransferSurfacePorts {
20
- open(binding: {
21
- toolId: string;
22
- principalId: string;
23
- }, emit: SurfaceEmitter): SurfaceExchange;
24
- /** Must close the exchange after receiving/classifying a decision, including errors. */
25
- resolveDecision(exchange: SurfaceExchange, emission: SurfaceEmission): Promise<{
26
- confirmed: true;
27
- } | {
28
- confirmed: false;
29
- reason: "declined" | "expired" | "abandoned";
30
- }>;
7
+ open(required: Parameters<SurfaceExchangeStore["open"]>[0], optional?: Record<string, never>): SurfaceExchangeConversation;
8
+ /** Host transport only. The core approval owner calls it once for a replacement plan;
9
+ * the host binds principal/tool/expiry and never accepts model input as consent. */
10
+ confirmApproval(required: {
11
+ ctx: ToolExecutionContext;
12
+ plan: DatabaseTransferPlan;
13
+ }, optional: ToolExecutionOptions): Promise<ApprovalAnswer>;
31
14
  /** Must close in finally; outcome-delivery failures cannot replace a settled result. */
32
- askThenReport<T>(exchange: SurfaceExchange, emission: SurfaceEmission, handle: (answer: SurfaceMessage) => Promise<{
33
- result: T;
34
- outcome?: SurfaceEmission;
35
- }>): Promise<T>;
36
- /** `optional.expiresAtMs` is the exchange's deadline when it reports one (see `SurfaceExchange.expiresAtMs`). */
37
- confirmation(plan: DatabaseTransferPlan, exchangeId: string, optional?: {
38
- readonly expiresAtMs?: number;
39
- }): SurfaceEmission;
15
+ askThenReport: SurfaceAskThenReport;
40
16
  destinationForm(exchangeId: string): SurfaceEmission;
41
17
  destinationOutcome(input: {
42
18
  exchangeId: string;
@@ -1,5 +1,5 @@
1
1
  import { readFile, unlink } from "node:fs/promises";
2
- import { ToolInputError } from "@jini-ai/core";
2
+ import { createApprovalHandler, ToolInputError } from "@jini-ai/core";
3
3
  import { countSourceRows, inspectTarget, runCopy, planTransfer, SourceSchemaMismatchError, IncompleteTransferPlanError, InvalidConnectionStringError, LEFT_OUT_REASON } from "../transfer/index.js";
4
4
  import { DOMAIN, PLAN_TOOL_ID, STATUS_TOOL_ID, RUN_PERMISSION, SNAPSHOT_SCOPE_ID, MIN_SERVER_VERSION_NUM, getDatabaseTransferAgentToolCatalog } from "./transfer-catalog.js";
5
5
  import { defaultDbMessages } from "../core/messages.js";
@@ -181,23 +181,6 @@ async function handlePlan(deps, ctx) {
181
181
  });
182
182
  return planResult(plan);
183
183
  }
184
- async function askToConfirm(ctx, surfaces, plan, emitSurface) {
185
- const exchange = surfaces.open({ toolId: DATABASE_TRANSFER_RUN_TOOL_ID, principalId: ctx.principal.id }, emitSurface);
186
- const emission = surfaces.confirmation(plan, exchange.id, exchange.expiresAtMs ? { expiresAtMs: exchange.expiresAtMs() } : {});
187
- const closeOnAbort = () => exchange.close();
188
- ctx.signal.addEventListener("abort", closeOnAbort, { once: true });
189
- try {
190
- const outcome = await surfaces.resolveDecision(exchange, emission);
191
- if (outcome.confirmed)
192
- return { confirmed: true };
193
- if (outcome.reason === "declined")
194
- return { confirmed: false, result: { copied: false, cancelled: true } };
195
- return { confirmed: false, result: { copied: false, cancelled: false, reason: outcome.reason } };
196
- }
197
- finally {
198
- ctx.signal.removeEventListener("abort", closeOnAbort);
199
- }
200
- }
201
184
  /** @complexity O(total rows), streamed. */
202
185
  async function copyPlanned(deps, plan) {
203
186
  const sources = snapshotSources(deps, plan.snapshot, plan.chatSnapshot);
@@ -238,23 +221,39 @@ const PLAN_TAKE_MESSAGES = {
238
221
  PLAN_NOT_FOUND: "no copy plan with that planId is waiting (a planId works once, for this principal, and a server restart drops plans). Call database_transfer_plan again.",
239
222
  PLAN_EXPIRED: "that copy plan expired (plans last 10 minutes). Call database_transfer_plan again.",
240
223
  };
224
+ /** The plan store retains actor/workspace binding and one-shot consumption. Core owns consent;
225
+ * the host supplies only transport, and permission is freshly evaluated after the human wait. */
241
226
  async function handleRun(deps, surfaces, ctx, optional = {}) {
242
- const planId = deps.ports.readers.string(deps.ports.readers.inputRecord(ctx.input), "planId");
243
- await deps.ports.requirePermission({ principalId: ctx.principal.id, permission: RUN_PERMISSION, entityType: DOMAIN });
244
- if (ctx.signal.aborted)
245
- return { copied: false, cancelled: false, reason: "abandoned" };
246
- const taken = deps.ports.plans.take({ planId, principalId: ctx.principal.id, workspaceId: deps.ports.workspaceId });
247
- if (!taken.ok)
248
- return { copied: false, cancelled: false, code: taken.code, message: PLAN_TAKE_MESSAGES[taken.code] };
249
- if (taken.plan.replaces !== null) {
250
- if (!optional.emitSurface) {
251
- throw new ToolInputError({ message: `${DATABASE_TRANSFER_RUN_TOOL_ID}: this execution context has no interactive confirmation channel (no emitSurface), so replacement cannot be confirmed here. Nothing was copied.` });
252
- }
253
- const decision = await askToConfirm(ctx, surfaces, taken.plan, optional.emitSurface);
254
- if (!decision.confirmed)
255
- return decision.result;
256
- }
257
- return copyPlanned(deps, taken.plan);
227
+ const handler = createApprovalHandler({
228
+ prepare: async ({ ctx: snapshot }) => {
229
+ const planId = deps.ports.readers.string(deps.ports.readers.inputRecord(snapshot.input), "planId");
230
+ await deps.ports.requirePermission({ principalId: snapshot.principal.id, permission: RUN_PERMISSION, entityType: DOMAIN });
231
+ const taken = deps.ports.plans.take({ planId, principalId: snapshot.principal.id, workspaceId: deps.ports.workspaceId });
232
+ if (!taken.ok)
233
+ return { refusal: { copied: false, cancelled: false, code: taken.code, message: PLAN_TAKE_MESSAGES[taken.code] } };
234
+ return { plan: taken.plan };
235
+ },
236
+ describe: ({ prepared }) => "refusal" in prepared
237
+ ? { ask: false, description: undefined }
238
+ : { ask: prepared.plan.replaces !== null, description: prepared.plan },
239
+ askHuman: ({ ctx: snapshot, description }, options) => {
240
+ if (!options.emitSurface)
241
+ throw new ToolInputError({ message: `${DATABASE_TRANSFER_RUN_TOOL_ID}: this execution context has no interactive confirmation channel (no emitSurface), so replacement cannot be confirmed here. Nothing was copied.` });
242
+ if (!description)
243
+ throw new ToolInputError({ message: "No transfer plan can be approved. Nothing was copied." });
244
+ return surfaces.confirmApproval({ ctx: snapshot, plan: description }, options);
245
+ },
246
+ notConfirmed: ({ reason }) => reason === "declined" ? { copied: false, cancelled: true } : { copied: false, cancelled: false, reason },
247
+ run: async ({ ctx: snapshot, prepared }) => {
248
+ if ("refusal" in prepared)
249
+ return prepared.refusal;
250
+ await deps.ports.requirePermission({ principalId: snapshot.principal.id, permission: RUN_PERMISSION, entityType: DOMAIN });
251
+ if (snapshot.signal.aborted)
252
+ return { copied: false, cancelled: false, reason: "abandoned" };
253
+ return copyPlanned(deps, prepared.plan);
254
+ },
255
+ });
256
+ return handler(ctx, optional);
258
257
  }
259
258
  function failedDestination(surfaces, exchangeId, code, message) {
260
259
  return { result: { saved: false, code, message }, outcome: surfaces.destinationOutcome({ exchangeId, state: "failure", message: `Not saved: ${message}.` }) };
@@ -298,11 +297,11 @@ async function handleSetDestination(deps, surfaces, ctx, optional = {}) {
298
297
  }
299
298
  if (ctx.signal.aborted)
300
299
  return { saved: false, reason: "abandoned" };
301
- const exchange = surfaces.open({ toolId: SET_DESTINATION_TOOL_ID, principalId: ctx.principal.id }, optional.emitSurface);
302
- const closeOnAbort = () => exchange.close();
300
+ const exchange = surfaces.open({ binding: { toolId: SET_DESTINATION_TOOL_ID, principalId: ctx.principal.id }, emit: optional.emitSurface });
301
+ const closeOnAbort = () => exchange.close({});
303
302
  ctx.signal.addEventListener("abort", closeOnAbort, { once: true });
304
303
  try {
305
- return await surfaces.askThenReport(exchange, surfaces.destinationForm(exchange.id), (answer) => handleDestinationAnswer(deps, surfaces, exchange.id, answer));
304
+ return await surfaces.askThenReport({ exchange, confirmationEmission: surfaces.destinationForm(exchange.id), handle: (answer) => handleDestinationAnswer(deps, surfaces, exchange.id, answer) });
306
305
  }
307
306
  finally {
308
307
  ctx.signal.removeEventListener("abort", closeOnAbort);
@@ -12,6 +12,9 @@ export declare function fitIdentifier(name: string): string;
12
12
  export declare function createTableSql(schema: string, table: TransferTable): string;
13
13
  /** Same rule as `manifest.ts`'s `reseedSequenceSql`, schema-qualified: empty -> next is 1, else max + 1. */
14
14
  export declare function reseedIdentitySql(schema: string, table: TransferTable, sqlTag?: string): string;
15
+ /** Writes declared indexes, retaining trusted host predicates and their uniqueness scope.
16
+ * @complexity O(index columns plus predicate bytes); emits SQL without executing it.
17
+ */
15
18
  export declare function indexSql(schema: string, table: TransferTable): string;
16
19
  /**
17
20
  * Every CHECK and foreign key, added NOT VALID and then validated; a failed validation is recorded
@@ -63,9 +63,12 @@ export function reseedIdentitySql(schema, table, sqlTag = "transfer") {
63
63
  })
64
64
  .join("");
65
65
  }
66
+ /** Writes declared indexes, retaining trusted host predicates and their uniqueness scope.
67
+ * @complexity O(index columns plus predicate bytes); emits SQL without executing it.
68
+ */
66
69
  export function indexSql(schema, table) {
67
70
  return table.indexes
68
- .map((index) => `CREATE ${index.unique ? "UNIQUE " : ""}INDEX ${quoteIdent(fitIdentifier(index.name))} ON ${qualified(schema, table.name)} (${index.columns.map(quoteIdent).join(", ")});\n`)
71
+ .map((index) => `CREATE ${index.unique ? "UNIQUE " : ""}INDEX ${quoteIdent(fitIdentifier(index.name))} ON ${qualified(schema, table.name)} (${index.columns.map(quoteIdent).join(", ")})${index.where === undefined ? "" : ` WHERE ${index.where}`};\n`)
69
72
  .join("");
70
73
  }
71
74
  const REFERENTIAL_ACTIONS = new Set(["NO ACTION", "RESTRICT", "CASCADE", "SET NULL", "SET DEFAULT"]);
@@ -84,7 +87,8 @@ function parentColumns(fk, byName) {
84
87
  const columns = fk.foreignColumns ?? parent.primaryKey;
85
88
  if (columns.length !== fk.columns.length)
86
89
  return null;
87
- const unique = sameColumns(columns, parent.primaryKey) || parent.indexes.some((index) => index.unique && sameColumns(index.columns, columns));
90
+ // A partial unique index covers only some rows; Postgres cannot use it as an FK target.
91
+ const unique = sameColumns(columns, parent.primaryKey) || parent.indexes.some((index) => index.unique && index.where === undefined && sameColumns(index.columns, columns));
88
92
  return unique ? columns : null;
89
93
  }
90
94
  function constraintsOf(schema, table, byName) {
@@ -11,6 +11,8 @@ export interface TransferIndex {
11
11
  readonly name: string;
12
12
  readonly columns: readonly string[];
13
13
  readonly unique: boolean;
14
+ /** Trusted, host-declared Postgres predicate SQL; never operator input or SQLite plugin SQL. */
15
+ readonly where?: string;
14
16
  }
15
17
  export interface TransferForeignKey {
16
18
  readonly name: string;
@@ -35,13 +37,5 @@ export interface TransferTable {
35
37
  readonly foreignKeys: readonly TransferForeignKey[];
36
38
  readonly checks: readonly TransferCheck[];
37
39
  }
38
- /** Host identifiers are required: changing a marker name would orphan earlier copies. */
39
- export interface TransferNaming {
40
- readonly defaultSchema: string;
41
- readonly markerTable: string;
42
- readonly unvalidatedTable: string;
43
- readonly schemaPrefix: string;
44
- /** Optional SQL dollar-quote tag for compatibility with existing script consumers. */
45
- readonly sqlTag?: string;
46
- }
40
+ export type { TransferNaming } from '../core/transfer-naming.js';
47
41
  //# sourceMappingURL=types.d.ts.map