@opengeni/db 4.4.0-canary.0 → 4.4.0-canary.2
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/dist/canonical-human-identities.js +4 -3
- package/dist/{chunk-2ZMTQVTR.js → chunk-2KOLL33E.js} +2 -2
- package/dist/chunk-45CP2YKY.js +1062 -0
- package/dist/chunk-45CP2YKY.js.map +1 -0
- package/dist/{chunk-6TKL3GQO.js → chunk-5UUWZDAV.js} +6531 -6480
- package/dist/chunk-5UUWZDAV.js.map +1 -0
- package/dist/{chunk-QLA3UQNX.js → chunk-6IJD3XXF.js} +17 -3
- package/dist/chunk-6IJD3XXF.js.map +1 -0
- package/dist/{chunk-232VC2LW.js → chunk-6V3HDEMR.js} +2 -2
- package/dist/{chunk-M7PSMVFF.js → chunk-CHBLBEU6.js} +2 -2
- package/dist/chunk-M4PKBJRS.js +20318 -0
- package/dist/chunk-M4PKBJRS.js.map +1 -0
- package/dist/chunk-S2TZ3F4L.js +237 -0
- package/dist/chunk-S2TZ3F4L.js.map +1 -0
- package/dist/{chunk-UK57QA2H.js → chunk-UOXWVP3T.js} +2 -2
- package/dist/{chunk-GVZJ7XSR.js → chunk-WFU6PS54.js} +11 -4
- package/dist/chunk-WFU6PS54.js.map +1 -0
- package/dist/{chunk-THJGMEK5.js → chunk-XJP7KJ6U.js} +121 -66
- package/dist/chunk-XJP7KJ6U.js.map +1 -0
- package/dist/connection-token-resolver.d.ts +2 -0
- package/dist/database.d.ts +2 -0
- package/dist/editable-artifact-durable-export.js +3 -2
- package/dist/editable-artifact-durable-export.js.map +1 -1
- package/dist/editable-artifacts.js +4 -3
- package/dist/external-identities.d.ts +1 -0
- package/dist/external-membership-operations.d.ts +44 -0
- package/dist/governed-learning-evaluator.d.ts +1 -14
- package/dist/host-mcp-bindings.d.ts +4 -0
- package/dist/host-mcp-resolvers.d.ts +47 -0
- package/dist/host-mcp-task-authority.d.ts +2 -6
- package/dist/index.d.ts +29 -31
- package/dist/index.js +8616 -8321
- package/dist/index.js.map +1 -1
- package/dist/knowledge-document-preparation.d.ts +56 -0
- package/dist/knowledge-entries-schema.d.ts +2479 -0
- package/dist/knowledge-entries.d.ts +421 -0
- package/dist/knowledge-indexing.d.ts +99 -0
- package/dist/knowledge-migration.d.ts +6 -0
- package/dist/managed-auth-session-sets.js +4 -3
- package/dist/mcp-operations.js +3 -2
- package/dist/mcp-operations.js.map +1 -1
- package/dist/migrate.js +2 -1
- package/dist/provision-roles.js +1 -1
- package/dist/retained-provider-commands.js +3 -2
- package/dist/retained-provider-commands.js.map +1 -1
- package/dist/runtime-posture.d.ts +7 -7
- package/dist/schema.d.ts +115 -12
- package/dist/schema.js +26 -1
- package/dist/session-background-commands.js +5 -4
- package/dist/session-command-output.js +8 -6
- package/dist/session-command-output.js.map +1 -1
- package/dist/session-event-slices.js +6 -4
- package/dist/session-event-slices.js.map +1 -1
- package/dist/session-mcp-credential-rotation.js +5 -4
- package/dist/session-mcp-credential-rotation.js.map +1 -1
- package/dist/session-tenancy.js +4 -3
- package/dist/video-generation.js +4 -3
- package/dist/workspace-artifacts.d.ts +1 -0
- package/dist/workspace-instruction-policies-schema.d.ts +21 -2
- package/dist/workspace-instruction-policies.d.ts +1 -1
- package/dist/workspace-membership-access.d.ts +11 -0
- package/dist/workspace-tool-defaults.js +5 -4
- package/dist/workspace-tool-defaults.js.map +1 -1
- package/drizzle/0461_unified_knowledge.sql +2859 -0
- package/drizzle/0462_agent_instruction_non_destructive_edits.sql +212 -0
- package/drizzle/0463_host_mcp_resolver_registration.sql +111 -0
- package/drizzle/0464_external_workspace_membership_operations.sql +166 -0
- package/package.json +6 -6
- package/src/connection-token-resolver.ts +75 -6
- package/src/database.ts +12 -1
- package/src/external-identities.ts +1 -0
- package/src/external-membership-operations.ts +134 -0
- package/src/governed-learning-evaluator.ts +0 -69
- package/src/host-mcp-binding-match.ts +1 -0
- package/src/host-mcp-bindings.ts +24 -1
- package/src/host-mcp-resolvers.ts +266 -0
- package/src/host-mcp-task-authority.ts +11 -10
- package/src/index.ts +307 -128
- package/src/knowledge-document-preparation.ts +90 -0
- package/src/knowledge-entries-schema.ts +264 -0
- package/src/knowledge-entries.ts +860 -0
- package/src/knowledge-indexing.ts +126 -0
- package/src/knowledge-migration.ts +761 -0
- package/src/knowledge-source-sync.ts +46 -7
- package/src/migrate.ts +19 -0
- package/src/provision-roles.ts +23 -57
- package/src/runtime-posture.ts +103 -7
- package/src/schema.ts +15 -3
- package/src/skills.ts +4 -0
- package/src/video-generation.ts +14 -0
- package/src/workspace-artifacts.ts +2 -0
- package/src/workspace-instruction-policies-schema.ts +1 -0
- package/src/workspace-membership-access.ts +61 -0
- package/dist/chunk-6TKL3GQO.js.map +0 -1
- package/dist/chunk-EYF6MH6C.js +0 -4772
- package/dist/chunk-EYF6MH6C.js.map +0 -1
- package/dist/chunk-GSBONN55.js +0 -533
- package/dist/chunk-GSBONN55.js.map +0 -1
- package/dist/chunk-GVZJ7XSR.js.map +0 -1
- package/dist/chunk-QLA3UQNX.js.map +0 -1
- package/dist/chunk-THJGMEK5.js.map +0 -1
- /package/dist/{chunk-2ZMTQVTR.js.map → chunk-2KOLL33E.js.map} +0 -0
- /package/dist/{chunk-232VC2LW.js.map → chunk-6V3HDEMR.js.map} +0 -0
- /package/dist/{chunk-M7PSMVFF.js.map → chunk-CHBLBEU6.js.map} +0 -0
- /package/dist/{chunk-UK57QA2H.js.map → chunk-UOXWVP3T.js.map} +0 -0
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
// src/lossless-json.ts
|
|
2
|
+
var JSON_STRING_PREFIX = "opengeni_lossless_json_string_v2_81f06e15:";
|
|
3
|
+
var JSON_KEY_PREFIX = "opengeni_lossless_json_key_v2_7ca6071d:";
|
|
4
|
+
var TEXT_PREFIX = "opengeni_lossless_text_v2_c4100a62:";
|
|
5
|
+
var MAX_JSON_DEPTH = 512;
|
|
6
|
+
var LOSSLESS_CONTENT_CODEC_VERSION = 1;
|
|
7
|
+
var LOSSLESS_CONTENT_WRITER_APPLICATION_NAME = "opengeni-lossless-v1-session-variable-sets-v1";
|
|
8
|
+
function withLosslessContentWriteVersion(value, contentKey, versionKey) {
|
|
9
|
+
const stamp = (entry) => {
|
|
10
|
+
if (!Object.hasOwn(entry, contentKey)) {
|
|
11
|
+
throw new Error(`Lossless content write omitted ${contentKey}`);
|
|
12
|
+
}
|
|
13
|
+
return { ...entry, [versionKey]: LOSSLESS_CONTENT_CODEC_VERSION };
|
|
14
|
+
};
|
|
15
|
+
return Array.isArray(value) ? value.map(stamp) : stamp(value);
|
|
16
|
+
}
|
|
17
|
+
var LOSSLESS_JSON_STRING_PREFIX = JSON_STRING_PREFIX;
|
|
18
|
+
var LOSSLESS_TEXT_PREFIX = TEXT_PREFIX;
|
|
19
|
+
var UnsupportedCanonicalValueError = class extends TypeError {
|
|
20
|
+
name = "UnsupportedCanonicalValueError";
|
|
21
|
+
};
|
|
22
|
+
function toPostgresLosslessJson(value) {
|
|
23
|
+
return encodeJsonValue(value, /* @__PURE__ */ new Set(), 0).value;
|
|
24
|
+
}
|
|
25
|
+
function fromPostgresLosslessJson(value, codecVersion) {
|
|
26
|
+
return codecVersion === LOSSLESS_CONTENT_CODEC_VERSION ? decodeJsonValue(value, 0).value : value;
|
|
27
|
+
}
|
|
28
|
+
function toPostgresLosslessText(value) {
|
|
29
|
+
if (isPostgresSafeString(value) && !value.includes(TEXT_PREFIX)) return value;
|
|
30
|
+
let stored = "";
|
|
31
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
32
|
+
const code = value.charCodeAt(index);
|
|
33
|
+
if (value.startsWith(TEXT_PREFIX, index)) {
|
|
34
|
+
stored += encodeTextCodeUnit(code);
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (code === 0 || code >= 56320 && code <= 57343) {
|
|
38
|
+
stored += encodeTextCodeUnit(code);
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
if (code >= 55296 && code <= 56319) {
|
|
42
|
+
const next = index + 1 < value.length ? value.charCodeAt(index + 1) : 0;
|
|
43
|
+
if (next < 56320 || next > 57343) {
|
|
44
|
+
stored += encodeTextCodeUnit(code);
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
stored += value.slice(index, index + 2);
|
|
48
|
+
index += 1;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
stored += value[index];
|
|
52
|
+
}
|
|
53
|
+
return stored;
|
|
54
|
+
}
|
|
55
|
+
function fromPostgresLosslessText(value, codecVersion) {
|
|
56
|
+
return codecVersion === LOSSLESS_CONTENT_CODEC_VERSION ? value.replaceAll(
|
|
57
|
+
new RegExp(` ${TEXT_PREFIX}([0-9a-f]{4}); `, "g"),
|
|
58
|
+
(_match, encoded) => String.fromCharCode(Number.parseInt(encoded, 16))
|
|
59
|
+
) : value;
|
|
60
|
+
}
|
|
61
|
+
function encodeTextCodeUnit(code) {
|
|
62
|
+
return ` ${TEXT_PREFIX}${code.toString(16).padStart(4, "0")}; `;
|
|
63
|
+
}
|
|
64
|
+
function encodeJsonValue(value, ancestors, depth) {
|
|
65
|
+
if (depth > MAX_JSON_DEPTH) {
|
|
66
|
+
throw new UnsupportedCanonicalValueError(
|
|
67
|
+
`Canonical JSON exceeds the maximum supported depth of ${MAX_JSON_DEPTH}`
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
if (value === null || typeof value === "boolean") return { value, changed: false };
|
|
71
|
+
if (typeof value === "string") {
|
|
72
|
+
if (isPostgresSafeString(value) && !value.startsWith(JSON_STRING_PREFIX)) {
|
|
73
|
+
return { value, changed: false };
|
|
74
|
+
}
|
|
75
|
+
return { value: `${JSON_STRING_PREFIX}${encodeUtf16(value)}`, changed: true };
|
|
76
|
+
}
|
|
77
|
+
if (typeof value === "number") {
|
|
78
|
+
if (!Number.isFinite(value) || Object.is(value, -0)) {
|
|
79
|
+
throw new UnsupportedCanonicalValueError(
|
|
80
|
+
"Canonical JSON requires finite non-negative-zero numbers"
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
return { value, changed: false };
|
|
84
|
+
}
|
|
85
|
+
if (typeof value === "undefined" || typeof value === "bigint" || typeof value === "function" || typeof value === "symbol") {
|
|
86
|
+
throw new UnsupportedCanonicalValueError(`Canonical JSON cannot contain ${typeof value}`);
|
|
87
|
+
}
|
|
88
|
+
if (!isPlainObject(value) && !Array.isArray(value)) {
|
|
89
|
+
throw new UnsupportedCanonicalValueError("Canonical JSON requires arrays and plain objects");
|
|
90
|
+
}
|
|
91
|
+
if (ancestors.has(value)) {
|
|
92
|
+
throw new UnsupportedCanonicalValueError("Canonical JSON cannot contain cyclic references");
|
|
93
|
+
}
|
|
94
|
+
if (Object.getOwnPropertySymbols(value).length > 0) {
|
|
95
|
+
throw new UnsupportedCanonicalValueError("Canonical JSON cannot contain symbol keys");
|
|
96
|
+
}
|
|
97
|
+
ancestors.add(value);
|
|
98
|
+
try {
|
|
99
|
+
if (Array.isArray(value)) {
|
|
100
|
+
const descriptors2 = Object.getOwnPropertyDescriptors(value);
|
|
101
|
+
const propertyNames = Object.getOwnPropertyNames(descriptors2);
|
|
102
|
+
const indexNames = propertyNames.filter((name) => name !== "length");
|
|
103
|
+
if (indexNames.length !== value.length || indexNames.some((name) => {
|
|
104
|
+
const index = Number(name);
|
|
105
|
+
return !Number.isInteger(index) || index < 0 || index >= value.length || String(index) !== name;
|
|
106
|
+
})) {
|
|
107
|
+
throw new UnsupportedCanonicalValueError(
|
|
108
|
+
"Canonical JSON arrays cannot contain non-index properties or holes"
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
const output2 = [];
|
|
112
|
+
let changed2 = false;
|
|
113
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
114
|
+
const descriptor = descriptors2[String(index)];
|
|
115
|
+
if (!descriptor || !descriptor.enumerable || !("value" in descriptor)) {
|
|
116
|
+
throw new UnsupportedCanonicalValueError(
|
|
117
|
+
"Canonical JSON arrays cannot contain holes, accessors, or hidden elements"
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
const encoded = encodeJsonValue(descriptor.value, ancestors, depth + 1);
|
|
121
|
+
output2.push(encoded.value);
|
|
122
|
+
changed2 ||= encoded.changed;
|
|
123
|
+
}
|
|
124
|
+
return changed2 ? { value: output2, changed: true } : { value, changed: false };
|
|
125
|
+
}
|
|
126
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
127
|
+
const output = {};
|
|
128
|
+
let changed = false;
|
|
129
|
+
for (const [key, descriptor] of Object.entries(descriptors)) {
|
|
130
|
+
if (!descriptor.enumerable || !("value" in descriptor)) {
|
|
131
|
+
throw new UnsupportedCanonicalValueError(
|
|
132
|
+
"Canonical JSON objects cannot contain accessors or hidden properties"
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
const encodedKey = isPostgresSafeString(key) && !key.startsWith(JSON_KEY_PREFIX) ? key : `${JSON_KEY_PREFIX}${encodeUtf16(key)}`;
|
|
136
|
+
if (Object.prototype.hasOwnProperty.call(output, encodedKey)) {
|
|
137
|
+
throw new UnsupportedCanonicalValueError("Canonical JSON key encoding collided");
|
|
138
|
+
}
|
|
139
|
+
const encodedValue = encodeJsonValue(descriptor.value, ancestors, depth + 1);
|
|
140
|
+
defineJsonDataProperty(output, encodedKey, encodedValue.value);
|
|
141
|
+
changed ||= encodedKey !== key || encodedValue.changed;
|
|
142
|
+
}
|
|
143
|
+
return changed ? { value: output, changed: true } : { value, changed: false };
|
|
144
|
+
} finally {
|
|
145
|
+
ancestors.delete(value);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
function decodeJsonValue(value, depth) {
|
|
149
|
+
if (depth > MAX_JSON_DEPTH) return { value, changed: false };
|
|
150
|
+
if (typeof value === "string") {
|
|
151
|
+
const decoded = decodeTaggedString(value, JSON_STRING_PREFIX);
|
|
152
|
+
return decoded === null ? { value, changed: false } : { value: decoded, changed: true };
|
|
153
|
+
}
|
|
154
|
+
if (!value || typeof value !== "object") return { value, changed: false };
|
|
155
|
+
if (Array.isArray(value)) {
|
|
156
|
+
const output2 = [];
|
|
157
|
+
let changed2 = false;
|
|
158
|
+
for (const entry of value) {
|
|
159
|
+
const decoded = decodeJsonValue(entry, depth + 1);
|
|
160
|
+
output2.push(decoded.value);
|
|
161
|
+
changed2 ||= decoded.changed;
|
|
162
|
+
}
|
|
163
|
+
return changed2 ? { value: output2, changed: true } : { value, changed: false };
|
|
164
|
+
}
|
|
165
|
+
if (!isPlainObject(value)) return { value, changed: false };
|
|
166
|
+
const output = {};
|
|
167
|
+
let changed = false;
|
|
168
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
169
|
+
const decodedKey = decodeTaggedString(key, JSON_KEY_PREFIX) ?? key;
|
|
170
|
+
if (Object.prototype.hasOwnProperty.call(output, decodedKey)) {
|
|
171
|
+
return { value, changed: false };
|
|
172
|
+
}
|
|
173
|
+
const decodedValue = decodeJsonValue(entry, depth + 1);
|
|
174
|
+
defineJsonDataProperty(output, decodedKey, decodedValue.value);
|
|
175
|
+
changed ||= decodedKey !== key || decodedValue.changed;
|
|
176
|
+
}
|
|
177
|
+
return changed ? { value: output, changed: true } : { value, changed: false };
|
|
178
|
+
}
|
|
179
|
+
function defineJsonDataProperty(target, key, value) {
|
|
180
|
+
Object.defineProperty(target, key, {
|
|
181
|
+
value,
|
|
182
|
+
enumerable: true,
|
|
183
|
+
configurable: true,
|
|
184
|
+
writable: true
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
function encodeUtf16(value) {
|
|
188
|
+
const bytes = Buffer.allocUnsafe(value.length * 2);
|
|
189
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
190
|
+
bytes.writeUInt16LE(value.charCodeAt(index), index * 2);
|
|
191
|
+
}
|
|
192
|
+
return bytes.toString("base64");
|
|
193
|
+
}
|
|
194
|
+
function decodeTaggedString(value, prefix) {
|
|
195
|
+
if (!value.startsWith(prefix)) return null;
|
|
196
|
+
const encoded = value.slice(prefix.length);
|
|
197
|
+
if (encoded.length === 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return null;
|
|
198
|
+
const bytes = Buffer.from(encoded, "base64");
|
|
199
|
+
if (bytes.byteLength % 2 !== 0 || bytes.toString("base64") !== encoded) return null;
|
|
200
|
+
let decoded = "";
|
|
201
|
+
for (let offset = 0; offset < bytes.byteLength; offset += 2) {
|
|
202
|
+
decoded += String.fromCharCode(bytes.readUInt16LE(offset));
|
|
203
|
+
}
|
|
204
|
+
return decoded;
|
|
205
|
+
}
|
|
206
|
+
function isPostgresSafeString(value) {
|
|
207
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
208
|
+
const code = value.charCodeAt(index);
|
|
209
|
+
if (code === 0) return false;
|
|
210
|
+
if (code >= 55296 && code <= 56319) {
|
|
211
|
+
const next = index + 1 < value.length ? value.charCodeAt(index + 1) : 0;
|
|
212
|
+
if (next < 56320 || next > 57343) return false;
|
|
213
|
+
index += 1;
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
if (code >= 56320 && code <= 57343) return false;
|
|
217
|
+
}
|
|
218
|
+
return true;
|
|
219
|
+
}
|
|
220
|
+
function isPlainObject(value) {
|
|
221
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
222
|
+
const prototype = Object.getPrototypeOf(value);
|
|
223
|
+
return prototype === Object.prototype || prototype === null;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export {
|
|
227
|
+
LOSSLESS_CONTENT_CODEC_VERSION,
|
|
228
|
+
LOSSLESS_CONTENT_WRITER_APPLICATION_NAME,
|
|
229
|
+
withLosslessContentWriteVersion,
|
|
230
|
+
LOSSLESS_JSON_STRING_PREFIX,
|
|
231
|
+
LOSSLESS_TEXT_PREFIX,
|
|
232
|
+
toPostgresLosslessJson,
|
|
233
|
+
fromPostgresLosslessJson,
|
|
234
|
+
toPostgresLosslessText,
|
|
235
|
+
fromPostgresLosslessText
|
|
236
|
+
};
|
|
237
|
+
//# sourceMappingURL=chunk-S2TZ3F4L.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lossless-json.ts"],"sourcesContent":["const JSON_STRING_PREFIX = \"opengeni_lossless_json_string_v2_81f06e15:\";\nconst JSON_KEY_PREFIX = \"opengeni_lossless_json_key_v2_7ca6071d:\";\nconst TEXT_PREFIX = \"opengeni_lossless_text_v2_c4100a62:\";\nconst MAX_JSON_DEPTH = 512;\n\n/**\n * Explicit out-of-band truth for values written by the lossless PostgreSQL\n * compatibility codec. Historical rows have NULL in their companion version\n * column and must never be decoded based on content shape alone.\n */\nexport const LOSSLESS_CONTENT_CODEC_VERSION = 1 as const;\nexport const LOSSLESS_CONTENT_WRITER_APPLICATION_NAME =\n \"opengeni-lossless-v1-session-variable-sets-v1\";\n\nexport function withLosslessContentWriteVersion<\n const ContentKey extends string,\n const VersionKey extends string,\n const Value extends object,\n>(\n value: Value & Record<ContentKey, unknown>,\n contentKey: ContentKey,\n versionKey: VersionKey,\n): Value & Record<VersionKey, typeof LOSSLESS_CONTENT_CODEC_VERSION>;\nexport function withLosslessContentWriteVersion<\n const ContentKey extends string,\n const VersionKey extends string,\n const Value extends object,\n>(\n value: readonly (Value & Record<ContentKey, unknown>)[],\n contentKey: ContentKey,\n versionKey: VersionKey,\n): Array<Value & Record<VersionKey, typeof LOSSLESS_CONTENT_CODEC_VERSION>>;\nexport function withLosslessContentWriteVersion(\n value: Record<string, unknown> | readonly Record<string, unknown>[],\n contentKey: string,\n versionKey: string,\n): Record<string, unknown> | Record<string, unknown>[] {\n const stamp = (entry: Record<string, unknown>) => {\n if (!Object.hasOwn(entry, contentKey)) {\n throw new Error(`Lossless content write omitted ${contentKey}`);\n }\n return { ...entry, [versionKey]: LOSSLESS_CONTENT_CODEC_VERSION };\n };\n return Array.isArray(value) ? value.map(stamp) : stamp(value as Record<string, unknown>);\n}\n\nexport const LEGACY_LOSSLESS_JSON_ENVELOPE_KEY =\n \"$opengeniCanonicalV8_6d9b6f48_2a3e_4d8a_9e33_7611d9d08985\";\nexport const LEGACY_LOSSLESS_TEXT_PREFIX = \"opengeni-canonical-text-v1:\";\nexport const LOSSLESS_JSON_STRING_PREFIX = JSON_STRING_PREFIX;\nexport const LOSSLESS_TEXT_PREFIX = TEXT_PREFIX;\n\nexport class UnsupportedCanonicalValueError extends TypeError {\n override readonly name = \"UnsupportedCanonicalValueError\";\n}\n\ntype TransformResult = { value: unknown; changed: boolean };\n\n/**\n * Preserve JSON structure and SQL-queryable control keys. Only strings that\n * PostgreSQL cannot represent (or that collide with this unshipped v2 tag) are\n * encoded. Non-JSON graph values are rejected instead of silently rewritten.\n */\nexport function toPostgresLosslessJson(value: unknown): unknown {\n return encodeJsonValue(value, new Set<object>(), 0).value;\n}\n\n/**\n * Restore an explicitly versioned JSON value after a PostgreSQL read. A NULL\n * version denotes literal legacy/old-writer data, including strings that happen\n * to be valid active-marker encodings.\n */\nexport function fromPostgresLosslessJson<T>(value: T, codecVersion: number | null | undefined): T {\n return codecVersion === LOSSLESS_CONTENT_CODEC_VERSION\n ? (decodeJsonValue(value, 0).value as T)\n : value;\n}\n\n/**\n * Lossless text-column boundary for NUL, lone UTF-16, and v2-prefix text.\n * Only the unrepresentable code unit is tagged, with SQL-visible spaces around\n * the tag, so ordinary surrounding words retain their full-text-search shape.\n */\nexport function toPostgresLosslessText(value: string): string {\n if (isPostgresSafeString(value) && !value.includes(TEXT_PREFIX)) return value;\n let stored = \"\";\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (value.startsWith(TEXT_PREFIX, index)) {\n stored += encodeTextCodeUnit(code);\n continue;\n }\n if (code === 0 || (code >= 0xdc00 && code <= 0xdfff)) {\n stored += encodeTextCodeUnit(code);\n continue;\n }\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = index + 1 < value.length ? value.charCodeAt(index + 1) : 0;\n if (next < 0xdc00 || next > 0xdfff) {\n stored += encodeTextCodeUnit(code);\n continue;\n }\n stored += value.slice(index, index + 2);\n index += 1;\n continue;\n }\n stored += value[index];\n }\n return stored;\n}\n\n/**\n * Decode only an explicitly versioned value introduced by this migration. The\n * nullable companion column, not the producer string, is the codec truth.\n */\nexport function fromPostgresLosslessText(\n value: string,\n codecVersion: number | null | undefined,\n): string {\n return codecVersion === LOSSLESS_CONTENT_CODEC_VERSION\n ? value.replaceAll(\n new RegExp(` ${TEXT_PREFIX}([0-9a-f]{4}); `, \"g\"),\n (_match, encoded: string) => String.fromCharCode(Number.parseInt(encoded, 16)),\n )\n : value;\n}\n\nfunction encodeTextCodeUnit(code: number): string {\n return ` ${TEXT_PREFIX}${code.toString(16).padStart(4, \"0\")}; `;\n}\n\nfunction encodeJsonValue(value: unknown, ancestors: Set<object>, depth: number): TransformResult {\n if (depth > MAX_JSON_DEPTH) {\n throw new UnsupportedCanonicalValueError(\n `Canonical JSON exceeds the maximum supported depth of ${MAX_JSON_DEPTH}`,\n );\n }\n if (value === null || typeof value === \"boolean\") return { value, changed: false };\n if (typeof value === \"string\") {\n if (isPostgresSafeString(value) && !value.startsWith(JSON_STRING_PREFIX)) {\n return { value, changed: false };\n }\n return { value: `${JSON_STRING_PREFIX}${encodeUtf16(value)}`, changed: true };\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value) || Object.is(value, -0)) {\n throw new UnsupportedCanonicalValueError(\n \"Canonical JSON requires finite non-negative-zero numbers\",\n );\n }\n return { value, changed: false };\n }\n if (\n typeof value === \"undefined\" ||\n typeof value === \"bigint\" ||\n typeof value === \"function\" ||\n typeof value === \"symbol\"\n ) {\n throw new UnsupportedCanonicalValueError(`Canonical JSON cannot contain ${typeof value}`);\n }\n if (!isPlainObject(value) && !Array.isArray(value)) {\n throw new UnsupportedCanonicalValueError(\"Canonical JSON requires arrays and plain objects\");\n }\n if (ancestors.has(value)) {\n throw new UnsupportedCanonicalValueError(\"Canonical JSON cannot contain cyclic references\");\n }\n if (Object.getOwnPropertySymbols(value).length > 0) {\n throw new UnsupportedCanonicalValueError(\"Canonical JSON cannot contain symbol keys\");\n }\n ancestors.add(value);\n try {\n if (Array.isArray(value)) {\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const propertyNames = Object.getOwnPropertyNames(descriptors);\n const indexNames = propertyNames.filter((name) => name !== \"length\");\n if (\n indexNames.length !== value.length ||\n indexNames.some((name) => {\n const index = Number(name);\n return (\n !Number.isInteger(index) || index < 0 || index >= value.length || String(index) !== name\n );\n })\n ) {\n throw new UnsupportedCanonicalValueError(\n \"Canonical JSON arrays cannot contain non-index properties or holes\",\n );\n }\n const output: unknown[] = [];\n let changed = false;\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = descriptors[String(index)];\n if (!descriptor || !descriptor.enumerable || !(\"value\" in descriptor)) {\n throw new UnsupportedCanonicalValueError(\n \"Canonical JSON arrays cannot contain holes, accessors, or hidden elements\",\n );\n }\n const encoded = encodeJsonValue(descriptor.value, ancestors, depth + 1);\n output.push(encoded.value);\n changed ||= encoded.changed;\n }\n return changed ? { value: output, changed: true } : { value, changed: false };\n }\n\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const output: Record<string, unknown> = {};\n let changed = false;\n for (const [key, descriptor] of Object.entries(descriptors)) {\n if (!descriptor.enumerable || !(\"value\" in descriptor)) {\n throw new UnsupportedCanonicalValueError(\n \"Canonical JSON objects cannot contain accessors or hidden properties\",\n );\n }\n const encodedKey =\n isPostgresSafeString(key) && !key.startsWith(JSON_KEY_PREFIX)\n ? key\n : `${JSON_KEY_PREFIX}${encodeUtf16(key)}`;\n if (Object.prototype.hasOwnProperty.call(output, encodedKey)) {\n throw new UnsupportedCanonicalValueError(\"Canonical JSON key encoding collided\");\n }\n const encodedValue = encodeJsonValue(descriptor.value, ancestors, depth + 1);\n defineJsonDataProperty(output, encodedKey, encodedValue.value);\n changed ||= encodedKey !== key || encodedValue.changed;\n }\n return changed ? { value: output, changed: true } : { value, changed: false };\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction decodeJsonValue(value: unknown, depth: number): TransformResult {\n if (depth > MAX_JSON_DEPTH) return { value, changed: false };\n if (typeof value === \"string\") {\n const decoded = decodeTaggedString(value, JSON_STRING_PREFIX);\n return decoded === null ? { value, changed: false } : { value: decoded, changed: true };\n }\n if (!value || typeof value !== \"object\") return { value, changed: false };\n if (Array.isArray(value)) {\n const output: unknown[] = [];\n let changed = false;\n for (const entry of value) {\n const decoded = decodeJsonValue(entry, depth + 1);\n output.push(decoded.value);\n changed ||= decoded.changed;\n }\n return changed ? { value: output, changed: true } : { value, changed: false };\n }\n if (!isPlainObject(value)) return { value, changed: false };\n\n const output: Record<string, unknown> = {};\n let changed = false;\n for (const [key, entry] of Object.entries(value)) {\n const decodedKey = decodeTaggedString(key, JSON_KEY_PREFIX) ?? key;\n if (Object.prototype.hasOwnProperty.call(output, decodedKey)) {\n return { value, changed: false };\n }\n const decodedValue = decodeJsonValue(entry, depth + 1);\n defineJsonDataProperty(output, decodedKey, decodedValue.value);\n changed ||= decodedKey !== key || decodedValue.changed;\n }\n return changed ? { value: output, changed: true } : { value, changed: false };\n}\n\n/**\n * JSON permits own keys such as `__proto__`. Assignment into an ordinary `{}`\n * would invoke the inherited legacy setter and silently replace the object's\n * prototype instead of creating data. Define every transformed key explicitly\n * so encode/decode preserve hostile-but-valid JSON keys and property order.\n */\nfunction defineJsonDataProperty(\n target: Record<string, unknown>,\n key: string,\n value: unknown,\n): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n}\n\nfunction encodeUtf16(value: string): string {\n const bytes = Buffer.allocUnsafe(value.length * 2);\n for (let index = 0; index < value.length; index += 1) {\n bytes.writeUInt16LE(value.charCodeAt(index), index * 2);\n }\n return bytes.toString(\"base64\");\n}\n\nfunction decodeTaggedString(value: string, prefix: string): string | null {\n if (!value.startsWith(prefix)) return null;\n const encoded = value.slice(prefix.length);\n if (encoded.length === 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return null;\n const bytes = Buffer.from(encoded, \"base64\");\n if (bytes.byteLength % 2 !== 0 || bytes.toString(\"base64\") !== encoded) return null;\n let decoded = \"\";\n for (let offset = 0; offset < bytes.byteLength; offset += 2) {\n decoded += String.fromCharCode(bytes.readUInt16LE(offset));\n }\n return decoded;\n}\n\nfunction isPostgresSafeString(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code === 0) return false;\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = index + 1 < value.length ? value.charCodeAt(index + 1) : 0;\n if (next < 0xdc00 || next > 0xdfff) return false;\n index += 1;\n continue;\n }\n if (code >= 0xdc00 && code <= 0xdfff) return false;\n }\n return true;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n"],"mappings":";AAAA,IAAM,qBAAqB;AAC3B,IAAM,kBAAkB;AACxB,IAAM,cAAc;AACpB,IAAM,iBAAiB;AAOhB,IAAM,iCAAiC;AACvC,IAAM,2CACX;AAoBK,SAAS,gCACd,OACA,YACA,YACqD;AACrD,QAAM,QAAQ,CAAC,UAAmC;AAChD,QAAI,CAAC,OAAO,OAAO,OAAO,UAAU,GAAG;AACrC,YAAM,IAAI,MAAM,kCAAkC,UAAU,EAAE;AAAA,IAChE;AACA,WAAO,EAAE,GAAG,OAAO,CAAC,UAAU,GAAG,+BAA+B;AAAA,EAClE;AACA,SAAO,MAAM,QAAQ,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,MAAM,KAAgC;AACzF;AAKO,IAAM,8BAA8B;AACpC,IAAM,uBAAuB;AAE7B,IAAM,iCAAN,cAA6C,UAAU;AAAA,EAC1C,OAAO;AAC3B;AASO,SAAS,uBAAuB,OAAyB;AAC9D,SAAO,gBAAgB,OAAO,oBAAI,IAAY,GAAG,CAAC,EAAE;AACtD;AAOO,SAAS,yBAA4B,OAAU,cAA4C;AAChG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AC,IAAI;AACtE,UAAI,OAAO,SAAU,OAAO,MAAQ,QAAO;AAC3C,eAAS;AACT;AAAA,IACF;AACA,QAAI,QAAQ,SAAU,QAAQ,MAAQ,QAAO;AAAA,EAC/C;AACA,SAAO;AACT;AAEA,SAAS,cAAc,OAAkD;AACvE,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,EAAG,QAAO;AACxE,QAAM,YAAY,OAAO,eAAe,KAAK;AAC7C,SAAO,cAAc,OAAO,aAAa,cAAc;AACzD;","names":["descriptors","output","changed"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
nestedPostgresSqlState,
|
|
3
3
|
rawRows
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-WFU6PS54.js";
|
|
5
5
|
|
|
6
6
|
// src/managed-auth-session-sets.ts
|
|
7
7
|
import {
|
|
@@ -296,4 +296,4 @@ export {
|
|
|
296
296
|
reapManagedAuthIsolatedSessions,
|
|
297
297
|
reapExpiredManagedAuthSessionSets
|
|
298
298
|
};
|
|
299
|
-
//# sourceMappingURL=chunk-
|
|
299
|
+
//# sourceMappingURL=chunk-UOXWVP3T.js.map
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
|
-
LOSSLESS_CONTENT_WRITER_APPLICATION_NAME,
|
|
3
2
|
schema_exports,
|
|
4
3
|
sessions,
|
|
5
4
|
workspaceSessionActivityRevisions,
|
|
6
5
|
workspaces
|
|
7
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-5UUWZDAV.js";
|
|
7
|
+
import {
|
|
8
|
+
LOSSLESS_CONTENT_WRITER_APPLICATION_NAME
|
|
9
|
+
} from "./chunk-S2TZ3F4L.js";
|
|
8
10
|
|
|
9
11
|
// src/persistence-errors.ts
|
|
10
12
|
var SQLSTATE_KEYS = ["sqlState", "sqlstate", "code"];
|
|
@@ -230,6 +232,11 @@ async function withSessionRlsActorContext(actor, fn) {
|
|
|
230
232
|
"withSessionRlsActorContext: initiatingHumanSubjectId must be null or non-empty"
|
|
231
233
|
);
|
|
232
234
|
}
|
|
235
|
+
if (actor.privateFileOwnerSubjectId !== void 0 && actor.privateFileOwnerSubjectId !== null && !actor.privateFileOwnerSubjectId.trim()) {
|
|
236
|
+
throw new Error(
|
|
237
|
+
"withSessionRlsActorContext: privateFileOwnerSubjectId must be null or non-empty"
|
|
238
|
+
);
|
|
239
|
+
}
|
|
233
240
|
return await sessionRlsActorContext.run(actor, fn);
|
|
234
241
|
}
|
|
235
242
|
var dbBindings = /* @__PURE__ */ new WeakMap();
|
|
@@ -366,7 +373,7 @@ async function setRlsContext(db, context) {
|
|
|
366
373
|
if (sessionActor) {
|
|
367
374
|
await setSubjectRlsContext(db, sessionActor.subjectId);
|
|
368
375
|
await db.execute(
|
|
369
|
-
sql`select set_config(
|
|
376
|
+
sql`select set_config('opengeni.private_file_owner', ${sessionActor.privateFileOwnerSubjectId ?? ""}, true), set_config(
|
|
370
377
|
'opengeni.initiating_human_subject_id',
|
|
371
378
|
${sessionActor.initiatingHumanSubjectId ?? ""},
|
|
372
379
|
true
|
|
@@ -767,4 +774,4 @@ export {
|
|
|
767
774
|
withAccountRls,
|
|
768
775
|
dbBindingFor
|
|
769
776
|
};
|
|
770
|
-
//# sourceMappingURL=chunk-
|
|
777
|
+
//# sourceMappingURL=chunk-WFU6PS54.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/persistence-errors.ts","../src/database.ts"],"sourcesContent":["export type DatabaseFailureCode = \"db_deadlock\" | \"db_serialization_failure\" | \"db_failure\";\n\nexport type PersistenceRetryOutcome = \"not_retryable\" | \"exhausted\";\n\nexport type SafeDatabaseErrorFacts = {\n severity?: string;\n schema?: string;\n table?: string;\n column?: string;\n dataType?: string;\n constraint?: string;\n routine?: string;\n};\n\nexport type PersistenceFailureDetails = {\n code: DatabaseFailureCode;\n sqlState: string | null;\n stage: string;\n eventTypes: string[];\n correlationId: string;\n attempts: number;\n retryOutcome: PersistenceRetryOutcome;\n database: SafeDatabaseErrorFacts;\n};\n\nconst SQLSTATE_KEYS = [\"sqlState\", \"sqlstate\", \"code\"] as const;\nconst NESTED_ERROR_KEYS = [\"cause\", \"original\", \"driverError\", \"error\", \"errors\"] as const;\nconst RETRYABLE_DATABASE_TRANSPORT_CODES = new Set([\n // postgres.js connection lifecycle failures.\n \"CONNECTION_CLOSED\",\n \"CONNECTION_DESTROYED\",\n \"CONNECTION_ENDED\",\n \"CONNECT_TIMEOUT\",\n // Node socket/DNS failures surfaced unchanged by postgres.js.\n \"EAI_AGAIN\",\n \"ECONNABORTED\",\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"EHOSTDOWN\",\n \"EHOSTUNREACH\",\n \"ENETDOWN\",\n \"ENETRESET\",\n \"ENETUNREACH\",\n \"ENOTFOUND\",\n \"EPIPE\",\n \"ETIMEDOUT\",\n]);\nconst DATABASE_ERROR_NAMES = new Set([\"DatabaseError\", \"DrizzleQueryError\", \"PostgresError\"]);\nconst DATABASE_DIAGNOSTIC_KEYS = [\n \"severity\",\n \"schema_name\",\n \"table_name\",\n \"column_name\",\n \"data_type_name\",\n \"constraint_name\",\n \"routine\",\n] as const;\nconst SAFE_FACT_KEYS = [\n [\"severity\", \"severity\"],\n [\"schema_name\", \"schema\"],\n [\"schema\", \"schema\"],\n [\"table_name\", \"table\"],\n [\"table\", \"table\"],\n [\"column_name\", \"column\"],\n [\"column\", \"column\"],\n [\"data_type_name\", \"dataType\"],\n [\"dataType\", \"dataType\"],\n [\"constraint_name\", \"constraint\"],\n [\"constraint\", \"constraint\"],\n [\"routine\", \"routine\"],\n] as const;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\");\n}\n\nfunction safeFact(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.length === 0) return undefined;\n return value;\n}\n\n/** Find the driver SQLSTATE even when Drizzle wrapped it under nested causes. */\nexport function nestedPostgresSqlState(error: unknown): string | null {\n const queue: unknown[] = [error];\n const seen = new Set<unknown>();\n let fallback: string | null = null;\n while (queue.length > 0 && seen.size < 64) {\n const current = queue.shift();\n if (!isRecord(current) || seen.has(current)) continue;\n seen.add(current);\n for (const key of SQLSTATE_KEYS) {\n const value = current[key];\n if (typeof value !== \"string\" || !/^[0-9A-Z]{5}$/i.test(value)) continue;\n const normalized = value.toUpperCase();\n // Node transport codes such as EPIPE happen to be five characters but\n // are not PostgreSQL SQLSTATEs.\n if (RETRYABLE_DATABASE_TRANSPORT_CODES.has(normalized)) continue;\n if (normalized === \"40P01\" || normalized === \"40001\") return normalized;\n fallback ??= normalized;\n }\n for (const key of NESTED_ERROR_KEYS) {\n const nested = current[key];\n if (Array.isArray(nested)) queue.push(...nested);\n else if (nested !== undefined) queue.push(nested);\n }\n }\n return fallback;\n}\n\nexport function databaseFailureCode(sqlState: string | null): DatabaseFailureCode {\n if (sqlState === \"40P01\") return \"db_deadlock\";\n if (sqlState === \"40001\") return \"db_serialization_failure\";\n return \"db_failure\";\n}\n\nexport function isRetryablePersistenceSqlState(sqlState: string | null): boolean {\n return sqlState === \"40P01\" || sqlState === \"40001\";\n}\n\n/**\n * Recognize only explicit postgres.js/Node transport codes, including nested\n * driver causes. These failures can arrive as plain Errors with no SQLSTATE or\n * database diagnostic fields when the connection dies before PostgreSQL can\n * answer. Messages are intentionally ignored: they are unstable and may\n * contain connection detail.\n */\nexport function isRetryableDatabaseTransportFailure(error: unknown): boolean {\n const queue: unknown[] = [error];\n const seen = new Set<unknown>();\n while (queue.length > 0 && seen.size < 64) {\n const current = queue.shift();\n if (!isRecord(current) || seen.has(current)) continue;\n seen.add(current);\n\n for (const key of [\"code\", \"errno\"] as const) {\n const value = current[key];\n if (\n typeof value === \"string\" &&\n RETRYABLE_DATABASE_TRANSPORT_CODES.has(value.toUpperCase())\n ) {\n return true;\n }\n }\n\n for (const key of NESTED_ERROR_KEYS) {\n const nested = current[key];\n if (Array.isArray(nested)) queue.push(...nested);\n else if (nested !== undefined) queue.push(nested);\n }\n }\n return false;\n}\n\n/**\n * Distinguish database/ORM failures from expected domain exceptions when a\n * driver omitted SQLSTATE. This checks shape only; callers retain the original\n * failure independently as canonical error evidence.\n */\nexport function isDatabasePersistenceFailure(error: unknown): boolean {\n if (isRetryableDatabaseTransportFailure(error) || nestedPostgresSqlState(error) !== null) {\n return true;\n }\n\n const queue: unknown[] = [error];\n const seen = new Set<unknown>();\n while (queue.length > 0 && seen.size < 64) {\n const current = queue.shift();\n if (!isRecord(current) || seen.has(current)) continue;\n seen.add(current);\n\n if (typeof current.name === \"string\" && DATABASE_ERROR_NAMES.has(current.name)) {\n return true;\n }\n if (\n typeof current.query === \"string\" &&\n (Object.hasOwn(current, \"params\") || Object.hasOwn(current, \"parameters\"))\n ) {\n return true;\n }\n if (DATABASE_DIAGNOSTIC_KEYS.some((key) => Object.hasOwn(current, key))) {\n return true;\n }\n\n for (const key of NESTED_ERROR_KEYS) {\n const nested = current[key];\n if (Array.isArray(nested)) queue.push(...nested);\n else if (nested !== undefined) queue.push(nested);\n }\n }\n return false;\n}\n\n/** Extract only PostgreSQL diagnostic identifiers; never query text/parameters. */\nexport function safeDatabaseErrorFacts(error: unknown): SafeDatabaseErrorFacts {\n const queue: unknown[] = [error];\n const seen = new Set<unknown>();\n const facts: SafeDatabaseErrorFacts = {};\n while (queue.length > 0 && seen.size < 64) {\n const current = queue.shift();\n if (!isRecord(current) || seen.has(current)) continue;\n seen.add(current);\n for (const [source, destination] of SAFE_FACT_KEYS) {\n if (facts[destination] !== undefined) continue;\n const value = safeFact(current[source]);\n if (value !== undefined) facts[destination] = value;\n }\n for (const key of NESTED_ERROR_KEYS) {\n const nested = current[key];\n if (Array.isArray(nested)) queue.push(...nested);\n else if (nested !== undefined) queue.push(nested);\n }\n }\n return facts;\n}\n\n/**\n * Typed persistence classification that retains the exact original failure as\n * `cause` for internal diagnostics. The ordinary Error message is deliberately\n * stable and source-free so a generic presentation path can never disclose SQL,\n * parameters, or driver detail by rendering `.message`.\n */\nexport class SessionEventPersistenceError extends Error {\n readonly name = \"SessionEventPersistenceError\";\n\n constructor(\n readonly details: PersistenceFailureDetails,\n cause?: unknown,\n ) {\n const label =\n details.code === \"db_deadlock\"\n ? \"Database deadlock\"\n : details.code === \"db_serialization_failure\"\n ? \"Database serialization failure\"\n : \"Database failure\";\n const operation = `${label} while persisting ${details.eventTypes.join(\", \") || \"session events\"}`;\n super(operation, cause === undefined ? undefined : { cause });\n }\n\n get code(): DatabaseFailureCode {\n return this.details.code;\n }\n}\n\nexport function isSessionEventPersistenceError(\n error: unknown,\n): error is SessionEventPersistenceError {\n return error instanceof SessionEventPersistenceError;\n}\n\nexport type IdempotentPersistenceTransactionOptions = {\n stage: string;\n eventTypes?: string[];\n maxAttempts?: number;\n correlationId?: string;\n onRetry?: (input: { attempt: number; sqlState: \"40P01\" | \"40001\" }) => void | Promise<void>;\n};\n\n/**\n * Retry only the supplied idempotent database transaction/savepoint. Provider\n * inference, tools, NATS, and all other external effects must remain outside\n * this function. A single correlation ID follows every persistence attempt.\n */\nexport async function runIdempotentPersistenceTransaction<T>(\n options: IdempotentPersistenceTransactionOptions,\n transaction: (attempt: number) => Promise<T>,\n): Promise<T> {\n const maxAttempts = options.maxAttempts ?? 3;\n if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n throw new Error(\"Persistence maxAttempts must be a positive integer\");\n }\n const correlationId = options.correlationId ?? crypto.randomUUID();\n const eventTypes = [...new Set(options.eventTypes ?? [])].sort();\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n try {\n return await transaction(attempt);\n } catch (error) {\n const sqlState = nestedPostgresSqlState(error);\n const retryable = isRetryablePersistenceSqlState(sqlState);\n if (retryable && attempt < maxAttempts) {\n await options.onRetry?.({\n attempt,\n sqlState: sqlState as \"40P01\" | \"40001\",\n });\n continue;\n }\n if (!isDatabasePersistenceFailure(error)) throw error;\n throw new SessionEventPersistenceError(\n {\n code: databaseFailureCode(sqlState),\n sqlState,\n stage: options.stage,\n eventTypes,\n correlationId,\n attempts: attempt,\n retryOutcome: retryable ? \"exhausted\" : \"not_retryable\",\n database: safeDatabaseErrorFacts(error),\n },\n error,\n );\n }\n }\n throw new Error(\"Unreachable persistence retry state\");\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { eq, sql, type SQL } from \"drizzle-orm\";\nimport type { PgDatabase, PgTransactionConfig } from \"drizzle-orm/pg-core\";\nimport { drizzle } from \"drizzle-orm/postgres-js\";\nimport postgres from \"postgres\";\n\nimport {\n runIdempotentPersistenceTransaction,\n type IdempotentPersistenceTransactionOptions,\n} from \"./persistence-errors\";\nimport { LOSSLESS_CONTENT_WRITER_APPLICATION_NAME } from \"./lossless-json\";\nimport * as schema from \"./schema\";\n\n// §7.7 driver widening (Step I). `Database` is the structural, cross-driver\n// query-layer port: every helper in this file accepts `db: Database` and uses\n// only the methods present on drizzle's base `PgDatabase` (select/insert/update/\n// delete/transaction/execute). Widening from the concrete\n// `PostgresJsDatabase<typeof schema>` to `PgDatabase<any, typeof schema>` is a\n// pure TYPE change — no runtime behavior changes — that lets an embedded host\n// inject ANY drizzle pg driver handle (node-postgres, neon-http, etc.) bound to\n// OpenGeni's schema, not just the postgres-js handle `createDb` builds. The\n// `any` for the query-result HKT is deliberate: it keeps `db.execute(sql\\`…\\`)`\n// callable across drivers whose raw-result shapes differ (postgres-js returns a\n// row array; node-postgres returns `{ rows }`). The three raw `db.execute(…)`\n// reads that index a row array (`getManagedUserByEmail` here is the only\n// host-facing one — see `userLookup`) stay postgres-js-shaped for standalone;\n// `userLookup` is the injection seam for hosts on a different driver.\n// `PostgresJsDatabase<typeof schema>` is assignable to this, so standalone is\n// unaffected.\n\nexport type Database = PgDatabase<any, typeof schema>;\n\ndeclare const sessionActivityDatabaseBrand: unique symbol;\n\n/**\n * A workspace-scoped transaction whose session activity commit gate is open.\n * Session-row writers accept this narrower handle so new call sites cannot\n * accidentally bypass the once-per-transaction revision finalizer.\n */\nexport type SessionActivityDatabase = Database & {\n readonly [sessionActivityDatabaseBrand]: true;\n};\n\nexport type DbClient = {\n db: Database;\n close: () => Promise<void>;\n};\n\nexport type RlsContext = {\n accountId: string;\n workspaceId?: string | null;\n};\n\nexport type SessionRlsActorContext = {\n subjectId: string;\n /** Host-verified personal file ownership, never a request-supplied subject. */\n privateFileOwnerSubjectId?: string | null;\n initiatingHumanSubjectId?: string | null;\n};\n\nconst sessionRlsActorContext = new AsyncLocalStorage<SessionRlsActorContext>();\n\nexport async function withSessionRlsActorContext<T>(\n actor: SessionRlsActorContext,\n fn: () => Promise<T>,\n): Promise<T> {\n if (!actor.subjectId.trim()) {\n throw new Error(\"withSessionRlsActorContext: a non-empty subjectId is required\");\n }\n if (\n actor.initiatingHumanSubjectId !== undefined &&\n actor.initiatingHumanSubjectId !== null &&\n !actor.initiatingHumanSubjectId.trim()\n ) {\n throw new Error(\n \"withSessionRlsActorContext: initiatingHumanSubjectId must be null or non-empty\",\n );\n }\n if (\n actor.privateFileOwnerSubjectId !== undefined &&\n actor.privateFileOwnerSubjectId !== null &&\n !actor.privateFileOwnerSubjectId.trim()\n ) {\n throw new Error(\n \"withSessionRlsActorContext: privateFileOwnerSubjectId must be null or non-empty\",\n );\n }\n return await sessionRlsActorContext.run(actor, fn);\n}\n\ntype RlsContextSettings = {\n accountId: string;\n workspaceId: string;\n};\n\n/**\n * RLS posture for the connection OpenGeni's query layer runs over (Step I, §7.7).\n *\n * - `\"force\"` (DEFAULT — today's standalone behavior, byte-for-byte): OpenGeni\n * connects as a NON-OWNER role (`opengeni_app`) and every table carries\n * `FORCE ROW LEVEL SECURITY`, so the workspace/account GUCs set by\n * `setRlsContext` are the ONLY thing that admits rows — even the table owner\n * is subject to RLS. This is the Fork-A isolation guarantee.\n * - `\"scoped\"` (embedded Fork-B opt-in): the host runs OpenGeni's queries over a\n * role that OWNS the dedicated schema (RLS need not be forced for that role),\n * relying on the host's own tenant boundary. OpenGeni STILL emits the\n * `set_config('opengeni.account_id'/'workspace_id', …)` GUCs defensively on\n * every scoped query, so the application query path is byte-identical between\n * the two strategies and the app code is RLS-mode-agnostic. The strategy is a\n * declared posture (consumed by `provisionRoles` and as a documented\n * invariant), NOT a query-path branch — there is deliberately no `if\n * (strategy === …)` anywhere in the helpers below. Picking `\"scoped\"` does not\n * relax any GUC; it only changes which DB role the host provisions/connects as\n * and asserts that the host accepts owning the isolation boundary.\n */\nexport type RlsStrategy = \"force\" | \"scoped\";\n\n/**\n * Resolve a host-IdP/Better-Auth user *identifier* by email. Injected via\n * `createDb({ userLookup })` (Step I). UNSET → today's raw parameterized select\n * against Better Auth's `auth_users` table (see `getManagedUserByEmail`), which\n * relies on the postgres-js array-shaped `db.execute` result. An embedded host\n * whose identity lives elsewhere (a different IdP table, a different driver, or\n * a non-`auth_users` user store) injects this closure so OpenGeni never touches\n * `auth_users` directly. Returns the user id, or null when no such user exists.\n */\nexport type UserLookup = (db: Database, email: string) => Promise<string | null>;\n\nexport type ManagedUserProfile = {\n id: string;\n name: string | null;\n email: string;\n};\n\n/** Host identity projection used by organization administration rosters. */\nexport type UserProfileLookup = (\n db: Database,\n userIds: readonly string[],\n) => Promise<ManagedUserProfile[]>;\n\nexport type CreateDbOptions = {\n /**\n * The Postgres `search_path` for this connection (Step I, §7.8 runtime half).\n * UNSET → today's behavior: NO `search_path` startup parameter is sent, so the\n * server default applies (`public` for standalone, where every table + the\n * `vector` extension + `gen_random_uuid()` live). For an embedded dedicated\n * schema, pass e.g. `\"opengeni,opengeni_private,public\"` — postgres-js sends\n * it as a per-session startup parameter (the supported, query-param-free way;\n * URL `?search_path=` is IGNORED by postgres-js). Keep `public` LAST so the\n * `vector` type and `gen_random_uuid()` (which live in `public` on the\n * pgvector image) still resolve — the schema-isolation contract live footgun.\n */\n searchPath?: string;\n /** RLS posture; defaults to `\"force\"` (today's standalone). */\n rlsStrategy?: RlsStrategy;\n /** Host-provided user-by-email resolver; unset → today's raw `auth_users` query. */\n userLookup?: UserLookup;\n /** Host-provided user profile projection; unset → standalone `auth_users`. */\n userProfileLookup?: UserProfileLookup;\n /** postgres-js pool size; defaults to today's `10`. */\n max?: number;\n /**\n * Connection-local default transaction isolation sent in the postgres-js\n * startup parameters. This is intentionally not a role/database default:\n * tests and embedded callers can exercise a different ambient isolation\n * without mutating a shared PostgreSQL role or affecting other connections.\n */\n isolationLevel?: postgres.ConnectionParameters[\"default_transaction_isolation\"];\n};\n\n/**\n * The active RLS strategy + userLookup for an injected `Database`, recorded in a\n * side WeakMap so helpers (and `getManagedUserByEmail`) can consult the host's\n * binding without changing every call signature. A handle with no recorded\n * config (e.g. one built outside `createDb`, or in a test) falls back to the\n * standalone defaults: `rlsStrategy: \"force\"`, raw `auth_users` lookup.\n */\ntype DbBinding = {\n rlsStrategy: RlsStrategy;\n userLookup?: UserLookup;\n userProfileLookup?: UserProfileLookup;\n};\n\nconst dbBindings = new WeakMap<object, DbBinding>();\n\n/** The strategy bound to a handle (or the `\"force\"` default). */\nexport function rlsStrategyFor(db: Database): RlsStrategy {\n return dbBindings.get(db as unknown as object)?.rlsStrategy ?? \"force\";\n}\n\n/**\n * Run a raw SQL query and read its rows as a typed array.\n *\n * Why this exists: the Step I driver widening (`Database = PgDatabase<any, …>`)\n * deliberately sets the query-result HKT to `any` so `db.execute(…)` is callable\n * across drivers whose raw-result shapes differ (postgres-js → row array;\n * node-postgres → `{ rows }`). A side effect is that `db.execute<T>(…)` now\n * resolves to `any`, erasing the per-row element type at the call site. OpenGeni's\n * OWN internal raw queries usually run over the postgres-js handle `createDb`\n * builds (array result), while an embedded host may inject a node-postgres style\n * driver (`{ rows }`). Normalize those two standard shapes in one place; reject\n * an unknown driver result rather than silently treating it as an empty query.\n */\nexport async function rawRows<T extends Record<string, unknown>>(\n executor: Pick<Database, \"execute\">,\n query: SQL,\n): Promise<T[]> {\n const result = await executor.execute<T>(query);\n if (Array.isArray(result)) {\n return result as unknown as T[];\n }\n const rows = (result as unknown as { rows?: unknown }).rows;\n if (Array.isArray(rows)) {\n return rows as T[];\n }\n throw new Error(\"Unsupported database execute() result shape\");\n}\n\nexport type SandboxProviderReadLockIdentity = {\n workspaceId: string;\n sandboxGroupId: string;\n leaseEpoch: number;\n instanceId: string;\n};\n\nexport class SandboxProviderReadLockUnavailableError extends Error {\n constructor() {\n super(\"Sandbox provider reads are temporarily busy. Retry the request.\");\n this.name = \"SandboxProviderReadLockUnavailableError\";\n }\n}\n\nconst SANDBOX_PROVIDER_READ_LOCK_WAIT_MS = 15_000;\nconst SANDBOX_PROVIDER_READ_LOCK_POLL_MAX_MS = 200;\n\nfunction sandboxProviderReadLockKey(identity: SandboxProviderReadLockIdentity): string {\n return [\n \"sandbox-provider-read\",\n identity.workspaceId,\n identity.sandboxGroupId,\n identity.leaseEpoch,\n identity.instanceId,\n ].join(\":\");\n}\n\nasync function waitForSandboxProviderReadLockPoll(\n delayMs: number,\n signal?: AbortSignal | undefined,\n): Promise<void> {\n if (signal?.aborted) {\n throw signal.reason ?? new DOMException(\"The operation was aborted\", \"AbortError\");\n }\n await new Promise<void>((resolve, reject) => {\n let settled = false;\n let timer: ReturnType<typeof setTimeout>;\n const cleanup = () => signal?.removeEventListener(\"abort\", abort);\n const finish = () => {\n if (settled) return;\n settled = true;\n cleanup();\n resolve();\n };\n const abort = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n cleanup();\n reject(signal?.reason ?? new DOMException(\"The operation was aborted\", \"AbortError\"));\n };\n timer = setTimeout(finish, delayMs);\n signal?.addEventListener(\"abort\", abort, { once: true });\n if (signal?.aborted) abort();\n });\n}\n\n/**\n * Cross-process exclusive boundary for one exact live provider instance's\n * API-direct read request. Modal accepts concurrent commands from one attached\n * handle, but independent API replicas reconstruct different handles; issuing\n * overlapping command groups through those handles can make an otherwise valid\n * read fail transiently. Keep concurrency inside one batched request while\n * serializing only separate requests that target the same lease identity.\n *\n * The callback intentionally runs while one transaction-pinned DB connection\n * holds the advisory lock. The direct lease holder separately prevents drain,\n * and the abort-aware bounded poll prevents a disconnected HTTP request from\n * occupying the connection indefinitely.\n */\nexport async function withSandboxProviderReadLock<T>(\n db: Database,\n identity: SandboxProviderReadLockIdentity,\n signal: AbortSignal | undefined,\n fn: () => Promise<T>,\n): Promise<T> {\n const key = sandboxProviderReadLockKey(identity);\n const deadline = Date.now() + SANDBOX_PROVIDER_READ_LOCK_WAIT_MS;\n return await db.transaction(async (lockedDb) => {\n let pollMs = 20;\n while (true) {\n if (signal?.aborted) {\n throw signal.reason ?? new DOMException(\"The operation was aborted\", \"AbortError\");\n }\n const [row] = await rawRows<{ acquired: boolean }>(\n lockedDb,\n sql`select pg_try_advisory_xact_lock(hashtextextended(${key}, 0)) as acquired`,\n );\n if (row?.acquired === true) return await fn();\n const remainingMs = deadline - Date.now();\n if (remainingMs <= 0) throw new SandboxProviderReadLockUnavailableError();\n await waitForSandboxProviderReadLockPoll(Math.min(pollMs, remainingMs), signal);\n pollMs = Math.min(pollMs * 2, SANDBOX_PROVIDER_READ_LOCK_POLL_MAX_MS);\n }\n });\n}\n\nexport function createDb(databaseUrl: string, options: CreateDbOptions = {}): DbClient {\n // `prepare: false` is REQUIRED for Azure Database for PostgreSQL Flexible\n // Server's transaction-pooling PgBouncer: postgres-js's default named prepared\n // statements (`s_N`) are bound to one backend, but a transaction pooler hands\n // each transaction a different backend, so a later `execute` intermittently\n // throws `prepared statement \"s_N\" does not exist`. Every RLS read in this\n // module (set_config + SELECT inside one db.transaction) rides on this pool, so\n // the failure surfaces as a \"worked, then didn't\" credential/permission read.\n // idle_timeout + max_lifetime recycle connections so a pooler-recycled backend\n // is never reused indefinitely; application_name aids server-side diagnostics.\n const client = postgres(databaseUrl, {\n max: options.max ?? 10,\n prepare: false,\n idle_timeout: 30,\n max_lifetime: 1800,\n // `connection` carries per-session Postgres STARTUP parameters. The exact\n // `application_name` is also the PgBouncer-compatible current-image receipt\n // for migration 0352's restrictive sessions policy; arbitrary custom startup\n // parameters are not portable through transaction poolers. `search_path`\n // (embedded only) is the supported, query-param-free way to scope a connection\n // to a dedicated schema — postgres-js IGNORES a URL `?search_path=`. Unset\n // searchPath → omit it so the server default (`public`) is unchanged for\n // standalone.\n connection: {\n application_name: LOSSLESS_CONTENT_WRITER_APPLICATION_NAME,\n ...(options.searchPath ? { search_path: options.searchPath } : {}),\n ...(options.isolationLevel ? { default_transaction_isolation: options.isolationLevel } : {}),\n },\n });\n const db = drizzle(client, { schema });\n dbBindings.set(db as unknown as object, {\n rlsStrategy: options.rlsStrategy ?? \"force\",\n ...(options.userLookup ? { userLookup: options.userLookup } : {}),\n ...(options.userProfileLookup ? { userProfileLookup: options.userProfileLookup } : {}),\n });\n return {\n db,\n close: async () => {\n await client.end();\n },\n };\n}\n\n/**\n * Register a host's `rlsStrategy`/`userLookup` against an externally-constructed\n * `Database` handle (e.g. one the embedded host built from its own driver and\n * injected, rather than via `createDb`). Lets the same WeakMap-backed lookups\n * work for injected handles. Standalone never calls this (it uses `createDb`).\n */\nexport function registerDbBinding(\n db: Database,\n binding: {\n rlsStrategy?: RlsStrategy;\n userLookup?: UserLookup;\n userProfileLookup?: UserProfileLookup;\n },\n): void {\n dbBindings.set(db as unknown as object, {\n rlsStrategy: binding.rlsStrategy ?? \"force\",\n ...(binding.userLookup ? { userLookup: binding.userLookup } : {}),\n ...(binding.userProfileLookup ? { userProfileLookup: binding.userProfileLookup } : {}),\n });\n}\n\nexport async function setRlsContext(db: Database, context: RlsContext): Promise<void> {\n // Fail loud on an empty/blank account id: a \"\" account would set an RLS GUC\n // that matches no tenant row, silently returning zero rows from every scoped\n // read (a phantom \"not found\" / \"no active subscription\"). An RLS context with\n // no account is always a bug at the call site, never a valid query scope.\n if (typeof context.accountId !== \"string\" || context.accountId.trim() === \"\") {\n throw new Error(\"setRlsContext: a non-empty accountId is required to establish an RLS context\");\n }\n // Transaction-local writer identity covers supported injected/embedded\n // database handles whose connection-level application_name is host-owned.\n // Standalone createDb connections also carry version receipts in their exact\n // application_name, while old OpenGeni binaries set neither current receipt.\n await db.execute(sql`select\n set_config('opengeni.account_id', ${context.accountId}, true),\n set_config('opengeni.workspace_id', ${context.workspaceId ?? \"\"}, true),\n set_config('opengeni.lossless_content_writer', '1', true),\n set_config('opengeni.sandbox_recovery_protocol_v2', '1', true),\n set_config('opengeni.pending_tool_event_output_v1', '1', true),\n set_config('opengeni.session_variable_set_attachments_v1', '1', true)`);\n const sessionActor = sessionRlsActorContext.getStore();\n if (sessionActor) {\n await setSubjectRlsContext(db, sessionActor.subjectId);\n await db.execute(\n sql`select set_config('opengeni.private_file_owner', ${sessionActor.privateFileOwnerSubjectId ?? \"\"}, true), set_config(\n 'opengeni.initiating_human_subject_id',\n ${sessionActor.initiatingHumanSubjectId ?? \"\"},\n true\n )`,\n );\n }\n}\n\nasync function readRlsContextSettings(db: Database): Promise<RlsContextSettings> {\n const [settings] = await rawRows<{\n account_id: string | null;\n workspace_id: string | null;\n }>(\n db,\n sql`select\n current_setting('opengeni.account_id', true) as account_id,\n current_setting('opengeni.workspace_id', true) as workspace_id`,\n );\n return {\n accountId: settings?.account_id ?? \"\",\n workspaceId: settings?.workspace_id ?? \"\",\n };\n}\n\nasync function assertRlsContextApplied(db: Database, context: RlsContext): Promise<void> {\n const applied = await readRlsContextSettings(db);\n const expectedWorkspaceId = context.workspaceId ?? \"\";\n if (applied.accountId !== context.accountId) {\n throw new Error(\n `RLS context not applied on the active backend: expected account ${context.accountId}, got \"${applied.accountId}\"`,\n );\n }\n if (applied.workspaceId !== expectedWorkspaceId) {\n throw new Error(\n `RLS context not applied on the active backend: expected workspace \"${expectedWorkspaceId}\", got \"${applied.workspaceId}\"`,\n );\n }\n}\n\nasync function restoreRlsContextSettings(\n db: Database,\n settings: RlsContextSettings,\n): Promise<void> {\n const [restored] = await rawRows<{\n account_id: string;\n workspace_id: string;\n }>(\n db,\n sql`select\n set_config('opengeni.account_id', ${settings.accountId}, true) as account_id,\n set_config('opengeni.workspace_id', ${settings.workspaceId}, true) as workspace_id`,\n );\n if (\n restored?.account_id !== settings.accountId ||\n restored.workspace_id !== settings.workspaceId\n ) {\n throw new Error(\"RLS context could not be restored after a nested scope\");\n }\n}\n\nexport async function withRlsContext<T>(\n db: Database,\n context: RlsContext,\n fn: (db: Database) => Promise<T>,\n transactionConfig?: PgTransactionConfig,\n sessionTenancyFence: \"shared\" | \"none\" = \"shared\",\n): Promise<T> {\n const restoreParentScope = isTransactionHandle(db);\n return await db.transaction(async (tx) => {\n const scoped = tx as unknown as Database;\n const parentScope = restoreParentScope ? await readRlsContextSettings(scoped) : null;\n await setRlsContext(scoped, context);\n if (context.workspaceId && sessionTenancyFence === \"shared\") {\n await scoped.execute(\n sql`select pg_advisory_xact_lock_shared(hashtextextended(${`session-tenancy:${context.workspaceId}`}, 0))`,\n );\n }\n // Defense-in-depth: read the LOCAL GUC back on THIS backend BEFORE running\n // the scoped query. The set_config and this read share one db.transaction,\n // which a transaction pooler pins to a single backend — so a mismatch here\n // means the context was genuinely lost (a torn transaction / pooler backend\n // swap), not normal operation. Without this guard such an event runs the\n // scoped read with an empty account_id and returns zero RLS-visible rows,\n // manufacturing a phantom \"no active subscription\" from a credential that is\n // in fact active. Convert that silent false into a loud, root-cause-bearing\n // error so the caller can retry rather than permanently mis-decide.\n await assertRlsContextApplied(scoped, context);\n const value = await fn(scoped);\n // A nested transaction is a savepoint, and SET LOCAL survives successful\n // savepoint release. Restore only the tenant scope the nested helper owns;\n // writer/protocol capabilities intentionally remain transaction-wide.\n if (parentScope) await restoreRlsContextSettings(scoped, parentScope);\n return value;\n }, transactionConfig);\n}\n\n/**\n * Run one bounded database operation on a transaction-pinned backend.\n *\n * Callers that also have an application deadline should check their abort\n * signal before returning from `fn`; throwing there rolls the transaction back\n * even when the application deadline won a surrounding Promise race.\n */\nexport async function withDatabaseStatementTimeout<T>(\n db: Database,\n timeoutMs: number,\n fn: (db: Database) => Promise<T>,\n): Promise<T> {\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new Error(\"withDatabaseStatementTimeout requires a positive timeout\");\n }\n const boundedTimeoutMs = Math.max(1, Math.floor(timeoutMs));\n return await db.transaction(async (tx) => {\n const scoped = tx as unknown as Database;\n await scoped.execute(\n sql`select set_config('statement_timeout', ${`${boundedTimeoutMs}ms`}, true)`,\n );\n return await fn(scoped);\n });\n}\n\nexport async function rlsContextForWorkspace(\n db: Database,\n workspaceId: string,\n): Promise<RlsContext> {\n const [row] = await db\n .select({ accountId: schema.workspaces.accountId })\n .from(schema.workspaces)\n .where(eq(schema.workspaces.id, workspaceId))\n .limit(1);\n if (!row) {\n throw new Error(`Workspace not found: ${workspaceId}`);\n }\n return { accountId: row.accountId, workspaceId };\n}\n\nexport async function withWorkspaceRls<T>(\n db: Database,\n workspaceId: string,\n fn: (db: Database) => Promise<T>,\n transactionConfig?: PgTransactionConfig,\n): Promise<T> {\n return await withRlsContext(\n db,\n await rlsContextForWorkspace(db, workspaceId),\n fn,\n transactionConfig,\n );\n}\n\ntype SessionActivityGate = {\n db: SessionActivityDatabase;\n owner: boolean;\n};\n\nfunction isTransactionHandle(db: Database): boolean {\n return typeof (db as Database & { rollback?: unknown }).rollback === \"function\";\n}\n\nasync function assertSessionActivityGateEntry(db: Database): Promise<void> {\n if (!isTransactionHandle(db)) return;\n const [gate] = await rawRows<{ state: string | null }>(\n db,\n sql`\n select nullif(\n current_setting('opengeni.session_activity_gate_state', true),\n ''\n ) as state\n `,\n );\n if (gate?.state === null || gate === undefined) {\n throw new Error(\"Session activity commit gate must start at the outer transaction boundary\");\n }\n}\n\nasync function beginSessionActivityGate(\n db: Database,\n workspaceId: string,\n): Promise<SessionActivityGate> {\n const [gate] = await rawRows<{\n prior_state: string | null;\n prior_workspace_id: string | null;\n }>(\n db,\n sql`\n with current_gate as materialized (\n select\n nullif(current_setting('opengeni.session_activity_gate_state', true), '') as prior_state,\n nullif(current_setting('opengeni.session_activity_gate_workspace_id', true), '') as prior_workspace_id\n )\n select\n prior_state,\n prior_workspace_id,\n case\n when prior_state is null\n then set_config('opengeni.session_activity_gate_state', 'open', true)\n else prior_state\n end as effective_state,\n case\n when prior_state is null\n then set_config('opengeni.session_activity_gate_workspace_id', ${workspaceId}, true)\n else prior_workspace_id\n end as effective_workspace_id\n from current_gate\n `,\n );\n if (!gate) {\n throw new Error(\"Session activity commit gate could not be opened\");\n }\n if (gate.prior_state === null) {\n return { db: db as SessionActivityDatabase, owner: true };\n }\n if (gate.prior_state === \"open\" && gate.prior_workspace_id === workspaceId) {\n return { db: db as SessionActivityDatabase, owner: false };\n }\n throw new Error(\"Session activity commit gate is already owned by another transaction scope\");\n}\n\nasync function finalizeSessionActivityGate(\n db: SessionActivityDatabase,\n workspaceId: string,\n): Promise<void> {\n // Resolve every deferred FK/constraint before taking the shared workspace\n // counter. The only row writes after that point stamp session rows already\n // modified and therefore already owned by this transaction.\n await db.execute(\n sql`select set_config('opengeni.session_activity_gate_state', 'preparing', true)`,\n );\n await db.execute(sql`set constraints all immediate`);\n // The first flush proves every pre-existing deferred obligation. Re-defer\n // only our commit guard so the marker-clearing writes below queue a fresh\n // proof against the final row state, then force that proof before returning.\n await db.execute(\n sql`set constraints sessions_activity_insert_commit_guard, sessions_activity_update_commit_guard deferred`,\n );\n const [result] = await rawRows<{\n had_pending: boolean;\n pending_count: number;\n revision: string | null;\n stamped_count: number;\n }>(\n db,\n sql`\n with gate as materialized (\n select set_config('opengeni.session_activity_gate_state', 'finalizing', true) as state\n ),\n pending as materialized (\n select ${schema.sessions.id}\n from ${schema.sessions}\n cross join gate\n where ${schema.sessions.workspaceId} = ${workspaceId}\n and ${schema.sessions.activityRevisionPendingXid}\n = pg_current_xact_id()::text::bigint\n ),\n advanced as (\n update ${schema.workspaceSessionActivityRevisions} as counter\n set revision = counter.revision + 1\n where counter.workspace_id = ${workspaceId}\n and exists (select 1 from pending)\n returning counter.revision\n ),\n stamped as (\n update ${schema.sessions} as session\n set\n activity_revision = advanced.revision,\n activity_revision_pending_xid = null\n from advanced\n where session.workspace_id = ${workspaceId}\n and session.activity_revision_pending_xid\n = pg_current_xact_id()::text::bigint\n returning session.id\n ),\n stats as materialized (\n select\n exists (select 1 from pending) as had_pending,\n (select count(*)::integer from pending) as pending_count,\n (select revision::text from advanced) as revision,\n (select count(*)::integer from stamped) as stamped_count\n ),\n finalized as materialized (\n select\n had_pending,\n pending_count,\n revision,\n stamped_count,\n set_config('opengeni.session_activity_gate_state', 'finalized', true) as state\n from stats\n )\n select had_pending, pending_count, revision, stamped_count\n from finalized\n `,\n );\n if (!result) {\n throw new Error(\"Session activity commit gate did not return a finalization result\");\n }\n if (result.had_pending && result.revision === null) {\n throw new Error(\"Workspace session activity counter is unavailable\");\n }\n if (result.stamped_count !== result.pending_count) {\n throw new Error(\"Session activity commit gate did not stamp every pending row\");\n }\n await db.execute(\n sql`set constraints sessions_activity_insert_commit_guard, sessions_activity_update_commit_guard immediate`,\n );\n // A restored activity scope can be followed by another workspace scope, or\n // by a SECURITY DEFINER lifecycle that opens and finalizes its own gate in\n // the same outer transaction. Keep the guards deferred after proving this\n // scope's final state so those later writes reach their own finalizer instead\n // of firing the commit guard at the first session update.\n await db.execute(\n sql`set constraints sessions_activity_insert_commit_guard, sessions_activity_update_commit_guard deferred`,\n );\n}\n\n/**\n * Run one workspace transaction with explicit once-per-transaction session\n * activity finalization. Nested callers reuse the outer gate; only its owner\n * finalizes immediately before the enclosing RLS transaction commits.\n */\nexport async function withSessionActivityRlsContext<T>(\n db: Database,\n context: RlsContext & { workspaceId: string },\n fn: (db: SessionActivityDatabase) => Promise<T>,\n transactionConfig?: PgTransactionConfig,\n fenceMode: \"shared\" | \"none\" = \"shared\",\n organizationMembershipFence = false,\n): Promise<T> {\n await assertSessionActivityGateEntry(db);\n return await withRlsContext(\n db,\n context,\n async (scopedDb) => {\n if (organizationMembershipFence) {\n // Claim can inherit membership-fenced authority after locking sessions.\n // Acquire membership before even a shared tenancy fence: an exclusive\n // tenancy/control waiter can otherwise complete the same lock cycle.\n await scopedDb.execute(sql`select pg_advisory_xact_lock(\n hashtextextended(${`organization-membership:${context.accountId}`}, 0))`);\n if (fenceMode === \"shared\") {\n await scopedDb.execute(sql`select pg_advisory_xact_lock_shared(\n hashtextextended(${`session-tenancy:${context.workspaceId}`}, 0))`);\n }\n }\n const gate = await beginSessionActivityGate(scopedDb, context.workspaceId);\n const value = await fn(gate.db);\n // The finalizer must never trust tenant GUCs that arbitrary callback code\n // could have changed. Nested RLS helpers restore their parent scope; this\n // assertion is the fail-closed commit-boundary proof for every other path.\n await assertRlsContextApplied(gate.db, context);\n if (gate.owner) {\n await finalizeSessionActivityGate(gate.db, context.workspaceId);\n }\n return value;\n },\n transactionConfig,\n organizationMembershipFence ? \"none\" : fenceMode,\n );\n}\n\nexport async function withWorkspaceSessionActivityRls<T>(\n db: Database,\n workspaceId: string,\n fn: (db: SessionActivityDatabase) => Promise<T>,\n transactionConfig?: PgTransactionConfig,\n): Promise<T> {\n return await withSessionActivityRlsContext(\n db,\n { ...(await rlsContextForWorkspace(db, workspaceId)), workspaceId },\n fn,\n transactionConfig,\n );\n}\n\n/**\n * Run one of several ordered workspace activity scopes inside a caller-owned\n * transaction. Each scope is fully finalized before restoring the caller's\n * gate GUCs, so the next workspace can reuse the same outer transaction.\n */\nexport async function withRestoredSessionActivityRlsContext<T>(\n db: Database,\n context: RlsContext & { workspaceId: string },\n fn: (db: SessionActivityDatabase) => Promise<T>,\n): Promise<T> {\n if (!isTransactionHandle(db)) {\n throw new Error(\"Sequential workspace activity scopes require a caller-owned transaction\");\n }\n const [prior] = await rawRows<{ state: string; workspace_id: string }>(\n db,\n sql`select\n coalesce(current_setting('opengeni.session_activity_gate_state', true), '') as state,\n coalesce(\n current_setting('opengeni.session_activity_gate_workspace_id', true), ''\n ) as workspace_id`,\n );\n try {\n return await withRlsContext(db, context, async (scopedDb) => {\n const gate = await beginSessionActivityGate(scopedDb, context.workspaceId);\n if (!gate.owner) {\n throw new Error(\"Sequential workspace activity scope unexpectedly reused an open gate\");\n }\n const value = await fn(gate.db);\n await assertRlsContextApplied(gate.db, context);\n await finalizeSessionActivityGate(gate.db, context.workspaceId);\n return value;\n });\n } finally {\n await db.execute(sql`select\n set_config('opengeni.session_activity_gate_state', ${prior?.state ?? \"\"}, true),\n set_config(\n 'opengeni.session_activity_gate_workspace_id', ${prior?.workspace_id ?? \"\"}, true\n )`);\n }\n}\n\n/**\n * Open one nested savepoint without losing the gate brand. Drizzle correctly\n * preserves the backend-local gate GUCs, but its structural transaction type\n * cannot express that provenance; keep the single trusted rebrand here.\n */\nexport async function withSessionActivitySavepoint<T>(\n db: SessionActivityDatabase,\n fn: (db: SessionActivityDatabase) => Promise<T>,\n): Promise<T> {\n return await db.transaction(async (tx) => await fn(tx as unknown as SessionActivityDatabase));\n}\n\nexport async function retrySessionActivityRls<T>(\n db: Database,\n workspaceId: string,\n options: IdempotentPersistenceTransactionOptions & {\n /** Claim can inherit membership-fenced causal authority after locking the\n * session. Acquire that fence before tenancy/control/session instead. An\n * enclosing transaction must preserve this same lock prefix. */\n organizationMembershipFence?: boolean;\n },\n fn: (db: SessionActivityDatabase) => Promise<T>,\n): Promise<T> {\n return await runIdempotentPersistenceTransaction(options, async () => {\n if (options.organizationMembershipFence) {\n const context = { ...(await rlsContextForWorkspace(db, workspaceId)), workspaceId };\n return await withSessionActivityRlsContext(db, context, fn, undefined, \"shared\", true);\n }\n return await withWorkspaceSessionActivityRls(db, workspaceId, fn);\n });\n}\n\nexport async function retryWorkspacePersistence<T>(\n db: Database,\n workspaceId: string,\n options: IdempotentPersistenceTransactionOptions,\n fn: (db: Database) => Promise<T>,\n): Promise<T> {\n return await runIdempotentPersistenceTransaction(options, async () => {\n return await withWorkspaceRls(db, workspaceId, fn);\n });\n}\n\nexport async function retryRlsPersistence<T>(\n db: Database,\n context: RlsContext,\n options: IdempotentPersistenceTransactionOptions,\n fn: (db: Database) => Promise<T>,\n): Promise<T> {\n return await runIdempotentPersistenceTransaction(options, async () => {\n return await withRlsContext(db, context, fn);\n });\n}\n\n/**\n * Personal workspace data needs both tenant and authenticated-principal GUCs.\n * `session_pins` uses this helper so FORCE RLS rejects another member's rows\n * even if a future query accidentally omits its explicit subject predicate.\n */\nexport async function withWorkspaceSubjectRls<T>(\n db: Database,\n workspaceId: string,\n subjectId: string,\n fn: (db: Database) => Promise<T>,\n transactionConfig?: PgTransactionConfig,\n sessionTenancyFence: \"shared\" | \"none\" = \"shared\",\n): Promise<T> {\n if (!subjectId.trim()) {\n throw new Error(\"withWorkspaceSubjectRls: a non-empty subjectId is required\");\n }\n const context = await rlsContextForWorkspace(db, workspaceId);\n return await withRlsContext(\n db,\n context,\n async (scopedDb) => {\n await setSubjectRlsContext(scopedDb, subjectId);\n return await fn(scopedDb);\n },\n transactionConfig,\n sessionTenancyFence,\n );\n}\n\nexport async function withWorkspaceSubjectSessionActivityRls<T>(\n db: Database,\n workspaceId: string,\n subjectId: string,\n fn: (db: SessionActivityDatabase) => Promise<T>,\n transactionConfig?: PgTransactionConfig,\n fenceMode: \"shared\" | \"none\" = \"shared\",\n): Promise<T> {\n if (!subjectId.trim()) {\n throw new Error(\"withWorkspaceSubjectSessionActivityRls: a non-empty subjectId is required\");\n }\n const context = await rlsContextForWorkspace(db, workspaceId);\n return await withSessionActivityRlsContext(\n db,\n { ...context, workspaceId },\n async (scopedDb) => {\n await setSubjectRlsContext(scopedDb, subjectId);\n return await fn(scopedDb);\n },\n transactionConfig,\n fenceMode,\n );\n}\n\n/** Apply and verify actor-private RLS on an already transaction-pinned handle. */\nexport async function setSubjectRlsContext(db: Database, subjectId: string): Promise<void> {\n if (!subjectId.trim()) {\n throw new Error(\"setSubjectRlsContext: a non-empty subjectId is required\");\n }\n await db.execute(sql`select set_config('opengeni.subject_id', ${subjectId}, true)`);\n const applied = await db.execute<{ subject_id: string | null }>(\n sql`select current_setting('opengeni.subject_id', true) as subject_id`,\n );\n if ((applied[0]?.subject_id ?? \"\") !== subjectId) {\n throw new Error(\"Authenticated subject RLS context was not applied on the active backend\");\n }\n}\n\nexport async function withWorkspaceUsageLock<T>(\n db: Database,\n workspaceId: string,\n fn: (db: Database) => Promise<T>,\n): Promise<T> {\n const context = await rlsContextForWorkspace(db, workspaceId);\n return await withRlsContext(db, context, async (scopedDb) => {\n await scopedDb.execute(sql`select pg_advisory_xact_lock(hashtext(${`usage:${workspaceId}`}))`);\n return await fn(scopedDb);\n });\n}\n\nexport async function withAccountRls<T>(\n db: Database,\n accountId: string,\n fn: (db: Database) => Promise<T>,\n): Promise<T> {\n return await withRlsContext(db, { accountId, workspaceId: null }, fn);\n}\n\n/** Internal lookup for the host binding attached to a database handle. */\nexport function dbBindingFor(db: Database): DbBinding | undefined {\n return dbBindings.get(db as unknown as object);\n}\n"],"mappings":";;;;;;;;;;;AAyBA,IAAM,gBAAgB,CAAC,YAAY,YAAY,MAAM;AACrD,IAAM,oBAAoB,CAAC,SAAS,YAAY,eAAe,SAAS,QAAQ;AAChF,IAAM,qCAAqC,oBAAI,IAAI;AAAA;AAAA,EAEjD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAM,uBAAuB,oBAAI,IAAI,CAAC,iBAAiB,qBAAqB,eAAe,CAAC;AAC5F,IAAM,2BAA2B;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,IAAM,iBAAiB;AAAA,EACrB,CAAC,YAAY,UAAU;AAAA,EACvB,CAAC,eAAe,QAAQ;AAAA,EACxB,CAAC,UAAU,QAAQ;AAAA,EACnB,CAAC,cAAc,OAAO;AAAA,EACtB,CAAC,SAAS,OAAO;AAAA,EACjB,CAAC,eAAe,QAAQ;AAAA,EACxB,CAAC,UAAU,QAAQ;AAAA,EACnB,CAAC,kBAAkB,UAAU;AA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