@jini-ai/db 0.7.3-next.1 → 0.7.3-next.3

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 (89) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +46 -1
  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/turn-lock.d.ts +2 -0
  24. package/dist/kernel/turn-lock.js +7 -0
  25. package/dist/pglite/copy-source.d.ts +45 -0
  26. package/dist/pglite/copy-source.js +36 -0
  27. package/dist/pglite/index.d.ts +1 -0
  28. package/dist/pglite/index.js +1 -0
  29. package/dist/react/recovery/Recovery.d.ts +205 -0
  30. package/dist/react/recovery/Recovery.js +141 -0
  31. package/dist/react/recovery/Recovery.restore-steps.d.ts +10 -0
  32. package/dist/react/recovery/Recovery.restore-steps.js +71 -0
  33. package/dist/recovery/agent-tools.d.ts +33 -0
  34. package/dist/recovery/agent-tools.js +166 -0
  35. package/dist/recovery/drift.d.ts +47 -0
  36. package/dist/recovery/drift.js +51 -0
  37. package/dist/recovery/journal-kernel.d.ts +80 -0
  38. package/dist/recovery/journal-kernel.js +40 -0
  39. package/dist/recovery/journal-repo.sql.d.ts +154 -0
  40. package/dist/recovery/journal-repo.sql.js +303 -0
  41. package/dist/recovery/journal-schema.d.ts +37 -0
  42. package/dist/recovery/journal-schema.js +110 -0
  43. package/dist/recovery/migrate-forward-hooks.d.ts +2 -1
  44. package/dist/recovery/migrate-forward-hooks.js +3 -3
  45. package/dist/recovery/operation-lock.d.ts +2 -17
  46. package/dist/recovery/reconcile-interrupted-migration.d.ts +2 -5
  47. package/dist/recovery/reconcile-interrupted-migration.js +0 -30
  48. package/dist/recovery/restore-hooks.d.ts +4 -0
  49. package/dist/recovery/restore-hooks.js +1 -1
  50. package/dist/recovery/tool-registrations.d.ts +175 -0
  51. package/dist/recovery/tool-registrations.js +295 -0
  52. package/dist/site/repo.memory.d.ts +149 -0
  53. package/dist/site/repo.memory.js +162 -0
  54. package/dist/site/tool-registrations.d.ts +130 -0
  55. package/dist/site/tool-registrations.js +185 -0
  56. package/dist/sqlite/backup-policy.d.ts +14 -0
  57. package/dist/sqlite/backup-policy.js +47 -3
  58. package/dist/sqlite/compaction-steps.d.ts +43 -0
  59. package/dist/sqlite/compaction-steps.js +73 -0
  60. package/dist/sqlite/compaction.d.ts +63 -0
  61. package/dist/sqlite/compaction.js +263 -0
  62. package/dist/sqlite/index.d.ts +2 -1
  63. package/dist/sqlite/index.js +2 -1
  64. package/dist/tools/index.d.ts +2 -0
  65. package/dist/tools/index.js +2 -0
  66. package/dist/tools/plan-store.d.ts +1 -1
  67. package/dist/tools/plan-store.js +10 -6
  68. package/dist/tools/site-db-messages.d.ts +10 -0
  69. package/dist/tools/site-db-messages.js +23 -0
  70. package/dist/tools/site-transfer-messages.d.ts +9 -0
  71. package/dist/tools/site-transfer-messages.js +20 -0
  72. package/dist/transfer/confirmation-ui.d.ts +19 -0
  73. package/dist/transfer/confirmation-ui.js +39 -0
  74. package/dist/transfer/copy-engine.js +11 -11
  75. package/dist/transfer/destination-store.d.ts +69 -0
  76. package/dist/transfer/destination-store.js +75 -0
  77. package/dist/transfer/index.d.ts +2 -0
  78. package/dist/transfer/index.js +2 -0
  79. package/dist/transfer/internal-ddl.d.ts +6 -2
  80. package/dist/transfer/internal-ddl.js +15 -15
  81. package/dist/transfer/postgres-ddl.js +2 -2
  82. package/dist/transfer/schema-catalog.d.ts +148 -0
  83. package/dist/transfer/schema-catalog.js +141 -0
  84. package/dist/transfer/sqlite-backup.d.ts +27 -0
  85. package/dist/transfer/sqlite-backup.js +31 -0
  86. package/dist/transfer/table-catalog.js +1 -0
  87. package/dist/watermark/kernel.d.ts +64 -0
  88. package/dist/watermark/kernel.js +45 -0
  89. package/package.json +105 -10
