gencow 0.1.299 → 0.2.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.
Files changed (149) hide show
  1. package/bin/gencow.mjs +0 -6
  2. package/core/package.json +1 -1
  3. package/docs/packaging.md +14 -4
  4. package/lib/cli-artifact-guard.mjs +53 -3
  5. package/lib/cli-dev-runtime.mjs +1 -0
  6. package/lib/cli-project-runtime.mjs +26 -14
  7. package/lib/codegen-command.mjs +16 -0
  8. package/lib/coding-guardrails.mjs +2 -0
  9. package/lib/dashboard-artifact.mjs +65 -0
  10. package/lib/dashboard-assets.mjs +20 -0
  11. package/lib/db-command.mjs +121 -80
  12. package/lib/db-migration-command-steps.mjs +19 -16
  13. package/lib/db-push-command.mjs +1 -1
  14. package/lib/deploy-codegen-preflight.mjs +1 -0
  15. package/lib/dev-cloud-command.mjs +1 -1
  16. package/lib/dev-local-command.mjs +19 -56
  17. package/lib/document-local-converter.mjs +11 -0
  18. package/lib/local-dashboard-plan.mjs +60 -0
  19. package/lib/local-database-commands.mjs +127 -0
  20. package/lib/local-development-migrations.mjs +157 -0
  21. package/lib/local-drizzle-database.config.mjs +10 -0
  22. package/lib/local-runtime-features.mjs +12 -0
  23. package/lib/rag-selection.mjs +7 -0
  24. package/lib/runtime-local-worker.mjs +116 -0
  25. package/lib/runtime-mode.mjs +3 -0
  26. package/lib/standalone-codegen-adapter.mjs +91 -0
  27. package/lib/ts-codegen-import-extension.mjs +228 -19
  28. package/package.json +16 -9
  29. package/runtime/config.mjs +218 -2
  30. package/runtime/engine/chunk-2HA4CUMS.mjs +90 -0
  31. package/runtime/engine/chunk-2JLO3KMM.mjs +305 -0
  32. package/runtime/engine/chunk-2SR2M7SR.mjs +1045 -0
  33. package/runtime/engine/chunk-3D7MHEUC.mjs +253 -0
  34. package/runtime/engine/chunk-3R7COBWG.mjs +309 -0
  35. package/runtime/engine/chunk-3ZKA54UW.mjs +1560 -0
  36. package/runtime/engine/chunk-45I4YR2J.mjs +9 -0
  37. package/runtime/engine/chunk-4MLRXO7F.mjs +74 -0
  38. package/runtime/engine/chunk-5575APCJ.mjs +215 -0
  39. package/runtime/engine/chunk-5GUJZQF3.mjs +114 -0
  40. package/runtime/engine/chunk-5MXY3T75.mjs +428 -0
  41. package/runtime/engine/chunk-5TACQ2US.mjs +44 -0
  42. package/runtime/engine/chunk-66G4YEDT.mjs +3104 -0
  43. package/runtime/engine/chunk-67YO53WW.mjs +1426 -0
  44. package/runtime/engine/chunk-6GQRM7XY.mjs +87 -0
  45. package/runtime/engine/chunk-6JO72SPP.mjs +68 -0
  46. package/runtime/engine/chunk-6W653LXI.mjs +13 -0
  47. package/runtime/engine/chunk-7ITSMI3S.mjs +69 -0
  48. package/runtime/engine/chunk-7KUJ2H2S.mjs +128 -0
  49. package/runtime/engine/chunk-A5BMQ5IC.mjs +45 -0
  50. package/runtime/engine/chunk-ADF3UR6L.mjs +428 -0
  51. package/runtime/engine/chunk-AEBW7XZJ.mjs +4510 -0
  52. package/runtime/engine/chunk-AGPQ5XIV.mjs +156 -0
  53. package/runtime/engine/chunk-CPU4OZSX.mjs +753 -0
  54. package/runtime/engine/chunk-CSWPPWBL.mjs +50 -0
  55. package/runtime/engine/chunk-DPWXSMWO.mjs +53 -0
  56. package/runtime/engine/chunk-EAIELFKU.mjs +151 -0
  57. package/runtime/engine/chunk-EDU5CBKT.mjs +10 -0
  58. package/runtime/engine/chunk-EQCTAET7.mjs +173 -0
  59. package/runtime/engine/chunk-EQCXDF2Z.mjs +70 -0
  60. package/runtime/engine/chunk-F3G4UGV4.mjs +330 -0
  61. package/runtime/engine/chunk-F62NUNOO.mjs +26 -0
  62. package/runtime/engine/chunk-FKPNIFRP.mjs +2492 -0
  63. package/runtime/engine/chunk-FM23RGVI.mjs +81 -0
  64. package/runtime/engine/chunk-FW5AK4YP.mjs +1041 -0
  65. package/runtime/engine/chunk-GDWYAGWV.mjs +23 -0
  66. package/runtime/engine/chunk-GO5PZUYW.mjs +53 -0
  67. package/runtime/engine/chunk-GOLP7OSG.mjs +340 -0
  68. package/runtime/engine/chunk-GSLM44EF.mjs +242 -0
  69. package/runtime/engine/chunk-GYAJ7OX2.mjs +125 -0
  70. package/runtime/engine/chunk-I3GWR43K.mjs +14 -0
  71. package/runtime/engine/chunk-IFMOTJNU.mjs +106 -0
  72. package/runtime/engine/chunk-IKQKBE2G.mjs +128 -0
  73. package/runtime/engine/chunk-ITH2NEKM.mjs +282 -0
  74. package/runtime/engine/chunk-J6SDRCG4.mjs +96 -0
  75. package/runtime/engine/chunk-JODRNM3S.mjs +29596 -0
  76. package/runtime/engine/chunk-JUDKX53X.mjs +137 -0
  77. package/runtime/engine/chunk-K2YZVPJ4.mjs +827 -0
  78. package/runtime/engine/chunk-KEZJUXEE.mjs +151 -0
  79. package/runtime/engine/chunk-KVLTJFCH.mjs +234 -0
  80. package/runtime/engine/chunk-KX2PRQPS.mjs +126 -0
  81. package/runtime/engine/chunk-LEW5ZMLR.mjs +76 -0
  82. package/runtime/engine/chunk-LINVSJEM.mjs +175 -0
  83. package/runtime/engine/chunk-M7K2ICSM.mjs +11 -0
  84. package/runtime/engine/chunk-MZXDXSDC.mjs +292 -0
  85. package/runtime/engine/chunk-N2TA2IK2.mjs +678 -0
  86. package/runtime/engine/chunk-N4LTCKJP.mjs +695 -0
  87. package/runtime/engine/chunk-N6GCLOUX.mjs +13 -0
  88. package/runtime/engine/chunk-NAG2OXS5.mjs +37 -0
  89. package/runtime/engine/chunk-NNZ2QJUG.mjs +381 -0
  90. package/runtime/engine/chunk-NZPPLDNW.mjs +15 -0
  91. package/runtime/engine/chunk-ODWM57W6.mjs +138 -0
  92. package/runtime/engine/chunk-P5IIXAIE.mjs +23 -0
  93. package/runtime/engine/chunk-PBOXB2BV.mjs +6 -0
  94. package/runtime/engine/chunk-PMOJLN2P.mjs +8 -0
  95. package/runtime/engine/chunk-PZFMKFHO.mjs +180 -0
  96. package/runtime/engine/chunk-QL2TQX2N.mjs +114 -0
  97. package/runtime/engine/chunk-RITT2RSJ.mjs +258 -0
  98. package/runtime/engine/chunk-RODBVJ5M.mjs +135 -0
  99. package/runtime/engine/chunk-RW65MPVY.mjs +261 -0
  100. package/runtime/engine/chunk-S67UYPB6.mjs +25 -0
  101. package/runtime/engine/chunk-SVJCOUI3.mjs +47 -0
  102. package/runtime/engine/chunk-TCN3ZASV.mjs +957 -0
  103. package/runtime/engine/chunk-U2NRG6KC.mjs +32 -0
  104. package/runtime/engine/chunk-UM3F7HUV.mjs +432 -0
  105. package/runtime/engine/chunk-VWU7JJ3P.mjs +146 -0
  106. package/runtime/engine/chunk-WDTKPPMU.mjs +310 -0
  107. package/runtime/engine/chunk-WJOO4XTB.mjs +31 -0
  108. package/runtime/engine/chunk-XNFVL2OY.mjs +63 -0
  109. package/runtime/engine/chunk-XPWJXP2J.mjs +58 -0
  110. package/runtime/engine/chunk-Y3HSBJ3I.mjs +1132 -0
  111. package/runtime/engine/chunk-YMH4RYSX.mjs +317 -0
  112. package/runtime/engine/chunk-YNOMPSGS.mjs +8 -0
  113. package/runtime/engine/chunk-YRBAYTEZ.mjs +251 -0
  114. package/runtime/engine/chunk-YRHM272W.mjs +528 -0
  115. package/runtime/engine/chunk-ZQUZAGIQ.mjs +149 -0
  116. package/runtime/engine/chunk-ZXMM7QFP.mjs +176 -0
  117. package/runtime/engine/chunk-ZZJSIPV2.mjs +262 -0
  118. package/runtime/engine/composition.mjs +325 -0
  119. package/runtime/engine/document-local.mjs +504 -0
  120. package/runtime/engine/graph.json +4134 -0
  121. package/runtime/engine/index.mjs +265 -0
  122. package/runtime/engine/local-postgres-support.mjs +69 -0
  123. package/runtime/engine/local.mjs +3275 -0
  124. package/runtime/engine/pglite-directory-lock.mjs +8 -0
  125. package/runtime/engine/rag.mjs +11 -0
  126. package/runtime/engine/search.mjs +18 -0
  127. package/runtime/framework-migrations/foundation-bootstrap/rag.sql +115 -0
  128. package/runtime/framework-migrations/foundation-bootstrap/workflow.sql +194 -0
  129. package/runtime/framework-migrations/journal-bootstrap/migration.sql +26 -0
  130. package/runtime/framework-migrations/manifest.json +56 -0
  131. package/runtime/framework-migrations/rag/20261006111509_mushy_warhawk/migration.sql +121 -0
  132. package/runtime/framework-migrations/rag/20261013234621_rag_v2_lifecycle_markers/migration.sql +6 -0
  133. package/runtime/framework-migrations/workflow/20261006111508_perpetual_star_brand/migration.sql +31 -0
  134. package/runtime/runtime-metadata.json +27 -0
  135. package/runtime/tooling.mjs +10399 -8951
  136. package/scripts/bundle-runtime-config.mjs +23 -0
  137. package/scripts/bundle-runtime.mjs +100 -0
  138. package/scripts/bundle-runtime.test.mjs +33 -0
  139. package/scripts/bundle-shared.mjs +3 -0
  140. package/scripts/copy-dashboard.mjs +16 -0
  141. package/scripts/pre-publish-check.mjs +23 -11
  142. package/templateFeature/sso/sso-auth-callback.tsx +37 -5
  143. package/templateFeature/tools/manifest.json +2 -1
  144. package/templateFeature/tools/tools.ts +3 -3
  145. package/runtime/server.mjs +0 -14389
  146. package/scripts/bundle-server.mjs +0 -223
  147. package/server/config.js +0 -1
  148. package/server/index.js +0 -1
  149. package/server/package.json +0 -6
