@jini-ai/db 0.2.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 (84) hide show
  1. package/CHANGELOG.md +26 -10
  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/dialect.d.ts +2 -1
  11. package/dist/kernel/dialect.js +5 -2
  12. package/dist/kernel/postgres/driver.d.ts +1 -1
  13. package/dist/kernel/postgres/driver.js +1 -1
  14. package/dist/kernel/postgres/pglite-socket.d.ts +1 -1
  15. package/dist/kernel/postgres/pglite-socket.js +1 -1
  16. package/dist/pg-fixture.d.ts +50 -0
  17. package/dist/pg-fixture.js +84 -0
  18. package/dist/pglite/owner.js +7 -0
  19. package/dist/postgres/index.d.ts +1 -1
  20. package/dist/postgres/index.js +1 -1
  21. package/dist/postgres/types.d.ts +1 -52
  22. package/dist/postgres/types.js +2 -13
  23. package/dist/recovery/deep-link.d.ts +60 -0
  24. package/dist/recovery/deep-link.js +16 -0
  25. package/dist/recovery/degraded-banners.d.ts +40 -0
  26. package/dist/recovery/degraded-banners.js +69 -0
  27. package/dist/recovery/disclosure.d.ts +58 -0
  28. package/dist/recovery/disclosure.js +55 -0
  29. package/dist/recovery/evaluate-boot-migration-policy.d.ts +41 -0
  30. package/dist/recovery/evaluate-boot-migration-policy.js +50 -0
  31. package/dist/recovery/hook-policy.d.ts +9 -0
  32. package/dist/recovery/hook-policy.js +2 -0
  33. package/dist/recovery/index.d.ts +15 -0
  34. package/dist/recovery/index.js +13 -0
  35. package/dist/recovery/lookup-adapters.d.ts +40 -0
  36. package/dist/recovery/lookup-adapters.js +44 -0
  37. package/dist/recovery/migrate-forward-execute.d.ts +65 -0
  38. package/dist/recovery/migrate-forward-execute.js +68 -0
  39. package/dist/recovery/migrate-forward-hooks.d.ts +118 -0
  40. package/dist/recovery/migrate-forward-hooks.js +85 -0
  41. package/dist/recovery/operation-lock.d.ts +78 -0
  42. package/dist/recovery/operation-lock.js +58 -0
  43. package/dist/recovery/reconcile-interrupted-migration.d.ts +73 -0
  44. package/dist/recovery/reconcile-interrupted-migration.js +47 -0
  45. package/dist/recovery/recovery-orchestrator.d.ts +204 -0
  46. package/dist/recovery/recovery-orchestrator.js +96 -0
  47. package/dist/recovery/restore-hooks.d.ts +105 -0
  48. package/dist/recovery/restore-hooks.js +154 -0
  49. package/dist/recovery/restore-point-create.d.ts +80 -0
  50. package/dist/recovery/restore-point-create.js +37 -0
  51. package/dist/sqlite/open.d.ts +1 -1
  52. package/dist/sqlite/open.js +3 -3
  53. package/dist/sqlite/restore-types.d.ts +7 -3
  54. package/dist/tools/read-tools.js +7 -4
  55. package/dist/tools/restore-points.d.ts +3 -0
  56. package/dist/tools/restore-points.js +2 -2
  57. package/dist/tools/surface-port.d.ts +11 -29
  58. package/dist/tools/timeline.d.ts +4 -0
  59. package/dist/tools/timeline.js +8 -2
  60. package/dist/tools/transfer-tools.js +36 -37
  61. package/dist/transfer/internal-ddl.d.ts +3 -0
  62. package/dist/transfer/internal-ddl.js +6 -2
  63. package/dist/transfer/types.d.ts +3 -9
  64. package/package.json +48 -6
  65. package/dist/kernel/pg-types.d.ts +0 -22
  66. package/dist/kernel/pg-types.js +0 -26
  67. package/dist/kernel/socket.d.ts +0 -8
  68. package/dist/kernel/socket.js +0 -8
  69. package/dist/pglite/dialect.d.ts +0 -11
  70. package/dist/pglite/dialect.js +0 -88
  71. package/dist/pglite/driver.d.ts +0 -30
  72. package/dist/pglite/driver.js +0 -46
  73. package/dist/pglite/ops.d.ts +0 -39
  74. package/dist/pglite/ops.js +0 -78
  75. package/dist/postgres/driver.d.ts +0 -23
  76. package/dist/postgres/driver.js +0 -41
  77. package/dist/postgres/ops.d.ts +0 -12
  78. package/dist/postgres/ops.js +0 -46
  79. package/dist/postgres/pglite-socket.d.ts +0 -23
  80. package/dist/postgres/pglite-socket.js +0 -51
  81. package/dist/sqlite/driver.d.ts +0 -71
  82. package/dist/sqlite/driver.js +0 -132
  83. package/dist/sqlite/ops.d.ts +0 -12
  84. package/dist/sqlite/ops.js +0 -40
package/CHANGELOG.md CHANGED
@@ -1,19 +1,20 @@
1
- ## Unreleased
1
+ ## 0.3.1 — 2026-10-08
2
2
 
