@sema-agent/core-stores-sql 7.69.1 → 7.71.0

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.
package/README.md CHANGED
@@ -3,14 +3,17 @@
3
3
  Core's storage seats (`EngineStorageBackend`: sessions, checkpoints, tool results, session policy, workflow journal,
4
4
  usage windows, background agents, mailbox, roster, file history, and the backend-level managed-retention executor)
5
5
  over one SQL database — PostgreSQL, or the MySQL protocol family (MySQL / InnoDB, MariaDB, TiDB) — to be built by
6
- neutral factories over a pool you hand in. Core itself ships only in-memory and file-backed stores, so a database-backed
7
- backend is built behind this face rather than inside core. Ships its own types; ES modules only.
6
+ neutral factories over a pool you hand in, and the SQL foundation your own stores are written over: the driver you
7
+ make once over that pool, its words, its notices and the codes every refusal of this package carries. Core itself
8
+ ships only in-memory and file-backed stores, so a database-backed backend is built behind this face rather than inside
9
+ core. Ships its own types; ES modules only.
8
10
 
9
11
  ## Read this first: this release carries no SQL stores
10
12
 
11
13
  The published versions so far fix the package's public face and how it is built, checked and released; they do not
12
14
  carry the stores yet. `createSqlStorageBackend` and `createSqlDriver` check the version pairing, read their options
13
- (refusing each wrong value by name) and then refuse — they do not return an object without its stores. Since no
15
+ (refusing each wrong value by name) and then refuse — they do not return an object without its stores
16
+ (`core-stores-sql.release.not-carried`). Since no
14
17
  driver can be made yet, the backend's last read, the driver, refuses every call (`options.driver was not made by
15
18
  createSqlDriver`). `baselineDdl(dialect)` resolves to an empty list and `publishedColumns()` returns an empty list. A
16
19
  later release fills the face in; a removed or re-kinded name is called out as breaking in the `@sema-agent/core`
@@ -21,11 +24,11 @@ release notes, the same as for core's own exports.
21
24
  One pool, one driver: make the driver once and hand it to the backend and to your own stores.
22
25
 
23
26
  ```ts
24
- const driver = createSqlDriver({ dialect: "pg", pool, onFailOpen: (tag, detail) => log.warn(tag, detail) });
27
+ const driver = createSqlDriver({ dialect: "pg", pool, onSqlNotice: (tag, detail, facts) => log.warn(SQL_NOTICE_TAGS[tag], tag, facts?.seat, detail) });
25
28
  const backend = createSqlStorageBackend({
26
29
  driver,
27
30
  retention: "managed",
28
- transactionHooks: { retention: { holdLock, liveReferences, beforeDelete, audit }, session: { beforeCommit } },
31
+ transactionHooks: { retention: { holdLock, liveReferences, beforeDelete, audit }, session: { birth, beforeCommit, afterCommit } },
29
32
  });
30
33
  await backend.ensureSchema(); // core's tables first
31
34
  const conn = await driver.connect();
