@jini-ai/db 0.7.3-next.2 → 0.7.4

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 (101) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +66 -2
  3. package/dist/core/ports.d.ts +2 -2
  4. package/dist/core/ports.js +2 -2
  5. package/dist/data-modules/data-module.d.ts +2 -46
  6. package/dist/data-modules/plugin-identity.d.ts +2 -11
  7. package/dist/data-modules/snapshot.d.ts +5 -3
  8. package/dist/data-modules/snapshot.js +5 -3
  9. package/dist/events/change-set-repo.sql.d.ts +18 -5
  10. package/dist/events/change-set-repo.sql.js +25 -8
  11. package/dist/events/index.d.ts +1 -1
  12. package/dist/events/outbox-repo.sql.d.ts +26 -1
  13. package/dist/events/outbox-repo.sql.js +36 -2
  14. package/dist/events/repo.rows.d.ts +22 -4
  15. package/dist/events/repo.rows.js +32 -4
  16. package/dist/kernel/idle-turn.d.ts +62 -0
  17. package/dist/kernel/idle-turn.js +32 -0
  18. package/dist/kernel/index.d.ts +1 -0
  19. package/dist/kernel/index.js +1 -0
  20. package/dist/kernel/kernel-core.js +28 -0
  21. package/dist/kernel/schema-scope.js +2 -0
  22. package/dist/kernel/sqlite/driver.js +2 -0
  23. package/dist/kernel/sqlite/index.d.ts +1 -1
  24. package/dist/kernel/sqlite/index.js +1 -1
  25. package/dist/kernel/sqlite/ops.d.ts +61 -0
  26. package/dist/kernel/sqlite/ops.js +82 -0
  27. package/dist/kernel/turn-lock.d.ts +2 -0
  28. package/dist/kernel/turn-lock.js +7 -0
  29. package/dist/migrate/runner.d.ts +3 -3
  30. package/dist/migrate/runner.js +4 -1
  31. package/dist/owner-store/index.js +1 -1
  32. package/dist/pglite/copy-source.d.ts +45 -0
  33. package/dist/pglite/copy-source.js +36 -0
  34. package/dist/pglite/index.d.ts +1 -0
  35. package/dist/pglite/index.js +1 -0
  36. package/dist/react/recovery/Recovery.d.ts +205 -0
  37. package/dist/react/recovery/Recovery.js +141 -0
  38. package/dist/react/recovery/Recovery.restore-steps.d.ts +10 -0
  39. package/dist/react/recovery/Recovery.restore-steps.js +71 -0
  40. package/dist/recovery/agent-tools.d.ts +33 -0
  41. package/dist/recovery/agent-tools.js +166 -0
  42. package/dist/recovery/drift.d.ts +47 -0
  43. package/dist/recovery/drift.js +51 -0
  44. package/dist/recovery/journal-kernel.d.ts +80 -0
  45. package/dist/recovery/journal-kernel.js +40 -0
  46. package/dist/recovery/journal-repo.sql.d.ts +154 -0
  47. package/dist/recovery/journal-repo.sql.js +303 -0
  48. package/dist/recovery/journal-schema.d.ts +37 -0
  49. package/dist/recovery/journal-schema.js +110 -0
  50. package/dist/recovery/migrate-forward-hooks.d.ts +2 -1
  51. package/dist/recovery/migrate-forward-hooks.js +3 -3
  52. package/dist/recovery/operation-lock.d.ts +2 -17
  53. package/dist/recovery/reconcile-interrupted-migration.d.ts +2 -5
  54. package/dist/recovery/reconcile-interrupted-migration.js +0 -30
  55. package/dist/recovery/restore-hooks.d.ts +4 -0
  56. package/dist/recovery/restore-hooks.js +1 -1
  57. package/dist/recovery/tool-registrations.d.ts +175 -0
  58. package/dist/recovery/tool-registrations.js +295 -0
  59. package/dist/site/repo.memory.d.ts +149 -0
  60. package/dist/site/repo.memory.js +162 -0
  61. package/dist/site/tool-registrations.d.ts +130 -0
  62. package/dist/site/tool-registrations.js +184 -0
  63. package/dist/sqlite/backup-policy.d.ts +14 -0
  64. package/dist/sqlite/backup-policy.js +47 -3
  65. package/dist/sqlite/compaction-steps.d.ts +43 -0
  66. package/dist/sqlite/compaction-steps.js +74 -0
  67. package/dist/sqlite/compaction.d.ts +63 -0
  68. package/dist/sqlite/compaction.js +263 -0
  69. package/dist/sqlite/db-ops.js +10 -11
  70. package/dist/sqlite/index.d.ts +2 -1
  71. package/dist/sqlite/index.js +2 -1
  72. package/dist/sqlite/open.d.ts +2 -1
  73. package/dist/sqlite/open.js +14 -4
  74. package/dist/tools/index.d.ts +2 -0
  75. package/dist/tools/index.js +2 -0
  76. package/dist/tools/plan-store.d.ts +1 -1
  77. package/dist/tools/plan-store.js +10 -6
  78. package/dist/tools/read-tools.d.ts +1 -1
  79. package/dist/tools/site-db-messages.d.ts +10 -0
  80. package/dist/tools/site-db-messages.js +23 -0
  81. package/dist/tools/site-transfer-messages.d.ts +9 -0
  82. package/dist/tools/site-transfer-messages.js +20 -0
  83. package/dist/transfer/confirmation-ui.d.ts +19 -0
  84. package/dist/transfer/confirmation-ui.js +39 -0
  85. package/dist/transfer/copy-engine.js +11 -11
  86. package/dist/transfer/copy-order.js +1 -3
  87. package/dist/transfer/destination-store.d.ts +83 -0
  88. package/dist/transfer/destination-store.js +82 -0
  89. package/dist/transfer/index.d.ts +2 -0
  90. package/dist/transfer/index.js +2 -0
  91. package/dist/transfer/internal-ddl.d.ts +6 -2
  92. package/dist/transfer/internal-ddl.js +15 -15
  93. package/dist/transfer/postgres-ddl.js +2 -2
  94. package/dist/transfer/schema-catalog.d.ts +148 -0
  95. package/dist/transfer/schema-catalog.js +141 -0
  96. package/dist/transfer/sqlite-backup.d.ts +27 -0
  97. package/dist/transfer/sqlite-backup.js +31 -0
  98. package/dist/transfer/table-catalog.js +1 -0
  99. package/dist/watermark/kernel.d.ts +64 -0
  100. package/dist/watermark/kernel.js +45 -0
  101. package/package.json +107 -9