@@ -0,0 +1,753 @@
1
+ import {
2
+ captureSearchCapabilityConfig,
3
+ dataRows,
4
+ prepareSearchInput
5
+ } from "./chunk-ADF3UR6L.mjs";
6
+ import {
7
+ runtimeScopedApplicationReads,
8
+ sameRuntimeScopedApplicationOwner,
9
+ sameRuntimeScopedRls
10
+ } from "./chunk-YRHM272W.mjs";
11
+ import {
12
+ ragSchemaError
13
+ } from "./chunk-P5IIXAIE.mjs";
14
+ import {
15
+ groundingScopeEnded
16
+ } from "./chunk-XNFVL2OY.mjs";
17
+ import {
18
+ workflowSchemaFailure
19
+ } from "./chunk-LINVSJEM.mjs";
20
+ import {
21
+ assertSearchScope
22
+ } from "./chunk-QL2TQX2N.mjs";
23
+ import {
24
+ RuntimeSearchError,
25
+ RuntimeSearchRlsContextError,
26
+ snapshotSearchRls
27
+ } from "./chunk-LEW5ZMLR.mjs";
28
+ import {
29
+ runtimeStartupError
30
+ } from "./chunk-IFMOTJNU.mjs";
31
+ import {
32
+ RuntimeDatabaseRlsError,
33
+ RuntimeDiagnosticError,
34
+ buildSearchIndexNames,
35
+ createRlsDb,
36
+ runtimeAdapterDependencyMissing,
37
+ runtimeDiagnostic,
38
+ scopedCoreRlsDiagnostic
39
+ } from "./chunk-AEBW7XZJ.mjs";
40
+
41
+ // ../runtime/dist/adapters/database/generation-binding.js
42
+ function assertDatabaseGeneration(binding, request) {
43
+ if (!request || !Object.isFrozen(request) || !Object.isFrozen(request.binding) || request.binding?.appId !== binding.appId || request.binding?.generationId !== binding.generationId) {
44
+ throw new RuntimeDatabaseRlsError("RUNTIME_DATABASE_GENERATION_MISMATCH", "request", "Correct the trusted host app/generation binding and use the current Runtime generation; request data cannot select a database.", "none");
45
+ }
46
+ }
47
+
48
+ // ../runtime/dist/adapters/database/managed-schema.js
49
+ function captureManagedSchemaComponents(input = []) {
50
+ if (!Array.isArray(input) || input.some((component) => component !== "workflow" && component !== "rag"))
51
+ throw runtimeStartupError("RUNTIME_COMPONENT_DEPENDENCY_INVALID", "Select only supported built-in managed database components before startup.");
52
+ return Object.freeze([...new Set(input)]);
53
+ }
54
+ function createManagedSchemaPreparation(owner, operations) {
55
+ const ready = /* @__PURE__ */ new Map();
56
+ let tail = Promise.resolve();
57
+ let closed = false;
58
+ function failure(component) {
59
+ return component === "rag" ? ragSchemaError() : workflowSchemaFailure();
60
+ }
61
+ async function prepareBuiltin(component) {
62
+ if (closed)
63
+ throw failure(component);
64
+ if (component === "workflow") {
65
+ const { validateRuntimeWorkflowSchema, workflowSchemaBootstrapUnavailable } = await import("./chunk-6W653LXI.mjs");
66
+ if (owner.engine === "pglite") {
67
+ const ready2 = await validateRuntimeWorkflowSchema(operations, true);
68
+ if (ready2 !== true) {
69
+ const { initializePgliteWorkflowSchema } = await import("./chunk-XPWJXP2J.mjs");
70
+ await initializePgliteWorkflowSchema(owner.client);
71
+ await validateRuntimeWorkflowSchema(operations);
72
+ }
73
+ } else if (owner.prepareWorkflow)
74
+ await owner.prepareWorkflow();
75
+ else {
76
+ const { validatePostgresCompletionFence } = await import("./chunk-S67UYPB6.mjs");
77
+ if (!await validateRuntimeWorkflowSchema(operations, true) || !await validatePostgresCompletionFence(operations))
78
+ throw workflowSchemaBootstrapUnavailable();
79
+ }
80
+ } else {
81
+ const { validateRuntimeRagSchema } = await import("./chunk-EDU5CBKT.mjs");
82
+ if (owner.engine === "pglite") {
83
+ const { initializePgliteRagSchema } = await import("./chunk-GO5PZUYW.mjs");
84
+ await initializePgliteRagSchema(owner.client, owner.operationalRoles);
85
+ await validateRuntimeRagSchema(operations, { operationalRoles: owner.operationalRoles });
86
+ } else {
87
+ if (owner.prepareRag)
88
+ await owner.prepareRag();
89
+ try {
90
+ if (!await operations.transaction((transaction) => validateRuntimeRagSchema(transaction, {
91
+ allowCompatibleMissing: true,
92
+ operationalRoles: owner.operationalRoles
93
+ }), { isolationLevel: "repeatable read", accessMode: "read only" })) {
94
+ throw ragSchemaError("RAG_SCHEMA_AUTHORITY_UNAVAILABLE");
95
+ }
96
+ } catch (error) {
97
+ if (!owner.prepareRag)
98
+ throw error;
99
+ const code = runtimeDiagnostic(error)?.code;
100
+ throw ragSchemaError(code?.startsWith("RAG_") ? code : "RAG_SCHEMA_INCOMPATIBLE", "unknown");
101
+ }
102
+ }
103
+ }
104
+ if (closed)
105
+ throw component === "rag" && (owner.engine === "pglite" || owner.prepareRag) ? ragSchemaError("RAG_SCHEMA_INCOMPATIBLE", "unknown") : failure(component);
106
+ return operations;
107
+ }
108
+ const preparation = Object.freeze({
109
+ prepare(component) {
110
+ if (component !== "workflow" && component !== "rag")
111
+ return Promise.reject(runtimeStartupError("RUNTIME_COMPONENT_DEPENDENCY_INVALID", "Use a supported built-in managed schema component; arbitrary setup SQL is unavailable."));
112
+ if (closed)
113
+ return Promise.reject(failure(component));
114
+ let promise = ready.get(component);
115
+ if (!promise) {
116
+ promise = tail.then(() => prepareBuiltin(component));
117
+ tail = promise.catch(() => {
118
+ });
119
+ ready.set(component, promise);
120
+ }
121
+ return promise;
122
+ }
123
+ });
124
+ return Object.freeze({
125
+ preparation,
126
+ async close() {
127
+ closed = true;
128
+ await tail;
129
+ }
130
+ });
131
+ }
132
+ async function loadPgliteManagedExtensions(components, search = false) {
133
+ if (!components.includes("rag") && !search)
134
+ return {};
135
+ const [{ vector }, { pg_trgm }] = await Promise.all([
136
+ import("@electric-sql/pglite/vector").catch(() => {
137
+ throw components.includes("rag") ? ragSchemaError("RAG_VECTOR_UNAVAILABLE") : runtimeAdapterDependencyMissing("database", "none");
138
+ }),
139
+ import("@electric-sql/pglite/contrib/pg_trgm").catch(() => {
140
+ throw components.includes("rag") ? ragSchemaError("RAG_TRIGRAM_UNAVAILABLE") : runtimeAdapterDependencyMissing("database", "none");
141
+ })
142
+ ]);
143
+ return { vector, pg_trgm };
144
+ }
145
+
146
+ // ../runtime/dist/adapters/database/administration-observation.js
147
+ import { sql } from "drizzle-orm";
148
+ var runtimeDatabaseInspection = Object.freeze({
149
+ async describe(database) {
150
+ const version = dataRows(await database.execute(sql`select version() as version`))[0]?.version;
151
+ const extensions = dataRows(await database.execute(sql`select extname as name, extversion as version from pg_extension order by extname limit 100`));
152
+ if (typeof version !== "string" || !version || version.length > 1024 || extensions.some((row) => typeof row.name !== "string" || typeof row.version !== "string"))
153
+ throw Error("Database observations unavailable");
154
+ return Object.freeze({
155
+ dbVersion: version,
156
+ extensions: Object.freeze(extensions.map((row) => Object.freeze({ name: row.name, version: row.version })))
157
+ });
158
+ }
159
+ });
160
+
161
+ // ../runtime/dist/adapters/search/postgres/session-reads.js
162
+ function createSearchSessionReads(database, scope, assertCurrent) {
163
+ const native = scope[runtimeScopedApplicationReads];
164
+ if (native) {
165
+ if (!sameRuntimeScopedApplicationOwner(native, scope) || !sameRuntimeScopedRls(native.rls, snapshotSearchRls(scope)))
166
+ throw new RuntimeSearchRlsContextError(scope);
167
+ return Object.freeze({
168
+ async execute(statement) {
169
+ assertCurrent();
170
+ try {
171
+ const result = await native.execute(statement);
172
+ assertCurrent();
173
+ return result;
174
+ } catch (error) {
175
+ assertCurrent();
176
+ throw error;
177
+ }
178
+ }
179
+ });
180
+ }
181
+ const rls = snapshotSearchRls(scope);
182
+ const scoped = createRlsDb(database, rls);
183
+ return Object.freeze({
184
+ execute: (statement) => scoped.transaction(async (tx) => {
185
+ assertCurrent();
186
+ const result = await tx.execute(statement);
187
+ assertCurrent();
188
+ return result;
189
+ })
190
+ });
191
+ }
192
+
193
+ // ../runtime/dist/adapters/search/postgres/readiness.js
194
+ import { sql as sql2 } from "drizzle-orm";
195
+
196
+ // ../runtime/dist/adapters/search/postgres/results.js
197
+ function searchRows(result) {
198
+ const rows = Array.isArray(result) ? result : result && typeof result === "object" && "rows" in result ? result.rows : void 0;
199
+ if (!Array.isArray(rows))
200
+ throw new Error("Search read result unavailable");
201
+ return rows;
202
+ }
203
+ var score = (value) => {
204
+ if (value === void 0 || value === null)
205
+ return void 0;
206
+ const numeric = Number(value);
207
+ return Number.isFinite(numeric) ? numeric : void 0;
208
+ };
209
+ function mapSearchResult(input, rows) {
210
+ const scoreKey = input.mode === "hybrid" ? "fused_score" : "score";
211
+ const selected = input.minScore === void 0 ? rows : rows.filter((row) => (score(row[scoreKey]) ?? -Infinity) >= input.minScore);
212
+ const items = selected.map((source) => {
213
+ if (typeof source.id !== "string" && typeof source.id !== "number")
214
+ throw new Error("Search ID unavailable");
215
+ const keyword = score(source.keyword_score), vector = score(source.vector_score), fused = score(source[scoreKey]) ?? 0;
216
+ const row = { ...source };
217
+ for (const field of [
218
+ "score",
219
+ "keyword_score",
220
+ "vector_score",
221
+ "fused_score",
222
+ "embedding",
223
+ input.vectorField
224
+ ])
225
+ delete row[field];
226
+ return {
227
+ id: source.id,
228
+ row,
229
+ score: fused,
230
+ matchedBy: input.mode === "lexical" ? ["fts", "trigram"] : input.mode === "vector" ? ["vector"] : [
231
+ ...keyword !== void 0 ? ["fts", "trigram"] : [],
232
+ ...vector !== void 0 ? ["vector"] : []
233
+ ],
234
+ ...input.mode === "hybrid" ? {
235
+ scores: {
236
+ ...keyword !== void 0 ? { keyword } : {},
237
+ ...vector !== void 0 ? { vector } : {},
238
+ fused
239
+ }
240
+ } : {}
241
+ };
242
+ });
243
+ return {
244
+ items,
245
+ meta: {
246
+ limit: input.limit,
247
+ offset: input.offset,
248
+ mode: input.mode,
249
+ indexReady: true,
250
+ ...items.length === input.limit ? { nextOffset: input.offset + input.limit } : {},
251
+ ...input.mode !== "vector" ? {
252
+ lexicalStrategies: ["fts", "trigram"],
253
+ keywordCandidateCount: input.mode === "lexical" ? items.length : selected.filter((row) => score(row.keyword_score) !== void 0).length
254
+ } : {},
255
+ ...input.mode !== "lexical" ? {
256
+ vectorCandidateCount: input.mode === "vector" ? items.length : selected.filter((row) => score(row.vector_score) !== void 0).length
257
+ } : {},
258
+ ...input.mode === "hybrid" ? { fusion: "rrf", fusedCandidateCount: items.length } : {},
259
+ ...input.minScore !== void 0 ? { minScoreApplied: input.minScore } : {}
260
+ }
261
+ };
262
+ }
263
+
264
+ // ../runtime/dist/adapters/search/postgres/readiness.js
265
+ var pgBooleanIncompatibleFilterTypes = /* @__PURE__ */ new Set([
266
+ "text",
267
+ "varchar",
268
+ "bpchar",
269
+ "uuid",
270
+ "int2",
271
+ "int4",
272
+ "int8",
273
+ "numeric",
274
+ "float4",
275
+ "float8"
276
+ ]);
277
+ async function assertSearchReadiness(input, scope, config, read) {
278
+ const fail = (code) => {
279
+ throw new RuntimeSearchError(code, scope.correlationId, scope.stage);
280
+ };
281
+ const extensions = searchRows(await read(sql2`SELECT extname,
282
+ pg_catalog.has_table_privilege(current_user, 'pg_catalog.pg_depend', 'SELECT') AS vector_catalog_readable
283
+ FROM pg_catalog.pg_extension WHERE extname IN ('pg_trgm','vector')`));
284
+ const vectorCatalogReadable = extensions.some((row) => row.vector_catalog_readable === true);
285
+ const installed = new Set(extensions.map((row) => row.extname));
286
+ if (input.mode !== "vector" && (!config.extensions.pgTrgm || !installed.has("pg_trgm")))
287
+ fail("SEARCH_EXTENSION_NOT_READY");
288
+ if (input.mode !== "lexical" && (!config.extensions.vector || !installed.has("vector") || input.mode === "hybrid" && !config.hybridSearch))
289
+ fail("SEARCH_CAPABILITY_DEGRADED");
290
+ if (/^_(?:gencow|drizzle)/i.test(input.table) || input.table === "drizzle_migrations")
291
+ fail("SEARCH_TABLE_UNAVAILABLE");
292
+ const relation = searchRows(await read(sql2`SELECT c.oid::text AS relation_id, c.relkind,
293
+ pg_catalog.has_schema_privilege(n.oid, 'USAGE') AS schema_usable
294
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
295
+ WHERE n.nspname='public' AND c.relname=${input.table} AND c.relkind IN ('r','p')`))[0];
296
+ if (!relation)
297
+ fail("SEARCH_TABLE_UNAVAILABLE");
298
+ const relationId = relation.relation_id;
299
+ const columns = searchRows(await read(sql2`SELECT a.attname AS name, t.oid::text AS type_oid, t.typname AS type, a.atttypmod AS dimension, a.attnotnull AS nonnull,
300
+ tn.nspname AS type_namespace,
301
+ (pg_catalog.has_table_privilege(a.attrelid, 'SELECT') OR
302
+ pg_catalog.has_column_privilege(a.attrelid, a.attnum, 'SELECT')) AS selectable,
303
+ ${vectorCatalogReadable ? sql2`EXISTS (SELECT 1 FROM pg_catalog.pg_depend d JOIN pg_catalog.pg_extension e ON e.oid=d.refobjid
304
+ WHERE d.classid='pg_catalog.pg_type'::regclass AND d.objid=t.oid
305
+ AND d.refclassid='pg_catalog.pg_extension'::regclass AND d.deptype='e' AND e.extname='vector')` : sql2`NULL::boolean`} AS vector_member
306
+ FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_type t ON t.oid=a.atttypid
307
+ JOIN pg_catalog.pg_namespace tn ON tn.oid=t.typnamespace
308
+ WHERE a.attrelid=${relationId}::oid AND a.attnum>0 AND NOT a.attisdropped`));
309
+ const names = new Map(columns.map((column) => [column.name, column]));
310
+ const required = [
311
+ "id",
312
+ "corpus",
313
+ "visibility_scope",
314
+ "owner_user_id",
315
+ ...input.fields,
316
+ ...input.filters.map((filter) => filter.field),
317
+ ...input.mode === "lexical" ? [] : [input.vectorField]
318
+ ];
319
+ if (required.some((field) => !names.has(field)))
320
+ fail("SEARCH_COLUMN_UNAVAILABLE");
321
+ const canReadWholeRow = relation.schema_usable === true && columns.every((column) => column.selectable === true);
322
+ const visibleBooleanEqualityByType = /* @__PURE__ */ new Map();
323
+ const hasVisibleBooleanEqualityCandidate = async (typeOid) => {
324
+ const cached = visibleBooleanEqualityByType.get(typeOid);
325
+ if (cached !== void 0)
326
+ return cached;
327
+ const candidate = searchRows(await read(sql2`SELECT EXISTS (
328
+ SELECT 1
329
+ FROM pg_catalog.pg_operator o
330
+ JOIN pg_catalog.pg_namespace opn ON opn.oid=o.oprnamespace
331
+ JOIN pg_catalog.pg_type left_type ON left_type.oid=o.oprleft
332
+ JOIN pg_catalog.pg_type right_type ON right_type.oid=o.oprright
333
+ JOIN pg_catalog.pg_type result_type ON result_type.oid=o.oprresult
334
+ JOIN pg_catalog.pg_type source_type ON source_type.oid=${typeOid}::oid
335
+ WHERE o.oprname='=' AND o.oprkind='b' AND pg_catalog.pg_operator_is_visible(o.oid)
336
+ AND (
337
+ o.oprleft=${typeOid}::oid
338
+ OR EXISTS (SELECT 1 FROM pg_catalog.pg_cast c
339
+ WHERE c.castsource=${typeOid}::oid AND c.casttarget=o.oprleft AND c.castcontext='i')
340
+ OR (left_type.typtype='d' AND left_type.typbasetype=${typeOid}::oid)
341
+ -- String-category casts and domain/base compatibility are not
342
+ -- exhaustively represented by pg_cast. Keep those candidates on
343
+ -- PostgreSQL's real operator resolver rather than over-rejecting.
344
+ OR (source_type.typcategory='S' AND left_type.typcategory='S')
345
+ OR (opn.nspname<>'pg_catalog' AND
346
+ (left_type.typtype='p' OR
347
+ (left_type.typnamespace<>'pg_catalog'::regnamespace AND source_type.typcategory='S')))
348
+ )
349
+ AND (
350
+ o.oprright='pg_catalog.bool'::regtype
351
+ OR EXISTS (SELECT 1 FROM pg_catalog.pg_cast c
352
+ WHERE c.castsource='pg_catalog.bool'::regtype AND c.casttarget=o.oprright AND c.castcontext='i')
353
+ OR (right_type.typtype='d' AND right_type.typbasetype='pg_catalog.bool'::regtype)
354
+ OR (opn.nspname<>'pg_catalog' AND right_type.typtype='p')
355
+ )
356
+ AND (
357
+ o.oprresult='pg_catalog.bool'::regtype
358
+ OR (result_type.typtype='d' AND result_type.typbasetype='pg_catalog.bool'::regtype)
359
+ OR (opn.nspname<>'pg_catalog' AND result_type.typtype='p')
360
+ )
361
+ ) AS has_candidate`))[0]?.has_candidate === true;
362
+ visibleBooleanEqualityByType.set(typeOid, candidate);
363
+ return candidate;
364
+ };
365
+ for (const filter of input.filters) {
366
+ if ((filter.operator === "eq" || filter.operator === "in") && filter.values.some((value) => typeof value === "boolean")) {
367
+ const column = names.get(filter.field);
368
+ if (!canReadWholeRow)
369
+ fail("SEARCH_DATABASE_ACCESS_DENIED");
370
+ if (column.type_namespace === "pg_catalog" && pgBooleanIncompatibleFilterTypes.has(String(column.type)) && !await hasVisibleBooleanEqualityCandidate(String(column.type_oid)))
371
+ fail("SEARCH_INVALID_FILTER");
372
+ }
373
+ }
374
+ const id = names.get("id");
375
+ if (!id.nonnull || !["text", "varchar", "bpchar", "uuid", "int2", "int4", "int8", "numeric", "float4", "float8"].includes(String(id.type)))
376
+ fail("SEARCH_COLUMN_UNAVAILABLE");
377
+ const unique = searchRows(await read(sql2`SELECT i.indexrelid FROM pg_catalog.pg_index i
378
+ JOIN pg_catalog.pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=i.indkey[0]
379
+ WHERE i.indrelid=${relationId}::oid AND i.indisunique AND i.indisvalid AND i.indisready
380
+ AND i.indnkeyatts=1 AND i.indpred IS NULL AND a.attname='id'`));
381
+ if (!unique.length)
382
+ fail("SEARCH_COLUMN_UNAVAILABLE");
383
+ if (input.mode !== "lexical") {
384
+ const vector = names.get(input.vectorField);
385
+ if (vector.type !== "vector" || vector.vector_member === false)
386
+ fail("SEARCH_COLUMN_UNAVAILABLE");
387
+ if (vector.vector_member === true && Number(vector.dimension) > 0 && Number(vector.dimension) !== input.vectorLength)
388
+ fail("SEARCH_INVALID_VECTOR");
389
+ }
390
+ if (input.mode === "vector")
391
+ return;
392
+ const contracts = input.fields.map((field) => buildSearchIndexNames(input.table, field));
393
+ const clauses = contracts.flatMap((contract, index) => {
394
+ const fieldPattern = `%${input.fields[index]}%`;
395
+ return [
396
+ sql2`(c.relname=${contract.fts}
397
+ AND pg_catalog.pg_get_indexdef(i.indexrelid) ILIKE '%to_tsvector(%'
398
+ AND pg_catalog.pg_get_indexdef(i.indexrelid) ILIKE ${fieldPattern}
399
+ AND EXISTS (SELECT 1 FROM unnest(i.indclass::oid[]) AS op_oid
400
+ JOIN pg_catalog.pg_opclass op ON op.oid=op_oid WHERE op.opcname='tsvector_ops'))`,
401
+ sql2`(c.relname=${contract.trigram}
402
+ AND pg_catalog.pg_get_indexdef(i.indexrelid) ILIKE '%normalize(%'
403
+ AND pg_catalog.pg_get_indexdef(i.indexrelid) ILIKE ${fieldPattern}
404
+ AND EXISTS (SELECT 1 FROM unnest(i.indclass::oid[]) AS op_oid
405
+ JOIN pg_catalog.pg_opclass op ON op.oid=op_oid WHERE op.opcname='gin_trgm_ops'))`
406
+ ];
407
+ });
408
+ const indexes = searchRows(await read(sql2`SELECT c.relname AS name
409
+ FROM pg_catalog.pg_index i JOIN pg_catalog.pg_class c ON c.oid=i.indexrelid
410
+ JOIN pg_catalog.pg_class t ON t.oid=i.indrelid JOIN pg_catalog.pg_am am ON am.oid=c.relam
411
+ WHERE i.indrelid=${relationId}::oid AND c.relnamespace=t.relnamespace
412
+ AND am.amname='gin' AND i.indisvalid=true AND i.indisready=true
413
+ AND (${clauses.length ? sql2.join(clauses, sql2` OR `) : sql2`false`})`));
414
+ const ready = new Set(indexes.map((row) => row.name));
415
+ if (contracts.some((contract) => !ready.has(contract.fts) || !ready.has(contract.trigram)))
416
+ fail("SEARCH_INDEX_NOT_READY");
417
+ }
418
+
419
+ // ../runtime/dist/adapters/search/postgres/plan.js
420
+ import { sql as sql4 } from "drizzle-orm";
421
+
422
+ // ../runtime/dist/adapters/search/postgres/lexical.js
423
+ import { sql as sql3 } from "drizzle-orm";
424
+ var searchColumn = (field, alias = "t") => sql3`${sql3.identifier(alias)}.${sql3.identifier(field)}`;
425
+ function lexicalExpression(field, alias = "t") {
426
+ return sql3`lower(normalize(regexp_replace(coalesce(${searchColumn(field, alias)}::text, ''), '[[:space:]]+', ' ', 'g'), NFC))`;
427
+ }
428
+ function lexicalPlan(input) {
429
+ const clauses = input.fields.flatMap((field) => {
430
+ const text = lexicalExpression(field);
431
+ return [
432
+ sql3`to_tsvector('simple', ${text}) @@ websearch_to_tsquery('simple', ${input.query})`,
433
+ Array.from(input.query).length === 2 ? sql3`${input.query} <% ${text}` : sql3`(${input.query} <<% ${text} OR ${text} ILIKE ('%' || ${input.query} || '%'))`
434
+ ];
435
+ });
436
+ const scores = input.fields.flatMap((field) => {
437
+ const text = lexicalExpression(field);
438
+ return [
439
+ sql3`ts_rank(to_tsvector('simple', ${text}), websearch_to_tsquery('simple', ${input.query}))::double precision`,
440
+ sql3`GREATEST(similarity(${text}, ${input.query}), strict_word_similarity(${input.query}, ${text}))::double precision`
441
+ ];
442
+ });
443
+ return {
444
+ where: sql3`(${sql3.join(clauses, sql3` OR `)})`,
445
+ score: sql3`GREATEST(${sql3.join(scores, sql3`, `)})`
446
+ };
447
+ }
448
+
449
+ // ../runtime/dist/adapters/search/postgres/plan.js
450
+ function searchPredicate(input, managed) {
451
+ const clauses = [
452
+ sql4`t.corpus = ${input.scope.corpus}`,
453
+ sql4`t.visibility_scope = ${input.scope.visibility}`,
454
+ input.owner === null ? sql4`t.owner_user_id IS NULL` : sql4`t.owner_user_id = ${input.owner}`
455
+ ];
456
+ for (const filter of input.filters) {
457
+ const column = searchColumn(filter.field);
458
+ clauses.push(filter.operator === "eq" ? sql4`${column} = ${filter.values[0]}` : filter.operator === "gte" ? sql4`${column} >= ${filter.values[0]}` : filter.operator === "lte" ? sql4`${column} <= ${filter.values[0]}` : sql4`${column} IN (${sql4.join(filter.values.map((value) => sql4`${value}`), sql4`, `)})`);
459
+ }
460
+ if (managed) {
461
+ clauses.push(sql4`EXISTS (SELECT 1 FROM public.rag_sources s WHERE s.id=t.source_id
462
+ AND s.corpus=t.corpus AND s.visibility_scope=t.visibility_scope AND s.owner_user_id IS NOT DISTINCT FROM t.owner_user_id)`);
463
+ clauses.push(sql4`octet_length(t.chunk_text)<=5600 AND octet_length(t.lexical_text)<=11200
464
+ AND octet_length(t.metadata::text)<=65536 AND jsonb_typeof(t.metadata)='object'
465
+ AND char_length(t.id)<=128 AND char_length(t.source_id)<=128
466
+ AND (t.section_id IS NULL OR char_length(t.section_id)<=128)
467
+ AND char_length(t.chunk_checksum)<=256`);
468
+ }
469
+ return sql4.join(clauses, sql4` AND `);
470
+ }
471
+ function searchStatement(input, managed) {
472
+ const table = sql4`public.${sql4.identifier(input.table)}`, where = searchPredicate(input, managed);
473
+ const vectorOrder = sql4`${searchColumn(input.vectorField)} <=> CAST(${input.vector} AS vector)`;
474
+ const vectorScore = sql4`(1 - (${vectorOrder}))::double precision`;
475
+ if (input.mode === "vector")
476
+ return sql4`SELECT t.*, ${vectorScore} AS score FROM ${table} t WHERE ${where}
477
+ ${input.minScore === void 0 ? sql4`` : sql4`AND ${vectorScore} >= ${input.minScore}`}
478
+ ORDER BY ${vectorOrder}, t.id ASC LIMIT ${input.limit} OFFSET ${input.offset}`;
479
+ const lexical = lexicalPlan(input);
480
+ if (input.mode === "lexical")
481
+ return sql4`SELECT t.*, ${lexical.score} AS score FROM ${table} t
482
+ WHERE ${lexical.where} AND ${where} ORDER BY score DESC, t.id ASC LIMIT ${input.limit} OFFSET ${input.offset}`;
483
+ const fused = sql4`(COALESCE(${input.keywordWeight}::double precision / (${input.rrfK} + kc.keyword_rank), 0)
484
+ + COALESCE(${input.vectorWeight}::double precision / (${input.rrfK} + vc.vector_rank), 0))::double precision`;
485
+ return sql4`WITH keyword_candidates AS (
486
+ SELECT t.id, ${lexical.score} AS keyword_score, ROW_NUMBER() OVER (ORDER BY ${lexical.score} DESC, t.id ASC) AS keyword_rank
487
+ FROM ${table} t WHERE ${lexical.where} AND ${where} ORDER BY ${lexical.score} DESC, t.id ASC LIMIT ${input.keywordCandidates}
488
+ ), vector_candidates AS (
489
+ SELECT t.id, ${vectorScore} AS vector_score, ROW_NUMBER() OVER (ORDER BY ${vectorOrder}, t.id ASC) AS vector_rank
490
+ FROM ${table} t WHERE ${where} ORDER BY ${vectorOrder}, t.id ASC LIMIT ${input.vectorCandidates}
491
+ ), ranked AS (
492
+ SELECT t.*, kc.keyword_score, vc.vector_score, ${fused} AS fused_score
493
+ FROM ${table} t LEFT JOIN keyword_candidates kc ON kc.id=t.id LEFT JOIN vector_candidates vc ON vc.id=t.id
494
+ WHERE ${where} AND (kc.id IS NOT NULL OR vc.id IS NOT NULL)
495
+ ) SELECT * FROM ranked ${input.minScore === void 0 ? sql4`` : sql4`WHERE fused_score >= ${input.minScore}`}
496
+ ORDER BY fused_score DESC, id ASC LIMIT ${input.limit} OFFSET ${input.offset}`;
497
+ }
498
+
499
+ // ../runtime/dist/adapters/search/postgres/database-error.js
500
+ function classifySearchDatabaseFailure(error, mode, hasFilters = false) {
501
+ const seen = /* @__PURE__ */ new Set();
502
+ let cause = error;
503
+ for (let depth = 0; depth < 8 && cause !== null && typeof cause === "object"; depth++) {
504
+ if (seen.has(cause))
505
+ break;
506
+ seen.add(cause);
507
+ for (const field of ["code", "errno"]) {
508
+ const value = Object.getOwnPropertyDescriptor(cause, field)?.value;
509
+ if (typeof value !== "string")
510
+ continue;
511
+ if (value === "42501")
512
+ return "SEARCH_DATABASE_ACCESS_DENIED";
513
+ if (value === "42P01")
514
+ return "SEARCH_TABLE_UNAVAILABLE";
515
+ if (value === "42703")
516
+ return "SEARCH_COLUMN_UNAVAILABLE";
517
+ if (value === "57014")
518
+ return "SEARCH_DATABASE_TIMEOUT";
519
+ if (["22000", "22003", "22P02"].includes(value)) {
520
+ return mode !== "lexical" && !hasFilters ? "SEARCH_INVALID_VECTOR" : "SEARCH_INVALID_OPTIONS";
521
+ }
522
+ }
523
+ cause = Object.getOwnPropertyDescriptor(cause, "cause")?.value;
524
+ }
525
+ return "SEARCH_DATABASE_UNAVAILABLE";
526
+ }
527
+
528
+ // ../runtime/dist/adapters/search/postgres/backend.js
529
+ function createPostgresSearchModes(input) {
530
+ const binding = Object.freeze({ ...input.binding });
531
+ const configured = input.config ?? captureSearchCapabilityConfig();
532
+ const config = Object.freeze({ ...configured, extensions: Object.freeze({ ...configured.extensions }) });
533
+ const application = input.application, managed = input.managed, assertOpen = input.assertOpen;
534
+ async function execute(scope, table, query, options, mode) {
535
+ const fail = (code) => new RuntimeSearchError(code, scope.correlationId, scope.stage);
536
+ const prepared = prepareSearchInput(scope, table, query, options, mode);
537
+ const isManaged = scope.ownership === "managed";
538
+ if (isManaged && (table !== "rag_chunks" || !managed))
539
+ throw fail("SEARCH_CAPABILITY_DEGRADED");
540
+ const selected = isManaged ? managed : application;
541
+ let db;
542
+ function assertCurrent() {
543
+ try {
544
+ if (scope.binding.appId !== binding.appId || scope.binding.generationId !== binding.generationId)
545
+ throw new Error();
546
+ assertOpen?.();
547
+ scope.assertActive();
548
+ } catch {
549
+ throw fail("SEARCH_SCOPE_ENDED");
550
+ }
551
+ }
552
+ async function active() {
553
+ assertCurrent();
554
+ try {
555
+ await scope.assertLive?.();
556
+ } catch {
557
+ throw fail("SEARCH_SCOPE_ENDED");
558
+ }
559
+ assertCurrent();
560
+ }
561
+ const read = async (statement) => {
562
+ await active();
563
+ const result = await (input.withExecutionFence ? input.withExecutionFence(scope.assertActive, async () => await db.execute(statement)) : db.execute(statement));
564
+ await active();
565
+ return result;
566
+ };
567
+ try {
568
+ assertCurrent();
569
+ db = typeof selected === "function" ? selected(scope, assertCurrent) : selected;
570
+ await active();
571
+ await assertSearchReadiness(prepared, scope, config, read);
572
+ const rows = searchRows(await read(searchStatement(prepared, isManaged)));
573
+ return mapSearchResult(prepared, rows);
574
+ } catch (error) {
575
+ if (error instanceof RuntimeDiagnosticError && error.diagnostic.code === "RUNTIME_DATABASE_RLS_CONTEXT_INVALID") {
576
+ assertCurrent();
577
+ throw error;
578
+ }
579
+ const rlsDiagnostic = scopedCoreRlsDiagnostic(error, scope.stage ?? "request", scope.correlationId);
580
+ if (rlsDiagnostic) {
581
+ assertCurrent();
582
+ throw rlsDiagnostic;
583
+ }
584
+ await active();
585
+ if (error instanceof RuntimeDiagnosticError)
586
+ throw error;
587
+ throw fail(classifySearchDatabaseFailure(error, mode, prepared.filters.length > 0));
588
+ }
589
+ }
590
+ return Object.freeze({
591
+ lexical: (scope, table, query, options) => execute(scope, table, query, options, "lexical"),
592
+ vector: (scope, table, options) => execute(scope, table, "", options, "vector"),
593
+ hybrid: (scope, table, query, options) => execute(scope, table, query, options, "hybrid")
594
+ });
595
+ }
596
+
597
+ // ../runtime/dist/adapters/grounding/canonical-reader.js
598
+ import { sql as sql5 } from "drizzle-orm";
599
+ var MAX_CANONICAL_CHUNK_IDS = 40;
600
+ var MAX_SECTION_PATH_ITEMS = 64;
601
+ var MAX_SECTION_PATH_SEGMENT_LENGTH = 512;
602
+ function rowsFrom(result) {
603
+ const rows = Array.isArray(result) ? result : result && typeof result === "object" && "rows" in result ? result.rows : void 0;
604
+ if (!Array.isArray(rows))
605
+ throw new Error("Canonical citation read result unavailable");
606
+ return rows;
607
+ }
608
+ function sectionPath(value) {
609
+ let path = value;
610
+ if (typeof path === "string") {
611
+ try {
612
+ path = JSON.parse(path);
613
+ } catch {
614
+ return void 0;
615
+ }
616
+ }
617
+ if (!Array.isArray(path) || path.length > MAX_SECTION_PATH_ITEMS || path.some((segment) => typeof segment !== "string" || segment.length > MAX_SECTION_PATH_SEGMENT_LENGTH))
618
+ return void 0;
619
+ return path.length ? Object.freeze([...path]) : void 0;
620
+ }
621
+ function page(value) {
622
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
623
+ }
624
+ function pageRange(startValue, endValue) {
625
+ const start = page(startValue), end = page(endValue), invalidStart = startValue !== null && startValue !== void 0 && start === void 0, invalidEnd = endValue !== null && endValue !== void 0 && end === void 0;
626
+ if (invalidStart && invalidEnd)
627
+ return void 0;
628
+ if (start === void 0 && end === void 0)
629
+ return void 0;
630
+ return { ...start !== void 0 ? { start } : {}, ...end !== void 0 ? { end } : {} };
631
+ }
632
+ function mapEvidence(row) {
633
+ if (typeof row.chunk_id !== "string" || typeof row.chunk_text !== "string" || typeof row.source_id !== "string" || typeof row.source_title !== "string")
634
+ throw new Error("Canonical citation reader returned a malformed row");
635
+ const path = sectionPath(row.section_path), sectionId = typeof row.section_id === "string" ? row.section_id : void 0, chunkPages = pageRange(row.chunk_page_start, row.chunk_page_end), sectionPages = pageRange(row.section_page_start, row.section_page_end);
636
+ return Object.freeze({
637
+ chunkId: row.chunk_id,
638
+ chunkText: row.chunk_text,
639
+ sourceId: row.source_id,
640
+ sourceTitle: row.source_title,
641
+ ...sectionId ? { sectionId } : {},
642
+ ...path ? { sectionPath: path } : {},
643
+ ...chunkPages?.start !== void 0 ? { chunkPageStart: chunkPages.start } : {},
644
+ ...chunkPages?.end !== void 0 ? { chunkPageEnd: chunkPages.end } : {},
645
+ ...sectionPages?.start !== void 0 ? { sectionPageStart: sectionPages.start } : {},
646
+ ...sectionPages?.end !== void 0 ? { sectionPageEnd: sectionPages.end } : {}
647
+ });
648
+ }
649
+ function citationQuery(prepared, ids) {
650
+ const idList = sql5.join(ids.map((id) => sql5`${id}`), sql5`, `);
651
+ return sql5`SELECT
652
+ t.id AS chunk_id,
653
+ t.chunk_text AS chunk_text,
654
+ t.source_id AS source_id,
655
+ s.source_title AS source_title,
656
+ sec.id AS section_id,
657
+ sec.section_path AS section_path,
658
+ t.page_start AS chunk_page_start,
659
+ t.page_end AS chunk_page_end,
660
+ sec.page_start AS section_page_start,
661
+ sec.page_end AS section_page_end
662
+ FROM public.rag_chunks t
663
+ JOIN public.rag_sources s
664
+ ON s.id=t.source_id
665
+ AND s.corpus=t.corpus
666
+ AND s.visibility_scope=t.visibility_scope
667
+ AND s.owner_user_id IS NOT DISTINCT FROM t.owner_user_id
668
+ LEFT JOIN public.rag_sections sec
669
+ ON sec.id=t.section_id
670
+ AND sec.source_id=t.source_id
671
+ AND sec.corpus=t.corpus
672
+ AND sec.visibility_scope=t.visibility_scope
673
+ AND sec.owner_user_id IS NOT DISTINCT FROM t.owner_user_id
674
+ WHERE ${searchPredicate(prepared, true)}
675
+ AND t.id IN (${idList})
676
+ ORDER BY array_position(ARRAY[${idList}]::text[],t.id)`;
677
+ }
678
+ function createPostgresGroundingCitationReader(input) {
679
+ const binding = Object.freeze({ ...input.binding });
680
+ const assertScope = async (scope) => {
681
+ try {
682
+ if (scope.binding.appId !== binding.appId || scope.binding.generationId !== binding.generationId)
683
+ throw new Error("Scope binding changed");
684
+ input.assertOpen?.();
685
+ scope.assertActive();
686
+ await scope.assertLive?.();
687
+ scope.assertActive();
688
+ input.assertOpen?.();
689
+ } catch (error) {
690
+ if (runtimeDiagnostic(error))
691
+ throw error;
692
+ throw groundingScopeEnded(scope.stage ?? "request", scope.correlationId);
693
+ }
694
+ };
695
+ return Object.freeze({
696
+ async read(scope, admittedIds, query, options) {
697
+ await assertScope(scope);
698
+ assertSearchScope(scope, options.scope);
699
+ if (!Array.isArray(admittedIds))
700
+ throw new RuntimeDiagnosticError({
701
+ code: "GROUNDING_INPUT_INVALID",
702
+ stage: scope.stage ?? "request",
703
+ capability: "application",
704
+ servingStarted: "unchanged",
705
+ dataImpact: "none",
706
+ retryable: false,
707
+ retryPrecondition: "Supply bounded canonical Search candidate identifiers before repeating this read.",
708
+ nextAction: "Correct the grounding input and retry this read; no database write was admitted.",
709
+ correlationId: scope.correlationId
710
+ });
711
+ const ids = [
712
+ ...new Set(admittedIds.filter((id) => typeof id === "string" && id.length > 0 && id.length <= 128 && !id.includes("\0")))
713
+ ].slice(0, MAX_CANONICAL_CHUNK_IDS);
714
+ if (ids.length === 0)
715
+ return Object.freeze([]);
716
+ const searchScope = Object.freeze({ ...scope, ownership: "managed" });
717
+ const application = typeof input.application === "function" ? input.application(searchScope, scope.assertActive) : input.application;
718
+ const prepared = prepareSearchInput(searchScope, "rag_chunks", query, { ...options, fields: ["chunk_text", "lexical_text"], limit: Math.min(ids.length, 100), offset: 0 }, "lexical");
719
+ let result;
720
+ try {
721
+ await assertScope(scope);
722
+ result = await (input.withExecutionFence ? input.withExecutionFence(scope.assertActive, async () => await application.execute(citationQuery(prepared, ids))) : application.execute(citationQuery(prepared, ids)));
723
+ } catch (error) {
724
+ const rlsDiagnostic = scopedCoreRlsDiagnostic(error, scope.stage ?? "request", scope.correlationId);
725
+ if (rlsDiagnostic) {
726
+ scope.assertActive();
727
+ throw rlsDiagnostic;
728
+ }
729
+ await assertScope(scope);
730
+ if (runtimeDiagnostic(error))
731
+ throw error;
732
+ if (error instanceof RuntimeSearchError)
733
+ throw error;
734
+ const code = classifySearchDatabaseFailure(error, "lexical", prepared.filters.length > 0);
735
+ throw new RuntimeSearchError(code, scope.correlationId, scope.stage);
736
+ }
737
+ await assertScope(scope);
738
+ const evidence = rowsFrom(result).map((row) => mapEvidence(row));
739
+ return Object.freeze(evidence);
740
+ }
741
+ });
742
+ }
743
+
744
+ export {
745
+ assertDatabaseGeneration,
746
+ captureManagedSchemaComponents,
747
+ createManagedSchemaPreparation,
748
+ loadPgliteManagedExtensions,
749
+ runtimeDatabaseInspection,
750
+ createSearchSessionReads,
751
+ createPostgresSearchModes,
752
+ createPostgresGroundingCitationReader
753
+ };