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,175 @@
1
+ import {
2
+ workflowSchemaDefaultMatches,
3
+ workflowSchemaIndexes,
4
+ workflowSchemaTables
5
+ } from "./chunk-GOLP7OSG.mjs";
6
+ import {
7
+ RuntimeCompositionError
8
+ } from "./chunk-IFMOTJNU.mjs";
9
+
10
+ // ../runtime/dist/workflow/schema-validation.js
11
+ import { sql } from "drizzle-orm";
12
+ function workflowSchemaFailure() {
13
+ return new RuntimeCompositionError({
14
+ code: "RUNTIME_WORKFLOW_SCHEMA_NOT_READY",
15
+ stage: "startup",
16
+ capability: "database",
17
+ servingStarted: false,
18
+ dataImpact: "none",
19
+ retryable: false,
20
+ retryPrecondition: "Restart only after the trusted managed-setup owner restores compatible workflow schema and operational readiness.",
21
+ nextAction: "Managed workflow schema is incompatible or not ready. Preserve data/history and restore managed setup through its trusted host owner before restarting. Do not edit tenant migrations or grants.",
22
+ correlationId: crypto.randomUUID()
23
+ });
24
+ }
25
+ function workflowSchemaBootstrapUnavailable() {
26
+ return new RuntimeCompositionError({
27
+ code: "RUNTIME_WORKFLOW_SCHEMA_BOOTSTRAP_UNAVAILABLE",
28
+ stage: "startup",
29
+ capability: "database",
30
+ servingStarted: false,
31
+ dataImpact: "none",
32
+ retryable: false,
33
+ retryPrecondition: "Restart only after an authorized app-scoped managed-setup owner restores compatible workflow schema and verifies operational readiness.",
34
+ nextAction: "Workflow setup is blocked because this database binding has operational access only. Restore the existing trusted managed-setup capability through its owner; do not edit tenant migrations, internal tables or grants.",
35
+ correlationId: crypto.randomUUID()
36
+ });
37
+ }
38
+ function rows(result) {
39
+ if (Array.isArray(result))
40
+ return result;
41
+ if (result && typeof result === "object" && "rows" in result && Array.isArray(result.rows))
42
+ return result.rows;
43
+ throw workflowSchemaFailure();
44
+ }
45
+ function sameColumns(left, right) {
46
+ return left.length === right.length && left.every((value, index) => right[index] === value);
47
+ }
48
+ function normalizedPredicate(value) {
49
+ return value?.toLowerCase().replaceAll(/status\s+in\s*\('pending'\s*,\s*'sending'\)/gu, "status = any (array['pending', 'sending'])").replaceAll(/[()]/g, "").replaceAll(/::text/g, "").replaceAll(/\s+/g, " ").trim() ?? null;
50
+ }
51
+ async function validateRuntimeWorkflowSchema(database, allowCompatibleMissing = false) {
52
+ const names = sql.join(workflowSchemaTables.map((table) => sql`${table.name}`), sql`, `);
53
+ try {
54
+ const columns = rows(await database.execute(sql`
55
+ SELECT relation.relname AS table_name, attribute.attname AS column_name,
56
+ type.typname AS type, NOT attribute.attnotnull AS nullable,
57
+ pg_get_expr(defaults.adbin, defaults.adrelid) AS default_value,
58
+ relation.relkind AS relation_kind,
59
+ attribute.attidentity AS identity, attribute.attgenerated AS generated,
60
+ EXISTS (
61
+ SELECT 1 FROM pg_depend default_depend
62
+ JOIN pg_class sequence_relation ON sequence_relation.oid = default_depend.refobjid
63
+ AND sequence_relation.relkind = 'S'
64
+ JOIN pg_namespace sequence_namespace ON sequence_namespace.oid = sequence_relation.relnamespace
65
+ JOIN pg_depend owner_depend ON owner_depend.classid = 'pg_class'::regclass
66
+ AND owner_depend.objid = sequence_relation.oid
67
+ AND owner_depend.refclassid = 'pg_class'::regclass
68
+ AND owner_depend.refobjid = relation.oid
69
+ AND owner_depend.refobjsubid = attribute.attnum
70
+ AND owner_depend.deptype IN ('a', 'i')
71
+ WHERE default_depend.classid = 'pg_attrdef'::regclass
72
+ AND default_depend.objid = defaults.oid
73
+ AND default_depend.refclassid = 'pg_class'::regclass
74
+ AND sequence_namespace.nspname = 'public'
75
+ AND (has_sequence_privilege(sequence_relation.oid, 'USAGE')
76
+ OR has_sequence_privilege(sequence_relation.oid, 'UPDATE'))
77
+ ) AS sequence_ready
78
+ FROM pg_class relation JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace
79
+ JOIN pg_attribute attribute ON attribute.attrelid = relation.oid AND attribute.attnum > 0 AND NOT attribute.attisdropped
80
+ JOIN pg_type type ON type.oid = attribute.atttypid
81
+ LEFT JOIN pg_attrdef defaults ON defaults.adrelid = relation.oid AND defaults.adnum = attribute.attnum
82
+ WHERE namespace.nspname = 'public' AND relation.relname IN (${names})
83
+ `));
84
+ const constraints = rows(await database.execute(sql`
85
+ SELECT relation.relname AS table_name, constraint_row.contype AS kind,
86
+ ARRAY(SELECT attribute.attname::text FROM unnest(constraint_row.conkey) WITH ORDINALITY key(number, position)
87
+ JOIN pg_attribute attribute ON attribute.attrelid = relation.oid AND attribute.attnum = key.number ORDER BY key.position) AS columns,
88
+ target.relname AS target,
89
+ ARRAY(SELECT attribute.attname::text FROM unnest(constraint_row.confkey) WITH ORDINALITY key(number, position)
90
+ JOIN pg_attribute attribute ON attribute.attrelid = target.oid AND attribute.attnum = key.number ORDER BY key.position) AS target_columns,
91
+ constraint_row.confdeltype AS delete_action, target_namespace.nspname AS target_namespace,
92
+ constraint_row.condeferrable AS deferred, constraint_row.convalidated AS validated
93
+ FROM pg_constraint constraint_row JOIN pg_class relation ON relation.oid = constraint_row.conrelid
94
+ JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace
95
+ LEFT JOIN pg_class target ON target.oid = constraint_row.confrelid
96
+ LEFT JOIN pg_namespace target_namespace ON target_namespace.oid = target.relnamespace
97
+ WHERE namespace.nspname = 'public' AND relation.relname IN (${names})
98
+ `));
99
+ const indexNames = sql.join(workflowSchemaIndexes.map((index) => sql`${index.name}`), sql`, `);
100
+ const indexes = rows(await database.execute(sql`
101
+ SELECT index_relation.relname AS name, table_relation.relname AS table_name,
102
+ method.amname AS method, index_row.indisvalid AS valid,
103
+ index_row.indisready AS ready, index_row.indisunique AS unique,
104
+ index_row.indnkeyatts AS key_count, index_row.indnatts AS attribute_count,
105
+ ARRAY(SELECT pg_get_indexdef(index_row.indexrelid, key.position, true)
106
+ FROM generate_series(1, index_row.indnkeyatts) key(position) ORDER BY key.position) AS keys,
107
+ ARRAY(SELECT index_row.indoption[key.position - 1]::int
108
+ FROM generate_series(1, index_row.indnkeyatts) key(position) ORDER BY key.position) AS options,
109
+ pg_get_expr(index_row.indpred, index_row.indrelid, true) AS predicate
110
+ FROM pg_class index_relation
111
+ JOIN pg_namespace namespace ON namespace.oid = index_relation.relnamespace
112
+ JOIN pg_index index_row ON index_row.indexrelid = index_relation.oid
113
+ JOIN pg_class table_relation ON table_relation.oid = index_row.indrelid
114
+ JOIN pg_am method ON method.oid = index_relation.relam
115
+ WHERE namespace.nspname = 'public' AND index_relation.relname IN (${indexNames})
116
+ `));
117
+ let ready = true;
118
+ for (const table of workflowSchemaTables) {
119
+ const found = columns.filter((column) => column.table_name === table.name);
120
+ if (!found.length && allowCompatibleMissing) {
121
+ ready = false;
122
+ continue;
123
+ }
124
+ const knownColumns = new Set(table.columns.map(([name]) => name));
125
+ if (found.some((column) => !knownColumns.has(column.column_name) && !column.nullable && column.default_value === null && column.identity === "" && column.generated === ""))
126
+ throw workflowSchemaFailure();
127
+ for (const [name, type, nullable, defaultValue, additive] of table.columns) {
128
+ const actual = found.find((column) => column.column_name === name);
129
+ if (!actual && additive && allowCompatibleMissing) {
130
+ ready = false;
131
+ continue;
132
+ }
133
+ if (!actual || actual.relation_kind !== "r" || actual.type !== type || actual.nullable !== nullable || defaultValue !== null && (defaultValue === "sequence" ? !actual.default_value?.startsWith("nextval(") || !actual.sequence_ready : !workflowSchemaDefaultMatches(table.name, name, defaultValue, actual.default_value?.toLowerCase() ?? null)))
134
+ throw workflowSchemaFailure();
135
+ }
136
+ const has = (kind, keys) => constraints.some((constraint) => constraint.table_name === table.name && constraint.kind === kind && !constraint.deferred && constraint.validated && sameColumns(constraint.columns, keys));
137
+ if (!has("p", table.primary) || table.unique.some((keys) => !has("u", keys)) || table.foreign.some(([column, target]) => !constraints.some((constraint) => constraint.table_name === table.name && constraint.kind === "f" && !constraint.deferred && constraint.validated && constraint.target_namespace === "public" && sameColumns(constraint.columns, [column]) && constraint.target === target && sameColumns(constraint.target_columns, ["id"]) && constraint.delete_action === "c")))
138
+ throw workflowSchemaFailure();
139
+ }
140
+ for (const expected of workflowSchemaIndexes) {
141
+ const actual = indexes.find((index) => index.name === expected.name);
142
+ if (!actual && allowCompatibleMissing) {
143
+ ready = false;
144
+ continue;
145
+ }
146
+ if (!actual || actual.table_name !== expected.table || actual.method !== "btree" || !actual.valid || !actual.ready || actual.unique !== (expected.unique ?? false) || actual.key_count !== expected.keys.length || actual.attribute_count !== expected.keys.length || !sameColumns(actual.keys, expected.keys) || actual.options.length !== expected.keys.length || actual.options.some((option, index) => {
147
+ const descending = expected.descending?.includes(expected.keys[index]) ?? false;
148
+ return option !== (descending ? 3 : 0);
149
+ }) || normalizedPredicate(actual.predicate) !== normalizedPredicate(expected.predicate ?? null))
150
+ throw workflowSchemaFailure();
151
+ }
152
+ if (!ready && !allowCompatibleMissing)
153
+ throw workflowSchemaFailure();
154
+ if (ready) {
155
+ const grants = rows(await database.execute(sql`
156
+ SELECT bool_and(has_table_privilege(relation.oid, 'SELECT') AND has_table_privilege(relation.oid, 'INSERT')
157
+ AND has_table_privilege(relation.oid, 'UPDATE') AND has_table_privilege(relation.oid, 'DELETE'))
158
+ AND has_schema_privilege('public', 'USAGE') AS allowed
159
+ FROM pg_class relation JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace
160
+ WHERE namespace.nspname = 'public' AND relation.relname IN (${names})
161
+ `));
162
+ if (grants[0]?.allowed !== true)
163
+ throw workflowSchemaFailure();
164
+ }
165
+ return ready;
166
+ } catch {
167
+ throw workflowSchemaFailure();
168
+ }
169
+ }
170
+
171
+ export {
172
+ workflowSchemaFailure,
173
+ workflowSchemaBootstrapUnavailable,
174
+ validateRuntimeWorkflowSchema
175
+ };
@@ -0,0 +1,11 @@
1
+ import {
2
+ runtimeWorkflowSchemaComponent
3
+ } from "./chunk-RITT2RSJ.mjs";
4
+ import "./chunk-ZXMM7QFP.mjs";
5
+ import "./chunk-PZFMKFHO.mjs";
6
+ import "./chunk-GOLP7OSG.mjs";
7
+ import "./chunk-SVJCOUI3.mjs";
8
+ import "./chunk-AEBW7XZJ.mjs";
9
+ export {
10
+ runtimeWorkflowSchemaComponent
11
+ };
@@ -0,0 +1,292 @@
1
+ import {
2
+ createRagOperationsScope,
3
+ ragOperationsError,
4
+ ragOperationsPredicate
5
+ } from "./chunk-2HA4CUMS.mjs";
6
+ import {
7
+ flushWorkflowDeferredWrites
8
+ } from "./chunk-5GUJZQF3.mjs";
9
+ import {
10
+ groundingProducerDiagnostic
11
+ } from "./chunk-XNFVL2OY.mjs";
12
+ import "./chunk-5TACQ2US.mjs";
13
+ import {
14
+ ragJobRows
15
+ } from "./chunk-JUDKX53X.mjs";
16
+ import {
17
+ RuntimeCapabilityUnavailableError,
18
+ RuntimeDiagnosticError,
19
+ runtimeDiagnostic,
20
+ runtimeSearchProducerDiagnostic
21
+ } from "./chunk-AEBW7XZJ.mjs";
22
+
23
+ // ../runtime/dist/rag/evaluation-input.js
24
+ function snapshotRagEvaluationFixtures(input, auth) {
25
+ auth.active();
26
+ if (!Array.isArray(input))
27
+ throw ragOperationsError("RAG_OPERATIONS_INPUT_INVALID");
28
+ if (input.length > 128)
29
+ throw ragOperationsError("RAG_OPERATIONS_SIZE_LIMIT_EXCEEDED");
30
+ let values;
31
+ try {
32
+ const json = JSON.stringify(input);
33
+ if (Buffer.byteLength(json) > 1048576)
34
+ throw ragOperationsError("RAG_OPERATIONS_SIZE_LIMIT_EXCEEDED");
35
+ values = JSON.parse(json);
36
+ } catch (error) {
37
+ if (runtimeDiagnostic(error)?.code === "RAG_OPERATIONS_SIZE_LIMIT_EXCEEDED")
38
+ throw error;
39
+ throw ragOperationsError("RAG_OPERATIONS_INPUT_INVALID");
40
+ }
41
+ return values.map((value) => {
42
+ if (!value || typeof value !== "object" || Array.isArray(value))
43
+ throw ragOperationsError("RAG_OPERATIONS_INPUT_INVALID");
44
+ const raw = value;
45
+ if (!raw.scope || typeof raw.scope !== "object" || Array.isArray(raw.scope))
46
+ throw ragOperationsError("RAG_OPERATIONS_INPUT_INVALID");
47
+ const scope = auth.scope(raw.scope);
48
+ if (typeof raw.name !== "string" || !raw.name.trim() || raw.name.length > 256 || typeof raw.query !== "string" || !raw.query.trim() || raw.query.length > 16384 || raw.expectedSourceIds !== void 0 && (!Array.isArray(raw.expectedSourceIds) || raw.expectedSourceIds.length > 8192 || raw.expectedSourceIds.some((id) => typeof id !== "string" || !id || id.length > 128)) || raw.expectedCitationCountMin !== void 0 && (typeof raw.expectedCitationCountMin !== "number" || !Number.isFinite(raw.expectedCitationCountMin) || raw.expectedCitationCountMin < 0) || raw.expectedClaims !== void 0 && (!Array.isArray(raw.expectedClaims) || raw.expectedClaims.length > 128))
49
+ throw ragOperationsError("RAG_OPERATIONS_INPUT_INVALID");
50
+ const expectedClaims = raw.expectedClaims?.map((value2) => {
51
+ if (!value2 || typeof value2 !== "object" || Array.isArray(value2))
52
+ throw ragOperationsError("RAG_OPERATIONS_INPUT_INVALID");
53
+ const item = value2;
54
+ if (typeof item.claim !== "string" || !item.claim.trim() || item.claim.length > 16384 || !["supported", "partial", "unsupported"].includes(String(item.verdict)))
55
+ throw ragOperationsError("RAG_OPERATIONS_INPUT_INVALID");
56
+ return { claim: item.claim.trim(), verdict: item.verdict };
57
+ });
58
+ return Object.freeze({
59
+ name: raw.name.trim(),
60
+ query: raw.query.trim(),
61
+ scope: Object.freeze({
62
+ corpus: scope.corpus,
63
+ visibility: scope.visibility,
64
+ ...scope.ownerUserId === null ? {} : { ownerUserId: scope.ownerUserId }
65
+ }),
66
+ expectedSourceIds: raw.expectedSourceIds,
67
+ expectedCitationCountMin: raw.expectedCitationCountMin,
68
+ expectedClaims
69
+ });
70
+ });
71
+ }
72
+
73
+ // ../runtime/dist/rag/evaluation.js
74
+ function createRagEvaluation(binding, persistence) {
75
+ const appId = binding.appId;
76
+ return Object.freeze({
77
+ scope(requireIdentity, search, grounding) {
78
+ const auth = createRagOperationsScope(requireIdentity);
79
+ return Object.freeze({
80
+ async run(input) {
81
+ const fixtures = snapshotRagEvaluationFixtures(input?.fixtures, auth), evaluationId = crypto.randomUUID();
82
+ const results = [], buckets = /* @__PURE__ */ new Map();
83
+ let effectsPossible = false, metricsPossible = false;
84
+ try {
85
+ const answer = fixtures.some((fixture) => fixture.expectedClaims?.length || fixture.expectedCitationCountMin !== void 0) ? grounding?.answer.bind(grounding) : void 0;
86
+ if (fixtures.some((fixture) => fixture.expectedClaims?.length || fixture.expectedCitationCountMin !== void 0) && !answer)
87
+ throw new RuntimeCapabilityUnavailableError("grounding");
88
+ for (const fixture of fixtures) {
89
+ const scope = auth.scope(fixture.scope), failures = [];
90
+ effectsPossible = true;
91
+ const found = await search("rag_chunks", fixture.query, {
92
+ fields: ["chunk_text", "lexical_text"],
93
+ scope: fixture.scope,
94
+ limit: 20
95
+ });
96
+ auth.active();
97
+ const searchEvidence = await persistence.validateSearch(scope, found, auth.active);
98
+ auth.active();
99
+ const matchedSourceIds = [...searchEvidence.matchedSourceIds];
100
+ for (const id of fixture.expectedSourceIds ?? [])
101
+ if (!matchedSourceIds.includes(id))
102
+ failures.push(`missing source ${id}`);
103
+ const claims = fixture.expectedClaims ?? [];
104
+ const grounded = answer && (claims.length || fixture.expectedCitationCountMin !== void 0) ? await answer({
105
+ question: fixture.query,
106
+ scope: fixture.scope,
107
+ claims: claims.length ? claims.map((claim) => ({ claimText: claim.claim })) : void 0
108
+ }) : null;
109
+ auth.active();
110
+ const answerEvidence = await persistence.validateAnswer(scope, searchEvidence, grounded, auth.active);
111
+ auth.active();
112
+ const citationCount = answerEvidence.citationCount;
113
+ if (fixture.expectedCitationCountMin !== void 0 && citationCount < fixture.expectedCitationCountMin)
114
+ failures.push(`citation count ${citationCount} < ${fixture.expectedCitationCountMin}`);
115
+ const claimStatuses = claims.map((claim, index) => {
116
+ const expected = claim.verdict === "partial" ? "partially_supported" : claim.verdict === "unsupported" ? "insufficient_evidence" : "supported";
117
+ const actual = answerEvidence.statuses[index] ?? null;
118
+ if (actual !== expected)
119
+ failures.push(`claim "${claim.claim}" expected ${expected}, got ${actual}`);
120
+ return { claim: claim.claim, expected: claim.verdict, actual };
121
+ });
122
+ const ok = failures.length === 0, key = JSON.stringify([scope.corpus, scope.visibility, scope.ownerUserId]);
123
+ const bucket = buckets.get(key) ?? { scope, passed: 0, failed: 0 };
124
+ bucket[ok ? "passed" : "failed"]++;
125
+ buckets.set(key, bucket);
126
+ results.push({
127
+ name: fixture.name,
128
+ ok,
129
+ failures,
130
+ matchedSourceIds,
131
+ citationCount,
132
+ claimStatuses
133
+ });
134
+ }
135
+ if (buckets.size) {
136
+ metricsPossible = true;
137
+ await persistence.writeMetrics(appId, evaluationId, buckets.values(), auth.active);
138
+ }
139
+ auth.active();
140
+ const passed = results.filter((result) => result.ok).length;
141
+ return {
142
+ ok: passed === results.length,
143
+ total: results.length,
144
+ passed,
145
+ failed: results.length - passed,
146
+ results
147
+ };
148
+ } catch (error) {
149
+ if (error instanceof RuntimeCapabilityUnavailableError) {
150
+ const unavailable = ragOperationsError("RAG_EVALUATION_CAPABILITY_UNAVAILABLE", effectsPossible ? "unknown" : "none");
151
+ if (!effectsPossible)
152
+ throw unavailable;
153
+ const uncertain = ragOperationsError("RAG_EVALUATION_OUTCOME_UNKNOWN", "unknown", evaluationId).diagnostic;
154
+ throw new RuntimeDiagnosticError({
155
+ ...uncertain,
156
+ code: unavailable.diagnostic.code,
157
+ nextAction: `${unavailable.diagnostic.nextAction} ${uncertain.nextAction}`
158
+ });
159
+ }
160
+ const diagnostic = runtimeDiagnostic(error);
161
+ if (!metricsPossible && diagnostic) {
162
+ if (!effectsPossible)
163
+ throw error;
164
+ const uncertain = ragOperationsError("RAG_EVALUATION_OUTCOME_UNKNOWN", "unknown", evaluationId).diagnostic;
165
+ const producer = groundingProducerDiagnostic(error) ?? runtimeSearchProducerDiagnostic(error);
166
+ throw new RuntimeDiagnosticError({
167
+ ...uncertain,
168
+ code: producer?.code ?? diagnostic.code,
169
+ capability: producer?.capability ?? diagnostic.capability ?? uncertain.capability,
170
+ ...producer?.correlationId ? { correlationId: producer.correlationId } : {},
171
+ ...producer ? {
172
+ retryPrecondition: `${producer.retryPrecondition} ${uncertain.retryPrecondition}`,
173
+ nextAction: `${producer.nextAction} ${uncertain.nextAction}`
174
+ } : {}
175
+ });
176
+ }
177
+ throw ragOperationsError("RAG_EVALUATION_OUTCOME_UNKNOWN", "unknown", evaluationId);
178
+ }
179
+ }
180
+ });
181
+ }
182
+ });
183
+ }
184
+
185
+ // ../runtime/dist/adapters/rag/pgvector/evaluation-evidence.js
186
+ import { sql } from "drizzle-orm";
187
+ var invalid = () => ragOperationsError("RAG_OPERATIONS_STATE_INVALID", "unknown");
188
+ function references(initial = []) {
189
+ const values = [...initial];
190
+ function add(chunk, source) {
191
+ if (values.length >= 8192 || typeof chunk !== "string" || !chunk || chunk.length > 128 || typeof source !== "string" || !source || source.length > 128)
192
+ throw invalid();
193
+ values.push(Object.freeze({ chunk, source }));
194
+ }
195
+ function addCitations(citations) {
196
+ if (!Array.isArray(citations) || citations.length > 8192)
197
+ throw invalid();
198
+ for (const citation of citations) {
199
+ if (!citation || !Array.isArray(citation.chunkIds) || !citation.chunkIds.length || citation.chunkIds.length > 8192)
200
+ throw invalid();
201
+ for (const chunk of citation.chunkIds)
202
+ add(chunk, citation.sourceId);
203
+ }
204
+ }
205
+ return { values, add, addCitations };
206
+ }
207
+ async function assertScoped(db, scope, values, active) {
208
+ for (let index = 0; index < values.length; index += 64) {
209
+ active();
210
+ const batch = values.slice(index, index + 64);
211
+ const valid = ragJobRows(await db.execute(sql`SELECT ch.id,ch.source_id FROM rag_chunks ch JOIN rag_sources s ON s.id=ch.source_id
212
+ WHERE ${ragOperationsPredicate("ch", scope)} AND ${ragOperationsPredicate("s", scope)} AND ch.id IN (${sql.join(batch.map((item) => sql`${item.chunk}`), sql`,`)})`));
213
+ active();
214
+ if (batch.some((item) => !valid.some((row) => row.id === item.chunk && row.source_id === item.source)))
215
+ throw invalid();
216
+ }
217
+ }
218
+ async function validateRagEvaluationSearch(db, scope, search, active) {
219
+ if (!search || !Array.isArray(search.items) || search.items.length > 20)
220
+ throw invalid();
221
+ const snapshot = references();
222
+ for (const hit of search.items) {
223
+ if (!hit)
224
+ throw invalid();
225
+ snapshot.add(hit.id, hit.row?.source_id);
226
+ }
227
+ const evidence = Object.freeze({
228
+ references: Object.freeze(snapshot.values),
229
+ matchedSourceIds: Object.freeze([...new Set(snapshot.values.map((item) => item.source))]),
230
+ citationCount: snapshot.values.length
231
+ });
232
+ await assertScoped(db, scope, evidence.references, active);
233
+ return evidence;
234
+ }
235
+ async function validateRagEvaluationAnswer(db, scope, search, answer, active) {
236
+ const snapshot = references(search.references), statuses = [];
237
+ if (answer) {
238
+ if (!Array.isArray(answer.citations) || !Array.isArray(answer.claims) || answer.citations.length > 8192 || answer.claims.length > 128)
239
+ throw invalid();
240
+ snapshot.addCitations(answer.citations);
241
+ for (const claim of answer.claims) {
242
+ if (!claim || !["supported", "partially_supported", "insufficient_evidence"].includes(claim.status))
243
+ throw invalid();
244
+ statuses.push(claim.status);
245
+ snapshot.addCitations(claim.citations);
246
+ }
247
+ }
248
+ const result = Object.freeze({
249
+ citationCount: answer ? answer.citations.length : search.citationCount,
250
+ statuses: Object.freeze(statuses)
251
+ });
252
+ await assertScoped(db, scope, snapshot.values, active);
253
+ return result;
254
+ }
255
+
256
+ // ../runtime/dist/adapters/rag/pgvector/evaluation-metrics.js
257
+ import { sql as sql2 } from "drizzle-orm";
258
+ async function writeRagEvaluationMetrics(database, appId, evaluationId, buckets, active) {
259
+ const recordedAt = (/* @__PURE__ */ new Date()).toISOString(), metadata = JSON.stringify({ evaluationId });
260
+ const metrics = [...buckets].flatMap((bucket) => ["passed", "failed"].map((outcome) => ({
261
+ id: crypto.randomUUID(),
262
+ scope: bucket.scope,
263
+ name: outcome === "passed" ? "fixture_pass_count" : "fixture_fail_count",
264
+ value: outcome === "passed" ? bucket.passed : bucket.failed
265
+ })));
266
+ await database.transaction(async (tx) => {
267
+ active();
268
+ for (const metric of metrics)
269
+ await tx.execute(sql2`INSERT INTO rag_operation_metrics(id,app_id,corpus,visibility_scope,owner_user_id,operation,metric_name,metric_value,unit,metadata,recorded_at)
270
+ VALUES (${metric.id},${appId},${metric.scope.corpus},${metric.scope.visibility},${metric.scope.ownerUserId},'evaluate',${metric.name},${metric.value},'count',${metadata}::jsonb,${recordedAt}::timestamptz)`);
271
+ await flushWorkflowDeferredWrites(tx);
272
+ for (const metric of metrics)
273
+ if (ragJobRows(await tx.execute(sql2`SELECT id FROM rag_operation_metrics WHERE id=${metric.id} AND app_id=${appId}
274
+ AND corpus=${metric.scope.corpus} AND visibility_scope=${metric.scope.visibility} AND owner_user_id IS NOT DISTINCT FROM ${metric.scope.ownerUserId}
275
+ AND recorded_at=${recordedAt}::timestamptz AND job_id IS NULL AND workflow_id IS NULL AND source_id IS NULL
276
+ AND operation='evaluate' AND metric_name=${metric.name} AND metric_value=${metric.value} AND unit='count' AND metadata=${metadata}::jsonb`)).length !== 1)
277
+ throw ragOperationsError("RAG_OPERATIONS_STATE_INVALID", "unknown");
278
+ active();
279
+ });
280
+ }
281
+
282
+ // ../runtime/dist/adapters/rag/pgvector/evaluation.js
283
+ function createRagEvaluation2(database, binding) {
284
+ return createRagEvaluation(binding, {
285
+ validateSearch: (scope, search, active) => validateRagEvaluationSearch(database, scope, search, active),
286
+ validateAnswer: (scope, search, answer, active) => validateRagEvaluationAnswer(database, scope, search, answer, active),
287
+ writeMetrics: (appId, evaluationId, buckets, active) => writeRagEvaluationMetrics(database, appId, evaluationId, buckets, active)
288
+ });
289
+ }
290
+ export {
291
+ createRagEvaluation2 as createRagEvaluation
292
+ };