@@ -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
@@ -0,0 +1,162 @@
1
+ /**
2
+ * @file In-memory `LedgerReadPort` double (ADR-006 rule-of-two's "one being built now" partner
3
+ * to `db/sqlite/database-journal-repo.ts`'s `SqliteDatabaseLedgerRepo`). Backs
4
+ * a host's hermetic test/dev composition, mirroring every other feature's
5
+ * `repo.memory.ts`/`repo.sqlite.ts` split in this codebase.
6
+ */
7
+ export class InMemoryDatabaseLedgerRepo {
8
+ rows = [];
9
+ now;
10
+ /**
11
+ * @param optional.initial Rows present initially.
12
+ * @param optional.now Clock for synthesized rows (defaults to the system clock).
13
+ */
14
+ constructor(_required = {}, { initial = [], now } = {}) {
15
+ this.rows = [...initial];
16
+ this.now = now ?? (() => new Date().toISOString());
17
+ }
18
+ async append(row) {
19
+ this.rows.push(row);
20
+ }
21
+ /** ADR-041/043/044/045 re-audit (2026-07-16, TM-adr041-043-044-045-audit-001, Finding 2 fix)
22
+ * — mirrors `SqliteDatabaseLedgerRepo.appendInterruptedRow`'s exact row shape.
23
+ *
24
+ * Round-5 re-audit (TM-adr041-043-044-045-audit-001, R5-F1 / Fable's
25
+ * R5-F1-INTERRUPTED-SECOND-BOOT-BRICK, both independently confirmed): idempotent on
26
+ * `migrationRunId` — a second boot with the same still-unresolved migration must re-detect and
27
+ * re-block without erroring, not treat the deterministic id as a fresh row. */
28
+ async appendInterruptedRow(params) {
29
+ const id = `interrupted-${params.migrationRunId}`;
30
+ if (this.rows.some((row) => row.id === id))
31
+ return;
32
+ await this.append({
33
+ id,
34
+ kind: "migration.interrupted",
35
+ createdAt: this.now(),
36
+ restorePointId: null,
37
+ outcome: "blocked_pending_recovery",
38
+ });
39
+ }
40
+ async query(filter) {
41
+ const filtered = this.rows
42
+ .filter((row) => !filter.kind || row.kind === filter.kind)
43
+ .filter((row) => !filter.outcome || row.outcome === filter.outcome)
44
+ .filter((row) => !filter.fromDate || row.createdAt >= filter.fromDate)
45
+ .filter((row) => !filter.toDate || row.createdAt <= filter.toDate)
46
+ .sort((a, b) => {
47
+ if (a.createdAt === b.createdAt)
48
+ return a.id < b.id ? 1 : -1;
49
+ return a.createdAt < b.createdAt ? 1 : -1;
50
+ });
51
+ const startIndex = filter.cursor ? filtered.findIndex((row) => row.id === filter.cursor) + 1 : 0;
52
+ const page = filtered.slice(startIndex, startIndex + filter.limit);
53
+ const nextCursor = startIndex + filter.limit < filtered.length ? page[page.length - 1]?.id ?? null : null;
54
+ return { items: page, nextCursor };
55
+ }
56
+ }
57
+ /**
58
+ * In-memory double for both `recovery/restore-points.ts`'s `CreateRestorePointRepoPort` (the
59
+ * idempotency-keyed persistence side) and `database/restore-points.ts`'s `RestorePointListPort`
60
+ * (the read side this dispatch adds) — the same dual-port shape
61
+ * `db/sqlite/database-journal-repo.ts`'s real `SqliteRestorePointsRepo` already implements.
62
+ * Backs a host's hermetic composition.
63
+ */
64
+ export class InMemoryRestorePointsRepo {
65
+ rows = [];
66
+ async save(row) {
67
+ this.rows.push(row);
68
+ }
69
+ async findByIdempotencyKey(key) {
70
+ const row = this.rows.find((r) => r.idempotencyKey === key);
71
+ return row ? { restorePointId: row.restorePointId, idempotencyKey: row.idempotencyKey } : null;
72
+ }
73
+ async list() {
74
+ return [...this.rows]
75
+ .sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))
76
+ .map((row) => ({
77
+ id: row.restorePointId,
78
+ trigger: row.trigger,
79
+ costClass: row.costClass ?? "cheap",
80
+ kind: row.kind ?? "file-snapshot",
81
+ watermarkAtCapture: row.watermarkAtCapture ?? null,
82
+ createdAt: row.createdAt,
83
+ // In-memory `restoreFromArtifact` is a no-op regardless of this value (no real file to
84
+ // restore into) — a fabricated in-process reference is enough to satisfy the type.
85
+ artifactRef: row.artifactRef ?? `memory://restore-point/${row.restorePointId}`,
86
+ }));
87
+ }
88
+ }
89
+ /** In-memory `SiteStatusPort` double, defaulted to `"SERVING"` — no boot-time reconciliation
90
+ * caller is wired this pass (`reconcileInterruptedMigrationOnBoot`/`evaluateBootMigrationPolicy`
91
+ * are domain logic only, not yet invoked from a composition root's boot sequence; see this
92
+ * dispatch's handoff), so this status only ever changes if a future route/boot-hook calls
93
+ * `.set()`. Backs a host's hermetic composition and, until a real persisted site-status store exists,
94
+ * its live composition too. */
95
+ export class InMemorySiteStatusRepo {
96
+ status = "SERVING";
97
+ async get(_siteId) {
98
+ return this.status;
99
+ }
100
+ async set(_siteId, status) {
101
+ this.status = status;
102
+ }
103
+ }
104
+ /** In-memory `MigrationRunsRepoPort` double (Finding 2 fix, TM-adr041-043-044-045-audit-001) —
105
+ * a host's hermetic composition never runs a real migration, so `findNonTerminalForSite`
106
+ * always returns `null` by default; tests that DO need to simulate a crash-interrupted migration
107
+ * can override via `setNonTerminal`. */
108
+ export class InMemoryMigrationRunsRepo {
109
+ nonTerminal = null;
110
+ setNonTerminal({ value }) {
111
+ this.nonTerminal = value;
112
+ }
113
+ async findNonTerminalForSite(_siteId) {
114
+ return this.nonTerminal;
115
+ }
116
+ /** Round-5 re-audit (2026-07-16, TM-adr041-043-044-045-audit-001, R5-F1/R5-F2 fix) — mirrors
117
+ * `SqliteMigrationRunsRepo.markResolved`: clears the tracked non-terminal run once resolved, so a
118
+ * subsequent boot's `findNonTerminalForSite` no longer re-detects it. */
119
+ async markResolved(params) {
120
+ if (this.nonTerminal?.id === params.id)
121
+ this.nonTerminal = null;
122
+ }
123
+ }
124
+ /** In-memory `DbOpsPort` double (`@jini-ai/core/contracts/site/gated-mutations-ports`) — reports the same static
125
+ * `cheap`/`file-snapshot` capability `db/sqlite/db-ops.ts`'s real `SqliteDbOpsAdapter` reports
126
+ * for a SQLite-backed site (this codebase's only dialect today), and fabricates an in-process
127
+ * `artifactRef` instead of performing a real online backup, since a host's hermetic
128
+ * composition never touches a real content.db file. a host's real composition uses
129
+ * `SqliteDbOpsAdapter` instead. */
130
+ export class InMemoryDbOpsAdapter {
131
+ watermark = 0;
132
+ async getCapabilities() {
133
+ return { restorePoint: { costClass: "cheap", kind: "file-snapshot" } };
134
+ }
135
+ async captureRestorePoint(required) {
136
+ this.watermark += 1;
137
+ return { artifactRef: `memory://restore-point/${required.scopeId}/${this.watermark}`, watermarkAtCapture: this.watermark };
138
+ }
139
+ /** No real content.db file exists in this hermetic composition — nothing to swap, no restart
140
+ * needed. a host's real composition uses `SqliteDbOpsAdapter.restoreFromArtifact`
141
+ * instead, which performs the actual atomic file swap. */
142
+ async restoreFromArtifact(_required) {
143
+ return { restartRequired: false };
144
+ }
145
+ }
146
+ /** In-memory `DatabaseIntrospectionPort` double (`adapter.sqlite.ts`) — a host's hermetic
147
+ * composition never opens a real `content.db`/`.site-meta.json` pair, so this reports a fixed,
148
+ * always-"in-sync" snapshot with zero pending migrations rather than touching a filesystem. Mirrors
149
+ * `InMemoryDbOpsAdapter`'s identical "plausible static double" precedent. */
150
+ export class InMemoryDatabaseIntrospectionAdapter {
151
+ async getHealth() {
152
+ return { canOpenDb: true, migrationsTableReadable: true, driftStatus: "in-sync" };
153
+ }
154
+ async getSchemaState() {
155
+ const snapshot = { version: 0, tag: "memory" };
156
+ return { status: "in-sync", siteMeta: snapshot, runtime: snapshot };
157
+ }
158
+ async listPendingMigrations() {
159
+ return { items: [] };
160
+ }
161
+ }
162
+ //# sourceMappingURL=repo.memory.js.map
@@ -0,0 +1,130 @@
1
+ import type { Clock } from "@jini-ai/core/primitives";
2
+ /**
3
+ * @file Database's half of ADR-049 Decision 4 (SPEC-017/ADR-041): maps the wireable subset of
4
+ * `agent-tools.ts`'s nine catalog entries onto the timeline/restore-point/introspection reads and
5
+ * the one clearly-reversible write, as `ToolRegistration`s.
6
+ *
7
+ * Risk framing: this domain is meaningfully higher-risk than Forms/Identity/content-types — a
8
+ * migrate-forward can rewrite schema and data across every other domain at once, sometimes
9
+ * irreversibly — so the surface is deliberately reads plus one write rather than full parity with
10
+ * the admin UI. One of the nine entries is still declared unwired, with its reason recorded on
11
+ * {@link UNWIRED_DATABASE_TOOL_IDS}. `database_execute_migrate_forward` asks the human
12
+ * in chat first and only runs on their click — see `contracts/core/human-confirm.ts`'s
13
+ * `humanConfirmedToolHandler`.
14
+ *
15
+ * Authorization shape: none of the underlying read functions (`getTimeline`, `listRestorePoints`,
16
+ * `createRestorePoint`, `DatabaseIntrospectionPort`'s three methods) call `authorize()` internally
17
+ * — the admin routes gate inline (or, for the introspection trio, there is no admin route to
18
+ * mirror yet, so this file's own inline check is the only gate) — so those handlers call the kit's
19
+ * `requireToolPermission` themselves. The one exception is `database_plan_migrate_forward`,
20
+ * documented at its own handler.
21
+ */
22
+ import type { createDatabaseReadTools, RestorePointListPort, RestorePointSavePort } from "@jini-ai/db/tools";
23
+ import { type AgentToolSideEffect, type ToolHandler, type ToolRegistration } from "@jini-ai/core";
24
+ import { type ToolPermissionAuthorizationPort, type ToolExecutionContext } from "@jini-ai/core";
25
+ import type { HumanConfirmSpec } from "@jini-ai/core/contracts/site/human-confirm";
26
+ import { type AuthorizeFn, type MutationActor } from "@jini-ai/core/contracts/events";
27
+ import type { confirm as gatewayConfirm, execute as gatewayExecute, plan as gatewayPlan, GatewayDeps } from "@jini-ai/core/gated-mutations";
28
+ import type { GatedMutationHooks } from "@jini-ai/core/gated-mutations";
29
+ import type { DbOpsPort } from "@jini-ai/core/contracts/site/gated-mutations-ports";
30
+ import type { AssistantSurfaceDeps } from "@jini-ai/core/contracts/site/daemon-surface-exchanges";
31
+ import type { ToolContributor } from "@jini-ai/core";
32
+ import type { buildMigrateForwardHooks, BuildMigrateForwardHooksInput } from "../recovery/migrate-forward-hooks.js";
33
+ import type { LedgerAppendPort } from "@jini-ai/db/recovery/migrate-forward-hooks";
34
+ import type { DbMessages } from "../tools/index.js";
35
+ import type { executeMigrateForward, OperationLockPort } from "../recovery/migrate-forward-execute.js";
36
+ import type { DatabaseIntrospectionPort } from "@jini-ai/core/contracts/site/database-introspection";
37
+ import type { LedgerReadPort } from "@jini-ai/db/tools";
38
+ /**
39
+ * The exact slice of the route-deps bag Database's tool handlers read. Declared structurally
40
+ * (rather than importing `server/routes/types`'s `RouteDeps`) so this module carries no back-edge
41
+ * into the composition root for the `RouteDeps` god type. This domain's `buildMigrateForwardHooks`/
42
+ * `LedgerAppendPort` now live in this module's own `gated-hooks.ts` (moved out of
43
+ * `server/gated-mutations-composition.ts`, closing the back-edge into `server/` that file's import
44
+ * previously required), so `server/routes/*` satisfies this interface structurally by passing its
45
+ * existing `RouteDeps` object; nothing there changes.
46
+ */
47
+ /** A core gateway call's input with the host's own deps type in place of core's. */
48
+ type HostDeps<T, G> = Omit<T, 'deps'> & {
49
+ deps: G;
50
+ };
51
+ /** `G` is the host's own gateway deps: Jini only hands them back to the host's gateway functions. */
52
+ export interface DatabaseToolDeps<G = GatewayDeps> {
53
+ createDatabaseReadTools: typeof createDatabaseReadTools;
54
+ executeMigrateForward: typeof executeMigrateForward;
55
+ authorize: AuthorizeFn;
56
+ workspaceId: string;
57
+ clock: Clock;
58
+ idGen: {
59
+ newId(): string;
60
+ };
61
+ databaseLedgerRepo: LedgerReadPort & LedgerAppendPort;
62
+ restorePointsRepo: RestorePointListPort & RestorePointSavePort;
63
+ databaseIntrospection: DatabaseIntrospectionPort;
64
+ dbOps: DbOpsPort;
65
+ gatedMutations: {
66
+ gatewayDeps: G;
67
+ };
68
+ catalog: readonly import('@jini-ai/core').AgentToolDefinition[];
69
+ messages: DbMessages;
70
+ surfaces: AssistantSurfaceDeps;
71
+ migrateForwardDialog: Omit<HumanConfirmSpec, 'toolId'>;
72
+ gatewayPlan: (required: HostDeps<Parameters<typeof gatewayPlan>[0], G>, optional?: Record<string, never>) => ReturnType<typeof gatewayPlan>;
73
+ gatewayConfirm: (required: HostDeps<Parameters<typeof gatewayConfirm>[0], G>, optional?: Record<string, never>) => ReturnType<typeof gatewayConfirm>;
74
+ gatewayExecute: <TResult>(required: HostDeps<Parameters<typeof gatewayExecute<TResult>>[0], G>, optional?: Record<string, never>) => ReturnType<typeof gatewayExecute<TResult>>;
75
+ buildMigrateForwardHooks(input: Omit<BuildMigrateForwardHooksInput, 'planHashOf' | 'resolveActorClassIdentity'>): ReturnType<typeof buildMigrateForwardHooks>;
76
+ operationLock: OperationLockPort;
77
+ mutationActor: DatabaseMutationActorBinding;
78
+ adaptLegacyAuthorize(input: {
79
+ authorize: AuthorizeFn;
80
+ }): ToolPermissionAuthorizationPort;
81
+ refuseUnexpectedKeys(input: Record<string, unknown>, allowed: readonly string[]): void;
82
+ humanConfirmedToolHandler(surfaces: AssistantSurfaceDeps, steps: {
83
+ flag: string;
84
+ prepare(input: {
85
+ ctx: ToolExecutionContext;
86
+ }): Promise<{
87
+ hooks: GatedMutationHooks<unknown, {
88
+ migrated: true;
89
+ }>;
90
+ plan: Awaited<ReturnType<typeof gatewayPlan>>;
91
+ costClass: 'cheap' | 'expensive' | 'unavailable';
92
+ }>;
93
+ dialog(): HumanConfirmSpec;
94
+ run(input: {
95
+ ctx: ToolExecutionContext;
96
+ prepared: Awaited<ReturnType<Parameters<DatabaseToolDeps<G>['humanConfirmedToolHandler']>[1]['prepare']>>;
97
+ confirmer: {
98
+ id: string;
99
+ kind: 'user';
100
+ };
101
+ }): Promise<unknown>;
102
+ }): ToolHandler;
103
+ }
104
+ type DatabaseMutationActorBinding = (required: {
105
+ readonly principalId: string;
106
+ }, optional?: Record<string, never>) => MutationActor;
107
+ /**
108
+ * Widened this dispatch (ADR-041 §3, closing `agent-tools.ts`'s own disclosed gap) with the three
109
+ * `DatabaseIntrospectionPort`-backed reads below — `database_get_health`, `database_get_schema_state`,
110
+ * `database_list_pending_migrations`. All three are pure passthroughs to `routeDeps.databaseIntrospection`
111
+ * (`features/database/adapter.sqlite.ts`); none of that port's methods call `authorize()`
112
+ * internally, so each handler runs the identical inline `requireToolPermission` check every other
113
+ * read handler in this file already runs.
114
+ */
115
+ /**
116
+ * This wiring layer's OWN risk classification, authored from what each handler below actually
117
+ * calls. See `DerivedRiskByToolId` in the kit for why it is independent of the catalog's own
118
+ * `sideEffects` declaration.
119
+ */
120
+ export declare const databaseDerivedRisk: ReadonlyMap<string, AgentToolSideEffect>;
121
+ export declare function buildDatabaseRegistrations<G = GatewayDeps>(routeDeps: DatabaseToolDeps<G>, _optional?: {}): ToolRegistration[];
122
+ /**
123
+ * Contributes Database's AI tools; called once by the composition root's
124
+ * `installFirstPartyToolContributors()`, never as an import side effect.
125
+ * Database drift logic belongs to the low-level database module, which must not value-import
126
+ * this feature: that would close a runtime cycle through assistant tool discovery.
127
+ */
128
+ export declare function contributeDatabaseTools(): ToolContributor<DatabaseToolDeps, AssistantSurfaceDeps>;
129
+ export {};
130
+ //# sourceMappingURL=tool-registrations.d.ts.map
@@ -0,0 +1,185 @@
1
+ import { toolMetadata } from '@jini-ai/core/tool-metadata/database';
2
+ import { AGENT_TOOL_PRINCIPAL_KIND, buildDomainRegistrations, indexCatalogById, isRecord, optionalBoolean, optionalNumber, optionalString, requireInputRecord, requireString, requireNoInput } from "@jini-ai/core";
3
+ import { requireToolPermission } from "@jini-ai/core";
4
+ import {} from "@jini-ai/core/contracts/events";
5
+ // `ToolInputError` specifically — the marker `@jini-ai/daemon`'s `ToolExecutor` reads to tag a
6
+ // rejection `errorKind: 'validation'` rather than the redacted-500 `'internal'` bucket a bare
7
+ // `Error` gets. Same reasoning as `features/post/tool-registrations.ts`'s identical import.
8
+ import { ToolInputError } from "@jini-ai/core";
9
+ /**
10
+ * Widened this dispatch (ADR-041 §3, closing `agent-tools.ts`'s own disclosed gap) with the three
11
+ * `DatabaseIntrospectionPort`-backed reads below — `database_get_health`, `database_get_schema_state`,
12
+ * `database_list_pending_migrations`. All three are pure passthroughs to `routeDeps.databaseIntrospection`
13
+ * (`features/database/adapter.sqlite.ts`); none of that port's methods call `authorize()`
14
+ * internally, so each handler runs the identical inline `requireToolPermission` check every other
15
+ * read handler in this file already runs.
16
+ */
17
+ /**
18
+ * This wiring layer's OWN risk classification, authored from what each handler below actually
19
+ * calls. See `DerivedRiskByToolId` in the kit for why it is independent of the catalog's own
20
+ * `sideEffects` declaration.
21
+ */
22
+ export const databaseDerivedRisk = new Map([
23
+ // -> getTimeline (timeline.ts): one LedgerReadPort.query() read.
24
+ ["database_query_timeline", "none"],
25
+ // -> listRestorePoints (restore-points.ts): one RestorePointListPort.list() read.
26
+ ["database_list_restore_points", "none"],
27
+ // -> gateway.ts's plan() via buildMigrateForwardHooks: authorizes, then recomputes a plan and
28
+ // returns it — verified directly against plan()'s own body, which persists nothing.
29
+ ["database_plan_migrate_forward", "none"],
30
+ // -> createRestorePoint (restore-points.ts) + dbOps.captureRestorePoint() +
31
+ // restorePointsRepo.save(): a real file snapshot plus a persisted row. The canonical wiring for
32
+ // this tool id — see `features/recovery/tool-registrations.ts` for why Recovery's own catalog
33
+ // entry of the same name is deliberately left unwired instead of double-registered.
34
+ ["backup_create_restore_point", "mutates-durable-state"],
35
+ // -> routeDeps.databaseIntrospection.getHealth() (adapter.sqlite.ts): read-only queries against
36
+ // an already-open connection plus one `.site-meta.json` file read. No write of any kind.
37
+ ["database_get_health", "none"],
38
+ // -> routeDeps.databaseIntrospection.getSchemaState(): same read-only shape as getHealth() above.
39
+ ["database_get_schema_state", "none"],
40
+ // -> routeDeps.databaseIntrospection.listPendingMigrations(): one bundled-journal file read plus
41
+ // one bounded `__drizzle_migrations` query. No write of any kind.
42
+ ["database_list_pending_migrations", "none"],
43
+ // -> gateway confirm() (as the human, after their click) + execute() via buildMigrateForwardHooks,
44
+ // inside executeMigrateForward's operation lock: dbOps.captureRestorePoint() +
45
+ // restorePointsRepo.save() + databaseLedgerRepo.append().
46
+ ["database_execute_migrate_forward", "mutates-durable-state"],
47
+ ]);
48
+ const MIGRATE_TOOL_ID = "database_execute_migrate_forward";
49
+ /** Database catalog entries this pass does not wire, and why — see `features/database/agent-tools.ts`'s own per-entry comments for the full reasoning. */
50
+ const UNWIRED_DATABASE_TOOL_IDS = new Set([
51
+ // No envelope-minting function exists (only the receiving side, `resolveDeepLinkContext`, does),
52
+ // and minting one honestly needs a schema-drift computation this pass has no adapter for.
53
+ "database_get_restore_guidance",
54
+ ]);
55
+ async function planDatabaseMigrateForward(routeDeps, ctx, mutationActor) {
56
+ const { buildMigrateForwardHooks, gatewayPlan } = routeDeps;
57
+ requireNoInput({ input: ctx.input });
58
+ // No explicit pre-check here: `gateway.ts`'s plan() calls authorize() unconditionally,
59
+ // BEFORE hooks.computePlan() ever runs — verified directly against its body (see
60
+ // `databaseDerivedRisk`'s comment for this tool). Adding a second check here would be the
61
+ // duplicate evaluator ADR-021 §2 forbids.
62
+ const hooks = buildMigrateForwardHooks({
63
+ workspaceId: routeDeps.workspaceId,
64
+ actor: mutationActor({ principalId: ctx.principal.id }),
65
+ clock: routeDeps.clock,
66
+ idGen: routeDeps.idGen,
67
+ dbOps: routeDeps.dbOps,
68
+ restorePointsRepo: routeDeps.restorePointsRepo,
69
+ databaseLedgerRepo: routeDeps.databaseLedgerRepo,
70
+ });
71
+ return gatewayPlan({
72
+ deps: routeDeps.gatedMutations.gatewayDeps,
73
+ principalId: ctx.principal.id,
74
+ principalKind: AGENT_TOOL_PRINCIPAL_KIND,
75
+ hooks: hooks,
76
+ });
77
+ }
78
+ function createMigrateHooks(routeDeps, mutationActor) {
79
+ const { buildMigrateForwardHooks } = routeDeps;
80
+ return ({ actorId }, _options = {}) => buildMigrateForwardHooks({
81
+ workspaceId: routeDeps.workspaceId,
82
+ actor: mutationActor({ principalId: actorId }),
83
+ clock: routeDeps.clock,
84
+ idGen: routeDeps.idGen,
85
+ dbOps: routeDeps.dbOps,
86
+ restorePointsRepo: routeDeps.restorePointsRepo,
87
+ databaseLedgerRepo: routeDeps.databaseLedgerRepo,
88
+ });
89
+ }
90
+ function createMigrateForwardHandler(routeDeps, surfaces, mutationActor) {
91
+ const migrateHooks = createMigrateHooks(routeDeps, mutationActor);
92
+ const { humanConfirmedToolHandler, refuseUnexpectedKeys, adaptLegacyAuthorize, gatewayPlan, gatewayConfirm, gatewayExecute } = routeDeps;
93
+ return humanConfirmedToolHandler(surfaces, {
94
+ flag: "migrated",
95
+ prepare: async ({ ctx }) => {
96
+ refuseUnexpectedKeys(ctx.input === undefined ? {} : requireInputRecord({ input: ctx.input }), []);
97
+ await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id, permission: "database.migrate" }, { entityType: "database" });
98
+ const hooks = migrateHooks({ actorId: ctx.principal.id });
99
+ const plan = await gatewayPlan({
100
+ deps: routeDeps.gatedMutations.gatewayDeps,
101
+ principalId: ctx.principal.id,
102
+ principalKind: AGENT_TOOL_PRINCIPAL_KIND,
103
+ hooks: hooks,
104
+ });
105
+ const costClass = plan.details.costClass;
106
+ if (costClass === "unavailable") {
107
+ throw new ToolInputError({ message: "DATABASE_RESTORE_POINT_UNAVAILABLE: this site can't take a restore point, so the database update is refused. Nothing was changed." });
108
+ }
109
+ return { hooks, plan, costClass };
110
+ },
111
+ dialog: () => ({ ...routeDeps.migrateForwardDialog, toolId: MIGRATE_TOOL_ID }),
112
+ run: async ({ ctx, prepared: { hooks, plan, costClass }, confirmer }) => {
113
+ const record = await gatewayConfirm({
114
+ deps: routeDeps.gatedMutations.gatewayDeps,
115
+ signal: ctx.signal,
116
+ principalId: confirmer.id,
117
+ principalKind: confirmer.kind,
118
+ hooks: hooks,
119
+ planId: plan.planId,
120
+ planHash: plan.planHash,
121
+ });
122
+ return routeDeps.executeMigrateForward({
123
+ siteId: routeDeps.workspaceId,
124
+ confirmationToken: record.confirmationToken,
125
+ costClass,
126
+ operationLock: routeDeps.operationLock,
127
+ gatewayExecute: () => gatewayExecute({
128
+ deps: routeDeps.gatedMutations.gatewayDeps,
129
+ signal: ctx.signal,
130
+ principalId: ctx.principal.id,
131
+ principalKind: AGENT_TOOL_PRINCIPAL_KIND,
132
+ hooks,
133
+ confirmationToken: record.confirmationToken,
134
+ }),
135
+ });
136
+ },
137
+ });
138
+ }
139
+ export function buildDatabaseRegistrations(routeDeps, _optional = {}) {
140
+ const { surfaces, mutationActor, adaptLegacyAuthorize } = routeDeps;
141
+ const CATALOG_BY_ID = indexCatalogById({ catalog: routeDeps.catalog });
142
+ const portable = routeDeps.createDatabaseReadTools({
143
+ readers: databaseInputReaders,
144
+ workspaceId: routeDeps.workspaceId, introspection: routeDeps.databaseIntrospection,
145
+ ledger: routeDeps.databaseLedgerRepo, restorePoints: routeDeps.restorePointsRepo,
146
+ dbOps: routeDeps.dbOps, clock: routeDeps.clock, idGen: routeDeps.idGen,
147
+ requirePermission: request => requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: request.principalId, permission: request.permission }, { entityType: request.entityType }),
148
+ }, { messages: routeDeps.messages });
149
+ const restorePointTool = portable.find(tool => tool.descriptor.id === "backup_create_restore_point");
150
+ if (restorePointTool === undefined)
151
+ throw new Error("Database tools have no backup restore point registration");
152
+ const handlers = {
153
+ ...Object.fromEntries(portable.filter(tool => tool.descriptor.id !== "backup_create_restore_point").map(tool => [tool.descriptor.id, tool.handler])),
154
+ database_plan_migrate_forward: (ctx) => planDatabaseMigrateForward(routeDeps, ctx, mutationActor),
155
+ backup_create_restore_point: restorePointTool.handler,
156
+ // Plans as the agent, asks the human, then confirms as the human and executes as the agent
157
+ // inside the same operation lock and cost-class refusal the admin execute route uses.
158
+ [MIGRATE_TOOL_ID]: createMigrateForwardHandler(routeDeps, surfaces, mutationActor),
159
+ };
160
+ return buildDomainRegistrations({ metadata: toolMetadata,
161
+ domain: "database",
162
+ catalogModule: "@jini-ai/db/tools",
163
+ catalog: CATALOG_BY_ID,
164
+ handlers,
165
+ derivedRisk: databaseDerivedRisk,
166
+ }, { unwiredToolIds: UNWIRED_DATABASE_TOOL_IDS });
167
+ }
168
+ /**
169
+ * Contributes Database's AI tools; called once by the composition root's
170
+ * `installFirstPartyToolContributors()`, never as an import side effect.
171
+ * Database drift logic belongs to the low-level database module, which must not value-import
172
+ * this feature: that would close a runtime cycle through assistant tool discovery.
173
+ */
174
+ export function contributeDatabaseTools() {
175
+ return { domain: "database", build: buildDatabaseRegistrations, risk: databaseDerivedRisk };
176
+ }
177
+ /** Host kit is the validation authority; factories receive the same reader behavior through ports. */
178
+ const databaseInputReaders = {
179
+ isRecord: (input) => isRecord({ value: input }), inputRecord: input => requireInputRecord({ input }), noInput: input => requireNoInput({ input }),
180
+ string: (input, key) => requireString({ input, key }),
181
+ optionalString: (input, key) => optionalString({ input, key }),
182
+ optionalNumber: (input, key) => optionalNumber({ input, key }),
183
+ optionalBoolean: (input, key) => optionalBoolean({ input, key }),
184
+ };
185
+ //# sourceMappingURL=tool-registrations.js.map
@@ -33,4 +33,18 @@ export declare function pruneDatabaseCopies({ copies, justWritten }: {
33
33
  protectedPaths?: ReadonlySet<string>;
34
34
  remove?: (copy: DatabaseCopy) => Promise<void>;
35
35
  }): Promise<void>;
36
+ /** Pure selection for a scheduled retention pass: which caller-owned copies a pass MAY remove.
37
+ * Nothing is selected unless `verifiedNewest` names the newest local copy, because pruning against an
38
+ * unverified (possibly torn) copy would spend the only good recovery window. Protected copies are
39
+ * kept beyond `keep`, and copies outside the anchor's folder are never candidates. Selection only:
40
+ * the caller removes files, under whatever lock its backup publication and recovery readers share.
41
+ * @complexity O(n log n) time, O(n) space; no filesystem access.
42
+ * @example selectDatabaseCopiesToPrune({ copies, verifiedNewest: newest.filePath }, { protectedPaths }); */
43
+ export declare function selectDatabaseCopiesToPrune({ copies, verifiedNewest }: {
44
+ copies: readonly DatabaseCopy[];
45
+ verifiedNewest: string | null | undefined;
46
+ }, { keep, protectedPaths }?: {
47
+ keep?: number;
48
+ protectedPaths?: ReadonlySet<string>;
49
+ }): DatabaseCopy[];
36
50
  //# sourceMappingURL=backup-policy.d.ts.map