@@ -0,0 +1,175 @@
1
+ import { type AgentToolDefinition, type AgentToolSideEffect, type ToolExecutionContext, type ToolHandler, type ToolMetadataById, type ToolRegistration, type ToolContributor } from "@jini-ai/core";
2
+ import type { plan as gatewayPlan, confirm as gatewayConfirm, execute as gatewayExecute } from "@jini-ai/core/gated-mutations";
3
+ import type { buildRestoreHooks, BuildRestoreHooksInput, toRecoveryResult } from "./restore-hooks.js";
4
+ import type { AuthorizeFn } from "@jini-ai/core/contracts/events";
5
+ import type { Clock } from "@jini-ai/core/primitives";
6
+ import type { AssistantSurfaceDeps } from "@jini-ai/core/contracts/site/daemon-surface-exchanges";
7
+ import type { DbOpsPort } from "@jini-ai/core/contracts/site/gated-mutations-ports";
8
+ import type { SiteStatusPort } from "@jini-ai/core/contracts/site/recovery-reconcile-interrupted-migration";
9
+ import { type RestorePointListPort } from "../tools/restore-points.js";
10
+ import { type DeepLinkRestorePointLookupPort } from "./deep-link.js";
11
+ import { type DisclosureWatermarkSourcePort } from "./disclosure.js";
12
+ import { type PlanRestoreGatewayPort, type ConfirmRestoreGatewayPort, type ExecuteRestoreGatewayPort, type ExecuteRestoreOperationLockPort } from "./recovery-orchestrator.js";
13
+ export interface RecoveryToolDeps {
14
+ authorize: AuthorizeFn;
15
+ workspaceId: string;
16
+ clock: Clock;
17
+ dbOps: Pick<DbOpsPort, "getCapabilities">;
18
+ restorePointsRepo: RestorePointListPort;
19
+ siteStatusRepo: Pick<SiteStatusPort, "get">;
20
+ disclosureWatermarkSource: DisclosureWatermarkSourcePort;
21
+ deepLinkRestorePointLookup: DeepLinkRestorePointLookupPort;
22
+ }
23
+ type RestorePreparation = {
24
+ restorePointId: string;
25
+ plan: {
26
+ planId: string;
27
+ planHash: string;
28
+ };
29
+ createdAt: string | undefined;
30
+ };
31
+ export interface RecoveryToolHost<D extends RecoveryToolDeps> {
32
+ refuseUnexpectedKeys(required: {
33
+ input: Record<string, unknown>;
34
+ allowed: readonly string[];
35
+ }): void;
36
+ buildRestoreHooks(required: {
37
+ deps: D;
38
+ actorId: string;
39
+ restorePointId: string;
40
+ }): ReturnType<typeof buildRestoreHooks>;
41
+ catalog: readonly AgentToolDefinition[];
42
+ metadata: ToolMetadataById;
43
+ catalogModule: string;
44
+ readPermission: string;
45
+ restorePermission: string;
46
+ coveredCategories: readonly string[];
47
+ capabilityGuidance: {
48
+ fullSiteBackup: {
49
+ discoveryTool: string;
50
+ planTool: string;
51
+ pushTool: string;
52
+ guidance: string;
53
+ };
54
+ portableExport: {
55
+ href: string;
56
+ guidance: string;
57
+ };
58
+ };
59
+ authorize(required: {
60
+ deps: D;
61
+ ctx: ToolExecutionContext;
62
+ permission: string;
63
+ entityType: string;
64
+ }, optional?: Record<string, never>): Promise<void>;
65
+ plan(required: {
66
+ deps: D;
67
+ actorId: string;
68
+ restorePointId: string;
69
+ principalKind: Parameters<PlanRestoreGatewayPort["plan"]>[0]["principalKind"];
70
+ }, optional?: Record<string, never>): ReturnType<PlanRestoreGatewayPort["plan"]>;
71
+ confirm(required: {
72
+ deps: D;
73
+ actorId: string;
74
+ restorePointId: string;
75
+ confirmer: {
76
+ id: string;
77
+ kind: "user";
78
+ };
79
+ hooks: ReturnType<typeof buildRestoreHooks>;
80
+ planId: string;
81
+ planHash: string;
82
+ signal: AbortSignal;
83
+ }, optional?: Record<string, never>): ReturnType<ConfirmRestoreGatewayPort["confirm"]>;
84
+ execute(required: {
85
+ deps: D;
86
+ actorId: string;
87
+ restorePointId: string;
88
+ confirmationToken: string;
89
+ hooks: ReturnType<typeof buildRestoreHooks>;
90
+ signal: AbortSignal;
91
+ }, optional?: Record<string, never>): ReturnType<ExecuteRestoreGatewayPort["execute"]>;
92
+ operationLock: ExecuteRestoreOperationLockPort;
93
+ isOperationInFlight(required: {
94
+ siteId: string;
95
+ }, optional?: Record<string, never>): boolean;
96
+ describe(required: RestorePreparation): {
97
+ toolId: string;
98
+ errorCode: string;
99
+ title: string;
100
+ details: readonly {
101
+ label: string;
102
+ value: string;
103
+ }[];
104
+ warning: string;
105
+ danger: boolean;
106
+ confirmLabel: string;
107
+ };
108
+ confirmedRestore(required: {
109
+ surfaces: AssistantSurfaceDeps;
110
+ prepare: (required: {
111
+ ctx: ToolExecutionContext;
112
+ }) => Promise<RestorePreparation>;
113
+ describe: RecoveryToolHost<D>["describe"];
114
+ run: (required: {
115
+ ctx: ToolExecutionContext;
116
+ prepared: RestorePreparation;
117
+ confirmer: {
118
+ id: string;
119
+ kind: "user";
120
+ };
121
+ }) => Promise<unknown>;
122
+ }, optional?: Record<string, never>): ToolHandler;
123
+ }
124
+ /**
125
+ * This wiring layer's OWN risk classification, authored from what each handler below actually
126
+ * calls. See `DerivedRiskByToolId` in the kit for why it is independent of the catalog's own
127
+ * `sideEffects` declaration. Neither excluded tool appears here at all, which is itself the
128
+ * strongest of the guards: an unclassified id cannot be wired.
129
+ */
130
+ export declare const recoveryDerivedRisk: ReadonlyMap<string, AgentToolSideEffect>;
131
+ export declare function buildRecoveryRegistrations<D extends RecoveryToolDeps>({ deps: routeDeps, surfaces, host }: {
132
+ deps: D;
133
+ surfaces: AssistantSurfaceDeps;
134
+ host: RecoveryToolHost<D>;
135
+ }, _optional?: Record<string, never>): ToolRegistration[];
136
+ export declare function contributeRecoveryTools<D extends RecoveryToolDeps>({ host }: {
137
+ host: RecoveryToolHost<D>;
138
+ }, _optional?: Record<string, never>): ToolContributor<D, AssistantSurfaceDeps>;
139
+ /** The host owns its gateway (token vocabulary, TTL, storage): this binder only forwards the host's
140
+ * gateway deps to the host-injected gateway functions, so it is generic over their deps shape. */
141
+ type WithGatewayDeps<TFn, TDeps> = TFn extends (input: infer TInput, ...rest: infer TRest) => infer TOut ? (input: Omit<TInput, "deps"> & {
142
+ deps: TDeps;
143
+ }, ...rest: TRest) => TOut : never;
144
+ export declare function bindRecoveryTools<D extends RecoveryToolDeps & Pick<BuildRestoreHooksInput, "idGen" | "databaseLedgerRepo" | "migrationRunsRepo"> & {
145
+ siteStatusRepo: BuildRestoreHooksInput["siteStatus"];
146
+ dbOps: RecoveryToolDeps["dbOps"] & BuildRestoreHooksInput["dbOps"];
147
+ gatedMutations: {
148
+ gatewayDeps: unknown;
149
+ };
150
+ }>(required: Omit<RecoveryToolHost<D>, "plan" | "confirm" | "execute" | "describe" | "confirmedRestore" | "buildRestoreHooks"> & {
151
+ buildRestoreHooks(input: Omit<BuildRestoreHooksInput, "planHashOf" | "resolveActorClassIdentity">): ReturnType<typeof buildRestoreHooks>;
152
+ gatewayPlan: WithGatewayDeps<typeof gatewayPlan, D["gatedMutations"]["gatewayDeps"]>;
153
+ gatewayConfirm: WithGatewayDeps<typeof gatewayConfirm, D["gatedMutations"]["gatewayDeps"]>;
154
+ gatewayExecute(input: Omit<Parameters<typeof gatewayExecute>[0], "hooks" | "deps"> & {
155
+ deps: D["gatedMutations"]["gatewayDeps"];
156
+ hooks: ReturnType<typeof buildRestoreHooks>;
157
+ }): ReturnType<ReturnType<typeof buildRestoreHooks>["executeMutation"]>;
158
+ toRecoveryResult: typeof toRecoveryResult;
159
+ dialog: {
160
+ errorCode: string;
161
+ title: string;
162
+ restorePointLabel: string;
163
+ warning: string;
164
+ confirmLabel: string;
165
+ };
166
+ humanConfirmedToolHandler(surfaces: AssistantSurfaceDeps, spec: Omit<Parameters<RecoveryToolHost<D>["confirmedRestore"]>[0], "surfaces" | "describe"> & {
167
+ flag: string;
168
+ dialog: RecoveryToolHost<D>["describe"];
169
+ }): ToolHandler;
170
+ }, _optional?: Record<string, never>): {
171
+ buildRecoveryRegistrations: (deps: D, surfaces: AssistantSurfaceDeps) => ToolRegistration[];
172
+ contributeRecoveryTools: () => ToolContributor<D, AssistantSurfaceDeps>;
173
+ };
174
+ export {};
175
+ //# sourceMappingURL=tool-registrations.d.ts.map
@@ -0,0 +1,295 @@
1
+ import { AGENT_TOOL_PRINCIPAL_KIND, buildDomainRegistrations, indexCatalogById, isRecord, requireInputRecord, requireNoInput, requireString, ToolInputError } from "@jini-ai/core";
2
+ import { listRestorePoints } from "../tools/restore-points.js";
3
+ import { resolveDeepLinkContext } from "./deep-link.js";
4
+ import { computeDisclosure } from "./disclosure.js";
5
+ import { confirmRestore, executeRestore, planRestore } from "./recovery-orchestrator.js";
6
+ import { resolveDegradedBanner } from "./degraded-banners.js";
7
+ const RESTORE_POINT_ENTITY = "restore-point";
8
+ /**
9
+ * This wiring layer's OWN risk classification, authored from what each handler below actually
10
+ * calls. See `DerivedRiskByToolId` in the kit for why it is independent of the catalog's own
11
+ * `sideEffects` declaration. Neither excluded tool appears here at all, which is itself the
12
+ * strongest of the guards: an unclassified id cannot be wired.
13
+ */
14
+ export const recoveryDerivedRisk = new Map([
15
+ // -> listRestorePoints (@jini-ai/db/tools, the same repo Database's own list
16
+ // tool reads): one read.
17
+ ["backup_list_restore_points", "none"],
18
+ // -> dbOps.getCapabilities(): pure, side-effect-free per its own doc comment.
19
+ ["backup_get_capabilities", "none"],
20
+ // -> planRestore (recovery-orchestrator.ts) + gateway.ts's plan() + computeDisclosure(): three
21
+ // reads composed together, nothing persisted.
22
+ ["backup_plan_restore", "none"],
23
+ // -> dbOps.getCapabilities() + siteStatusRepo.get() + isOperationInFlight() (a lock PEEK, not an
24
+ // acquire) + resolveDegradedBanner() (pure): all reads.
25
+ ["recovery_get_status", "none"],
26
+ // -> resolveDeepLinkContext (deep-link.ts): one DeepLinkRestorePointLookupPort read; never
27
+ // mutates the input envelope (see that function's own doc comment).
28
+ ["recovery_resolve_deep_link", "none"],
29
+ // -> gateway confirm() (as the human, after their click) + execute() via buildRestoreHooks,
30
+ // inside executeRestore's operation lock: swaps the site's data for the restore point's.
31
+ ["backup_execute_restore", "mutates-durable-state"],
32
+ ]);
33
+ const RESTORE_TOOL_ID = "backup_execute_restore";
34
+ const UNWIRED_RECOVERY_TOOL_IDS = new Set([
35
+ // Pre-existing (SPEC-019) catalog entry, deliberately left unwired HERE: this id collides with
36
+ // `features/database/agent-tools.ts`'s own `backup_create_restore_point`, which
37
+ // `buildDatabaseRegistrations` already wires as the canonical tool (ADR-041 §6 names the
38
+ // Database/Storage domain as this permission's "named tool"). Recovery's OWN local
39
+ // `createRestorePoint` (`recovery/restore-points.ts`) never calls `DbOpsPort.captureRestorePoint()`
40
+ // — wiring it here too would silently mint a SECOND, artifact-less restore point under the same
41
+ // tool id, reintroducing the exact "artifactRef silently dropped" defect
42
+ // `database/restore-points.ts`'s own file header records as already fixed. One tool id, one
43
+ // handler, backed by the real snapshot path.
44
+ "backup_create_restore_point",
45
+ ]);
46
+ /** One field's "must be typeof number" check for {@link requireDeepLinkEnvelope} — same rejection
47
+ * style as the kit's own `requireNumber`, just scoped to a nested envelope field path. */
48
+ function requireEnvelopeNumber({ value, fieldPath }, _optional = {}) {
49
+ if (typeof value !== "number")
50
+ throw new ToolInputError({ message: `'${fieldPath}' (number) is required` });
51
+ return value;
52
+ }
53
+ /** One field's "must be typeof string" check for {@link requireDeepLinkEnvelope}. */
54
+ function requireEnvelopeString({ value, fieldPath }, _optional = {}) {
55
+ if (typeof value !== "string")
56
+ throw new ToolInputError({ message: `'${fieldPath}' (string) is required` });
57
+ return value;
58
+ }
59
+ /** One field's "must be a string, or explicitly null" check — `ledgerEventId`/`restorePointId`
60
+ * are the only two nullable fields on the envelope. */
61
+ function requireEnvelopeStringOrNull({ value, fieldPath }, _optional = {}) {
62
+ if (value !== null && typeof value !== "string")
63
+ throw new ToolInputError({ message: `'${fieldPath}' must be a string or null` });
64
+ return value;
65
+ }
66
+ /**
67
+ * Validates a raw `envelope` value against `recovery_resolve_deep_link`'s published schema and
68
+ * returns it narrowed to `DatabaseContextEnvelope`.
69
+ *
70
+ * Hand-written rather than delegating to `Jini packages/user-management/src/server/agent-tool-input.ts`'s generic schema
71
+ * interpreter, because this is the only nested-object tool input in the whole wiring layer and that
72
+ * interpreter is flat-only — it cannot express a nested `envelope` object at all.
73
+ *
74
+ * @throws {ToolInputError} Naming the first missing/mistyped field, matching the kit's
75
+ * `requireString`/`requireNumber` rejection style.
76
+ * @complexity O(1) — a fixed number of field checks.
77
+ * @overallScore 100
78
+ */
79
+ function requireDeepLinkEnvelope({ raw }, _optional = {}) {
80
+ const candidate = { value: raw };
81
+ if (!isRecord(candidate))
82
+ throw new ToolInputError({ message: "'envelope' (object) is required" });
83
+ const value = candidate.value;
84
+ return {
85
+ v: requireEnvelopeNumber({ value: value.v, fieldPath: "envelope.v" }),
86
+ correlationId: requireEnvelopeString({ value: value.correlationId, fieldPath: "envelope.correlationId" }),
87
+ siteId: requireEnvelopeString({ value: value.siteId, fieldPath: "envelope.siteId" }),
88
+ ledgerEventId: requireEnvelopeStringOrNull({ value: value.ledgerEventId, fieldPath: "envelope.ledgerEventId" }),
89
+ restorePointId: requireEnvelopeStringOrNull({ value: value.restorePointId, fieldPath: "envelope.restorePointId" }),
90
+ drift: requireEnvelopeString({ value: value.drift, fieldPath: "envelope.drift" }),
91
+ intent: requireEnvelopeString({ value: value.intent, fieldPath: "envelope.intent" }),
92
+ issuedAt: requireEnvelopeString({ value: value.issuedAt, fieldPath: "envelope.issuedAt" }),
93
+ };
94
+ }
95
+ function createRecoveryPlanner(routeDeps, host) {
96
+ // Plans a restore as the agent and folds in the discarded-write-window disclosure — shared by
97
+ // `backup_plan_restore` and the confirm dialog of `backup_execute_restore`.
98
+ const planRestoreWithDisclosure = async ({ actorId, restorePointId }, _optional = {}) => {
99
+ const result = await planRestore({
100
+ deps: {
101
+ dbOps: {
102
+ getCapabilities: async () => {
103
+ const capabilities = await routeDeps.dbOps.getCapabilities();
104
+ return { costClass: capabilities.restorePoint.costClass, restorePointKind: capabilities.restorePoint.kind };
105
+ },
106
+ },
107
+ gateway: {
108
+ plan: input => host.plan({ deps: routeDeps, actorId, restorePointId: input.restorePointId, principalKind: input.principalKind }),
109
+ },
110
+ },
111
+ input: { principalId: actorId, principalKind: AGENT_TOOL_PRINCIPAL_KIND, restorePointId },
112
+ });
113
+ if (!result.ok)
114
+ throw new Error(result.error.message ?? result.error.code);
115
+ const disclosure = await computeDisclosure({
116
+ deps: { watermarkSource: routeDeps.disclosureWatermarkSource, coveredCategories: host.coveredCategories },
117
+ input: { restorePointId },
118
+ });
119
+ return { plan: result.value, disclosure };
120
+ };
121
+ return { planRestoreWithDisclosure };
122
+ }
123
+ async function readRecoveryStatus(routeDeps, ctx, host) {
124
+ requireNoInput({ input: ctx.input });
125
+ await host.authorize({ deps: routeDeps, ctx, permission: host.readPermission, entityType: RESTORE_POINT_ENTITY });
126
+ const capabilities = await routeDeps.dbOps.getCapabilities();
127
+ const siteStatus = await routeDeps.siteStatusRepo.get(routeDeps.workspaceId);
128
+ const banner = resolveDegradedBanner({
129
+ capabilities: {
130
+ costClass: capabilities.restorePoint.costClass,
131
+ operationInFlight: host.isOperationInFlight({ siteId: routeDeps.workspaceId }, {}),
132
+ pendingMigration: siteStatus === "PENDING_MIGRATION",
133
+ migrationInterrupted: siteStatus === "BLOCKED_PENDING_RECOVERY",
134
+ // Matches `@jini-ai/cms/admin-http/routes/recovery/status`'s own honest stub — no per-category
135
+ // write-count tracker exists anywhere in this codebase yet (see `disclosure.ts`'s doc).
136
+ watermarkBaselineAvailable: false,
137
+ },
138
+ });
139
+ return { costClass: capabilities.restorePoint.costClass, banner };
140
+ }
141
+ async function resolveRecoveryDeepLink(routeDeps, ctx, host) {
142
+ const candidate = { value: ctx.input };
143
+ if (!isRecord(candidate))
144
+ throw new ToolInputError({ message: "'envelope' (object) is required" });
145
+ const envelope = requireDeepLinkEnvelope({ raw: candidate.value.envelope });
146
+ await host.authorize({ deps: routeDeps, ctx, permission: host.readPermission, entityType: RESTORE_POINT_ENTITY });
147
+ return resolveDeepLinkContext({
148
+ deps: { lookup: routeDeps.deepLinkRestorePointLookup },
149
+ input: { principalId: ctx.principal.id, principalKind: AGENT_TOOL_PRINCIPAL_KIND, envelope },
150
+ });
151
+ }
152
+ function createRecoveryRestoreRun(routeDeps, host) {
153
+ return async ({ ctx, prepared: { restorePointId, plan }, confirmer }) => {
154
+ const hooks = host.buildRestoreHooks({ deps: routeDeps, actorId: ctx.principal.id, restorePointId });
155
+ const confirmed = await confirmRestore({
156
+ deps: {
157
+ gateway: { confirm: params => host.confirm({ deps: routeDeps, actorId: ctx.principal.id, restorePointId, confirmer, hooks, planId: params.planId, planHash: params.planHash, signal: ctx.signal }) },
158
+ },
159
+ input: { principalId: confirmer.id, principalKind: confirmer.kind, planId: plan.planId, planHash: plan.planHash, disclosureAcknowledged: true },
160
+ });
161
+ if (!confirmed.ok)
162
+ throw new Error(confirmed.error.message ?? confirmed.error.code);
163
+ // `Result<unknown>` admits a value with no token; refuse before taking the operation lock.
164
+ const confirmedValue = { value: confirmed.value };
165
+ const confirmationToken = isRecord(confirmedValue) ? confirmedValue.value.confirmationToken : undefined;
166
+ if (typeof confirmationToken !== "string" || confirmationToken === "") {
167
+ throw new Error("RESTORE_CONFIRM_MALFORMED: the confirmation step returned no confirmation token, so nothing was restored.");
168
+ }
169
+ const executed = await executeRestore({
170
+ deps: {
171
+ gateway: {
172
+ execute: params => host.execute({ deps: routeDeps, actorId: ctx.principal.id, restorePointId, hooks, confirmationToken: params.confirmationToken, signal: ctx.signal }),
173
+ },
174
+ operationLock: host.operationLock,
175
+ clock: routeDeps.clock,
176
+ },
177
+ input: {
178
+ principalId: ctx.principal.id,
179
+ principalKind: "agent",
180
+ confirmationToken,
181
+ siteId: routeDeps.workspaceId,
182
+ delegatedByPrincipalId: confirmer.id,
183
+ },
184
+ });
185
+ if (!executed.ok)
186
+ throw new Error(executed.error.message ?? executed.error.code);
187
+ return { restored: true, ...executed.value };
188
+ };
189
+ }
190
+ // Plans as the agent, asks the human, then confirms as the human and executes as the agent
191
+ // inside the same operation lock the admin execute route uses. No restore point is taken
192
+ // first, so the dialog says the current data is replaced and it can't be undone. The human's
193
+ // confirm click is the disclosure acknowledgment (CIC U-002).
194
+ function createRecoveryRestoreHandler(routeDeps, surfaces, host, { planRestoreWithDisclosure }) {
195
+ return host.confirmedRestore({ surfaces,
196
+ prepare: async ({ ctx }) => {
197
+ const input = requireInputRecord({ input: ctx.input });
198
+ host.refuseUnexpectedKeys({ input: input, allowed: ["restorePointId"] });
199
+ const restorePointId = requireString({ input: input, key: "restorePointId" });
200
+ await host.authorize({ deps: routeDeps, ctx, permission: host.restorePermission, entityType: RESTORE_POINT_ENTITY });
201
+ const { plan } = await planRestoreWithDisclosure({ actorId: ctx.principal.id, restorePointId });
202
+ const { items } = await listRestorePoints({ repo: routeDeps.restorePointsRepo });
203
+ const createdAt = items.find((item) => item.id === restorePointId)?.createdAt;
204
+ return { restorePointId, plan: plan, createdAt };
205
+ },
206
+ describe: host.describe,
207
+ run: createRecoveryRestoreRun(routeDeps, host), });
208
+ }
209
+ function createRecoveryListHandler(routeDeps, host) {
210
+ return async (ctx) => {
211
+ requireNoInput({ input: ctx.input });
212
+ await host.authorize({ deps: routeDeps, ctx, permission: host.readPermission, entityType: RESTORE_POINT_ENTITY });
213
+ // Same repo/function Database's own `database_list_restore_points` reads — one persisted
214
+ // list, two gated views (ADR-045 §1, "Database and Recovery are sibling faces").
215
+ return listRestorePoints({ repo: routeDeps.restorePointsRepo });
216
+ };
217
+ }
218
+ function createRecoveryCapabilitiesHandler(routeDeps, host) {
219
+ return async (ctx) => {
220
+ requireNoInput({ input: ctx.input });
221
+ await host.authorize({ deps: routeDeps, ctx, permission: host.readPermission, entityType: RESTORE_POINT_ENTITY });
222
+ const capabilities = await routeDeps.dbOps.getCapabilities();
223
+ return { costClass: capabilities.restorePoint.costClass, kind: capabilities.restorePoint.kind,
224
+ ...host.capabilityGuidance,
225
+ };
226
+ };
227
+ }
228
+ export function buildRecoveryRegistrations({ deps: routeDeps, surfaces, host }, _optional = {}) {
229
+ const planner = createRecoveryPlanner(routeDeps, host);
230
+ const { planRestoreWithDisclosure } = planner;
231
+ const handlers = {
232
+ backup_list_restore_points: createRecoveryListHandler(routeDeps, host),
233
+ backup_get_capabilities: createRecoveryCapabilitiesHandler(routeDeps, host),
234
+ backup_plan_restore: async (ctx) => {
235
+ const restorePointId = requireString({ input: requireInputRecord({ input: ctx.input }), key: "restorePointId" });
236
+ // Defensive, explicit check ahead of `planRestore()`: that function's own cost-class
237
+ // short-circuit (COST_CLASS_UNAVAILABLE) returns BEFORE the gateway's internal authorize()
238
+ // ever runs — a pre-existing gap this wiring found in the real HTTP route too (it calls
239
+ // `planRestore` with no authorize() of its own either). This tool stays strictly more
240
+ // conservative than that route by never skipping the check, rather than reproducing the gap.
241
+ await host.authorize({ deps: routeDeps, ctx, permission: host.readPermission, entityType: RESTORE_POINT_ENTITY });
242
+ // An unknown id is a caller mistake, not a planning question — reject it here rather than
243
+ // letting it reach `planRestore()`/the gateway, which have no reason to name a nonexistent
244
+ // restore point in a way that points the caller back to the list tool.
245
+ const points = await routeDeps.restorePointsRepo.list();
246
+ if (!points.some((point) => point.id === restorePointId)) {
247
+ throw new ToolInputError({ message: `restore point '${restorePointId}' was not found — call backup_list_restore_points for valid ids` });
248
+ }
249
+ // Folds in the discarded-write-window disclosure, matching this tool's own catalog
250
+ // description ("including the discarded-write-window disclosure") — the human admin UI reads
251
+ // this from a separate `/recovery/disclosure` request; a tool call composes both in one turn.
252
+ return planRestoreWithDisclosure({ actorId: ctx.principal.id, restorePointId });
253
+ },
254
+ recovery_get_status: ctx => readRecoveryStatus(routeDeps, ctx, host),
255
+ recovery_resolve_deep_link: ctx => resolveRecoveryDeepLink(routeDeps, ctx, host),
256
+ [RESTORE_TOOL_ID]: createRecoveryRestoreHandler(routeDeps, surfaces, host, planner),
257
+ };
258
+ return buildDomainRegistrations({ metadata: host.metadata, domain: "recovery", catalogModule: host.catalogModule,
259
+ catalog: indexCatalogById({ catalog: host.catalog }), handlers, derivedRisk: recoveryDerivedRisk }, { unwiredToolIds: UNWIRED_RECOVERY_TOOL_IDS });
260
+ }
261
+ export function contributeRecoveryTools({ host }, _optional = {}) {
262
+ return { domain: "recovery", build: (deps, surfaces) => buildRecoveryRegistrations({ deps, surfaces, host }), risk: recoveryDerivedRisk };
263
+ }
264
+ export function bindRecoveryTools(required, _optional = {}) {
265
+ const host = { ...required,
266
+ buildRestoreHooks: ({ deps: routeDeps, actorId, restorePointId }) => required.buildRestoreHooks({
267
+ workspaceId: routeDeps.workspaceId, actorId,
268
+ // Assistant tool path (P10-H2): the restore ledger records the agent kind.
269
+ actor: { id: actorId, kind: "agent" }, restorePointId, clock: routeDeps.clock, idGen: routeDeps.idGen,
270
+ restorePointsRepo: routeDeps.restorePointsRepo, databaseLedgerRepo: routeDeps.databaseLedgerRepo,
271
+ dbOps: routeDeps.dbOps, migrationRunsRepo: routeDeps.migrationRunsRepo, siteStatus: routeDeps.siteStatusRepo,
272
+ }),
273
+ plan: ({ deps: routeDeps, actorId, restorePointId, principalKind }) => required.toRecoveryResult({ run: () => required.gatewayPlan({
274
+ deps: routeDeps.gatedMutations.gatewayDeps, principalId: actorId, principalKind,
275
+ hooks: host.buildRestoreHooks({ deps: routeDeps, actorId, restorePointId }),
276
+ }) }, {}),
277
+ confirm: ({ deps: routeDeps, confirmer, hooks, planId, planHash, signal }) => required.toRecoveryResult({ run: async () => {
278
+ const record = await required.gatewayConfirm({ deps: routeDeps.gatedMutations.gatewayDeps,
279
+ principalId: confirmer.id, principalKind: confirmer.kind, signal, hooks, planId, planHash });
280
+ return { confirmationToken: record.confirmationToken };
281
+ } }, {}),
282
+ execute: ({ deps: routeDeps, actorId, hooks, confirmationToken, signal }) => required.toRecoveryResult({ run: () => required.gatewayExecute({
283
+ deps: routeDeps.gatedMutations.gatewayDeps, principalId: actorId, principalKind: AGENT_TOOL_PRINCIPAL_KIND, hooks, confirmationToken, signal,
284
+ }) }, {}),
285
+ describe: ({ restorePointId, createdAt }) => ({
286
+ toolId: RESTORE_TOOL_ID, errorCode: required.dialog.errorCode, title: required.dialog.title,
287
+ details: [{ label: required.dialog.restorePointLabel, value: createdAt ? `${restorePointId} (${createdAt})` : restorePointId }],
288
+ warning: required.dialog.warning, danger: true, confirmLabel: required.dialog.confirmLabel,
289
+ }),
290
+ confirmedRestore: ({ surfaces, prepare, describe, run }) => required.humanConfirmedToolHandler(surfaces, { flag: "restored", prepare, dialog: describe, run }),
291
+ };
292
+ return { buildRecoveryRegistrations: (deps, surfaces) => buildRecoveryRegistrations({ deps, surfaces, host }),
293
+ contributeRecoveryTools: () => contributeRecoveryTools({ host }), };
294
+ }
295
+ //# sourceMappingURL=tool-registrations.js.map
@@ -0,0 +1,149 @@
1
+ import type { LedgerReadPort, LedgerRow } from "../tools/index.js";
2
+ import type { CreateRestorePointRepoPort } from "../recovery/restore-point-create.js";
3
+ import type { RestorePointListPort, RestorePointRecord } from "../tools/index.js";
4
+ import type { BootLedgerPort, MigrationRunsRepoPort, SiteServeStatus } from "../recovery/reconcile-interrupted-migration.js";
5
+ import type { SiteStatusPort } from "@jini-ai/core/contracts/site/recovery-reconcile-interrupted-migration";
6
+ import type { DbOpsPort } from "@jini-ai/core/contracts/site/gated-mutations-ports";
7
+ import type { DatabaseHealthSummary, DatabaseIntrospectionPort, PendingMigration, SchemaStateSummary } from "@jini-ai/core/contracts/site/database-introspection";
8
+ /**
9
+ * @file In-memory `LedgerReadPort` double (ADR-006 rule-of-two's "one being built now" partner
10
+ * to `db/sqlite/database-journal-repo.ts`'s `SqliteDatabaseLedgerRepo`). Backs
11
+ * a host's hermetic test/dev composition, mirroring every other feature's
12
+ * `repo.memory.ts`/`repo.sqlite.ts` split in this codebase.
13
+ */
14
+ export declare class InMemoryDatabaseLedgerRepo implements LedgerReadPort, BootLedgerPort {
15
+ private rows;
16
+ private readonly now;
17
+ /**
18
+ * @param optional.initial Rows present initially.
19
+ * @param optional.now Clock for synthesized rows (defaults to the system clock).
20
+ */
21
+ constructor(_required?: Record<string, never>, { initial, now }?: {
22
+ initial?: LedgerRow[];
23
+ now?: () => string;
24
+ });
25
+ append(row: LedgerRow): Promise<void>;
26
+ /** ADR-041/043/044/045 re-audit (2026-07-16, TM-adr041-043-044-045-audit-001, Finding 2 fix)
27
+ * — mirrors `SqliteDatabaseLedgerRepo.appendInterruptedRow`'s exact row shape.
28
+ *
29
+ * Round-5 re-audit (TM-adr041-043-044-045-audit-001, R5-F1 / Fable's
30
+ * R5-F1-INTERRUPTED-SECOND-BOOT-BRICK, both independently confirmed): idempotent on
31
+ * `migrationRunId` — a second boot with the same still-unresolved migration must re-detect and
32
+ * re-block without erroring, not treat the deterministic id as a fresh row. */
33
+ appendInterruptedRow(params: {
34
+ siteId: string;
35
+ migrationRunId: string;
36
+ }): Promise<void>;
37
+ query(filter: {
38
+ kind?: string;
39
+ fromDate?: string;
40
+ toDate?: string;
41
+ outcome?: string;
42
+ cursor?: string | null;
43
+ limit: number;
44
+ }): Promise<{
45
+ items: LedgerRow[];
46
+ nextCursor: string | null;
47
+ }>;
48
+ }
49
+ /**
50
+ * In-memory double for both `recovery/restore-points.ts`'s `CreateRestorePointRepoPort` (the
51
+ * idempotency-keyed persistence side) and `database/restore-points.ts`'s `RestorePointListPort`
52
+ * (the read side this dispatch adds) — the same dual-port shape
53
+ * `db/sqlite/database-journal-repo.ts`'s real `SqliteRestorePointsRepo` already implements.
54
+ * Backs a host's hermetic composition.
55
+ */
56
+ export declare class InMemoryRestorePointsRepo implements CreateRestorePointRepoPort, RestorePointListPort {
57
+ private readonly rows;
58
+ save(row: {
59
+ restorePointId: string;
60
+ idempotencyKey: string;
61
+ trigger: string;
62
+ createdAt: string;
63
+ createdBy: string;
64
+ costClass?: string;
65
+ kind?: string;
66
+ watermarkAtCapture?: number | null;
67
+ artifactRef?: string;
68
+ }): Promise<void>;
69
+ findByIdempotencyKey(key: string): Promise<{
70
+ restorePointId: string;
71
+ idempotencyKey: string;
72
+ } | null>;
73
+ list(): Promise<RestorePointRecord[]>;
74
+ }
75
+ /** In-memory `SiteStatusPort` double, defaulted to `"SERVING"` — no boot-time reconciliation
76
+ * caller is wired this pass (`reconcileInterruptedMigrationOnBoot`/`evaluateBootMigrationPolicy`
77
+ * are domain logic only, not yet invoked from a composition root's boot sequence; see this
78
+ * dispatch's handoff), so this status only ever changes if a future route/boot-hook calls
79
+ * `.set()`. Backs a host's hermetic composition and, until a real persisted site-status store exists,
80
+ * its live composition too. */
81
+ export declare class InMemorySiteStatusRepo implements SiteStatusPort {
82
+ private status;
83
+ get(_siteId: string): Promise<SiteServeStatus>;
84
+ set(_siteId: string, status: SiteServeStatus): Promise<void>;
85
+ }
86
+ /** In-memory `MigrationRunsRepoPort` double (Finding 2 fix, TM-adr041-043-044-045-audit-001) —
87
+ * a host's hermetic composition never runs a real migration, so `findNonTerminalForSite`
88
+ * always returns `null` by default; tests that DO need to simulate a crash-interrupted migration
89
+ * can override via `setNonTerminal`. */
90
+ export declare class InMemoryMigrationRunsRepo implements MigrationRunsRepoPort {
91
+ private nonTerminal;
92
+ setNonTerminal({ value }: {
93
+ value: {
94
+ id: string;
95
+ status: string;
96
+ } | null;
97
+ }): void;
98
+ findNonTerminalForSite(_siteId: string): Promise<{
99
+ id: string;
100
+ status: string;
101
+ } | null>;
102
+ /** Round-5 re-audit (2026-07-16, TM-adr041-043-044-045-audit-001, R5-F1/R5-F2 fix) — mirrors
103
+ * `SqliteMigrationRunsRepo.markResolved`: clears the tracked non-terminal run once resolved, so a
104
+ * subsequent boot's `findNonTerminalForSite` no longer re-detects it. */
105
+ markResolved(params: {
106
+ id: string;
107
+ }): Promise<void>;
108
+ }
109
+ /** In-memory `DbOpsPort` double (`@jini-ai/core/contracts/site/gated-mutations-ports`) — reports the same static
110
+ * `cheap`/`file-snapshot` capability `db/sqlite/db-ops.ts`'s real `SqliteDbOpsAdapter` reports
111
+ * for a SQLite-backed site (this codebase's only dialect today), and fabricates an in-process
112
+ * `artifactRef` instead of performing a real online backup, since a host's hermetic
113
+ * composition never touches a real content.db file. a host's real composition uses
114
+ * `SqliteDbOpsAdapter` instead. */
115
+ export declare class InMemoryDbOpsAdapter implements DbOpsPort {
116
+ private watermark;
117
+ getCapabilities(): Promise<{
118
+ restorePoint: {
119
+ costClass: "cheap" | "expensive" | "unavailable";
120
+ kind: "file-snapshot" | "logical-dump" | "external";
121
+ };
122
+ }>;
123
+ captureRestorePoint(required: {
124
+ scopeId: string;
125
+ }): Promise<{
126
+ artifactRef: string;
127
+ watermarkAtCapture: number;
128
+ }>;
129
+ /** No real content.db file exists in this hermetic composition — nothing to swap, no restart
130
+ * needed. a host's real composition uses `SqliteDbOpsAdapter.restoreFromArtifact`
131
+ * instead, which performs the actual atomic file swap. */
132
+ restoreFromArtifact(_required: {
133
+ artifactRef: string;
134
+ }): Promise<{
135
+ restartRequired: boolean;
136
+ }>;
137
+ }
138
+ /** In-memory `DatabaseIntrospectionPort` double (`adapter.sqlite.ts`) — a host's hermetic
139
+ * composition never opens a real `content.db`/`.site-meta.json` pair, so this reports a fixed,
140
+ * always-"in-sync" snapshot with zero pending migrations rather than touching a filesystem. Mirrors
141
+ * `InMemoryDbOpsAdapter`'s identical "plausible static double" precedent. */
142
+ export declare class InMemoryDatabaseIntrospectionAdapter implements DatabaseIntrospectionPort {
143
+ getHealth(): Promise<DatabaseHealthSummary>;
144
+ getSchemaState(): Promise<SchemaStateSummary>;
145
+ listPendingMigrations(): Promise<{
146
+ items: PendingMigration[];
147
+ }>;
148
+ }
149
+ //# sourceMappingURL=repo.memory.d.ts.map