3
- ### BREAKING
4
-
5
- - `DatabaseReadToolPorts.clock` now takes core `Clock.nowMs()`; restore-point timestamps use `nowIso({ clock })` at the existing sampling point.
3
+ - Tovu clean-up release: code Tovu moved into Jini, plus the Jini clean-up (see the commit log).
6
4
 
7
- ### Fixed
5
+ ## 0.3.0 — 2026-10-05
8
6
 
9
- - Add a `default` condition to every JavaScript subpath, pointing to its existing ESM entry, so tsx CommonJS bootstraps can resolve the package without `ERR_PACKAGE_PATH_NOT_EXPORTED`.
7
+ ### BREAKING
10
8
 
11
- - `databaseFile<DB>` accepts `StorageKernel<DB>` so hosts can pass typed kernels without casting or erasing their schema. Query and null behavior are unchanged.
9
+ - `createRestorePoint` takes a required `kind` (the host passes `getCapabilities().restorePoint.kind`, the same source as `costClass`) and returns it as-is. It always returned `"file-snapshot"` before, so a Postgres host's logical dump was returned and persisted as a file snapshot. `backup_create_restore_point` passes it.
10
+ - `getTimeline` refuses a non-integer or non-positive `limit` instead of passing it to the query.
12
11
 
13
- - Align transfer handlers with core's second-argument `ToolExecutionOptions.emitSurface` and canonical `SurfaceEmitter`; preserve fail-closed confirmation behavior. Forward resolved catalog messages and adapt native SQLite snapshot fixtures with explicit raw-row result types.
14
- - Move the canonical `defaultDbMessages` definition to a driver-free core module and export `DbMessages` through the existing tools entry. Extend optional host copy to the 16 remaining consumer-facing prose sites, including read-tool registration and copy preflight.
15
- - Neutral runtime defaults now refer to the source; hosts can supply their exact prior wording. Tool IDs, permissions, refusal/cost gates, persisted naming, SQL bytes and schema vectors are unchanged.
12
+ ### Fixed
16
13
 
14
+ - `database_query_timeline` reads `limit` through core's `readToolLimit` (default 50, cap 200): `0` or a non-integer is a model-facing input error and an over-cap value is capped, instead of a redacted plain `Error`. Needs `@jini-ai/core` ^0.4.1.
15
+ - `database_transfer_run` hands the exchange's deadline to `TransferSurfacePorts.confirmation` (new optional third argument `{ expiresAtMs }`) when the exchange reports one through the new optional `SurfaceExchange.expiresAtMs()`, so a host's confirmation card can count down and close on time.
16
+ - SQLite JSON equality (`jsonScalarEquals`) checks `json_type` first, so `true`/`false` never equal `1`/`0`.
17
+ - Internal `@jini-ai/core` dependency is a caret range (`workspace:^`) instead of an exact pin.
17
18
 
18
19
  ## 0.2.0 — 2026-10-02
19
20
 
@@ -25,6 +26,21 @@
25
26
  - BREAKING: Import AgentToolDefinition, AgentToolSideEffect and AgentToolActorClassRule from core; db no longer declares or exports duplicate catalog types.
26
27
  - Transfer descriptions derive from host naming and replaceable `defaultDbMessages`; the display catalog defaults to neutral `app` / `app_` names. Persisted naming is unchanged.
27
28
 
29
+ ### Also shipped in 0.2.0 (published 2026-10-03; was listed under Unreleased)
30
+
31
+ #### BREAKING
32
+
33
+ - `DatabaseReadToolPorts.clock` now takes core `Clock.nowMs()`; restore-point timestamps use `nowIso({ clock })` at the existing sampling point.
34
+
35
+ #### Fixed
36
+
37
+ - Add a `default` condition to every JavaScript subpath, pointing to its existing ESM entry, so tsx CommonJS bootstraps can resolve the package without `ERR_PACKAGE_PATH_NOT_EXPORTED`.
38
+
39
+ - `databaseFile<DB>` accepts `StorageKernel<DB>` so hosts can pass typed kernels without casting or erasing their schema. Query and null behavior are unchanged.
40
+
41
+ - Align transfer handlers with core's second-argument `ToolExecutionOptions.emitSurface` and canonical `SurfaceEmitter`; preserve fail-closed confirmation behavior. Forward resolved catalog messages and adapt native SQLite snapshot fixtures with explicit raw-row result types.
42
+ - Move the canonical `defaultDbMessages` definition to a driver-free core module and export `DbMessages` through the existing tools entry. Extend optional host copy to the 16 remaining consumer-facing prose sites, including read-tool registration and copy preflight.
43
+ - Neutral runtime defaults now refer to the source; hosts can supply their exact prior wording. Tool IDs, permissions, refusal/cost gates, persisted naming, SQL bytes and schema vectors are unchanged.
28
44
 
29
45
  ## Unreleased — C2 generic additions
30
46
 
@@ -17,7 +17,9 @@
17
17
  * rather than rejection: a `scopeId` is an internal routing key, and failing a backup because a
18
18
  * workspace slug contains a colon would be the worse outcome.
19
19
  */