@@ -38,10 +41,72 @@ try {
38
41
  ```
39
42
 
40
43
  - **The driver** carries how its connections are initialized and what the engine reported (`SqlDriver.facts`, and
41
- `SqlTxConn.facts` on each connection), and the one fail-open sink every read of the package reports through; a tag
42
- is one word of `SQL_FAIL_OPEN_TAGS`. The backend takes only a driver `createSqlDriver` made.
44
+ `SqlTxConn.facts` on each connection), and the one notice sink everything the package does on its own reports
45
+ through, the option `onSqlNotice` (not `onNotice`, the engine's own option's name, nor the older `onFailOpen`: each
46
+ is refused by name, saying the new one). The backend and the stores have no sink of their own: what they report goes
47
+ to the sink of the driver they were given. A notice is never an error and the call it happened in answers as
48
+ documented: it is a fail-open step (the package could not take a step — a read, a log line, a row it could not
49
+ decode, a hook of yours that threw after a commit — and went on with a documented default standing in), a self-heal
50
+ (it found a condition and repaired it) or a refusal that stands (it could not take a read it made to explain a
51
+ refusal: the refusal stays as it was, nothing stands in for the read); its tag is one key of `SQL_NOTICE_TAGS`, whose
52
+ value is that kind. A tag is `core-stores-sql.<driver | store | seat>.<what>`: `store.row-unreadable` is one tag for
53
+ every seat's store (a row it could not decode, answered as absent). What you route on beside the tag is a typed
54
+ member of the sink's third argument (`SqlNoticeFacts`), never a word read out of the detail: `seat`, the store seat
55
+ the step was taken for (`SqlNoticeSeat`, a member name of core's storage backend contract — `"sessionStore"`, …),
56
+ on every store's notice and absent on the driver's. A detail
57
+ never repeats a cell's content or an error's text. The tags are declared here; the driver and the stores mint them
58
+ when they move into this package. The backend takes only a driver
59
+ `createSqlDriver` made, and
60
+ `isSqlDriver(value)` answers whether a value is one — an object of the same shape is not. A statement's third
61
+ argument, `{ deadlineMs }`, is the longest it may run.
62
+ - **A refusal** of this package — any of its calls, at startup or later — is an `Error` whose `code` is one key of
63
+ `SQL_ERROR_CODES`; the table's value says whether repeating the same call can succeed (`transient`) or not until
64
+ something named changes (`terminal`). Read it with `sqlFaultOf(caught)`, which reads the `code` member and nothing
65
+ else, never the message: `sqlFaultOf(error)?.permanence === "terminal"` at startup is a refusal to start, not a
66
+ reason to retry — with one exception this version has: `schema.unchecked` (whether core's tables are there could not
67
+ be asked) is also the code of a connection error on that read, because the judge of the engines' own errors arrives
68
+ with the stores; to retry such a read, read the refusal's `cause` yourself.
43
69
  - **The hooks** (`SqlTransactionHooks`) are the only way a deployment's tables take part in the backend's
44
- transactions; each runs inside the transaction and gets its statement face only (`SqlStatementFace`).
70
+ transactions; each but `session.afterCommit` runs inside the transaction and gets its statement face only
71
+ (`SqlStatementFace`). The session hooks are told one closed vocabulary of writes (`SqlSessionWrite`): five to a
72
+ session tree's root row — `birth`, `import`, `delete`, `delete-unreadable` (an operator's delete of a row whose head
73
+ cannot be read), `retention-delete` —, a placed row being born and reaped with its tree; and `append`, a commit of
74
+ entries to a session's log, told for every session, a placed one included (`leafId` — the session's leaf once the
75
+ commit is in, `null` at the root —, `leafSeq` — the log's length then —, `owner` as the commit read it,
76
+ `incarnation`). An `import` replaces the log whole and carries the same `leafId` and `leafSeq`, meaning the same —
77
+ the leaf of the head its commit answers, and the imported log's entry count —: a reader of the leaf
78
+ resets at an `import` and takes the leaf it carries as its new starting point (an import whose `decide` answers
79
+ `"keep"` writes nothing and is told to no hook). The hooks:
80
+ - `session.birth` runs inside the transaction that creates a root row (a create, a fork — `forkedFrom` names the
81
+ source —, an import of an id with no row), after the row and the log it starts with are written and before the
82
+ commit;
83
+ - `session.beforeCommit` runs inside the transaction of a write that changes or removes a root row, with the row
84
+ locked (an import of an id with no row: before the row is created; an import: once its `decide` answered `"replace"`)
85
+ and before anything is written, and is told the row's occupant (`incarnation`; absent when the backend read
86
+ none — always on a `delete-unreadable`). One that refuses answers `{ refuse, code }` and what it sent is taken back:
87
+ an import, a delete or a delete of an unreadable row rejects with `core-stores-sql.hook.refused`, its sentence is
88
+ `refuse`, and `code` — yours, to route on — is the refusal's `hostCode`; a retention delete skips that session and
89
+ goes on with the others. An answer whose `refuse` or `code` is not a string is refused by name
90
+ (`options.invalid`), never carried with your code dropped;
91
+ - `session.afterCommit` runs after the commit, once per commit, with every session write it made in order (an
92
+ array), and no statement face; the call that made the commit — an append's included — answers after it has
93
+ settled. Appends are the hot path, so a hook that hangs hangs every append of every session: it must not wait on
94
+ anything the engine does (a call of the session store, a run, a turn).
95
+
96
+ In the transaction a hook is told each write, because it acts in that write's step; after the commit it is told the
97
+ commit. A caller hands its own opaque string with a write it starts: `callerContext` (`SqlSessionCall`), the last
98
+ argument of each writing method of the backend's session store (`backend.sessionStore`: `acquire`, `register`, `fork`,
99
+ `delete`, `deleteUnreadable`, `logTransfer.beginReplace`). The package never reads it and never stores it; it hands it,
100
+ as given, on that write to every hook told of it — `birth` and `beforeCommit` in the write's transaction,
101
+ `afterCommit` after its commit — per call, never per id. A retention delete and an append carry none: neither arm of
102
+ `SqlSessionWrite` has the member. So that `call` keeps its place, a parameter core adds to one of these six methods
103
+ goes into an options object the method takes, never in as one more positional parameter (giving `register`, `delete`
104
+ or `deleteUnreadable`, which take none today, their first would move it: a hard-breaking change, named so in its
105
+ release).
106
+
107
+ A hook inside the transaction that throws rolls the whole transaction back, and the call rejects with what it threw,
108
+ unwrapped (a refusal of this package your hook let through still reads as that refusal). An `afterCommit` that throws rolls nothing back (the writes are committed): the call answers as it would
109
+ have, and the driver's sink is told `core-stores-sql.session.after-commit-threw`.
45
110
  - **The schema** of core's tables is the package's: `ensureSchema()` creates, migrates and checks them under its own
46
111
  lock (`SQL_ENSURE_LOCK`), records the applied migrations in its own version table (`SQL_SCHEMA_VERSION_TABLE`) and
47
112
  answers a `SqlSchemaReport`. Your own ensure runs after it, starts with `assertCoreSchemaReady`, and uses a lock of
@@ -72,20 +137,42 @@ version moves with every core release whether or not this package changed.
72
137
 
73
138
  ## Exports
74
139
 
140
+ Two groups, one entry. Each name below is a value or a type exported from the package root.
141
+
142
+ ### Core's seats
143
+
75
144
  Neutral factories and neutral types only. No store class, no dialect class, no SQL statement list, no ensure leg and
76
145
  no SQL predicate generator is exported: the face hands out seats, not classes, and a caller that reached for one of
77
- those would be going around the neutral seam. Each name below is a value or a type exported from the package root.
146
+ those would be going around the neutral seam.
78
147
 
79
148
  | Group | Names |
80
149
  | --- | --- |
81
150
  | Backend | `createSqlStorageBackend` `SqlStorageBackend` `SqlStorageBackendOptions` `SqlSweepLeg` `SqlSweepReceipt` |
82
- | Hooks | `SqlTransactionHooks` `SqlStatementFace` `SqlRetentionOp` |
83
- | Driver | `createSqlDriver` `SqlDriver` `SqlTxConn` `SqlEngineFacts` `SqlWallSource` `PgPoolLike` `MysqlPoolLike` |
84
- | Fail-open | `SQL_FAIL_OPEN_TAGS` `SqlFailOpenTag` `SqlFailOpenSink` |
85
- | Words | `SqlDialect` `SqlEngine` |
151
+ | Hooks | `SqlTransactionHooks` `SqlRetentionOp` `SqlSessionWrite` `SqlSessionCall` |
86
152
  | Schema | `assertCoreSchemaReady` `SQL_ENSURE_LOCK` `SQL_SCHEMA_VERSION_TABLE` `SqlSchemaReport` `baselineDdl` `publishedColumns` `PublishedColumn` |
87
153
  | File history | `SqlBlobBytesPort` `SqlBlobKey` |
88
154
 
155
+ ### The SQL foundation
156
+
157
+ What your own stores are written over, for your own tables (never core's): one driver over your pool, the statement
158
+ face a connection gives, the words the driver speaks, its notices, and the refusal codes.
159
+
160
+ | Group | Names |
161
+ | --- | --- |
162
+ | Driver | `createSqlDriver` `isSqlDriver` `SqlDriver` `SqlTxConn` `SqlStatementFace` `SqlQueryOptions` `SqlResult` `SqlRow` `SqlEngineFacts` `SqlWallSource` `PgPoolLike` `MysqlPoolLike` |
163
+ | Words | `SqlDialect` `SqlEngine` |
164
+ | Notices | `SQL_NOTICE_TAGS` `SqlNoticeTag` `SqlNoticeKind` `SqlNoticeSink` `SqlNoticeFacts` `SqlNoticeSeat` |
165
+ | Refusals | `SQL_ERROR_CODES` `SqlErrorCode` `sqlFaultOf` |
166
+
167
+ This group only grows from 7.70.0 — the version it first ships in — until the stores arrive in this package: a name in it is not removed or renamed; a member it
168
+ has keeps its type, its optionality and its meaning; a type in it — the faces you implement or hand in (`SqlDriver`,
169
+ `SqlTxConn`, `SqlEngineFacts`, the two pool faces) among them — gains optional members only; a call gains optional
170
+ trailing arguments only; and a closed table (`SQL_NOTICE_TAGS`, `SQL_ERROR_CODES`) gains rows, a word set words, each
171
+ row keeping its value. Write your stores against these
172
+ types as published (`import type { … } from "@sema-agent/core-stores-sql"`), not a copy of them. Three more helpers
173
+ for your own stores — a judge of the engines' own errors, JSON column reads, an index-adding primitive — are not in
174
+ this version; they arrive with the stores.
175
+
89
176
  `SqlDialect` is which SQL text is written (`pg` or `mysql`; the caller says it). `SqlEngine` is which engine answered
90
177
  (`pg`, `innodb` or `tidb`; probed, never configured). `baselineDdl` is the statements a new database is sent, recorded
91
178
  by running the ensure legs; `publishedColumns` is the readable-column list. `PgPoolLike` and `MysqlPoolLike` are
package/dist/backend.d.ts CHANGED
@@ -9,15 +9,40 @@
9
9
  * refused by name, the driver last) and then refuses: no driver can be made yet, so the driver read refuses every
10
10
  * call, and a backend whose seats are missing is never returned.
11
11
  */
12
- import type { EngineStorageBackend, ManagedRetentionCapability } from "@sema-agent/core";
13
- import { type SqlStorageBackendOptions } from "./options.js";
12
+ import type { EngineStorageBackend, ManagedRetentionCapability, SessionLogTransfer, SessionStore } from "@sema-agent/core";
13
+ import { type SqlSessionCall, type SqlStorageBackendOptions } from "./options.js";
14
14
  import type { SqlSchemaReport } from "./schema.js";
15
15
  /** One leg of {@link SqlStorageBackend.sweep}: roster rows past their age, workflow journals past their retention,
16
16
  * file-history bytes no row references past the grace window, tool results past their age. */
17
17
  export type SqlSweepLeg = "roster-aged" | "workflow-journal-expired" | "file-history-orphan-blobs" | "tool-results-aged";
18
18
  /** What one sweep removed, per leg. */
19
19
  export type SqlSweepReceipt = Readonly<Record<SqlSweepLeg, number>>;
20
+ /** A writing method of core's session store, taking one more trailing argument: the caller's {@link SqlSessionCall}.
21
+ * So that it keeps its place, a parameter core adds to one of these six methods goes into an options object the method
22
+ * takes, never in as one more positional parameter; giving one with no options object today (`register`, `delete`,
23
+ * `deleteUnreadable`) its first would move it — a hard-breaking change of this store, named so in its release. */
24
+ type WithSessionCall<F> = F extends (...args: infer A) => infer R ? (...args: [...A, call?: SqlSessionCall]) => R : never;
25
+ /**
26
+ * The backend's session store: core's `SessionStore`, each writing method taking the caller's {@link SqlSessionCall} as
27
+ * its last argument, after core's own — `acquire` (of an id with no row: a birth), `register`, `fork`, `delete`,
28
+ * `deleteUnreadable` and the log transfer's `beginReplace` (an import). Its `callerContext` reaches the session hooks told
29
+ * of the write that call makes; a call that writes nothing hands it to no hook. A write no call of the store starts — a
30
+ * retention delete, an append — carries none. Reached as `SqlStorageBackend["sessionStore"]`: a seat's face, not a store
31
+ * class, so the package exports no name for it.
32
+ */
33
+ interface SqlSessionStore extends Omit<SessionStore, "acquire" | "register" | "fork" | "delete" | "deleteUnreadable" | "logTransfer"> {
34
+ acquire: WithSessionCall<SessionStore["acquire"]>;
35
+ register?: WithSessionCall<NonNullable<SessionStore["register"]>>;
36
+ fork?: WithSessionCall<NonNullable<SessionStore["fork"]>>;
37
+ delete?: WithSessionCall<NonNullable<SessionStore["delete"]>>;
38
+ deleteUnreadable?: WithSessionCall<NonNullable<SessionStore["deleteUnreadable"]>>;
39
+ readonly logTransfer?: Omit<SessionLogTransfer, "beginReplace"> & {
40
+ beginReplace: WithSessionCall<SessionLogTransfer["beginReplace"]>;
41
+ };
42
+ }
20
43
  export interface SqlStorageBackend extends EngineStorageBackend {
44
+ /** `RunnerDeps.sessionStore`: core's session store, each writing method taking the caller's {@link SqlSessionCall}. */
45
+ readonly sessionStore: SqlSessionStore;
21
46
  /** The managed-retention executor over this backend's tables (one transaction per call, across every seat). */
22
47
  readonly retention: ManagedRetentionCapability;
23
48
  /** Create the tables and indexes this backend owns, if absent, and run its registered migrations not yet applied —
@@ -30,3 +55,4 @@ export interface SqlStorageBackend extends EngineStorageBackend {
30
55
  }): Promise<SqlSweepReceipt>;
31
56
  }
32
57
  export declare function createSqlStorageBackend(opts: SqlStorageBackendOptions): SqlStorageBackend;
58
+ export {};
package/dist/backend.js CHANGED
@@ -5,5 +5,5 @@ export function createSqlStorageBackend(opts) {
5
5
  const entry = "createSqlStorageBackend";
6
6
  assertCoreVersion(entry);
7
7
  readBackendOptions(entry, opts);
8
- throw refusal(entry, "this version of the package carries no SQL stores — the options are valid, but a backend without its stores is not returned");
8
+ throw refusal("core-stores-sql.release.not-carried", entry, "this version of the package carries no SQL stores — the options are valid, but a backend without its stores is not returned");
9
9
  }
@@ -2,13 +2,13 @@ import { refusal } from "./refusal.js";
2
2
  const PORT_MEMBERS = Object.freeze(["put", "get", "delete"]);
3
3
  export function readBlobBytesPort(entry, where, value) {
4
4
  if (typeof value !== "object" || value === null)
5
- throw refusal(entry, `${where} must be an object with put / get / delete (got ${value === null ? "null" : typeof value})`);
5
+ throw refusal("core-stores-sql.options.invalid", entry, `${where} must be an object with put / get / delete (got ${value === null ? "null" : typeof value})`);
6
6
  const port = value;
7
7
  const missing = PORT_MEMBERS.filter((m) => typeof port[m] !== "function");
8
8
  if (missing.length > 0)
9
- throw refusal(entry, `${where} has no ${missing.map((m) => `${m}()`).join(" / ")} — a byte port puts, gets and deletes`);
9
+ throw refusal("core-stores-sql.options.invalid", entry, `${where} has no ${missing.map((m) => `${m}()`).join(" / ")} — a byte port puts, gets and deletes`);
10
10
  if (port["list"] !== undefined && typeof port["list"] !== "function")
11
- throw refusal(entry, `${where}.list must be a function when given (got ${port["list"] === null ? "null" : typeof port["list"]})`);
11
+ throw refusal("core-stores-sql.options.invalid", entry, `${where}.list must be a function when given (got ${port["list"] === null ? "null" : typeof port["list"]})`);
12
12
  return value;
13
13
  }
14
14
  export const BLOB_TRANSITIONS = Object.freeze([
@@ -40,7 +40,7 @@ export async function recordBaseline(dialect, roster) {
40
40
  const names = new Set();
41
41
  for (const leg of legs) {
42
42
  if (names.has(leg.name))
43
- throw refusal(entry, `the ${dialect} ensure roster names "${leg.name}" twice — a leg's name is its identity`);
43
+ throw refusal("core-stores-sql.package.defect", entry, `the ${dialect} ensure roster names "${leg.name}" twice — a leg's name is its identity`);
44
44
  names.add(leg.name);
45
45
  }
46
46
  const recorded = [];
@@ -57,7 +57,7 @@ export async function recordBaseline(dialect, roster) {
57
57
  if (LOCK_RE.test(statement) || SELECT_RE.test(statement))
58
58
  continue;
59
59
  if (!BASELINE_RE.test(statement)) {
60
- throw refusal(entry, `an ensure leg (${dialect}) sent a statement that is neither CREATE nor INSERT — ${statement.replace(/\s+/g, " ").slice(0, 200)} — a table is changed by changing its CREATE, not by an incremental seam`);
60
+ throw refusal("core-stores-sql.package.defect", entry, `an ensure leg (${dialect}) sent a statement that is neither CREATE nor INSERT — ${statement.replace(/\s+/g, " ").slice(0, 200)} — a table is changed by changing its CREATE, not by an incremental seam`);
61
61
  }
62
62
  baseline.push(statement.replace(/;\s*$/, ""));
63
63
  }