20
- export declare function sanitizeForFilename(value: string): string;
20
+ export declare function sanitizeForFilename({ value }: {
21
+ value: string;
22
+ }, _options?: Record<string, never>): string;
21
23
  /**
22
24
  * Builds the artifact filename for one restore point.
23
25
  *
@@ -29,6 +31,7 @@ export declare function restorePointFilename(parts: {
29
31
  scopeId: string;
30
32
  watermarkAtCapture: number;
31
33
  timestamp: number;
34
+ }, { extension }?: {
32
35
  extension?: string;
33
36
  }): string;
34
37
  //# sourceMappingURL=artifact-naming.d.ts.map
@@ -17,7 +17,7 @@
17
17
  * rather than rejection: a `scopeId` is an internal routing key, and failing a backup because a
18
18
  * workspace slug contains a colon would be the worse outcome.
19
19
  */
20
- export function sanitizeForFilename(value) {
20
+ export function sanitizeForFilename({ value }, _options = {}) {
21
21
  return value.replace(/[^a-zA-Z0-9_-]/g, '_');
22
22
  }
23
23
  /**
@@ -27,8 +27,7 @@ export function sanitizeForFilename(value) {
27
27
  * operator sorting a directory can see how far each artifact lags without opening any of them —
28
28
  * and so a lost ledger row does not render the files on disk anonymous.
29
29
  */
30
- export function restorePointFilename(parts) {
31
- const extension = parts.extension ?? 'db';
32
- return `restore-point-${sanitizeForFilename(parts.scopeId)}-wm${parts.watermarkAtCapture}-${parts.timestamp}.${extension}`;
30
+ export function restorePointFilename(parts, { extension = 'db' } = {}) {
31
+ return `restore-point-${sanitizeForFilename({ value: parts.scopeId })}-wm${parts.watermarkAtCapture}-${parts.timestamp}.${extension}`;
33
32
  }
34
33
  //# sourceMappingURL=artifact-naming.js.map
@@ -5,4 +5,5 @@ export { PGLITE_SOCKET_FILE } from "./socket.js";
5
5
  export { PG_OID, PG_PARSERS, parseInt8 } from "./pg-types.js";
6
6
  export { parseJsonOrUndef, row, rows } from "./row-values.js";
7
7
  export type { DbRow, JsonObject } from "./row-values.js";
8
+ export type { TransferNaming } from './transfer-naming.js';
8
9
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,4 @@
1
- import type { TransferNaming } from "../transfer/types.js";
1
+ import type { TransferNaming } from "./transfer-naming.js";
2
2
  /** Copy-only display defaults; actual persisted schema/marker names remain required host inputs. */
3
3
  export interface DbTransferMessages {
4
4
  plan(required: {
@@ -19,4 +19,56 @@ export declare const PG_OID: {
19
19
  export declare function parseInt8(text: string): number | bigint;
20
20
  /** Parser overrides by type oid. */
21
21
  export declare const PG_PARSERS: Readonly<Record<number, (text: string) => unknown>>;
22
+ /**
23
+ * @file The slice of node-postgres (`pg`) this package uses, written structurally: the consumer
24
+ * passes its own `pg` module (`import pg from "pg"`), so this package needs neither `pg` nor its
25
+ * types, and the one copy that runs is the consumer's.
26
+ */
27
+ /** Pool options this package sets. */
28
+ export interface PgPoolOptions {
29
+ connectionString?: string;
30
+ host?: string;
31
+ port?: number;
32
+ user?: string;
33
+ database?: string;
34
+ max?: number;
35
+ idleTimeoutMillis?: number;
36
+ types?: {
37
+ getTypeParser(oid: number, format?: "text" | "binary"): (value: string) => unknown;
38
+ };
39
+ }
40
+ /** The result shape used by a Postgres connection; independent of query builders. */
41
+ export interface PgQueryResult<Row> {
42
+ command: "UPDATE" | "DELETE" | "INSERT" | "SELECT" | "MERGE";
43
+ rowCount: number;
44
+ rows: Row[];
45
+ }
46
+ /** A cursor accepted by a Postgres connection. */
47
+ export interface PgCursor<Row> {
48
+ read(rowsCount: number): Promise<Row[]>;
49
+ close(): Promise<void>;
50
+ }
51
+ /** A checked-out pool connection, described structurally rather than through Kysely. */
52
+ export interface PgPoolClient {
53
+ processID?: number;
54
+ query<Row>(sql: string, parameters: ReadonlyArray<unknown>): Promise<PgQueryResult<Row>>;
55
+ query<Row>(cursor: PgCursor<Row>): PgCursor<Row>;
56
+ release(): void;
57
+ }
58
+ /** The pool operations used by the kernel binding plus the idle-error event. */
59
+ export interface PgPool {
60
+ connect(): Promise<PgPoolClient>;
61
+ end(): Promise<void>;
62
+ options: object;
63
+ on(event: "error", listener: (err: Error) => void): unknown;
64
+ }
65
+ /** The `pg` module's default export: `import pg from "pg"`, passed as `{ pg }`. */
66
+ export interface PgModule {
67
+ readonly Pool: new (options: PgPoolOptions) => PgPool;
68
+ readonly types: {
69
+ getTypeParser(oid: number, format?: "text" | "binary"): (value: never) => unknown;
70
+ };
71
+ }
72
+ /** node-postgres type parsing aligned with PGlite's (`PG_PARSERS`), for one pool only. */
73
+ export declare function pgTypesFor(pg: PgModule, parsers: Readonly<Record<number, (text: string) => unknown>>): NonNullable<PgPoolOptions["types"]>;
22
74
  //# sourceMappingURL=pg-types.d.ts.map
@@ -23,4 +23,12 @@ export const PG_PARSERS = {
23
23
  [PG_OID.json]: compactJson,
24
24
  [PG_OID.jsonb]: compactJson,
25
25
  };
26
+ /** node-postgres type parsing aligned with PGlite's (`PG_PARSERS`), for one pool only. */
27
+ export function pgTypesFor(pg, parsers) {
28
+ return {
29
+ getTypeParser(oid, format) {
30
+ return parsers[oid] ?? pg.types.getTypeParser(oid, format);
31
+ },
32
+ };
33
+ }
26
34
  //# sourceMappingURL=pg-types.js.map
@@ -0,0 +1,10 @@
1
+ /** Host identifiers are required: changing a marker name would orphan earlier copies. */
2
+ export interface TransferNaming {
3
+ readonly defaultSchema: string;
4
+ readonly markerTable: string;
5
+ readonly unvalidatedTable: string;
6
+ readonly schemaPrefix: string;
7
+ /** Optional SQL dollar-quote tag for compatibility with existing script consumers. */
8
+ readonly sqlTag?: string;
9
+ }
10
+ //# sourceMappingURL=transfer-naming.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=transfer-naming.js.map
@@ -12,7 +12,8 @@ export declare function jsonText(dialect: StorageDialect, column: Expression<unk
12
12
  /**
13
13
  * `column` at `path` equals the JSON scalar `value` (string, number or boolean), as a boolean
14
14
  * expression. SQLite has no JSON boolean type — `json_extract` reads `true`/`false` as `1`/`0` — so
15
- * a boolean is bound as `1`/`0` there; Postgres compares the two `jsonb` values, so `10` matches
15
+ * check `json_type` before comparing the bound `1`/`0`, so booleans never match numbers.
16
+ * Postgres compares the two `jsonb` values, so `10` matches
16
17
  * `10.0` and a string never matches a number.
17
18
  */
18
19
  export declare function jsonScalarEquals(dialect: StorageDialect, column: Expression<unknown>, path: readonly string[], value: string | number | boolean): RawBuilder<boolean>;
@@ -40,14 +40,17 @@ export function jsonText(dialect, column, path) {
40
40
  /**
41
41
  * `column` at `path` equals the JSON scalar `value` (string, number or boolean), as a boolean
42
42
  * expression. SQLite has no JSON boolean type — `json_extract` reads `true`/`false` as `1`/`0` — so
43
- * a boolean is bound as `1`/`0` there; Postgres compares the two `jsonb` values, so `10` matches
43
+ * check `json_type` before comparing the bound `1`/`0`, so booleans never match numbers.
44
+ * Postgres compares the two `jsonb` values, so `10` matches
44
45
  * `10.0` and a string never matches a number.
45
46
  */
46
47
  export function jsonScalarEquals(dialect, column, path, value) {
47
48
  if (dialect === "postgres")
48
49
  return sql `((${column}::jsonb #> ${pgPath(path)}) = ${JSON.stringify(value)}::jsonb)`;
49
50
  const bound = typeof value === "boolean" ? (value ? 1 : 0) : value;
50
- return sql `(json_extract(${column}, ${sqlitePath(path)}) = ${bound})`;
51
+ const types = typeof value === "number" ? ["integer", "real"] : typeof value === "boolean" ? ["true", "false"] : ["text"];
52
+ const at = sqlitePath(path);
53
+ return sql `(json_type(${column}, ${at}) IN (${sql.join(types)}) AND json_extract(${column}, ${at}) = ${bound})`;
51
54
  }
52
55
  /**
53
56
  * A sort key for the value at `path`: SQLite's typed `json_extract`, Postgres' `jsonb` value, so
@@ -1,5 +1,5 @@
1
1
  import { type StorageKernel } from "../index.js";
2
- import { type PgModule } from "../../postgres/types.js";
2
+ import { type PgModule } from "../../core/pg-types.js";
3
3
  /**
4
4
  * @file The node-postgres driver: a connection POOL to any Postgres server (local, Supabase, Neon).
5
5
  * Kysely's own Postgres dialect; each transaction checks out its own connection, so unrelated
@@ -1,7 +1,7 @@
1
1
  import { Kysely, PostgresDialect } from "kysely";
2
2
  import { PG_PARSERS } from "../../core/index.js";
3
3
  import { buildKernel, postgresLockKey } from "../index.js";
4
- import { pgTypesFor } from "../../postgres/types.js";
4
+ import { pgTypesFor } from "../../core/pg-types.js";
5
5
  /**
6
6
  * @file The node-postgres driver: a connection POOL to any Postgres server (local, Supabase, Neon).
7
7
  * Kysely's own Postgres dialect; each transaction checks out its own connection, so unrelated
@@ -1,5 +1,5 @@
1
1
  import { type StorageKernel } from "../index.js";
2
- import { type PgModule } from "../../postgres/types.js";
2
+ import { type PgModule } from "../../core/pg-types.js";
3
3
  /**
4
4
  * @file A storage kernel that reaches a PGlite data dir through its owner's Unix socket
5
5
  * (`@jini-ai/db/pglite`'s `startPgliteOwner`): node-postgres with ONE connection and the kernel's turn lock, because PGlite
@@ -2,7 +2,7 @@ import { dirname } from "node:path";
2
2
  import { Kysely, PostgresDialect } from "kysely";
3
3
  import { PG_PARSERS, PGLITE_SOCKET_FILE } from "../../core/index.js";
4
4
  import { buildKernel, postgresLockKey } from "../index.js";
5
- import { pgTypesFor } from "../../postgres/types.js";
5
+ import { pgTypesFor } from "../../core/pg-types.js";
6
6
  /**
7
7
  * @file A storage kernel that reaches a PGlite data dir through its owner's Unix socket
8
8
  * (`@jini-ai/db/pglite`'s `startPgliteOwner`): node-postgres with ONE connection and the kernel's turn lock, because PGlite
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @file Minimal `psql` shell-out helper for tests that prove semantics against a real, local
3
+ * Postgres server.
4
+ *
5
+ * Why shell out rather than use a driver: no `pg`/`postgres` npm package is installed in this repo
6
+ * yet (`src/platform/db/postgres/db-ops.ts` is explicitly evaluation-only per its own header — see the
7
+ * postgres-supabase-database-backend-spec.md architecture doc). Adding one is a real dependency
8
+ * decision this task was explicitly told not to make unilaterally. `psql` is already on the host
9
+ * running these tests, so it is the only way to prove behavior against a live server without adding
10
+ * a new runtime dependency mid-task. This file is TEST INFRASTRUCTURE ONLY — nothing in
11
+ * `manifest.ts`/`verify.ts` depends on it, and it must never be imported from product code.
12
+ */
13
+ import { type SpawnSyncReturns } from "node:child_process";
14
+ export interface PsqlResult {
15
+ readonly ok: boolean;
16
+ readonly stdout: string;
17
+ readonly stderr: string;
18
+ }
19
+ export interface PgFixtureOptions {
20
+ /** Replace only subprocess execution; SQL selection and cleanup still run in the real fixture. */
21
+ spawnSync?: (binary: string, args: string[], options: {
22
+ encoding: "utf8";
23
+ }) => Pick<SpawnSyncReturns<string>, "status" | "error"> & {
24
+ stdout: string | null;
25
+ stderr: string | null;
26
+ };
27
+ }
28
+ /**
29
+ * Bind a test fixture to an explicit server and role. Environment selection belongs to the host;
30
+ * the admin database stays fixed so connection configuration cannot redirect cleanup.
31
+ * The subprocess port makes refusal and ordering paths directly assertable without a live server.
32
+ * @complexity Construction is constant time and space; each method runs one or two subprocesses.
33
+ */
34
+ export declare function createPgFixture(required: {
35
+ host: string;
36
+ user: string;
37
+ port?: string | undefined;
38
+ }, optional?: PgFixtureOptions): {
39
+ psql: (required: {
40
+ database: string;
41
+ sql: string;
42
+ }, _optional?: Record<string, never>) => PsqlResult;
43
+ recreateDatabase: (required: {
44
+ database: string;
45
+ }, _optional?: Record<string, never>) => void;
46
+ dropDatabase: (required: {
47
+ database: string;
48
+ }, _optional?: Record<string, never>) => void;
49
+ };
50
+ //# sourceMappingURL=pg-fixture.d.ts.map
@@ -0,0 +1,84 @@
1
+ /**
2
+ * @file Minimal `psql` shell-out helper for tests that prove semantics against a real, local
3
+ * Postgres server.
4
+ *
5
+ * Why shell out rather than use a driver: no `pg`/`postgres` npm package is installed in this repo
6
+ * yet (`src/platform/db/postgres/db-ops.ts` is explicitly evaluation-only per its own header — see the
7
+ * postgres-supabase-database-backend-spec.md architecture doc). Adding one is a real dependency
8
+ * decision this task was explicitly told not to make unilaterally. `psql` is already on the host
9
+ * running these tests, so it is the only way to prove behavior against a live server without adding
10
+ * a new runtime dependency mid-task. This file is TEST INFRASTRUCTURE ONLY — nothing in
11
+ * `manifest.ts`/`verify.ts` depends on it, and it must never be imported from product code.
12
+ */
13
+ import { spawnSync } from "node:child_process";
14
+ /** Defaults match the fixture Postgres this repo's dispatch brief describes: Homebrew Postgres 14
15
+ * listening on the Unix socket in `/tmp`, role `la`, no password (peer/trust auth on the socket).
16
+ * `PGHOST`/`PGPORT`/`PGUSER` (standard libpq env var names) override these defaults so CI can point
17
+ * this at a TCP service container instead of a developer's local socket. When unset, behavior is
18
+ * byte-for-byte identical to before this file read the environment — every local dev run is
19
+ * unaffected. `PGPASSWORD`, if set, needs no code here: `spawnSync` inherits the parent process's
20
+ * environment by default, and `psql` itself already honors `PGPASSWORD` natively.
21
+ *
22
+ * Deliberately NOT overridable via env: `ADMIN_DATABASE` below stays a hardcoded `"postgres"` so a
23
+ * stray or misconfigured env var can never redirect the *admin* connection target. Only the *server*
24
+ * address (host/port/user) is configurable here — never which database on that server gets dropped by
25
+ * `recreateDatabase()`/`dropDatabase()` (that's always the caller-supplied `database` argument, e.g.
26
+ * the distinctively-named `migration_fixture`, not this constant). */
27
+ // The driver-dependency rationale above records the original extraction decision. Drivers are
28
+ // now available; this explicit test entry keeps psql-based semantic proofs and cleanup ordering.
29
+ const ADMIN_DATABASE = "postgres";
30
+ /**
31
+ * Bind a test fixture to an explicit server and role. Environment selection belongs to the host;
32
+ * the admin database stays fixed so connection configuration cannot redirect cleanup.
33
+ * The subprocess port makes refusal and ordering paths directly assertable without a live server.
34
+ * @complexity Construction is constant time and space; each method runs one or two subprocesses.
35
+ */
36
+ export function createPgFixture(required, optional = {}) {
37
+ const { host, user, port } = required;
38
+ const run = optional.spawnSync ?? spawnSync;
39
+ /**
40
+ * Runs one `-c` command against `database` via `psql`. Uses `ON_ERROR_STOP=1` so a failing
41
+ * statement inside a multi-statement `-c` string aborts rather than continuing past it, and reports
42
+ * failure via `ok: false` rather than throwing — callers proving a REJECTION (e.g. "int4 must refuse
43
+ * 2147483648") need the failure as a value, not an exception to catch.
44
+ * Throws if the executable cannot be started; inherits libpq credentials from the environment.
45
+ * @complexity One subprocess; output memory is proportional to the returned text.
46
+ */
47
+ function psql(required, _optional = {}) {
48
+ const { database, sql } = required;
49
+ // `-q` (quiet) suppresses command-completion tags ("INSERT 0 1", "CREATE TABLE", …) that would
50
+ // otherwise interleave with `-t -A`'s unaligned tuple output and corrupt a caller's parse of the
51
+ // actual returned value(s).
52
+ const result = run("psql", ["-h", host, "-U", user, ...(port ? ["-p", port] : []), "-d", database, "-v", "ON_ERROR_STOP=1", "-q", "-t", "-A", "-c", sql], { encoding: "utf8" });
53
+ if (result.error) {
54
+ throw new Error(`psql could not be run (${result.error.message}). This test suite requires a local psql binary on PATH ` +
55
+ `and a Postgres server reachable at host "${host}" as role "${user}" — see this file's own doc.`);
56
+ }
57
+ return { ok: result.status === 0, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
58
+ }
59
+ /** Drops (if present) and recreates `database` against the admin connection, so fixture tests are
60
+ * repeatable regardless of what a previous run left behind. A failed DROP prevents CREATE;
61
+ * either failure throws its exact database-specific diagnostic.
62
+ * @complexity At most two sequential subprocesses; output memory follows the command output.
63
+ */
64
+ function recreateDatabase(required, _optional = {}) {
65
+ const { database } = required;
66
+ const drop = psql({ database: ADMIN_DATABASE, sql: `DROP DATABASE IF EXISTS ${database};` });
67
+ if (!drop.ok)
68
+ throw new Error(`failed to drop fixture database "${database}": ${drop.stderr}`);
69
+ const create = psql({ database: ADMIN_DATABASE, sql: `CREATE DATABASE ${database};` });
70
+ if (!create.ok)
71
+ throw new Error(`failed to create fixture database "${database}": ${create.stderr}`);
72
+ }
73
+ /** Idempotent cleanup of the caller-selected database; throws when PostgreSQL refuses it.
74
+ * @complexity One subprocess; output memory follows the command output.
75
+ */
76
+ function dropDatabase(required, _optional = {}) {
77
+ const { database } = required;
78
+ const drop = psql({ database: ADMIN_DATABASE, sql: `DROP DATABASE IF EXISTS ${database};` });
79
+ if (!drop.ok)
80
+ throw new Error(`failed to drop fixture database "${database}": ${drop.stderr}`);
81
+ }
82
+ return { psql, recreateDatabase, dropDatabase };
83
+ }
84
+ //# sourceMappingURL=pg-fixture.js.map
@@ -306,6 +306,10 @@ export async function startPgliteOwner(required, optional = {}) {
306
306
  const releaseLock = acquireOwnerLock({ dataDir, lockFileName: required.lockFileName });
307
307
  let db;
308
308
  let server;
309
+ // WASM initialization can await native work with no referenced Node handle. Until the socket
310
+ // starts, keep this awaited boot alive; otherwise a CLI exits with only the owner lock written.
311
+ // Release on both success and failure, so an idle or refused boot retains no extra timer.
312
+ const startupRef = setInterval(() => { }, 1_000);
309
313
  try {
310
314
  ensurePrivateDir(socketDir);
311
315
  // We hold the lock, so a socket file here was left by a dead owner.
@@ -331,6 +335,9 @@ export async function startPgliteOwner(required, optional = {}) {
331
335
  releaseLock();
332
336
  throw error;
333
337
  }
338
+ finally {
339
+ clearInterval(startupRef);
340
+ }
334
341
  const serving = server;
335
342
  const open = db;
336
343
  let closing;
@@ -1,3 +1,3 @@
1
1
  /** Structural Postgres connection types and per-pool parser policy. No Kysely dependency. */
2
- export { pgTypesFor, type PgModule, type PgPoolOptions, type PgPool, type PgPoolClient, type PgQueryResult, type PgCursor } from "./types.js";
2
+ export { pgTypesFor, type PgModule, type PgPoolOptions, type PgPool, type PgPoolClient, type PgQueryResult, type PgCursor } from "../core/pg-types.js";
3
3
  //# sourceMappingURL=index.d.ts.map
@@ -1,3 +1,3 @@
1
1
  /** Structural Postgres connection types and per-pool parser policy. No Kysely dependency. */
2
- export { pgTypesFor } from "./types.js";
2
+ export { pgTypesFor } from "../core/pg-types.js";
3
3
  //# sourceMappingURL=index.js.map
@@ -1,53 +1,2 @@
1
- /**
2
- * @file The slice of node-postgres (`pg`) this package uses, written structurally: the consumer
3
- * passes its own `pg` module (`import pg from "pg"`), so this package needs neither `pg` nor its
4
- * types, and the one copy that runs is the consumer's.
5
- */
6
- /** Pool options this package sets. */
7
- export interface PgPoolOptions {
8
- connectionString?: string;
9
- host?: string;
10
- port?: number;
11
- user?: string;
12
- database?: string;
13
- max?: number;
14
- idleTimeoutMillis?: number;
15
- types?: {
16
- getTypeParser(oid: number, format?: "text" | "binary"): (value: string) => unknown;
17
- };
18
- }
19
- /** The result shape used by a Postgres connection; independent of query builders. */
20
- export interface PgQueryResult<Row> {
21
- command: "UPDATE" | "DELETE" | "INSERT" | "SELECT" | "MERGE";
22
- rowCount: number;
23
- rows: Row[];
24
- }
25
- /** A cursor accepted by a Postgres connection. */
26
- export interface PgCursor<Row> {
27
- read(rowsCount: number): Promise<Row[]>;
28
- close(): Promise<void>;
29
- }
30
- /** A checked-out pool connection, described structurally rather than through Kysely. */
31
- export interface PgPoolClient {
32
- processID?: number;
33
- query<Row>(sql: string, parameters: ReadonlyArray<unknown>): Promise<PgQueryResult<Row>>;
34
- query<Row>(cursor: PgCursor<Row>): PgCursor<Row>;
35
- release(): void;
36
- }
37
- /** The pool operations used by the kernel binding plus the idle-error event. */
38
- export interface PgPool {
39
- connect(): Promise<PgPoolClient>;
40
- end(): Promise<void>;
41
- options: object;
42
- on(event: "error", listener: (err: Error) => void): unknown;
43
- }
44
- /** The `pg` module's default export: `import pg from "pg"`, passed as `{ pg }`. */
45
- export interface PgModule {
46
- readonly Pool: new (options: PgPoolOptions) => PgPool;
47
- readonly types: {
48
- getTypeParser(oid: number, format?: "text" | "binary"): (value: never) => unknown;
49
- };
50
- }
51
- /** node-postgres type parsing aligned with PGlite's (`PG_PARSERS`), for one pool only. */
52
- export declare function pgTypesFor(pg: PgModule, parsers: Readonly<Record<number, (text: string) => unknown>>): NonNullable<PgPoolOptions["types"]>;
1
+ export * from '../core/pg-types.js';
53
2
  //# sourceMappingURL=types.d.ts.map
@@ -1,14 +1,3 @@
1
- /**
2
- * @file The slice of node-postgres (`pg`) this package uses, written structurally: the consumer
3
- * passes its own `pg` module (`import pg from "pg"`), so this package needs neither `pg` nor its
4
- * types, and the one copy that runs is the consumer's.
5
- */
6
- /** node-postgres type parsing aligned with PGlite's (`PG_PARSERS`), for one pool only. */
7
- export function pgTypesFor(pg, parsers) {
8
- return {
9
- getTypeParser(oid, format) {
10
- return parsers[oid] ?? pg.types.getTypeParser(oid, format);
11
- },
12
- };
13
- }
1
+ // Compatibility path; the shared implementation lives in core.
2
+ export * from '../core/pg-types.js';
14
3
  //# sourceMappingURL=types.js.map
@@ -0,0 +1,60 @@
1
+ import type { PrincipalKind } from "./recovery-orchestrator.js";
2
+ /**
3
+ * @file SPEC-019 C-306 / REQ-20 / REQ-21 / INV-04 — deep-link envelope resolution (ADR-045 §5,
4
+ * ADR-041 §7).
5
+ *
6
+ * Purpose:
7
+ * `resolveDeepLinkContext` never trusts a `DatabaseContextEnvelope`'s carried values — every id is
8
+ * independently re-looked-up server-side on arrival (INV-04). A stale, pruned, or outright forged
9
+ * `restorePointId` (even one that is syntactically plausible, e.g. ULID-shaped) resolves to
10
+ * `{found:false}` rather than proceeding with the envelope's own claimed value — the envelope
11
+ * carries display continuity only, never authority (ADR-041 §7's own rule, restated for this
12
+ * domain's receiving side).
13
+ *
14
+ * How it relates to the project:
15
+ * Isolated into its own file specifically so this mandatory re-verification rule is a single,
16
+ * reviewable unit (ADR-PIPE-019 File Map) — every other Recovery surface that renders envelope
17
+ * context must route through this function rather than reading `envelope.restorePointId` directly.
18
+ */
19
+ export interface DatabaseContextEnvelope {
20
+ v: number;
21
+ correlationId: string;
22
+ siteId: string;
23
+ ledgerEventId: string | null;
24
+ restorePointId: string | null;
25
+ drift: string;
26
+ intent: string;
27
+ issuedAt: string;
28
+ }
29
+ export interface DeepLinkRestorePointLookupPort {
30
+ findRestorePointById(id: string): Promise<{
31
+ restorePointId: string;
32
+ capturedAt: string;
33
+ } | null>;
34
+ }
35
+ export interface ResolveDeepLinkContextRequired {
36
+ deps: {
37
+ lookup: DeepLinkRestorePointLookupPort;
38
+ };
39
+ input: {
40
+ principalId: string;
41
+ principalKind: PrincipalKind;
42
+ envelope: DatabaseContextEnvelope;
43
+ };
44
+ }
45
+ export interface RecoveryContextResponse {
46
+ found: boolean;
47
+ restorePoint: {
48
+ restorePointId: string;
49
+ capturedAt: string;
50
+ } | null;
51
+ }
52
+ /**
53
+ * AC-30/AC-31/EC-03/INV-04 — re-resolves `envelope.restorePointId` via the injected lookup port;
54
+ * never reads the envelope's carried value into the response directly, and never mutates the
55
+ * input envelope object.
56
+ *
57
+ * @complexity O(1) — one lookup call.
58
+ */
59
+ export declare function resolveDeepLinkContext(required: ResolveDeepLinkContextRequired, _optional?: Record<string, never>): Promise<RecoveryContextResponse>;
60
+ //# sourceMappingURL=deep-link.d.ts.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * AC-30/AC-31/EC-03/INV-04 — re-resolves `envelope.restorePointId` via the injected lookup port;
3
+ * never reads the envelope's carried value into the response directly, and never mutates the
4
+ * input envelope object.
5
+ *
6
+ * @complexity O(1) — one lookup call.
7
+ */
8
+ export async function resolveDeepLinkContext(required, _optional = {}) {
9
+ const { deps, input } = required;
10
+ if (!input.envelope.restorePointId) {
11
+ return { found: false, restorePoint: null };
12
+ }
13
+ const restorePoint = await deps.lookup.findRestorePointById(input.envelope.restorePointId);
14
+ return restorePoint ? { found: true, restorePoint } : { found: false, restorePoint: null };
15
+ }
16
+ //# sourceMappingURL=deep-link.js.map
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @file SPEC-019 C-308 / behavior.spec.md §1.1 — degraded-state banner precedence resolver
3
+ * (ADR-045 §4).
4
+ *
5
+ * Purpose:
6
+ * Fixed precedence, highest to lowest: `migration.interrupted` > `PENDING_MIGRATION` >
7
+ * operation-in-flight > `costClass:'unavailable'` > watermark-baseline-unavailable. Only the
8
+ * PRIMARY banner selection is this resolver's contract (EC-06) — "an interrupted-run banner stays
9
+ * visible beneath a superseded pending-migration banner" is a rendering-layer composition concern
10
+ * this function does not own.
11
+ *
12
+ * `PENDING_MIGRATION`'s action always deep-links to the Database Timeline's own migration ceremony, never a
13
+ * Recovery restore-flow action (AC-27/INV-07, ADR-045 §4) — restoring to an older snapshot does
14
+ * not resolve schema drift against the current runtime.
15
+ */
16
+ export type DegradedBannerKind = "migration-interrupted" | "pending-migration" | "operation-in-flight" | "cost-unavailable" | "watermark-baseline-unavailable";
17
+ export type DegradedBannerActionKind = "deep-link-to-database-migration" | "unblock-interrupted-migration" | "none";
18
+ export interface DegradedBanner {
19
+ kind: DegradedBannerKind;
20
+ accessibleText: string;
21
+ actionKind: DegradedBannerActionKind;
22
+ }
23
+ export interface DegradedBannerCapabilities {
24
+ costClass: "cheap" | "expensive" | "unavailable";
25
+ operationInFlight: boolean;
26
+ pendingMigration: boolean;
27
+ migrationInterrupted: boolean;
28
+ watermarkBaselineAvailable: boolean;
29
+ }
30
+ export interface ResolveDegradedBannerRequired {
31
+ capabilities: DegradedBannerCapabilities;
32
+ }
33
+ /**
34
+ * AC-27/AC-29/EC-06/INV-07 — resolves the single primary degraded banner per the fixed precedence
35
+ * order, or `null` when no degraded condition holds.
36
+ *
37
+ * @complexity O(1) — a fixed sequence of independent comparisons, no loop.
38
+ */
39
+ export declare function resolveDegradedBanner(required: ResolveDegradedBannerRequired, _optional?: Record<string, never>): DegradedBanner | null;
40
+ //# sourceMappingURL=degraded-banners.d.ts.map