package/dist/driver.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { type SqlFailOpenSink } from "./fail-open.js";
1
+ import { type SqlNoticeSink } from "./notice.js";
2
2
  declare const SQL_DIALECTS: readonly ["pg", "mysql"];
3
3
  /** The SQL text family the stores write in: `"pg"` (PostgreSQL) or `"mysql"` (the MySQL protocol family, TiDB included). */
4
4
  export type SqlDialect = (typeof SQL_DIALECTS)[number];
5
5
  /** The engine a driver found behind the pool: PostgreSQL, InnoDB (MySQL / MariaDB) or TiDB. Probed, never configured. */
6
6
  export type SqlEngine = "pg" | "innodb" | "tidb";
7
7
  /** Where a wall's number came from: `"reported"` = the engine answered it; `"assumed"` = the engine's documented
8
- * default stood in because the read could not be taken (a fail-open read, reported through the driver's sink). */
8
+ * default stood in because the read could not be taken (a fail-open read, told to the driver's notice sink). */
9
9
  export type SqlWallSource = "reported" | "assumed";
10
10
  /**
11
11
  * What the driver found about the engine when it initialized a connection. Read, never configured: the caller states
@@ -60,14 +60,24 @@ export interface MysqlPoolLike {
60
60
  query(sql: string, values?: unknown[]): Promise<unknown>;
61
61
  getConnection(): Promise<MysqlConnectionLike>;
62
62
  }
63
- interface SqlResult {
64
- rows: Record<string, unknown>[];
63
+ /** One row a statement answered: column name → value, as the pool's driver decoded it. */
64
+ export type SqlRow = Record<string, unknown>;
65
+ /** What a statement answered, the same shape over both dialects. */
66
+ export interface SqlResult {
67
+ rows: SqlRow[];
65
68
  /** Rows an INSERT / UPDATE / DELETE touched; 0 for a SELECT. */
66
69
  affected: number;
67
70
  }
71
+ /** How one statement is sent. */
72
+ export interface SqlQueryOptions {
73
+ /** The longest the statement may run, in milliseconds, counted from when it is sent — a positive integer. Past it the
74
+ * call rejects with `core-stores-sql.statement.deadline` (transient); a value that is not a positive integer is
75
+ * refused, `core-stores-sql.options.invalid`. Absent = the call sets no deadline of its own. */
76
+ readonly deadlineMs?: number;
77
+ }
68
78
  /** One pooled connection with transaction control, released by its borrower. `begin()` is the one transaction verb. */
69
79
  export interface SqlTxConn {
70
- query(sql: string, params?: unknown[]): Promise<SqlResult>;
80
+ query(sql: string, params?: unknown[], opts?: SqlQueryOptions): Promise<SqlResult>;
71
81
  begin(): Promise<void>;
72
82
  commit(): Promise<void>;
73
83
  rollback(): Promise<void>;
@@ -83,28 +93,33 @@ export interface SqlDriver {
83
93
  * initialization was refused. An admission check with no connection in hand reads this one; the same wall judgment
84
94
  * runs again on {@link SqlTxConn.facts} of the connection that writes — one judgment, read twice, not two readings. */
85
95
  readonly facts: SqlEngineFacts | null;
86
- query(sql: string, params?: unknown[]): Promise<SqlResult>;
96
+ query(sql: string, params?: unknown[], opts?: SqlQueryOptions): Promise<SqlResult>;
87
97
  connect(): Promise<SqlTxConn>;
88
98
  }
99
+ /** Whether `value` is a driver {@link createSqlDriver} made. An object of the same shape is not one: the answer is the
100
+ * package's record of the drivers it made, which no copy of a driver's members carries. */
101
+ export declare function isSqlDriver(value: unknown): value is SqlDriver;
89
102
  /** The one reading of a driver handed to the backend: present, and one {@link createSqlDriver} made. */
90
103
  export declare function readDriver(entry: string, value: unknown): SqlDriver;
91
104
  /** The one reading of a dialect word. Any other value — `"tidb"` included — is refused by name. */
92
105
  export declare function readDialect(entry: string, value: unknown): SqlDialect;
93
106
  /** The pool, read against the face its dialect needs: a pool missing a member the driver calls is refused by name. */
94
107
  export declare function readPool(entry: string, dialect: SqlDialect, value: unknown): PgPoolLike | MysqlPoolLike;
95
- /** Refuse any key outside `allowed`: a misspelled option must not be read as an absent one. */
96
- export declare function refuseUnknownKeys(entry: string, where: string, value: Record<string, unknown>, allowed: readonly string[]): void;
108
+ /** Refuse any key outside `allowed`: a misspelled option must not be read as an absent one. A key in `renamed` is one this
109
+ * package had under that name — the sentence says the name it has now (the package's own words, never the caller's). */
110
+ export declare function refuseUnknownKeys(entry: string, where: string, value: Record<string, unknown>, allowed: readonly string[], renamed?: Readonly<Record<string, string>>): void;
97
111
  /** Read a factory's options argument as a record, or refuse. */
98
112
  export declare function readRecord(entry: string, where: string, value: unknown): Record<string, unknown>;
99
113
  /**
100
114
  * The SQL driver over one pool: `dialect` is which SQL text the stores write, `pool` is the caller's pool of that
101
- * dialect (borrowed, never ended), and `onFailOpen` is told once per fail-open read the package takes — the driver's
102
- * and every store's. In this version the package carries no driver: the options are read (version, dialect, pool,
103
- * sink — each refused by name when wrong) and then the call refuses, rather than return a driver that cannot run.
115
+ * dialect (borrowed, never ended), and `onSqlNotice` is told once per notice the package gives — the driver's and
116
+ * every store's, a fail-open read, a self-heal or a refusal that stands ({@link SqlNoticeSink}). In this version the
117
+ * package carries no driver: the options are read (version, dialect, pool, sink — each refused by name when wrong) and
118
+ * then the call refuses (`core-stores-sql.release.not-carried`), rather than return a driver that cannot run.
104
119
  */
105
120
  export declare function createSqlDriver(opts: {
106
121
  dialect: SqlDialect;
107
122
  pool: PgPoolLike | MysqlPoolLike;
108
- onFailOpen?: SqlFailOpenSink;
123
+ onSqlNotice?: SqlNoticeSink;
109
124
  }): SqlDriver;
110
125
  export {};
package/dist/driver.js CHANGED
@@ -1,51 +1,56 @@
1
1
  import { assertCoreVersion } from "./version-check.js";
2
2
  import { refusal } from "./refusal.js";
3
3
  import { callerKey, callerText } from "@sema-agent/core";
4
- import { readFailOpenSink } from "./fail-open.js";
4
+ import { readNoticeSink } from "./notice.js";
5
5
  const SQL_DIALECTS = Object.freeze(["pg", "mysql"]);
6
6
  const MADE_DRIVERS = new WeakSet();
7
+ export function isSqlDriver(value) {
8
+ return typeof value === "object" && value !== null && MADE_DRIVERS.has(value);
9
+ }
7
10
  export function readDriver(entry, value) {
8
11
  if (value === undefined)
9
- throw refusal(entry, "driver is required — the driver createSqlDriver made over your pool (one pool, one driver: hand the same one to your own stores)");
12
+ throw refusal("core-stores-sql.options.invalid", entry, "driver is required — the driver createSqlDriver made over your pool (one pool, one driver: hand the same one to your own stores)");
10
13
  if (typeof value !== "object" || value === null)
11
- throw refusal(entry, `driver must be the object createSqlDriver returned (got ${value === null ? "null" : typeof value})`);
12
- if (!MADE_DRIVERS.has(value))
13
- throw refusal(entry, "options.driver was not made by createSqlDriver — an object of the same shape cannot vouch for how its connections were initialized");
14
+ throw refusal("core-stores-sql.options.invalid", entry, `driver must be the object createSqlDriver returned (got ${value === null ? "null" : typeof value})`);
15
+ if (!isSqlDriver(value))
16
+ throw refusal("core-stores-sql.options.invalid", entry, "options.driver was not made by createSqlDriver — an object of the same shape cannot vouch for how its connections were initialized");
14
17
  return value;
15
18
  }
16
19
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17
20
  export function readDialect(entry, value) {
18
21
  if (typeof value === "string" && SQL_DIALECTS.includes(value))
19
22
  return value;
20
- throw refusal(entry, `dialect must be one of ${SQL_DIALECTS.map((d) => JSON.stringify(d)).join(" | ")} (got ${callerText(value)}); TiDB, MySQL and MariaDB are all "mysql"`);
23
+ throw refusal("core-stores-sql.options.invalid", entry, `dialect must be one of ${SQL_DIALECTS.map((d) => JSON.stringify(d)).join(" | ")} (got ${callerText(value)}); TiDB, MySQL and MariaDB are all "mysql"`);
21
24
  }
22
25
  const POOL_MEMBERS = Object.freeze({ pg: Object.freeze(["query", "connect"]), mysql: Object.freeze(["query", "getConnection"]) });
23
26
  export function readPool(entry, dialect, value) {
24
27
  if (typeof value !== "object" || value === null)
25
- throw refusal(entry, `pool is required — a ${dialect === "pg" ? "node-postgres" : "mysql2 promise"} pool (got ${value === null ? "null" : typeof value})`);
28
+ throw refusal("core-stores-sql.options.invalid", entry, `pool is required — a ${dialect === "pg" ? "node-postgres" : "mysql2 promise"} pool (got ${value === null ? "null" : typeof value})`);
26
29
  const missing = POOL_MEMBERS[dialect].filter((m) => typeof value[m] !== "function");
27
30
  if (missing.length > 0) {
28
- throw refusal(entry, `pool has no ${missing.map((m) => `${m}()`).join(" / ")}, which a ${JSON.stringify(dialect)} pool must have — is it a pool of the other dialect?`);
31
+ throw refusal("core-stores-sql.options.invalid", entry, `pool has no ${missing.map((m) => `${m}()`).join(" / ")}, which a ${JSON.stringify(dialect)} pool must have — is it a pool of the other dialect?`);
29
32
  }
30
33
  return value;
31
34
  }
32
- export function refuseUnknownKeys(entry, where, value, allowed) {
35
+ export function refuseUnknownKeys(entry, where, value, allowed, renamed = {}) {
33
36
  const unknown = Object.keys(value).filter((k) => !allowed.includes(k));
37
+ const now = unknown.filter((k) => Object.hasOwn(renamed, k)).map((k) => `${k} is now ${renamed[k]}`);
34
38
  if (unknown.length > 0)
35
- throw refusal(entry, `${where} carries ${unknown.map((k) => callerKey(k)).join(", ")}, which ${unknown.length === 1 ? "is" : "are"} not ${where === "options" ? "an option" : "a member"} of this version (known: ${allowed.join(", ")})`);
39
+ throw refusal("core-stores-sql.options.invalid", entry, `${where} carries ${unknown.map((k) => callerKey(k)).join(", ")}, which ${unknown.length === 1 ? "is" : "are"} not ${where === "options" ? "an option" : "a member"} of this version (known: ${allowed.join(", ")})${now.length > 0 ? ` — ${now.join(", ")}` : ""}`);
36
40
  }
37
41
  export function readRecord(entry, where, value) {
38
42
  if (!isObject(value))
39
- throw refusal(entry, `${where} must be an object (got ${value === null ? "null" : Array.isArray(value) ? "an array" : typeof value})`);
43
+ throw refusal("core-stores-sql.options.invalid", entry, `${where} must be an object (got ${value === null ? "null" : Array.isArray(value) ? "an array" : typeof value})`);
40
44
  return value;
41
45
  }
42
- const DRIVER_OPTION_KEYS = Object.freeze(["dialect", "pool", "onFailOpen"]);
46
+ const DRIVER_OPTION_KEYS = Object.freeze(["dialect", "pool", "onSqlNotice"]);
47
+ const RENAMED_DRIVER_OPTIONS = Object.freeze({ onFailOpen: "onSqlNotice", onNotice: "onSqlNotice" });
43
48
  export function createSqlDriver(opts) {
44
49
  const entry = "createSqlDriver";
45
50
  assertCoreVersion(entry);
46
51
  const record = readRecord(entry, "options", opts);
47
- refuseUnknownKeys(entry, "options", record, DRIVER_OPTION_KEYS);
52
+ refuseUnknownKeys(entry, "options", record, DRIVER_OPTION_KEYS, RENAMED_DRIVER_OPTIONS);
48
53
  readPool(entry, readDialect(entry, record["dialect"]), record["pool"]);
49
- readFailOpenSink(entry, record["onFailOpen"]);
50
- throw refusal(entry, "this version of the package carries no SQL driver — the options are valid, but there is no driver to return");
54
+ readNoticeSink(entry, record["onSqlNotice"]);
55
+ throw refusal("core-stores-sql.release.not-carried", entry, "this version of the package carries no SQL driver — the options are valid, but there is no driver to return");
51
56
  }
package/dist/index.d.ts CHANGED
@@ -1,14 +1,17 @@
1
1
  /**
2
- * `@sema-agent/core-stores-sql` — core's storage seats over PostgreSQL and the MySQL protocol family.
2
+ * `@sema-agent/core-stores-sql` — core's storage seats over PostgreSQL and the MySQL protocol family, and the SQL
3
+ * foundation a deployment's own stores are written over.
3
4
  *
4
- * The public face is neutral factories, neutral types and the closed sets a deployment reads: no store class, no
5
- * dialect class, no statement list, no ensure leg is exported. A caller makes one driver over its pool and gets
6
- * core's seats back from a backend over that driver.
5
+ * Two groups, one entry. Core's seats: neutral factories, neutral types and the closed sets a deployment reads — no
6
+ * store class, no dialect class, no statement list, no ensure leg is exported; a caller gets core's seats back from a
7
+ * backend over a driver. The SQL foundation: the driver a deployment makes once over its pool and hands to the backend
8
+ * and to its own stores, the words it speaks, its notices, and the codes every refusal of this package carries.
7
9
  */
8
10
  export { createSqlStorageBackend, type SqlStorageBackend, type SqlSweepLeg, type SqlSweepReceipt } from "./backend.js";
9
- export type { SqlRetentionOp, SqlStatementFace, SqlStorageBackendOptions, SqlTransactionHooks } from "./options.js";
10
- export { createSqlDriver, type MysqlPoolLike, type PgPoolLike, type SqlDialect, type SqlDriver, type SqlEngine, type SqlEngineFacts, type SqlTxConn, type SqlWallSource, } from "./driver.js";
11
- export { SQL_FAIL_OPEN_TAGS, type SqlFailOpenSink, type SqlFailOpenTag } from "./fail-open.js";
11
+ export type { SqlRetentionOp, SqlSessionCall, SqlSessionWrite, SqlStatementFace, SqlStorageBackendOptions, SqlTransactionHooks } from "./options.js";
12
+ export { createSqlDriver, isSqlDriver, type MysqlPoolLike, type PgPoolLike, type SqlDialect, type SqlDriver, type SqlEngine, type SqlEngineFacts, type SqlQueryOptions, type SqlResult, type SqlRow, type SqlTxConn, type SqlWallSource, } from "./driver.js";
13
+ export { SQL_NOTICE_TAGS, type SqlNoticeFacts, type SqlNoticeKind, type SqlNoticeSeat, type SqlNoticeSink, type SqlNoticeTag } from "./notice.js";
14
+ export { SQL_ERROR_CODES, sqlFaultOf, type SqlErrorCode } from "./refusal.js";
12
15
  export type { SqlBlobBytesPort, SqlBlobKey } from "./blob-index.js";
13
16
  export { assertCoreSchemaReady, SQL_ENSURE_LOCK, SQL_SCHEMA_VERSION_TABLE, type SqlSchemaReport } from "./schema.js";
14
17
  export { baselineDdl } from "./ddl-recorder.js";
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export { createSqlStorageBackend } from "./backend.js";
2
- export { createSqlDriver, } from "./driver.js";
3
- export { SQL_FAIL_OPEN_TAGS } from "./fail-open.js";
2
+ export { createSqlDriver, isSqlDriver, } from "./driver.js";
3
+ export { SQL_NOTICE_TAGS } from "./notice.js";
4
+ export { SQL_ERROR_CODES, sqlFaultOf } from "./refusal.js";
4
5
  export { assertCoreSchemaReady, SQL_ENSURE_LOCK, SQL_SCHEMA_VERSION_TABLE } from "./schema.js";
5
6
  export { baselineDdl } from "./ddl-recorder.js";
6
7
  export { publishedColumns } from "./published-columns.js";
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The package's one notice sink and the closed table of what it can be told.
3
+ *
4
+ * A notice is something the package did on its own that a deployment should know about and that the call it happened
5
+ * in does not report — not an error, never thrown: the call answers as its documentation says. It is one of three
6
+ * kinds ({@link SqlNoticeKind}): a FAIL-OPEN step, one the package took and, when it could not, went on past with a
7
+ * documented default standing in (a wall the engine would not report, a log line it could not write, a stored row it
8
+ * could not decode, a deployment's after-commit hook that threw); a SELF-HEAL, a condition the package found and
9
+ * repaired by itself; or a REFUSAL-STANDS, a read the package made to explain a refusal and could not take — the
10
+ * refusal it was about to give stands as it was, nothing stands in for the missing read, and nothing was repaired.
11
+ * Every notice — the driver's, the backend's and every store's — is told to ONE sink, the one the deployment hands
12
+ * {@link import("./driver.js").createSqlDriver} as `onSqlNotice`: one pool, one driver, one sink; the backend takes no
13
+ * sink of its own, it tells the sink of the driver it was given. The tag says which notice it is and the table says its
14
+ * kind; tags are a closed set, so a deployment can route each one, and a tag added is a change it is told about, not
15
+ * one it finds in a broken dashboard. A `detail` names where and what — a table, a row's key, a value's kind — and never
16
+ * repeats a value the package did not write (a cell's content, a database's or a deployment's error text). What a
17
+ * deployment routes on beside the tag is a typed member of the notice's third argument ({@link SqlNoticeFacts}), never a
18
+ * word it would read out of the detail: `seat`, the store seat the step was taken for.
19
+ *
20
+ * A tag is `core-stores-sql.<driver | store | seat>.<what>`: `driver` for the driver's own steps, `store` for a step
21
+ * every seat's store takes alike (one tag, the seat in `facts.seat` — not one tag per seat), and a seat's word for a
22
+ * step only that seat takes. What a call did is its answer, never a notice: a sweep's receipt, an ensure's
23
+ * report. This version declares the driver's five — three fail-open reads, the self-heal of a connection whose packet
24
+ * wall was below the engine's (the driver closes it and judges a new one, past the wall), and the refusal-stands read
25
+ * of the global packet wall on the connection that was refused —, the stores' one: `store.row-unreadable`, a row a
26
+ * store read and could not decode, answered as absent (the read-back posture "an absence that discloses"; a store that
27
+ * refuses such a row instead throws, and tells nothing here), and the session seat's one: `session.after-commit-threw`,
28
+ * a deployment's after-commit hook that threw, the commit's writes standing committed. The driver and the stores mint them when
29
+ * they move into the package; today the table is their declaration. A step a store takes that no tag here names brings its tag into
30
+ * the table in the commit that moves the store in.
31
+ */
32
+ import type { EngineStorageBackend } from "@sema-agent/core";
33
+ /** A store seat of core's storage backend contract, by its member's name (`"sessionStore"`, `"checkpointStore"`, …): every
34
+ * member but the retention executor and the release. A seat's own tags carry its word — the name without `Store`, in
35
+ * kebab case (`sessionStore` → `session`). */
36
+ export type SqlNoticeSeat = Exclude<keyof EngineStorageBackend, "retention" | "dispose">;
37
+ /** The typed members of a notice beside its sentence. `seat`: the store seat the step was taken for — on every store's
38
+ * notice; absent ⇔ the driver's own step. */
39
+ export interface SqlNoticeFacts {
40
+ readonly seat?: SqlNoticeSeat;
41
+ }
42
+ /** What a notice is: a step that could not be taken and was gone past with a documented default standing in
43
+ * (`fail-open`), a condition the package repaired (`self-heal`), or a read for a refusal that could not be taken, the
44
+ * refusal standing as it was (`refusal-stands`). */
45
+ export type SqlNoticeKind = "fail-open" | "self-heal" | "refusal-stands";
46
+ /** Every tag the notice sink can be told, each with its kind, in one frozen table. */
47
+ export declare const SQL_NOTICE_TAGS: Readonly<{
48
+ readonly "core-stores-sql.driver.packet-wall-log-unwritten": "fail-open";
49
+ readonly "core-stores-sql.driver.tidb-row-cap-unread": "fail-open";
50
+ readonly "core-stores-sql.driver.packet-cap-unread": "fail-open";
51
+ readonly "core-stores-sql.driver.packet-wall-healed": "self-heal";
52
+ readonly "core-stores-sql.driver.packet-wall-global-unread": "refusal-stands";
53
+ /** A row a store read and could not decode — a cell of a shape its column never holds, a payload that does not parse —
54
+ * answered as absent (not listed, not counted, not handed out). `facts.seat`: the store's seat; `detail`: the table,
55
+ * the row's key and which cell could not be read, as its kind — never its content. */
56
+ readonly "core-stores-sql.store.row-unreadable": "fail-open";
57
+ /** A deployment's `transactionHooks.session.afterCommit` threw or rejected: the commit's writes stay committed and the
58
+ * call answers as it would have. `facts.seat`: `"sessionStore"`; `detail`: how many writes the commit made and of
59
+ * which ops, and the thrown value's kind — never its text. */
60
+ readonly "core-stores-sql.session.after-commit-threw": "fail-open";
61
+ }>;
62
+ /** A notice the package gives: one key of {@link SQL_NOTICE_TAGS}. */
63
+ export type SqlNoticeTag = keyof typeof SQL_NOTICE_TAGS;
64
+ /** The sink told once per notice: `tag` names it (its kind is `SQL_NOTICE_TAGS[tag]`), `detail` says what happened —
65
+ * for a fail-open read, what stood in for it; for a refusal-stands read, which read could not be taken —, and `facts`
66
+ * holds its typed members ({@link SqlNoticeFacts}); the package passes it with every notice (`{}` on a driver's). A
67
+ * trailing parameter of the frozen group is optional, so a sink of two parameters still fits. */
68
+ export type SqlNoticeSink = (tag: SqlNoticeTag, detail: string, facts?: SqlNoticeFacts) => void;
69
+ /** The sink option, read: absent, or a function. */
70
+ export declare function readNoticeSink(entry: string, value: unknown): SqlNoticeSink | undefined;
package/dist/notice.js ADDED
@@ -0,0 +1,17 @@
1
+ import { refusal } from "./refusal.js";
2
+ export const SQL_NOTICE_TAGS = Object.freeze({
3
+ "core-stores-sql.driver.packet-wall-log-unwritten": "fail-open",
4
+ "core-stores-sql.driver.tidb-row-cap-unread": "fail-open",
5
+ "core-stores-sql.driver.packet-cap-unread": "fail-open",
6
+ "core-stores-sql.driver.packet-wall-healed": "self-heal",
7
+ "core-stores-sql.driver.packet-wall-global-unread": "refusal-stands",
8
+ "core-stores-sql.store.row-unreadable": "fail-open",
9
+ "core-stores-sql.session.after-commit-threw": "fail-open",
10
+ });
11
+ export function readNoticeSink(entry, value) {
12
+ if (value === undefined)
13
+ return undefined;
14
+ if (typeof value !== "function")
15
+ throw refusal("core-stores-sql.options.invalid", entry, `onSqlNotice must be a function when given (got ${value === null ? "null" : typeof value})`);
16
+ return value;
17
+ }
package/dist/options.d.ts CHANGED
@@ -7,11 +7,12 @@
7
7
  * before it.
8
8
  *
9
9
  * A deployment takes part in the backend's transactions through one closed table of hooks
10
- * ({@link SqlTransactionHooks}); each hook runs inside the backend's transaction, on the connection that transaction
11
- * holds, and gets its statement face only — the transaction is the backend's to commit or roll back. A hook sends
12
- * statements and nothing else: a side effect outside the database (a directory, an object) is recorded as a row of
13
- * the deployment's own in the same transaction and carried out by the deployment after the commit, so a rollback
14
- * takes it back.
10
+ * ({@link SqlTransactionHooks}); each hook but one runs inside the backend's transaction, on the connection that
11
+ * transaction holds, and gets its statement face only — the transaction is the backend's to commit or roll back. A hook
12
+ * inside the transaction sends statements and nothing else: a side effect outside the database (a directory, an
13
+ * object) is recorded as a row of the deployment's own in the same transaction and carried out by the deployment after
14
+ * the commit, so a rollback takes it back. The one hook outside it, `session.afterCommit`, is that "after the commit":
15
+ * it is told a commit's session writes once the database has acknowledged it; the row is what survives its failure.
15
16
  */
16
17
  import { type ManagedRetentionCapability, type RetentionDeclaration, type RetentionReceipt } from "@sema-agent/core";
17
18
  import { type SqlDriver, type SqlTxConn } from "./driver.js";
@@ -20,15 +21,116 @@ import { type SqlBlobBytesPort } from "./blob-index.js";
20
21
  export type SqlStatementFace = Pick<SqlTxConn, "query">;
21
22
  /** The destructive retention calls a hook is told about — the executor's members that delete. */
22
23
  export type SqlRetentionOp = Exclude<keyof ManagedRetentionCapability, "listRetentionDomains">;
24
+ /**
25
+ * What a caller hands the package's session store with a write it starts — the last argument of each of the store's
26
+ * writing methods (the `sessionStore` of {@link import("./backend.js").SqlStorageBackend}). `callerContext` is opaque: the package never reads
27
+ * it, never stores it (no table of the backend's has a place for it, and no read gives it back), and hands it, as it was
28
+ * given, on that write to every session hook told of it ({@link SqlSessionWrite}) — inside the write's own transaction
29
+ * to `birth` and `beforeCommit`, after its commit to `afterCommit`. It rides
30
+ * the call, never the id: two concurrent calls for one id each hand their hooks their own. Absent ⇒ the caller handed
31
+ * none. A `callerContext` that is not a string, or a key this version has no member for, is refused by name
32
+ * (`core-stores-sql.options.invalid`) before anything is written — its value never repeated.
33
+ */
34
+ export interface SqlSessionCall {
35
+ readonly callerContext?: string;
36
+ }
37
+ /**
38
+ * One write of the backend's to a session, as the session hooks are told it — closed by `op`. The first five are writes
39
+ * to a session tree's ROOT row:
40
+ * - `"birth"`: a root row was created — a create (`acquire` of an id with no row, `register`), a fork (`forkedFrom`:
41
+ * the source row and the occupant it had when the fork copied it), or an import of an id with no row. `incarnation` is
42
+ * the occupant the row was born with;
43
+ * - `"import"`: an import's commit that replaces a root row's log — its `decide` answered `"replace"`; a `"keep"` writes
44
+ * nothing and is no write (an id with no row is also a `"birth"`, made after it);
45
+ * - `"delete"`: an owner's delete (`SessionStore.delete`);
46
+ * - `"delete-unreadable"`: an operator's delete of a row whose head cannot be read (`SessionStore.deleteUnreadable`);
47
+ * - `"retention-delete"`: the managed-retention executor's delete of an expired session (`deleteExpiredSessions`).
48
+ * On the four that are not a birth, `incarnation` is the row's occupant as the backend read it with the row locked;
49
+ * absent ⇒ the backend read none (an id with no row yet, a row written before occupants, and always on a
50
+ * `"delete-unreadable"`: a row whose head cannot be read names no occupant) — the deployment then acts on every occupant
51
+ * it holds for the id. `callerContext` is the {@link SqlSessionCall} of the call that started the write, verbatim;
52
+ * absent ⇒ none was handed. A retention delete has no caller to hand one — the executor starts it, not a call of the
53
+ * store's —, so the `"retention-delete"` arm has no such member. A placed row (a subagent's, inside its
54
+ * parent's tree) is no root: it is born and reaped with its tree, and no root-row write is told of it. The fork's own
55
+ * judgments (the target id, a source that is not there) are the session store's and come first: a fork refused is no
56
+ * birth.
57
+ *
58
+ * The sixth is a write to a session's LOG, told for every session — a placed one included:
59
+ * - `"append"`: a commit of entries appended to `sessionId`'s log. `leafId` is the session's leaf once the commit is in
60
+ * (`getLeafId()`: the entry it was left on — not always the last appended, since a leaf entry moves it to an earlier
61
+ * entry or to `null`, the root) and `leafSeq` the log's length once the commit is in — its `SessionLogMark` — so
62
+ * within one occupant (`incarnation`, as on the root-row writes) and between imports it only grows, and a reader that
63
+ * has seen a higher one can drop a lower one. `owner` is the session row's owner as the commit read it (`null`:
64
+ * anonymous). An append is started by the session it appends to, not by a call of the store's, so it carries no
65
+ * `callerContext`.
66
+ *
67
+ * An `"import"` replaces a log whole, so it carries the same `leafId` and `leafSeq`, meaning the same: the session's leaf
68
+ * and its log's length once the import's commit is in — the `leafId` of the head that commit answers (core's
69
+ * `SessionLogReplace.commit`), and the imported log's entry count (`beforeCommit`, told it after `decide` and before the write, is told them as what the commit
70
+ * leaves). Its `leafSeq` may be lower than an append's before it: a reader of the leaf resets at an `"import"` and
71
+ * takes the leaf it carries as its new starting point. A `"leafId" in write` test admits an import as well as an append:
72
+ * narrow on `op`.
73
+ */
74
+ export type SqlSessionWrite = {
75
+ readonly op: "birth";
76
+ readonly rootSessionId: string;
77
+ readonly incarnation: string;
78
+ readonly forkedFrom?: {
79
+ readonly sessionId: string;
80
+ readonly incarnation?: string;
81
+ };
82
+ readonly callerContext?: string;
83
+ } | {
84
+ readonly op: "import";
85
+ readonly rootSessionId: string;
86
+ readonly incarnation?: string;
87
+ readonly leafId: string | null;
88
+ readonly leafSeq: number;
89
+ readonly callerContext?: string;
90
+ } | {
91
+ readonly op: "delete" | "delete-unreadable";
92
+ readonly rootSessionId: string;
93
+ readonly incarnation?: string;
94
+ readonly callerContext?: string;
95
+ } | {
96
+ readonly op: "retention-delete";
97
+ readonly rootSessionId: string;
98
+ readonly incarnation?: string;
99
+ } | {
100
+ readonly op: "append";
101
+ readonly sessionId: string;
102
+ readonly incarnation?: string;
103
+ readonly leafId: string | null;
104
+ readonly leafSeq: number;
105
+ readonly owner: string | null;
106
+ };
23
107
  /**
24
108
  * Where a deployment's tables take part in the backend's transactions. Closed: each group and each hook is named
25
109
  * here, and any other key is refused.
26
110
  *
111
+ * One rule for a hook that throws (or rejects): a hook inside the transaction — every hook but `session.afterCommit` —
112
+ * that throws: the backend rolls the whole transaction back and the call rejects with what the hook threw, as it threw it
113
+ * (not wrapped: a refusal of this package the hook let through — a statement of its past its deadline — reads as that
114
+ * refusal through `sqlFaultOf`, anything else is the deployment's own to read; a hook that wants the session `conflict` a
115
+ * writer retries throws that `SessionError` itself). For a retention call that is the whole call: no session of it is
116
+ * deleted. A hook that REFUSES (`session.beforeCommit`'s `{ refuse, code }`) has what it sent taken back with the refusal:
117
+ * the transaction of an import, a delete or a delete of an unreadable row is rolled back; a retention candidate's `beforeCommit` runs under a
118
+ * savepoint of the backend's, rolled back to on a refusal, so the candidate is skipped and the others go on. A `session.afterCommit` that throws: nothing is rolled back
119
+ * (the writes are committed), the call answers as it would have, and the driver's sink is told
120
+ * `core-stores-sql.session.after-commit-threw` (fail-open) — the detail names how many writes the commit made and of which
121
+ * ops, and the thrown value's kind, never its text.
122
+ *
123
+ * One grain for the session hooks: a hook inside the transaction is told each write as the backend makes it, because it
124
+ * acts in that write's step (its rows go in with the write; a refusal takes back that write alone); the hook after the
125
+ * commit is told the commit — every session write it made, in order, in one call —, because what it does follows the
126
+ * commit, not a write.
127
+ *
27
128
  * A destructive retention transaction runs, in order: `holdLock` → the backend locks its candidates (`FOR UPDATE`,
28
129
  * each candidate's session row included) → `session.beforeCommit` for each candidate session
29
130
  * (`deleteExpiredSessions` only) → `liveReferences` over the candidates left → `beforeDelete` over the final set (the
30
131
  * candidates minus the refused minus the referenced) → the backend deletes its rows and writes its tombstones →
31
- * `audit` → commit. A session no hook lets go is in no later hook's input.
132
+ * `audit` → commit → `session.afterCommit` once, with every session deleted. A session no hook lets go is in no later
133
+ * hook's input.
32
134
  */
33
135
  export interface SqlTransactionHooks {
34
136
  readonly retention?: {
@@ -58,18 +160,47 @@ export interface SqlTransactionHooks {
58
160
  };
59
161
  readonly session?: {
60
162
  /**
61
- * Called before a write of the backend's that changes a session tree's root — an import's commit, an owner's
62
- * delete, a retention delete — after the root's session row is locked and before anything is written.
63
- * `{ refuse }` ⇒ nothing is written: an import or a delete rejects with an error carrying the deployment's
64
- * sentence (not the session `conflict` code — a conflict is retried, a refusal is not); a retention delete counts
65
- * the session as skipped and goes on with the others.
163
+ * INSIDE the transaction that creates a root row ({@link SqlSessionWrite} `"birth"`), after the backend has written
164
+ * the row and the log it starts with (a fork's copied log, an import's log; a create's is empty) and before the
165
+ * commit — so a deployment row written here may reference
166
+ * it, and is committed or rolled back with it. Throws ⇒ the whole transaction is rolled back, the row is not there,
167
+ * and the call rejects with what the hook threw.
66
168
  */
67
- beforeCommit?(txn: SqlStatementFace, write: {
68
- readonly op: "import" | "delete" | "retention-delete";
69
- readonly rootSessionId: string;
70
- }): Promise<"proceed" | {
169
+ birth?(txn: SqlStatementFace, write: Extract<SqlSessionWrite, {
170
+ readonly op: "birth";
171
+ }>): Promise<void>;
172
+ /**
173
+ * INSIDE the transaction of a write that changes or removes a root row — an import's commit, an owner's delete, an
174
+ * operator's delete of an unreadable row, a retention delete ({@link SqlSessionWrite}) — after the root's session row
175
+ * is locked (an import of an id with no row: before the row is created; an import: once its `decide` answered `"replace"`)
176
+ * and before anything is written. An append is
177
+ * not told here: it changes a log, not a row.
178
+ * `{ refuse, code }` ⇒ nothing is written: an import, a delete or a delete of an unreadable row rejects with the package's refusal
179
+ * `core-stores-sql.hook.refused` (terminal — not the session `conflict` code: a conflict is retried, a refusal is
180
+ * not), whose sentence is `refuse` and whose `hostCode` is `code`, the deployment's own code to route on; an answer
181
+ * whose `refuse` or `code` is not a string is refused by name (`core-stores-sql.options.invalid`), its code never
182
+ * dropped silently; a retention delete counts the session as skipped and goes on with the others. Throws ⇒ the
183
+ * whole transaction is rolled back and the call rejects with what the hook threw.
184
+ */
185
+ beforeCommit?(txn: SqlStatementFace, write: Exclude<SqlSessionWrite, {
186
+ readonly op: "birth" | "append";
187
+ }>): Promise<"proceed" | {
71
188
  readonly refuse: string;
189
+ readonly code: string;
72
190
  }>;
191
+ /**
192
+ * AFTER the commit, outside any transaction (no statement face): called once per commit that made a session write —
193
+ * an append included, for every session —, with every session write the commit made, in the order it made them (an
194
+ * import of an id with no row: its `"import"`, then its `"birth"`; a retention delete: each session deleted), and
195
+ * only once the database acknowledged the commit: a write rolled back, refused, or whose commit's outcome the backend
196
+ * could not read is never told. The call that made the commit — an append's included — answers after this has
197
+ * settled. An append is the hot path — every turn of every session makes them —, so a hook that hangs hangs every
198
+ * append, not one delete or import: it must not wait on anything the engine does (a call of the session store, a run,
199
+ * a turn), since the engine may be waiting on the very append it was told. Throws or rejects ⇒ nothing is rolled back,
200
+ * the call answers as it would have, and the driver's sink is told `core-stores-sql.session.after-commit-threw`.
201
+ * Called whether or not the transaction ran a session hook.
202
+ */
203
+ afterCommit?(writes: readonly SqlSessionWrite[]): void | Promise<void>;
73
204
  };
74
205
  }
75
206
  /** The options of {@link import("./backend.js").createSqlStorageBackend}. */
@@ -87,5 +218,11 @@ export interface SqlStorageBackendOptions {
87
218
  blobs?: SqlBlobBytesPort;
88
219
  };
89
220
  }
221
+ /** The hook table, read: two closed levels, each hook a function when given; the answer holds the deployment's own
222
+ * functions, each as it was given. */
223
+ export declare function readTransactionHooks(entry: string, value: unknown): SqlTransactionHooks;
224
+ /** A call's {@link SqlSessionCall}, read — the one reading the session store applies before a write: absent, or a closed
225
+ * record whose `callerContext` is a string when given; the answer holds the caller's string as it was given. */
226
+ export declare function readSessionCall(entry: string, value: unknown): SqlSessionCall;
90
227
  /** Read the backend's options, or refuse naming the first wrong value. */
91
228
  export declare function readBackendOptions(entry: string, value: unknown): SqlStorageBackendOptions;
package/dist/options.js CHANGED
@@ -5,24 +5,24 @@ import { refusal } from "./refusal.js";
5
5
  const OPTION_KEYS = Object.freeze(["driver", "retention", "transactionHooks", "fileHistory"]);
6
6
  const HOOK_GROUPS = Object.freeze({
7
7
  retention: Object.freeze(["holdLock", "liveReferences", "beforeDelete", "audit"]),
8
- session: Object.freeze(["beforeCommit"]),
8
+ session: Object.freeze(["birth", "beforeCommit", "afterCommit"]),
9
9
  });
10
10
  const FILE_HISTORY_KEYS = Object.freeze(["blobs"]);
11
11
  function readFunction(entry, where, value) {
12
12
  if (value !== undefined && typeof value !== "function")
13
- throw refusal(entry, `${where} must be a function when given (got ${value === null ? "null" : typeof value})`);
13
+ throw refusal("core-stores-sql.options.invalid", entry, `${where} must be a function when given (got ${value === null ? "null" : typeof value})`);
14
14
  }
15
15
  function readRetention(entry, value) {
16
16
  if (value === undefined)
17
- throw refusal(entry, `retention is required — "managed" or "none", the declaration core reads`);
17
+ throw refusal("core-stores-sql.options.invalid", entry, `retention is required — "managed" or "none", the declaration core reads`);
18
18
  try {
19
19
  return readRetentionDeclaration("options.retention", value);
20
20
  }
21
21
  catch (error) {
22
- throw refusal(entry, `retention: ${error instanceof Error ? error.message : String(error)}`, error);
22
+ throw refusal("core-stores-sql.options.invalid", entry, `retention: ${error instanceof Error ? error.message : String(error)}`, error);
23
23
  }
24
24
  }
25
- function readTransactionHooks(entry, value) {
25
+ export function readTransactionHooks(entry, value) {
26
26
  const groups = readRecord(entry, "transactionHooks", value);
27
27
  refuseUnknownKeys(entry, "transactionHooks", groups, Object.keys(HOOK_GROUPS));
28
28
  for (const [group, hooks] of Object.entries(HOOK_GROUPS)) {
@@ -36,6 +36,19 @@ function readTransactionHooks(entry, value) {
36
36
  }
37
37
  return groups;
38
38
  }
39
+ const SESSION_CALL_KEYS = Object.freeze(["callerContext"]);
40
+ export function readSessionCall(entry, value) {
41
+ if (value === undefined)
42
+ return {};
43
+ const record = readRecord(entry, "call", value);
44
+ refuseUnknownKeys(entry, "call", record, SESSION_CALL_KEYS);
45
+ const callerContext = record["callerContext"];
46
+ if (callerContext === undefined)
47
+ return {};
48
+ if (typeof callerContext !== "string")
49
+ throw refusal("core-stores-sql.options.invalid", entry, `call.callerContext must be a string when given (got ${callerContext === null ? "null" : typeof callerContext})`);
50
+ return { callerContext };
51
+ }
39
52
  function readFileHistory(entry, value) {
40
53
  const record = readRecord(entry, "fileHistory", value);
41
54
  refuseUnknownKeys(entry, "fileHistory", record, FILE_HISTORY_KEYS);
@@ -6,11 +6,11 @@ export function readPublishedColumns(rows) {
6
6
  for (const row of rows) {
7
7
  for (const field of ["table", "column", "meaning", "coreFace"]) {
8
8
  if (typeof row[field] !== "string" || row[field].trim() === "")
9
- throw refusal("publishedColumns", `a published column has no ${field} (${JSON.stringify(row)})`);
9
+ throw refusal("core-stores-sql.package.defect", "publishedColumns", `a published column has no ${field} (${JSON.stringify(row)})`);
10
10
  }
11
11
  const key = `${row.table}.${row.column}`;
12
12
  if (seen.has(key))
13
- throw refusal("publishedColumns", `${key} is published twice`);
13
+ throw refusal("core-stores-sql.package.defect", "publishedColumns", `${key} is published twice`);
14
14
  seen.add(key);
15
15
  out.push(Object.freeze({ table: row.table, column: row.column, meaning: row.meaning, coreFace: row.coreFace }));
16
16
  }
package/dist/refusal.d.ts CHANGED
@@ -1,6 +1,73 @@
1
1
  /**
2
- * The one way this package refuses. Every refusal is an `Error` whose message starts with the package name and the
3
- * entry point that refused, so a host log line names where the refusal came from without a stack. A refusal that
4
- * passes on a judgment core made carries core's error as its `cause`.
2
+ * The one way this package refuses, and the one way a caller reads a refusal.
3
+ *
4
+ * Every refusal is an `Error` whose message starts with the package name and the entry point that refused, so a host
5
+ * log line names where the refusal came from without a stack, and whose `code` member is one word of
6
+ * {@link SQL_ERROR_CODES}: what kind of refusal it is and, through the table, whether repeating the same call can
7
+ * succeed. The sentence is for a person; a program tells two refusals apart by the code alone ({@link sqlFaultOf}). A
8
+ * refusal that passes on a judgment core made, or an error the database raised, carries it as its `cause`; the
9
+ * database's own words stay there and are not repeated in the package's sentence. An error a deployment's hook throws
10
+ * inside the backend's transaction is not wrapped in a refusal: the call rejects with it as it was thrown (a refusal of
11
+ * this package the hook let through — a statement of its past its deadline — reads as that refusal; anything else as the
12
+ * deployment's own). A hook that runs after the commit cannot make the call reject (`SqlTransactionHooks`).
5
13
  */
6
- export declare function refusal(entry: string, why: string, cause?: unknown): Error;
14
+ import { type GovernanceRetryClass } from "@sema-agent/core";
15
+ /**
16
+ * Every code a refusal of this package carries, each with core's retry word for it — can repeating the same call
17
+ * succeed? `transient` = a later retry can, with nothing changed first; `terminal` = not until something named changes
18
+ * first (the deployment, its configuration, the database, the install). Closed: a code arrives with its row, and a
19
+ * code a caller has never seen is a change it is told about.
20
+ */
21
+ export declare const SQL_ERROR_CODES: Readonly<{
22
+ /** A value the caller handed in is wrong — an option, an argument, a pool, a hook, a byte port, a sink. */
23
+ readonly "core-stores-sql.options.invalid": "terminal";
24
+ /** The `@sema-agent/core` resolved at runtime is not the one this package was cut with. */
25
+ readonly "core-stores-sql.version.mismatch": "terminal";
26
+ /** This package's own package.json could not be read, so the version it was cut with is unknown. */
27
+ readonly "core-stores-sql.version.unreadable": "terminal";
28
+ /** A table the package ships is malformed — its migration registry, its ensure roster, its published columns. */
29
+ readonly "core-stores-sql.package.defect": "terminal";
30
+ /** This release of the package does not carry what the call makes — no driver, no stores: the call was valid, and
31
+ * there is nothing to return. */
32
+ readonly "core-stores-sql.release.not-carried": "terminal";
33
+ /** Core's tables are not there, or are not this version's: the backend's `ensureSchema()` has not run on this database. */
34
+ readonly "core-stores-sql.schema.not-ready": "terminal";
35
+ /** Whether core's tables are there could not be asked: the read of the database's own catalog failed (its error is
36
+ * the `cause`) and no refusal of this package judged that failure. `terminal` is the word for what the package can
37
+ * tell today: it holds no judge of the engines' own errors yet (one arrives with the stores), so a permission refusal
38
+ * (a user that may not read the catalog may not on the next try either) and a connection error alike (a reset, a
39
+ * refused connection, a failover) land here. A caller that would retry a connection error reads the `cause` itself.
40
+ * A failure the driver judged keeps the driver's code instead — a statement past its deadline is still
41
+ * `statement.deadline`. */
42
+ readonly "core-stores-sql.schema.unchecked": "terminal";
43
+ /** A statement ran past the deadline its call gave (`SqlQueryOptions.deadlineMs`). */
44
+ readonly "core-stores-sql.statement.deadline": "transient";
45
+ /** The engine answered a connection's initialization and refused it, or read back values the driver did not set (its
46
+ * error, when it raised one, is the `cause`). */
47
+ readonly "core-stores-sql.driver.init-refused": "terminal";
48
+ /** The engine did not answer a connection's initialization (the connection broke, or timed out, before it did). */
49
+ readonly "core-stores-sql.driver.init-unreached": "transient";
50
+ /** A deployment's hook refused the write (`SqlTransactionHooks.session.beforeCommit`); the hook's own code is the
51
+ * refusal's `hostCode`. */
52
+ readonly "core-stores-sql.hook.refused": "terminal";
53
+ }>;
54
+ /** A code of a refusal of this package: one key of {@link SQL_ERROR_CODES}. */
55
+ export type SqlErrorCode = keyof typeof SQL_ERROR_CODES;
56
+ /**
57
+ * The one reading of a caught value: a refusal of this package — its code, whether repeating the call can succeed, and
58
+ * on `hook.refused` the hook's own code — or `undefined` for anything else. It reads the value's `code` member only:
59
+ * never the message, never `instanceof`, so a refusal of another copy of this package reads the same.
60
+ */
61
+ export declare function sqlFaultOf(caught: unknown): {
62
+ readonly code: SqlErrorCode;
63
+ readonly permanence: GovernanceRetryClass;
64
+ readonly hostCode?: string;
65
+ } | undefined;
66
+ /** A refusal: `@sema-agent/core-stores-sql <entry>: <why>`, with its code, and the error it passes on as its `cause`. */
67
+ export declare function refusal(code: SqlErrorCode, entry: string, why: string, cause?: unknown): Error;
68
+ /** The refusal of a write a deployment's `session.beforeCommit` refused: its sentence, `hook.refused`, and its own code as
69
+ * `hostCode` — the code the deployment routes on, carried beside the package's and never in its place. The answer is the
70
+ * deployment's value, so it is read, not trusted: one that does not carry both a `refuse` and a `code` that are strings is not
71
+ * carried with the code dropped — it is refused by name, `options.invalid`, saying what it lacked. Total: a member that
72
+ * throws when read is absent, and the sentence names the value by its kind (`callerText`), never its text. */
73
+ export declare function hookRefusal(entry: string, verdict: unknown): Error;
package/dist/refusal.js CHANGED
@@ -1,3 +1,42 @@
1
- export function refusal(entry, why, cause) {
2
- return new Error(`@sema-agent/core-stores-sql ${entry}: ${why}`, cause === undefined ? undefined : { cause });
1
+ import { callerText } from "@sema-agent/core";
2
+ export const SQL_ERROR_CODES = Object.freeze({
3
+ "core-stores-sql.options.invalid": "terminal",
4
+ "core-stores-sql.version.mismatch": "terminal",
5
+ "core-stores-sql.version.unreadable": "terminal",
6
+ "core-stores-sql.package.defect": "terminal",
7
+ "core-stores-sql.release.not-carried": "terminal",
8
+ "core-stores-sql.schema.not-ready": "terminal",
9
+ "core-stores-sql.schema.unchecked": "terminal",
10
+ "core-stores-sql.statement.deadline": "transient",
11
+ "core-stores-sql.driver.init-refused": "terminal",
12
+ "core-stores-sql.driver.init-unreached": "transient",
13
+ "core-stores-sql.hook.refused": "terminal",
14
+ });
15
+ function memberOf(value, key) {
16
+ if ((typeof value !== "object" && typeof value !== "function") || value === null)
17
+ return undefined;
18
+ try {
19
+ return value[key];
20
+ }
21
+ catch {
22
+ return undefined;
23
+ }
24
+ }
25
+ export function sqlFaultOf(caught) {
26
+ const code = memberOf(caught, "code");
27
+ if (typeof code !== "string" || !Object.hasOwn(SQL_ERROR_CODES, code))
28
+ return undefined;
29
+ const known = code;
30
+ const hostCode = known === "core-stores-sql.hook.refused" ? memberOf(caught, "hostCode") : undefined;
31
+ return Object.freeze({ code: known, permanence: SQL_ERROR_CODES[known], ...(typeof hostCode === "string" ? { hostCode } : {}) });
32
+ }
33
+ export function refusal(code, entry, why, cause) {
34
+ return Object.assign(new Error(`@sema-agent/core-stores-sql ${entry}: ${why}`, cause === undefined ? undefined : { cause }), { code });
35
+ }
36
+ export function hookRefusal(entry, verdict) {
37
+ const [refuse, code] = [memberOf(verdict, "refuse"), memberOf(verdict, "code")];
38
+ if (typeof refuse !== "string" || typeof code !== "string") {
39
+ return refusal("core-stores-sql.options.invalid", entry, `a hook refused without answering { refuse, code } as two strings — the deployment's own code to route on is required (got refuse ${callerText(refuse)}, code ${callerText(code)})`);
40
+ }
41
+ return Object.assign(refusal("core-stores-sql.hook.refused", entry, refuse), { hostCode: code });
3
42
  }
package/dist/schema.d.ts CHANGED
@@ -1,22 +1,3 @@
1
- /**
2
- * Who creates and changes core's tables, and how a deployment checks they are there before it touches its own.
3
- *
4
- * Core's tables have one owner — this package. The backend's `ensureSchema()` creates the missing tables and indexes,
5
- * runs the registered migrations not yet applied (each in its own transaction, its version row written in the same
6
- * transaction), reconciles the column sets (a database that skipped a version, or is missing a column, is refused by
7
- * name), and answers what it did ({@link SqlSchemaReport}). All of it runs under the package's own ensure lock
8
- * ({@link SQL_ENSURE_LOCK}: taken by a non-blocking try with jittered back-off, never a blocking wait — a session
9
- * parked in a blocking lock holds a snapshot that a concurrent index build waits on), and the applied migrations are
10
- * rows of the package's own version table ({@link SQL_SCHEMA_VERSION_TABLE}).
11
- *
12
- * A deployment's own ensure runs AFTER the backend's: its tables reference core's, so core's must be there first. The
13
- * order is the deployment's call order — `await backend.ensureSchema()`, then its own — and the first statement of its
14
- * own ensure is {@link assertCoreSchemaReady}, which refuses loudly when core's ensure has not run, instead of letting
15
- * a reference to a missing table be created, ignored, or fail later on a user's request.
16
- *
17
- * The migration registry ships empty: this version carries no tables, and the first stores arrive with their tables
18
- * created whole.
19
- */
20
1
  import { type SqlDialect } from "./driver.js";
21
2
  import type { SqlStatementFace } from "./options.js";
22
3
  /** What one `ensureSchema()` did. */
package/dist/schema.js CHANGED
@@ -1,5 +1,6 @@
1
+ import { callerText } from "@sema-agent/core";
1
2
  import { readDialect } from "./driver.js";
2
- import { refusal } from "./refusal.js";
3
+ import { refusal, sqlFaultOf } from "./refusal.js";
3
4
  export const SQL_SCHEMA_VERSION_TABLE = "core_schema_migrations";
4
5
  export const SQL_ENSURE_LOCK = Object.freeze({ pg: 1_397_836_867, mysql: "sema_core_ensure_schema" });
5
6
  export const SQL_MIGRATIONS = Object.freeze([]);
@@ -9,17 +10,17 @@ export function readMigrations(entry, rows) {
9
10
  let previous;
10
11
  for (const row of rows) {
11
12
  if (typeof row.id !== "string" || row.id.trim() === "")
12
- throw refusal(entry, `a registered migration has no id (${JSON.stringify(row.id)})`);
13
+ throw refusal("core-stores-sql.package.defect", entry, `a registered migration has no id (${JSON.stringify(row.id)})`);
13
14
  if (seen.has(row.id))
14
- throw refusal(entry, `the migration "${row.id}" is registered twice — its id is its identity in ${SQL_SCHEMA_VERSION_TABLE}`);
15
+ throw refusal("core-stores-sql.package.defect", entry, `the migration "${row.id}" is registered twice — its id is its identity in ${SQL_SCHEMA_VERSION_TABLE}`);
15
16
  seen.add(row.id);
16
17
  if (typeof row.introducedIn !== "string" || !VERSION_RE.test(row.introducedIn))
17
- throw refusal(entry, `the migration "${row.id}" names no X.Y.Z version it was introduced in (${JSON.stringify(row.introducedIn)})`);
18
+ throw refusal("core-stores-sql.package.defect", entry, `the migration "${row.id}" names no X.Y.Z version it was introduced in (${JSON.stringify(row.introducedIn)})`);
18
19
  if (typeof row.run !== "function")
19
- throw refusal(entry, `the migration "${row.id}" has no run()`);
20
+ throw refusal("core-stores-sql.package.defect", entry, `the migration "${row.id}" has no run()`);
20
21
  const version = row.introducedIn.split(".").map(Number);
21
22
  if (previous !== undefined && compareVersions(version, previous) < 0)
22
- throw refusal(entry, `the migration "${row.id}" (${row.introducedIn}) is registered after a later version's — migrations run in the order they were introduced`);
23
+ throw refusal("core-stores-sql.package.defect", entry, `the migration "${row.id}" (${row.introducedIn}) is registered after a later version's — migrations run in the order they were introduced`);
23
24
  previous = version;
24
25
  }
25
26
  return rows;
@@ -43,21 +44,30 @@ function isYes(value) {
43
44
  return value > 0n;
44
45
  return typeof value === "string" && /^[1-9]\d*$/.test(value);
45
46
  }
47
+ function answered(value) {
48
+ if (value === undefined || value === null || typeof value === "boolean" || typeof value === "number")
49
+ return String(value);
50
+ if (typeof value === "bigint" && value > -(10n ** 20n) && value < 10n ** 20n)
51
+ return String(value);
52
+ if (typeof value === "string" && /^\d{1,20}$/.test(value))
53
+ return JSON.stringify(value);
54
+ return callerText(value);
55
+ }
46
56
  const ORDER = "run the backend's ensureSchema() first and the deployment's own ensure after it — a deployment table that references a core table needs that table to be there";
47
57
  export async function checkCoreSchema(entry, face, dialect, registry) {
48
58
  const which = readDialect(entry, dialect);
49
59
  if (typeof face !== "object" || face === null || typeof face.query !== "function")
50
- throw refusal(entry, "face must be a connection's statement face (an object with query())");
60
+ throw refusal("core-stores-sql.options.invalid", entry, "face must be a connection's statement face (an object with query())");
51
61
  const migrations = readMigrations(entry, registry);
52
62
  let present;
53
63
  try {
54
64
  present = (await face.query(VERSION_TABLE_PROBE[which], [SQL_SCHEMA_VERSION_TABLE])).rows[0]?.["present"];
55
65
  }
56
66
  catch (error) {
57
- throw refusal(entry, `could not ask whether core's version table ${SQL_SCHEMA_VERSION_TABLE} is there (${error instanceof Error ? error.message : String(error)}) — a check that cannot be made does not pass`, error);
67
+ throw refusal(sqlFaultOf(error)?.code ?? "core-stores-sql.schema.unchecked", entry, `could not ask whether core's version table ${SQL_SCHEMA_VERSION_TABLE} is there — a check that cannot be made does not pass (the database's error is the cause)`, error);
58
68
  }
59
69
  if (!isYes(present))
60
- throw refusal(entry, `core's tables are not there: its version table ${SQL_SCHEMA_VERSION_TABLE} is missing (the probe answered ${JSON.stringify(typeof present === "bigint" ? String(present) : present)}) — ${ORDER}`);
70
+ throw refusal("core-stores-sql.schema.not-ready", entry, `core's tables are not there: its version table ${SQL_SCHEMA_VERSION_TABLE} is missing (the probe answered ${answered(present)}) — ${ORDER}`);
61
71
  if (migrations.length === 0)
62
72
  return;
63
73
  let applied;
@@ -65,11 +75,11 @@ export async function checkCoreSchema(entry, face, dialect, registry) {
65
75
  applied = new Set((await face.query(`SELECT id FROM ${SQL_SCHEMA_VERSION_TABLE}`)).rows.map((row) => String(row["id"])));
66
76
  }
67
77
  catch (error) {
68
- throw refusal(entry, `could not read core's version table ${SQL_SCHEMA_VERSION_TABLE} (${error instanceof Error ? error.message : String(error)}) — a check that cannot be made does not pass`, error);
78
+ throw refusal(sqlFaultOf(error)?.code ?? "core-stores-sql.schema.unchecked", entry, `could not read core's version table ${SQL_SCHEMA_VERSION_TABLE} — a check that cannot be made does not pass (the database's error is the cause)`, error);
69
79
  }
70
80
  const missing = migrations.filter((m) => !applied.has(m.id)).map((m) => m.id);
71
81
  if (missing.length > 0)
72
- throw refusal(entry, `core's tables are not those of this version: the migration(s) ${missing.join(", ")} have not run — ${ORDER}`);
82
+ throw refusal("core-stores-sql.schema.not-ready", entry, `core's tables are not those of this version: the migration(s) ${missing.join(", ")} have not run — ${ORDER}`);
73
83
  }
74
84
  export async function assertCoreSchemaReady(face, dialect) {
75
85
  await checkCoreSchema("assertCoreSchemaReady", face, dialect, SQL_MIGRATIONS);
@@ -7,11 +7,11 @@ export function readOwnVersion(entry) {
7
7
  parsed = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
8
8
  }
9
9
  catch (error) {
10
- throw refusal(entry, `this package's own package.json could not be read (${error instanceof Error ? error.message : String(error)}), so the version it was cut with is unknown`);
10
+ throw refusal("core-stores-sql.version.unreadable", entry, `this package's own package.json could not be read (${error instanceof Error ? error.message : String(error)}), so the version it was cut with is unknown`);
11
11
  }
12
12
  const version = typeof parsed === "object" && parsed !== null ? parsed.version : undefined;
13
13
  if (typeof version !== "string" || version === "")
14
- throw refusal(entry, `this package's own package.json carries no version (got ${JSON.stringify(version)})`);
14
+ throw refusal("core-stores-sql.version.unreadable", entry, `this package's own package.json carries no version (got ${JSON.stringify(version)})`);
15
15
  return version;
16
16
  }
17
17
  export function coreVersionProblem(packageVersion, coreVersion) {
@@ -23,5 +23,5 @@ export function coreVersionProblem(packageVersion, coreVersion) {
23
23
  export function assertCoreVersion(entry) {
24
24
  const problem = coreVersionProblem(readOwnVersion(entry), CONTRACT_KIT_ENGINE_VERSION);
25
25
  if (problem !== undefined)
26
- throw refusal(entry, problem);
26
+ throw refusal("core-stores-sql.version.mismatch", entry, problem);
27
27
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sema-agent/core-stores-sql",
3
- "version": "7.69.1",
3
+ "version": "7.71.0",
4
4
  "private": false,
5
5
  "description": "Core's storage seats over PostgreSQL and the MySQL protocol family (MySQL, MariaDB, TiDB): neutral factories over a caller's pool. This version carries no SQL stores yet: the public face only.",
6
6
  "type": "module",
@@ -26,7 +26,7 @@
26
26
  "node": ">=20.18.1"
27
27
  },
28
28
  "peerDependencies": {
29
- "@sema-agent/core": "7.69.1"
29
+ "@sema-agent/core": "7.71.0"
30
30
  },
31
31
  "publishConfig": {
32
32
  "access": "public"
@@ -34,5 +34,5 @@
34
34
  "scripts": {
35
35
  "build": "tsc -p tsconfig.json && tsc -p tsconfig.json --emitDeclarationOnly --removeComments false"
36
36
  },
37
- "gitHead": "f55aa37580df15af00315b548890b3283ba1290e"
37
+ "gitHead": "a0e02e8e809ea212f3b023c3612e5fd34658dbc5"
38
38
  }
@@ -1,8 +0,0 @@
1
- /** Every tag the fail-open sink can be told, in one frozen list. */
2
- export declare const SQL_FAIL_OPEN_TAGS: readonly ["core-stores-sql.driver.packet-wall-log-unwritten", "core-stores-sql.driver.tidb-row-cap-unread", "core-stores-sql.driver.packet-cap-unread"];
3
- /** A fail-open read the package took: one word of {@link SQL_FAIL_OPEN_TAGS}. */
4
- export type SqlFailOpenTag = (typeof SQL_FAIL_OPEN_TAGS)[number];
5
- /** The sink told once per fail-open read: `tag` names the read, `detail` says what stood in for it. */
6
- export type SqlFailOpenSink = (tag: SqlFailOpenTag, detail: string) => void;
7
- /** The sink option, read: absent, or a function. */
8
- export declare function readFailOpenSink(entry: string, value: unknown): SqlFailOpenSink | undefined;
package/dist/fail-open.js DELETED
@@ -1,13 +0,0 @@
1
- import { refusal } from "./refusal.js";
2
- export const SQL_FAIL_OPEN_TAGS = Object.freeze([
3
- "core-stores-sql.driver.packet-wall-log-unwritten",
4
- "core-stores-sql.driver.tidb-row-cap-unread",
5
- "core-stores-sql.driver.packet-cap-unread",
6
- ]);
7
- export function readFailOpenSink(entry, value) {
8
- if (value === undefined)
9
- return undefined;
10
- if (typeof value !== "function")
11
- throw refusal(entry, `onFailOpen must be a function when given (got ${value === null ? "null" : typeof value})`);
12
- return value;
13
- }