weave-typescript 0.27.0 → 0.29.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.
@@ -0,0 +1,2924 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.listEntitiesByThreadQuery = exports.upsertEntityRelationshipQuery = exports.upsertThreadEntityQuery = exports.upsertEntityQuery = exports.listThreadActivityByThreadQuery = exports.createThreadActivityQuery = exports.listThreadReconciliationByPendingThreadQuery = exports.upsertThreadReconciliationQuery = exports.deleteThreadReconciliationByPendingThreadQuery = exports.getIngestionRunThreadCountsQuery = exports.listThreadsByIDsQuery = exports.listThreadsBySupersedesQuery = exports.markThreadsSupersededQuery = exports.bulkRejectThreadsQuery = exports.rejectThreadQuery = exports.bulkApproveThreadsQuery = exports.approveThreadQuery = exports.deleteDocumentThreadByOrganizationAndIDQuery = exports.editDocumentThreadQuery = exports.editPendingThreadQuery = exports.updateThreadClassificationQuery = exports.promoteThreadNextEmbeddingsByOrganizationQuery = exports.setThreadNextEmbeddingQuery = exports.updateThreadEmbeddingQuery = exports.listPendingThreadsByOrganizationQuery = exports.listPendingThreadsByRunQuery = exports.listThreadsByDocumentQuery = exports.listThreadsByIngestionRunQuery = exports.getThreadByOrganizationAndIDQuery = exports.createThreadQuery = exports.deleteDocumentByOrganizationAndIDQuery = exports.listDocumentTagsByDocumentIDQuery = exports.createDocumentTagQuery = exports.deleteDocumentTagByDocumentIDAndTagQuery = exports.deleteDocumentTagsByDocumentIDQuery = exports.listIngestionHistoryQuery = exports.listIngestionRunsByDocumentQuery = exports.listIngestionRunsByOrganizationQuery = exports.updateIngestionRunStateQuery = exports.getIngestionRunByOrganizationAndIDQuery = exports.createIngestionRunQuery = exports.getDatabaseConfigQuery = exports.getAccessibleDocumentSummaryQuery = exports.listAccessibleDocumentSummariesQuery = exports.listDocumentsByOrganizationQuery = exports.setDocumentStatusQuery = exports.setDocumentParseResultQuery = exports.getDocumentByOrganizationAndFingerprintQuery = exports.getDocumentByOrganizationAndIDQuery = exports.createDocumentQuery = void 0;
4
+ exports.deactivateFacetConfigQuery = exports.upsertFacetConfigQuery = exports.listActiveFacetConfigsQuery = exports.listFacetConfigsQuery = exports.syncOrganizationIngestionReasoningDefaultsQuery = exports.upsertOrganizationIngestionSettingsQuery = exports.getOrganizationIngestionSettingsQuery = exports.ensureOrganizationIngestionSettingsQuery = void 0;
5
+ exports.createDocument = createDocument;
6
+ exports.getDocumentByOrganizationAndID = getDocumentByOrganizationAndID;
7
+ exports.getDocumentByOrganizationAndFingerprint = getDocumentByOrganizationAndFingerprint;
8
+ exports.setDocumentParseResult = setDocumentParseResult;
9
+ exports.setDocumentStatus = setDocumentStatus;
10
+ exports.listDocumentsByOrganization = listDocumentsByOrganization;
11
+ exports.listAccessibleDocumentSummaries = listAccessibleDocumentSummaries;
12
+ exports.getAccessibleDocumentSummary = getAccessibleDocumentSummary;
13
+ exports.getDatabaseConfig = getDatabaseConfig;
14
+ exports.createIngestionRun = createIngestionRun;
15
+ exports.getIngestionRunByOrganizationAndID = getIngestionRunByOrganizationAndID;
16
+ exports.updateIngestionRunState = updateIngestionRunState;
17
+ exports.listIngestionRunsByOrganization = listIngestionRunsByOrganization;
18
+ exports.listIngestionRunsByDocument = listIngestionRunsByDocument;
19
+ exports.listIngestionHistory = listIngestionHistory;
20
+ exports.deleteDocumentTagsByDocumentID = deleteDocumentTagsByDocumentID;
21
+ exports.createDocumentTag = createDocumentTag;
22
+ exports.listDocumentTagsByDocumentID = listDocumentTagsByDocumentID;
23
+ exports.createThread = createThread;
24
+ exports.getThreadByOrganizationAndID = getThreadByOrganizationAndID;
25
+ exports.listThreadsByIngestionRun = listThreadsByIngestionRun;
26
+ exports.listThreadsByDocument = listThreadsByDocument;
27
+ exports.listPendingThreadsByRun = listPendingThreadsByRun;
28
+ exports.listPendingThreadsByOrganization = listPendingThreadsByOrganization;
29
+ exports.updateThreadEmbedding = updateThreadEmbedding;
30
+ exports.setThreadNextEmbedding = setThreadNextEmbedding;
31
+ exports.updateThreadClassification = updateThreadClassification;
32
+ exports.editPendingThread = editPendingThread;
33
+ exports.editDocumentThread = editDocumentThread;
34
+ exports.approveThread = approveThread;
35
+ exports.bulkApproveThreads = bulkApproveThreads;
36
+ exports.rejectThread = rejectThread;
37
+ exports.bulkRejectThreads = bulkRejectThreads;
38
+ exports.listThreadsBySupersedes = listThreadsBySupersedes;
39
+ exports.listThreadsByIDs = listThreadsByIDs;
40
+ exports.getIngestionRunThreadCounts = getIngestionRunThreadCounts;
41
+ exports.deleteThreadReconciliationByPendingThread = deleteThreadReconciliationByPendingThread;
42
+ exports.upsertThreadReconciliation = upsertThreadReconciliation;
43
+ exports.listThreadReconciliationByPendingThread = listThreadReconciliationByPendingThread;
44
+ exports.createThreadActivity = createThreadActivity;
45
+ exports.listThreadActivityByThread = listThreadActivityByThread;
46
+ exports.upsertEntity = upsertEntity;
47
+ exports.upsertThreadEntity = upsertThreadEntity;
48
+ exports.upsertEntityRelationship = upsertEntityRelationship;
49
+ exports.listEntitiesByThread = listEntitiesByThread;
50
+ exports.ensureOrganizationIngestionSettings = ensureOrganizationIngestionSettings;
51
+ exports.getOrganizationIngestionSettings = getOrganizationIngestionSettings;
52
+ exports.upsertOrganizationIngestionSettings = upsertOrganizationIngestionSettings;
53
+ exports.syncOrganizationIngestionReasoningDefaults = syncOrganizationIngestionReasoningDefaults;
54
+ exports.listFacetConfigs = listFacetConfigs;
55
+ exports.listActiveFacetConfigs = listActiveFacetConfigs;
56
+ exports.upsertFacetConfig = upsertFacetConfig;
57
+ exports.deactivateFacetConfig = deactivateFacetConfig;
58
+ exports.createDocumentQuery = `-- name: CreateDocument :one
59
+ INSERT INTO weave.documents (
60
+ id,
61
+ organization_id,
62
+ filename,
63
+ mime_type,
64
+ fingerprint,
65
+ storage_ref,
66
+ status,
67
+ scope,
68
+ sensitivity_tags,
69
+ uploaded_by_user_id,
70
+ metadata
71
+ ) VALUES (
72
+ $1,
73
+ $2,
74
+ $3,
75
+ $4,
76
+ $5,
77
+ $6,
78
+ $7,
79
+ $8,
80
+ $9,
81
+ $10,
82
+ $11
83
+ )
84
+ RETURNING
85
+ id,
86
+ organization_id,
87
+ filename,
88
+ mime_type,
89
+ parser_name,
90
+ fingerprint,
91
+ storage_ref,
92
+ status,
93
+ scope,
94
+ sensitivity_tags,
95
+ uploaded_by_user_id,
96
+ uploaded_at,
97
+ updated_at,
98
+ page_count,
99
+ char_count,
100
+ metadata`;
101
+ async function createDocument(client, args) {
102
+ const result = await client.query({
103
+ text: exports.createDocumentQuery,
104
+ values: [args.id, args.organizationId, args.filename, args.mimeType, args.fingerprint, args.storageRef, args.status, args.scope, args.sensitivityTags, args.uploadedByUserId, args.metadata],
105
+ rowMode: "array"
106
+ });
107
+ if (result.rows.length !== 1) {
108
+ return null;
109
+ }
110
+ const row = result.rows[0];
111
+ return {
112
+ id: row[0],
113
+ organizationId: row[1],
114
+ filename: row[2],
115
+ mimeType: row[3],
116
+ parserName: row[4],
117
+ fingerprint: row[5],
118
+ storageRef: row[6],
119
+ status: row[7],
120
+ scope: row[8],
121
+ sensitivityTags: row[9],
122
+ uploadedByUserId: row[10],
123
+ uploadedAt: row[11],
124
+ updatedAt: row[12],
125
+ pageCount: row[13],
126
+ charCount: row[14],
127
+ metadata: row[15]
128
+ };
129
+ }
130
+ exports.getDocumentByOrganizationAndIDQuery = `-- name: GetDocumentByOrganizationAndID :one
131
+ SELECT
132
+ id,
133
+ organization_id,
134
+ filename,
135
+ mime_type,
136
+ parser_name,
137
+ fingerprint,
138
+ storage_ref,
139
+ status,
140
+ scope,
141
+ sensitivity_tags,
142
+ uploaded_by_user_id,
143
+ uploaded_at,
144
+ updated_at,
145
+ page_count,
146
+ char_count,
147
+ metadata
148
+ FROM weave.documents
149
+ WHERE organization_id = $1
150
+ AND id = $2`;
151
+ async function getDocumentByOrganizationAndID(client, args) {
152
+ const result = await client.query({
153
+ text: exports.getDocumentByOrganizationAndIDQuery,
154
+ values: [args.organizationId, args.id],
155
+ rowMode: "array"
156
+ });
157
+ if (result.rows.length !== 1) {
158
+ return null;
159
+ }
160
+ const row = result.rows[0];
161
+ return {
162
+ id: row[0],
163
+ organizationId: row[1],
164
+ filename: row[2],
165
+ mimeType: row[3],
166
+ parserName: row[4],
167
+ fingerprint: row[5],
168
+ storageRef: row[6],
169
+ status: row[7],
170
+ scope: row[8],
171
+ sensitivityTags: row[9],
172
+ uploadedByUserId: row[10],
173
+ uploadedAt: row[11],
174
+ updatedAt: row[12],
175
+ pageCount: row[13],
176
+ charCount: row[14],
177
+ metadata: row[15]
178
+ };
179
+ }
180
+ exports.getDocumentByOrganizationAndFingerprintQuery = `-- name: GetDocumentByOrganizationAndFingerprint :one
181
+ SELECT
182
+ id,
183
+ organization_id,
184
+ filename,
185
+ mime_type,
186
+ parser_name,
187
+ fingerprint,
188
+ storage_ref,
189
+ status,
190
+ scope,
191
+ sensitivity_tags,
192
+ uploaded_by_user_id,
193
+ uploaded_at,
194
+ updated_at,
195
+ page_count,
196
+ char_count,
197
+ metadata
198
+ FROM weave.documents
199
+ WHERE organization_id = $1
200
+ AND fingerprint = $2`;
201
+ async function getDocumentByOrganizationAndFingerprint(client, args) {
202
+ const result = await client.query({
203
+ text: exports.getDocumentByOrganizationAndFingerprintQuery,
204
+ values: [args.organizationId, args.fingerprint],
205
+ rowMode: "array"
206
+ });
207
+ if (result.rows.length !== 1) {
208
+ return null;
209
+ }
210
+ const row = result.rows[0];
211
+ return {
212
+ id: row[0],
213
+ organizationId: row[1],
214
+ filename: row[2],
215
+ mimeType: row[3],
216
+ parserName: row[4],
217
+ fingerprint: row[5],
218
+ storageRef: row[6],
219
+ status: row[7],
220
+ scope: row[8],
221
+ sensitivityTags: row[9],
222
+ uploadedByUserId: row[10],
223
+ uploadedAt: row[11],
224
+ updatedAt: row[12],
225
+ pageCount: row[13],
226
+ charCount: row[14],
227
+ metadata: row[15]
228
+ };
229
+ }
230
+ exports.setDocumentParseResultQuery = `-- name: SetDocumentParseResult :one
231
+ UPDATE weave.documents
232
+ SET
233
+ parser_name = $1,
234
+ status = $2,
235
+ page_count = $3,
236
+ char_count = $4,
237
+ updated_at = now()
238
+ WHERE organization_id = $5
239
+ AND id = $6
240
+ RETURNING
241
+ id,
242
+ organization_id,
243
+ filename,
244
+ mime_type,
245
+ parser_name,
246
+ fingerprint,
247
+ storage_ref,
248
+ status,
249
+ scope,
250
+ sensitivity_tags,
251
+ uploaded_by_user_id,
252
+ uploaded_at,
253
+ updated_at,
254
+ page_count,
255
+ char_count,
256
+ metadata`;
257
+ async function setDocumentParseResult(client, args) {
258
+ const result = await client.query({
259
+ text: exports.setDocumentParseResultQuery,
260
+ values: [args.parserName, args.status, args.pageCount, args.charCount, args.organizationId, args.id],
261
+ rowMode: "array"
262
+ });
263
+ if (result.rows.length !== 1) {
264
+ return null;
265
+ }
266
+ const row = result.rows[0];
267
+ return {
268
+ id: row[0],
269
+ organizationId: row[1],
270
+ filename: row[2],
271
+ mimeType: row[3],
272
+ parserName: row[4],
273
+ fingerprint: row[5],
274
+ storageRef: row[6],
275
+ status: row[7],
276
+ scope: row[8],
277
+ sensitivityTags: row[9],
278
+ uploadedByUserId: row[10],
279
+ uploadedAt: row[11],
280
+ updatedAt: row[12],
281
+ pageCount: row[13],
282
+ charCount: row[14],
283
+ metadata: row[15]
284
+ };
285
+ }
286
+ exports.setDocumentStatusQuery = `-- name: SetDocumentStatus :one
287
+ UPDATE weave.documents
288
+ SET
289
+ status = $1,
290
+ updated_at = now()
291
+ WHERE organization_id = $2
292
+ AND id = $3
293
+ RETURNING
294
+ id,
295
+ organization_id,
296
+ filename,
297
+ mime_type,
298
+ parser_name,
299
+ fingerprint,
300
+ storage_ref,
301
+ status,
302
+ scope,
303
+ sensitivity_tags,
304
+ uploaded_by_user_id,
305
+ uploaded_at,
306
+ updated_at,
307
+ page_count,
308
+ char_count,
309
+ metadata`;
310
+ async function setDocumentStatus(client, args) {
311
+ const result = await client.query({
312
+ text: exports.setDocumentStatusQuery,
313
+ values: [args.status, args.organizationId, args.id],
314
+ rowMode: "array"
315
+ });
316
+ if (result.rows.length !== 1) {
317
+ return null;
318
+ }
319
+ const row = result.rows[0];
320
+ return {
321
+ id: row[0],
322
+ organizationId: row[1],
323
+ filename: row[2],
324
+ mimeType: row[3],
325
+ parserName: row[4],
326
+ fingerprint: row[5],
327
+ storageRef: row[6],
328
+ status: row[7],
329
+ scope: row[8],
330
+ sensitivityTags: row[9],
331
+ uploadedByUserId: row[10],
332
+ uploadedAt: row[11],
333
+ updatedAt: row[12],
334
+ pageCount: row[13],
335
+ charCount: row[14],
336
+ metadata: row[15]
337
+ };
338
+ }
339
+ exports.listDocumentsByOrganizationQuery = `-- name: ListDocumentsByOrganization :many
340
+ SELECT
341
+ id,
342
+ organization_id,
343
+ filename,
344
+ mime_type,
345
+ parser_name,
346
+ fingerprint,
347
+ storage_ref,
348
+ status,
349
+ scope,
350
+ sensitivity_tags,
351
+ uploaded_by_user_id,
352
+ uploaded_at,
353
+ updated_at,
354
+ page_count,
355
+ char_count,
356
+ metadata
357
+ FROM weave.documents
358
+ WHERE organization_id = $1
359
+ ORDER BY uploaded_at DESC
360
+ LIMIT $3 OFFSET $2`;
361
+ async function listDocumentsByOrganization(client, args) {
362
+ const result = await client.query({
363
+ text: exports.listDocumentsByOrganizationQuery,
364
+ values: [args.organizationId, args.pageOffset, args.pageSize],
365
+ rowMode: "array"
366
+ });
367
+ return result.rows.map(row => {
368
+ return {
369
+ id: row[0],
370
+ organizationId: row[1],
371
+ filename: row[2],
372
+ mimeType: row[3],
373
+ parserName: row[4],
374
+ fingerprint: row[5],
375
+ storageRef: row[6],
376
+ status: row[7],
377
+ scope: row[8],
378
+ sensitivityTags: row[9],
379
+ uploadedByUserId: row[10],
380
+ uploadedAt: row[11],
381
+ updatedAt: row[12],
382
+ pageCount: row[13],
383
+ charCount: row[14],
384
+ metadata: row[15]
385
+ };
386
+ });
387
+ }
388
+ exports.listAccessibleDocumentSummariesQuery = `-- name: ListAccessibleDocumentSummaries :many
389
+ WITH latest_runs AS (
390
+ SELECT DISTINCT ON (r.document_id)
391
+ r.document_id,
392
+ r.id AS latest_ingestion_run_id,
393
+ r.status AS latest_ingestion_status
394
+ FROM weave.ingestion_runs r
395
+ WHERE r.organization_id = $1
396
+ ORDER BY r.document_id, r.started_at DESC
397
+ ),
398
+ thread_counts AS (
399
+ SELECT
400
+ t.document_id,
401
+ COUNT(*)::int AS thread_count,
402
+ COUNT(*) FILTER (
403
+ WHERE t.retrieval_status = 'THREAD_RETRIEVAL_STATUS_PENDING'
404
+ )::int AS pending_count,
405
+ COUNT(*) FILTER (
406
+ WHERE t.retrieval_status = 'THREAD_RETRIEVAL_STATUS_APPROVED'
407
+ )::int AS approved_count,
408
+ COUNT(*) FILTER (
409
+ WHERE t.retrieval_status = 'THREAD_RETRIEVAL_STATUS_REJECTED'
410
+ )::int AS rejected_count
411
+ FROM weave.threads t
412
+ WHERE t.organization_id = $1
413
+ GROUP BY t.document_id
414
+ ),
415
+ tag_data AS (
416
+ SELECT
417
+ dt.document_id,
418
+ array_agg(dt.tag ORDER BY dt.tag ASC) AS tags,
419
+ array_agg(dt.confidence ORDER BY dt.tag ASC) AS tag_confidences
420
+ FROM weave.document_tags dt
421
+ JOIN weave.documents d ON d.id = dt.document_id
422
+ WHERE d.organization_id = $1
423
+ GROUP BY dt.document_id
424
+ )
425
+ SELECT
426
+ d.id,
427
+ d.organization_id,
428
+ d.filename,
429
+ d.mime_type,
430
+ d.parser_name,
431
+ d.status,
432
+ d.scope,
433
+ d.sensitivity_tags,
434
+ COALESCE(tag_data.tags, '{}'::text[]) AS tags,
435
+ COALESCE(tag_data.tag_confidences, '{}'::real[]) AS tag_confidences,
436
+ d.uploaded_by_user_id,
437
+ d.uploaded_at,
438
+ d.updated_at,
439
+ d.page_count,
440
+ d.char_count,
441
+ d.metadata,
442
+ COALESCE(latest_runs.latest_ingestion_run_id, '00000000-0000-0000-0000-000000000000'::uuid) AS latest_ingestion_run_id,
443
+ COALESCE(latest_runs.latest_ingestion_status, 'INGESTION_RUN_STATUS_UNSPECIFIED') AS latest_ingestion_status,
444
+ COALESCE(thread_counts.thread_count, 0)::int AS thread_count,
445
+ COALESCE(thread_counts.pending_count, 0)::int AS pending_count,
446
+ COALESCE(thread_counts.approved_count, 0)::int AS approved_count,
447
+ COALESCE(thread_counts.rejected_count, 0)::int AS rejected_count
448
+ FROM weave.documents d
449
+ LEFT JOIN latest_runs ON latest_runs.document_id = d.id
450
+ LEFT JOIN thread_counts ON thread_counts.document_id = d.id
451
+ LEFT JOIN tag_data ON tag_data.document_id = d.id
452
+ WHERE d.organization_id = $1
453
+ AND (
454
+ d.scope = 'DOCUMENT_SCOPE_ORG'
455
+ OR (d.scope = 'DOCUMENT_SCOPE_PRIVATE'
456
+ AND d.uploaded_by_user_id = $2)
457
+ OR (d.scope = 'DOCUMENT_SCOPE_RESTRICTED'
458
+ AND EXISTS (
459
+ SELECT 1
460
+ FROM weave.user_sensitivity_clearances c
461
+ WHERE c.organization_id = $1
462
+ AND c.user_id = $2
463
+ AND cardinality(d.sensitivity_tags) = 1
464
+ AND c.sensitivity_tag_slug = d.sensitivity_tags[1]
465
+ ))
466
+ )
467
+ AND (cardinality($3::text[]) = 0 OR d.status = ANY($3::text[]))
468
+ AND (cardinality($4::text[]) = 0 OR latest_runs.latest_ingestion_status = ANY($4::text[]))
469
+ AND (cardinality($5::text[]) = 0 OR d.scope = ANY($5::text[]))
470
+ AND (cardinality($6::text[]) = 0 OR tag_data.tags && $6::text[] OR d.sensitivity_tags && $6::text[])
471
+ AND (cardinality($7::text[]) = 0 OR d.sensitivity_tags && $7::text[])
472
+ AND ($8::timestamptz IS NULL OR d.uploaded_at >= $8::timestamptz)
473
+ AND ($9::timestamptz IS NULL OR d.uploaded_at <= $9::timestamptz)
474
+ ORDER BY d.uploaded_at DESC, d.id DESC
475
+ LIMIT $11 OFFSET $10`;
476
+ async function listAccessibleDocumentSummaries(client, args) {
477
+ const result = await client.query({
478
+ text: exports.listAccessibleDocumentSummariesQuery,
479
+ values: [args.organizationId, args.actingUserId, args.documentStatuses, args.ingestionStatuses, args.scopes, args.tags, args.restrictedTags, args.uploadedAfter, args.uploadedBefore, args.pageOffset, args.pageSize],
480
+ rowMode: "array"
481
+ });
482
+ return result.rows.map(row => {
483
+ return {
484
+ id: row[0],
485
+ organizationId: row[1],
486
+ filename: row[2],
487
+ mimeType: row[3],
488
+ parserName: row[4],
489
+ status: row[5],
490
+ scope: row[6],
491
+ sensitivityTags: row[7],
492
+ tags: row[8],
493
+ tagConfidences: row[9],
494
+ uploadedByUserId: row[10],
495
+ uploadedAt: row[11],
496
+ updatedAt: row[12],
497
+ pageCount: row[13],
498
+ charCount: row[14],
499
+ metadata: row[15],
500
+ latestIngestionRunId: row[16],
501
+ latestIngestionStatus: row[17],
502
+ threadCount: row[18],
503
+ pendingCount: row[19],
504
+ approvedCount: row[20],
505
+ rejectedCount: row[21]
506
+ };
507
+ });
508
+ }
509
+ exports.getAccessibleDocumentSummaryQuery = `-- name: GetAccessibleDocumentSummary :one
510
+ WITH latest_runs AS (
511
+ SELECT DISTINCT ON (r.document_id)
512
+ r.document_id,
513
+ r.id AS latest_ingestion_run_id,
514
+ r.status AS latest_ingestion_status
515
+ FROM weave.ingestion_runs r
516
+ WHERE r.organization_id = $1
517
+ AND r.document_id = $2
518
+ ORDER BY r.document_id, r.started_at DESC
519
+ ),
520
+ thread_counts AS (
521
+ SELECT
522
+ t.document_id,
523
+ COUNT(*)::int AS thread_count,
524
+ COUNT(*) FILTER (
525
+ WHERE t.retrieval_status = 'THREAD_RETRIEVAL_STATUS_PENDING'
526
+ )::int AS pending_count,
527
+ COUNT(*) FILTER (
528
+ WHERE t.retrieval_status = 'THREAD_RETRIEVAL_STATUS_APPROVED'
529
+ )::int AS approved_count,
530
+ COUNT(*) FILTER (
531
+ WHERE t.retrieval_status = 'THREAD_RETRIEVAL_STATUS_REJECTED'
532
+ )::int AS rejected_count
533
+ FROM weave.threads t
534
+ WHERE t.organization_id = $1
535
+ AND t.document_id = $2
536
+ GROUP BY t.document_id
537
+ ),
538
+ tag_data AS (
539
+ SELECT
540
+ dt.document_id,
541
+ array_agg(dt.tag ORDER BY dt.tag ASC) AS tags,
542
+ array_agg(dt.confidence ORDER BY dt.tag ASC) AS tag_confidences
543
+ FROM weave.document_tags dt
544
+ JOIN weave.documents d ON d.id = dt.document_id
545
+ WHERE d.organization_id = $1
546
+ AND dt.document_id = $2
547
+ GROUP BY dt.document_id
548
+ )
549
+ SELECT
550
+ d.id,
551
+ d.organization_id,
552
+ d.filename,
553
+ d.mime_type,
554
+ d.parser_name,
555
+ d.status,
556
+ d.scope,
557
+ d.sensitivity_tags,
558
+ COALESCE(tag_data.tags, '{}'::text[]) AS tags,
559
+ COALESCE(tag_data.tag_confidences, '{}'::real[]) AS tag_confidences,
560
+ d.uploaded_by_user_id,
561
+ d.uploaded_at,
562
+ d.updated_at,
563
+ d.page_count,
564
+ d.char_count,
565
+ d.metadata,
566
+ COALESCE(latest_runs.latest_ingestion_run_id, '00000000-0000-0000-0000-000000000000'::uuid) AS latest_ingestion_run_id,
567
+ COALESCE(latest_runs.latest_ingestion_status, 'INGESTION_RUN_STATUS_UNSPECIFIED') AS latest_ingestion_status,
568
+ COALESCE(thread_counts.thread_count, 0)::int AS thread_count,
569
+ COALESCE(thread_counts.pending_count, 0)::int AS pending_count,
570
+ COALESCE(thread_counts.approved_count, 0)::int AS approved_count,
571
+ COALESCE(thread_counts.rejected_count, 0)::int AS rejected_count
572
+ FROM weave.documents d
573
+ LEFT JOIN latest_runs ON latest_runs.document_id = d.id
574
+ LEFT JOIN thread_counts ON thread_counts.document_id = d.id
575
+ LEFT JOIN tag_data ON tag_data.document_id = d.id
576
+ WHERE d.organization_id = $1
577
+ AND d.id = $2
578
+ AND (
579
+ d.scope = 'DOCUMENT_SCOPE_ORG'
580
+ OR (d.scope = 'DOCUMENT_SCOPE_PRIVATE'
581
+ AND d.uploaded_by_user_id = $3)
582
+ OR (d.scope = 'DOCUMENT_SCOPE_RESTRICTED'
583
+ AND EXISTS (
584
+ SELECT 1
585
+ FROM weave.user_sensitivity_clearances c
586
+ WHERE c.organization_id = $1
587
+ AND c.user_id = $3
588
+ AND cardinality(d.sensitivity_tags) = 1
589
+ AND c.sensitivity_tag_slug = d.sensitivity_tags[1]
590
+ ))
591
+ )`;
592
+ async function getAccessibleDocumentSummary(client, args) {
593
+ const result = await client.query({
594
+ text: exports.getAccessibleDocumentSummaryQuery,
595
+ values: [args.organizationId, args.documentId, args.actingUserId],
596
+ rowMode: "array"
597
+ });
598
+ if (result.rows.length !== 1) {
599
+ return null;
600
+ }
601
+ const row = result.rows[0];
602
+ return {
603
+ id: row[0],
604
+ organizationId: row[1],
605
+ filename: row[2],
606
+ mimeType: row[3],
607
+ parserName: row[4],
608
+ status: row[5],
609
+ scope: row[6],
610
+ sensitivityTags: row[7],
611
+ tags: row[8],
612
+ tagConfidences: row[9],
613
+ uploadedByUserId: row[10],
614
+ uploadedAt: row[11],
615
+ updatedAt: row[12],
616
+ pageCount: row[13],
617
+ charCount: row[14],
618
+ metadata: row[15],
619
+ latestIngestionRunId: row[16],
620
+ latestIngestionStatus: row[17],
621
+ threadCount: row[18],
622
+ pendingCount: row[19],
623
+ approvedCount: row[20],
624
+ rejectedCount: row[21]
625
+ };
626
+ }
627
+ exports.getDatabaseConfigQuery = `-- name: GetDatabaseConfig :one
628
+ SELECT
629
+ id,
630
+ embedding_dimension,
631
+ deployment_mode,
632
+ created_at,
633
+ updated_at
634
+ FROM weave.database_config
635
+ WHERE id = 1`;
636
+ async function getDatabaseConfig(client) {
637
+ const result = await client.query({
638
+ text: exports.getDatabaseConfigQuery,
639
+ values: [],
640
+ rowMode: "array"
641
+ });
642
+ if (result.rows.length !== 1) {
643
+ return null;
644
+ }
645
+ const row = result.rows[0];
646
+ return {
647
+ id: row[0],
648
+ embeddingDimension: row[1],
649
+ deploymentMode: row[2],
650
+ createdAt: row[3],
651
+ updatedAt: row[4]
652
+ };
653
+ }
654
+ exports.createIngestionRunQuery = `-- name: CreateIngestionRun :one
655
+ INSERT INTO weave.ingestion_runs (
656
+ id,
657
+ organization_id,
658
+ document_id,
659
+ status,
660
+ reasoning_model_id,
661
+ reasoning_provider_configuration_id,
662
+ embedding_model_id,
663
+ embedding_provider_configuration_id,
664
+ embedding_dimensions
665
+ ) VALUES (
666
+ $1,
667
+ $2,
668
+ $3,
669
+ $4,
670
+ $5,
671
+ $6,
672
+ $7,
673
+ $8,
674
+ $9
675
+ )
676
+ RETURNING
677
+ id,
678
+ organization_id,
679
+ document_id,
680
+ status,
681
+ reasoning_model_id,
682
+ reasoning_provider_configuration_id,
683
+ embedding_model_id,
684
+ embedding_provider_configuration_id,
685
+ embedding_dimensions,
686
+ thread_count,
687
+ pending_count,
688
+ approved_count,
689
+ rejected_count,
690
+ error,
691
+ token_usage,
692
+ started_at,
693
+ completed_at,
694
+ committed_at`;
695
+ async function createIngestionRun(client, args) {
696
+ const result = await client.query({
697
+ text: exports.createIngestionRunQuery,
698
+ values: [args.id, args.organizationId, args.documentId, args.status, args.reasoningModelId, args.reasoningProviderConfigurationId, args.embeddingModelId, args.embeddingProviderConfigurationId, args.embeddingDimensions],
699
+ rowMode: "array"
700
+ });
701
+ if (result.rows.length !== 1) {
702
+ return null;
703
+ }
704
+ const row = result.rows[0];
705
+ return {
706
+ id: row[0],
707
+ organizationId: row[1],
708
+ documentId: row[2],
709
+ status: row[3],
710
+ reasoningModelId: row[4],
711
+ reasoningProviderConfigurationId: row[5],
712
+ embeddingModelId: row[6],
713
+ embeddingProviderConfigurationId: row[7],
714
+ embeddingDimensions: row[8],
715
+ threadCount: row[9],
716
+ pendingCount: row[10],
717
+ approvedCount: row[11],
718
+ rejectedCount: row[12],
719
+ error: row[13],
720
+ tokenUsage: row[14],
721
+ startedAt: row[15],
722
+ completedAt: row[16],
723
+ committedAt: row[17]
724
+ };
725
+ }
726
+ exports.getIngestionRunByOrganizationAndIDQuery = `-- name: GetIngestionRunByOrganizationAndID :one
727
+ SELECT
728
+ id,
729
+ organization_id,
730
+ document_id,
731
+ status,
732
+ reasoning_model_id,
733
+ reasoning_provider_configuration_id,
734
+ embedding_model_id,
735
+ embedding_provider_configuration_id,
736
+ embedding_dimensions,
737
+ thread_count,
738
+ pending_count,
739
+ approved_count,
740
+ rejected_count,
741
+ error,
742
+ token_usage,
743
+ started_at,
744
+ completed_at,
745
+ committed_at
746
+ FROM weave.ingestion_runs
747
+ WHERE organization_id = $1
748
+ AND id = $2`;
749
+ async function getIngestionRunByOrganizationAndID(client, args) {
750
+ const result = await client.query({
751
+ text: exports.getIngestionRunByOrganizationAndIDQuery,
752
+ values: [args.organizationId, args.id],
753
+ rowMode: "array"
754
+ });
755
+ if (result.rows.length !== 1) {
756
+ return null;
757
+ }
758
+ const row = result.rows[0];
759
+ return {
760
+ id: row[0],
761
+ organizationId: row[1],
762
+ documentId: row[2],
763
+ status: row[3],
764
+ reasoningModelId: row[4],
765
+ reasoningProviderConfigurationId: row[5],
766
+ embeddingModelId: row[6],
767
+ embeddingProviderConfigurationId: row[7],
768
+ embeddingDimensions: row[8],
769
+ threadCount: row[9],
770
+ pendingCount: row[10],
771
+ approvedCount: row[11],
772
+ rejectedCount: row[12],
773
+ error: row[13],
774
+ tokenUsage: row[14],
775
+ startedAt: row[15],
776
+ completedAt: row[16],
777
+ committedAt: row[17]
778
+ };
779
+ }
780
+ exports.updateIngestionRunStateQuery = `-- name: UpdateIngestionRunState :one
781
+ UPDATE weave.ingestion_runs
782
+ SET
783
+ status = $1,
784
+ thread_count = $2,
785
+ pending_count = $3,
786
+ approved_count = $4,
787
+ rejected_count = $5,
788
+ error = $6,
789
+ token_usage = $7,
790
+ completed_at = $8,
791
+ committed_at = $9
792
+ WHERE id = $10
793
+ AND organization_id = $11
794
+ RETURNING
795
+ id,
796
+ organization_id,
797
+ document_id,
798
+ status,
799
+ reasoning_model_id,
800
+ reasoning_provider_configuration_id,
801
+ embedding_model_id,
802
+ embedding_provider_configuration_id,
803
+ embedding_dimensions,
804
+ thread_count,
805
+ pending_count,
806
+ approved_count,
807
+ rejected_count,
808
+ error,
809
+ token_usage,
810
+ started_at,
811
+ completed_at,
812
+ committed_at`;
813
+ async function updateIngestionRunState(client, args) {
814
+ const result = await client.query({
815
+ text: exports.updateIngestionRunStateQuery,
816
+ values: [args.status, args.threadCount, args.pendingCount, args.approvedCount, args.rejectedCount, args.error, args.tokenUsage, args.completedAt, args.committedAt, args.id, args.organizationId],
817
+ rowMode: "array"
818
+ });
819
+ if (result.rows.length !== 1) {
820
+ return null;
821
+ }
822
+ const row = result.rows[0];
823
+ return {
824
+ id: row[0],
825
+ organizationId: row[1],
826
+ documentId: row[2],
827
+ status: row[3],
828
+ reasoningModelId: row[4],
829
+ reasoningProviderConfigurationId: row[5],
830
+ embeddingModelId: row[6],
831
+ embeddingProviderConfigurationId: row[7],
832
+ embeddingDimensions: row[8],
833
+ threadCount: row[9],
834
+ pendingCount: row[10],
835
+ approvedCount: row[11],
836
+ rejectedCount: row[12],
837
+ error: row[13],
838
+ tokenUsage: row[14],
839
+ startedAt: row[15],
840
+ completedAt: row[16],
841
+ committedAt: row[17]
842
+ };
843
+ }
844
+ exports.listIngestionRunsByOrganizationQuery = `-- name: ListIngestionRunsByOrganization :many
845
+ SELECT
846
+ id,
847
+ organization_id,
848
+ document_id,
849
+ status,
850
+ reasoning_model_id,
851
+ reasoning_provider_configuration_id,
852
+ embedding_model_id,
853
+ embedding_provider_configuration_id,
854
+ embedding_dimensions,
855
+ thread_count,
856
+ pending_count,
857
+ approved_count,
858
+ rejected_count,
859
+ error,
860
+ token_usage,
861
+ started_at,
862
+ completed_at,
863
+ committed_at
864
+ FROM weave.ingestion_runs
865
+ WHERE organization_id = $1
866
+ ORDER BY started_at DESC
867
+ LIMIT $3 OFFSET $2`;
868
+ async function listIngestionRunsByOrganization(client, args) {
869
+ const result = await client.query({
870
+ text: exports.listIngestionRunsByOrganizationQuery,
871
+ values: [args.organizationId, args.pageOffset, args.pageSize],
872
+ rowMode: "array"
873
+ });
874
+ return result.rows.map(row => {
875
+ return {
876
+ id: row[0],
877
+ organizationId: row[1],
878
+ documentId: row[2],
879
+ status: row[3],
880
+ reasoningModelId: row[4],
881
+ reasoningProviderConfigurationId: row[5],
882
+ embeddingModelId: row[6],
883
+ embeddingProviderConfigurationId: row[7],
884
+ embeddingDimensions: row[8],
885
+ threadCount: row[9],
886
+ pendingCount: row[10],
887
+ approvedCount: row[11],
888
+ rejectedCount: row[12],
889
+ error: row[13],
890
+ tokenUsage: row[14],
891
+ startedAt: row[15],
892
+ completedAt: row[16],
893
+ committedAt: row[17]
894
+ };
895
+ });
896
+ }
897
+ exports.listIngestionRunsByDocumentQuery = `-- name: ListIngestionRunsByDocument :many
898
+ SELECT
899
+ id,
900
+ organization_id,
901
+ document_id,
902
+ status,
903
+ reasoning_model_id,
904
+ reasoning_provider_configuration_id,
905
+ embedding_model_id,
906
+ embedding_provider_configuration_id,
907
+ embedding_dimensions,
908
+ thread_count,
909
+ pending_count,
910
+ approved_count,
911
+ rejected_count,
912
+ error,
913
+ token_usage,
914
+ started_at,
915
+ completed_at,
916
+ committed_at
917
+ FROM weave.ingestion_runs
918
+ WHERE organization_id = $1
919
+ AND document_id = $2
920
+ ORDER BY started_at DESC`;
921
+ async function listIngestionRunsByDocument(client, args) {
922
+ const result = await client.query({
923
+ text: exports.listIngestionRunsByDocumentQuery,
924
+ values: [args.organizationId, args.documentId],
925
+ rowMode: "array"
926
+ });
927
+ return result.rows.map(row => {
928
+ return {
929
+ id: row[0],
930
+ organizationId: row[1],
931
+ documentId: row[2],
932
+ status: row[3],
933
+ reasoningModelId: row[4],
934
+ reasoningProviderConfigurationId: row[5],
935
+ embeddingModelId: row[6],
936
+ embeddingProviderConfigurationId: row[7],
937
+ embeddingDimensions: row[8],
938
+ threadCount: row[9],
939
+ pendingCount: row[10],
940
+ approvedCount: row[11],
941
+ rejectedCount: row[12],
942
+ error: row[13],
943
+ tokenUsage: row[14],
944
+ startedAt: row[15],
945
+ completedAt: row[16],
946
+ committedAt: row[17]
947
+ };
948
+ });
949
+ }
950
+ exports.listIngestionHistoryQuery = `-- name: ListIngestionHistory :many
951
+ SELECT
952
+ r.id AS ingestion_run_id,
953
+ d.id AS document_id,
954
+ d.filename AS document_name,
955
+ d.status AS document_status,
956
+ r.status AS ingestion_status,
957
+ r.thread_count,
958
+ r.pending_count,
959
+ r.approved_count,
960
+ r.rejected_count,
961
+ d.uploaded_at,
962
+ r.started_at,
963
+ r.completed_at,
964
+ r.committed_at
965
+ FROM weave.ingestion_runs r
966
+ JOIN weave.documents d ON d.id = r.document_id
967
+ WHERE r.organization_id = $1
968
+ ORDER BY r.started_at DESC
969
+ LIMIT $3 OFFSET $2`;
970
+ async function listIngestionHistory(client, args) {
971
+ const result = await client.query({
972
+ text: exports.listIngestionHistoryQuery,
973
+ values: [args.organizationId, args.pageOffset, args.pageSize],
974
+ rowMode: "array"
975
+ });
976
+ return result.rows.map(row => {
977
+ return {
978
+ ingestionRunId: row[0],
979
+ documentId: row[1],
980
+ documentName: row[2],
981
+ documentStatus: row[3],
982
+ ingestionStatus: row[4],
983
+ threadCount: row[5],
984
+ pendingCount: row[6],
985
+ approvedCount: row[7],
986
+ rejectedCount: row[8],
987
+ uploadedAt: row[9],
988
+ startedAt: row[10],
989
+ completedAt: row[11],
990
+ committedAt: row[12]
991
+ };
992
+ });
993
+ }
994
+ exports.deleteDocumentTagsByDocumentIDQuery = `-- name: DeleteDocumentTagsByDocumentID :exec
995
+ DELETE FROM weave.document_tags dt
996
+ USING weave.documents d
997
+ WHERE dt.document_id = d.id
998
+ AND d.organization_id = $1
999
+ AND dt.document_id = $2`;
1000
+ async function deleteDocumentTagsByDocumentID(client, args) {
1001
+ await client.query({
1002
+ text: exports.deleteDocumentTagsByDocumentIDQuery,
1003
+ values: [args.organizationId, args.documentId],
1004
+ rowMode: "array"
1005
+ });
1006
+ }
1007
+ exports.deleteDocumentTagByDocumentIDAndTagQuery = `-- name: DeleteDocumentTagByDocumentIDAndTag :execrows
1008
+ DELETE FROM weave.document_tags dt
1009
+ USING weave.documents d
1010
+ WHERE dt.document_id = d.id
1011
+ AND d.organization_id = $1
1012
+ AND dt.document_id = $2
1013
+ AND dt.tag = $3`;
1014
+ exports.createDocumentTagQuery = `-- name: CreateDocumentTag :one
1015
+ INSERT INTO weave.document_tags (
1016
+ document_id,
1017
+ tag,
1018
+ confidence
1019
+ ) VALUES (
1020
+ $1,
1021
+ $2,
1022
+ $3
1023
+ )
1024
+ RETURNING document_id, tag, confidence`;
1025
+ async function createDocumentTag(client, args) {
1026
+ const result = await client.query({
1027
+ text: exports.createDocumentTagQuery,
1028
+ values: [args.documentId, args.tag, args.confidence],
1029
+ rowMode: "array"
1030
+ });
1031
+ if (result.rows.length !== 1) {
1032
+ return null;
1033
+ }
1034
+ const row = result.rows[0];
1035
+ return {
1036
+ documentId: row[0],
1037
+ tag: row[1],
1038
+ confidence: row[2]
1039
+ };
1040
+ }
1041
+ exports.listDocumentTagsByDocumentIDQuery = `-- name: ListDocumentTagsByDocumentID :many
1042
+ SELECT document_id, tag, confidence
1043
+ FROM weave.document_tags dt
1044
+ JOIN weave.documents d ON d.id = dt.document_id
1045
+ WHERE d.organization_id = $1
1046
+ AND dt.document_id = $2
1047
+ ORDER BY confidence DESC, tag ASC`;
1048
+ async function listDocumentTagsByDocumentID(client, args) {
1049
+ const result = await client.query({
1050
+ text: exports.listDocumentTagsByDocumentIDQuery,
1051
+ values: [args.organizationId, args.documentId],
1052
+ rowMode: "array"
1053
+ });
1054
+ return result.rows.map(row => {
1055
+ return {
1056
+ documentId: row[0],
1057
+ tag: row[1],
1058
+ confidence: row[2]
1059
+ };
1060
+ });
1061
+ }
1062
+ exports.deleteDocumentByOrganizationAndIDQuery = `-- name: DeleteDocumentByOrganizationAndID :execrows
1063
+ DELETE FROM weave.documents
1064
+ WHERE organization_id = $1
1065
+ AND id = $2`;
1066
+ exports.createThreadQuery = `-- name: CreateThread :one
1067
+ INSERT INTO weave.threads (
1068
+ id,
1069
+ organization_id,
1070
+ document_id,
1071
+ ingestion_run_id,
1072
+ text,
1073
+ knowledge_type,
1074
+ facet_fields,
1075
+ confidence,
1076
+ temporal_validity,
1077
+ classification,
1078
+ retrieval_status,
1079
+ source_location,
1080
+ metadata
1081
+ ) VALUES (
1082
+ $1,
1083
+ $2,
1084
+ $3,
1085
+ $4,
1086
+ $5,
1087
+ $6,
1088
+ $7,
1089
+ $8,
1090
+ $9,
1091
+ $10,
1092
+ $11,
1093
+ $12,
1094
+ $13
1095
+ )
1096
+ RETURNING
1097
+ id,
1098
+ organization_id,
1099
+ document_id,
1100
+ ingestion_run_id,
1101
+ text,
1102
+ text_original,
1103
+ knowledge_type,
1104
+ facet_fields,
1105
+ confidence,
1106
+ temporal_validity,
1107
+ classification,
1108
+ retrieval_status,
1109
+ source_location,
1110
+ superseded_by,
1111
+ supersedes,
1112
+ cluster_id,
1113
+ extracted_at,
1114
+ approved_at,
1115
+ approved_by_user_id,
1116
+ edited,
1117
+ metadata`;
1118
+ async function createThread(client, args) {
1119
+ const result = await client.query({
1120
+ text: exports.createThreadQuery,
1121
+ values: [args.id, args.organizationId, args.documentId, args.ingestionRunId, args.text, args.knowledgeType, args.facetFields, args.confidence, args.temporalValidity, args.classification, args.retrievalStatus, args.sourceLocation, args.metadata],
1122
+ rowMode: "array"
1123
+ });
1124
+ if (result.rows.length !== 1) {
1125
+ return null;
1126
+ }
1127
+ const row = result.rows[0];
1128
+ return {
1129
+ id: row[0],
1130
+ organizationId: row[1],
1131
+ documentId: row[2],
1132
+ ingestionRunId: row[3],
1133
+ text: row[4],
1134
+ textOriginal: row[5],
1135
+ knowledgeType: row[6],
1136
+ facetFields: row[7],
1137
+ confidence: row[8],
1138
+ temporalValidity: row[9],
1139
+ classification: row[10],
1140
+ retrievalStatus: row[11],
1141
+ sourceLocation: row[12],
1142
+ supersededBy: row[13],
1143
+ supersedes: row[14],
1144
+ clusterId: row[15],
1145
+ extractedAt: row[16],
1146
+ approvedAt: row[17],
1147
+ approvedByUserId: row[18],
1148
+ edited: row[19],
1149
+ metadata: row[20]
1150
+ };
1151
+ }
1152
+ exports.getThreadByOrganizationAndIDQuery = `-- name: GetThreadByOrganizationAndID :one
1153
+ SELECT
1154
+ t.id,
1155
+ t.organization_id,
1156
+ t.document_id,
1157
+ d.filename AS document_name,
1158
+ t.ingestion_run_id,
1159
+ t.text,
1160
+ t.text_original,
1161
+ t.knowledge_type,
1162
+ t.facet_fields,
1163
+ t.confidence,
1164
+ t.temporal_validity,
1165
+ t.classification,
1166
+ t.retrieval_status,
1167
+ t.source_location,
1168
+ t.superseded_by,
1169
+ t.supersedes,
1170
+ t.cluster_id,
1171
+ t.extracted_at,
1172
+ t.approved_at,
1173
+ t.approved_by_user_id,
1174
+ t.edited,
1175
+ t.metadata
1176
+ FROM weave.threads t
1177
+ JOIN weave.documents d ON d.id = t.document_id
1178
+ WHERE t.organization_id = $1
1179
+ AND t.id = $2`;
1180
+ async function getThreadByOrganizationAndID(client, args) {
1181
+ const result = await client.query({
1182
+ text: exports.getThreadByOrganizationAndIDQuery,
1183
+ values: [args.organizationId, args.id],
1184
+ rowMode: "array"
1185
+ });
1186
+ if (result.rows.length !== 1) {
1187
+ return null;
1188
+ }
1189
+ const row = result.rows[0];
1190
+ return {
1191
+ id: row[0],
1192
+ organizationId: row[1],
1193
+ documentId: row[2],
1194
+ documentName: row[3],
1195
+ ingestionRunId: row[4],
1196
+ text: row[5],
1197
+ textOriginal: row[6],
1198
+ knowledgeType: row[7],
1199
+ facetFields: row[8],
1200
+ confidence: row[9],
1201
+ temporalValidity: row[10],
1202
+ classification: row[11],
1203
+ retrievalStatus: row[12],
1204
+ sourceLocation: row[13],
1205
+ supersededBy: row[14],
1206
+ supersedes: row[15],
1207
+ clusterId: row[16],
1208
+ extractedAt: row[17],
1209
+ approvedAt: row[18],
1210
+ approvedByUserId: row[19],
1211
+ edited: row[20],
1212
+ metadata: row[21]
1213
+ };
1214
+ }
1215
+ exports.listThreadsByIngestionRunQuery = `-- name: ListThreadsByIngestionRun :many
1216
+ SELECT
1217
+ t.id,
1218
+ t.organization_id,
1219
+ t.document_id,
1220
+ d.filename AS document_name,
1221
+ t.ingestion_run_id,
1222
+ t.text,
1223
+ t.text_original,
1224
+ t.knowledge_type,
1225
+ t.facet_fields,
1226
+ t.confidence,
1227
+ t.temporal_validity,
1228
+ t.classification,
1229
+ t.retrieval_status,
1230
+ t.source_location,
1231
+ t.superseded_by,
1232
+ t.supersedes,
1233
+ t.cluster_id,
1234
+ t.extracted_at,
1235
+ t.approved_at,
1236
+ t.approved_by_user_id,
1237
+ t.edited,
1238
+ t.metadata
1239
+ FROM weave.threads t
1240
+ JOIN weave.documents d ON d.id = t.document_id
1241
+ WHERE t.organization_id = $1
1242
+ AND t.ingestion_run_id = $2
1243
+ ORDER BY t.extracted_at ASC, t.id ASC`;
1244
+ async function listThreadsByIngestionRun(client, args) {
1245
+ const result = await client.query({
1246
+ text: exports.listThreadsByIngestionRunQuery,
1247
+ values: [args.organizationId, args.ingestionRunId],
1248
+ rowMode: "array"
1249
+ });
1250
+ return result.rows.map(row => {
1251
+ return {
1252
+ id: row[0],
1253
+ organizationId: row[1],
1254
+ documentId: row[2],
1255
+ documentName: row[3],
1256
+ ingestionRunId: row[4],
1257
+ text: row[5],
1258
+ textOriginal: row[6],
1259
+ knowledgeType: row[7],
1260
+ facetFields: row[8],
1261
+ confidence: row[9],
1262
+ temporalValidity: row[10],
1263
+ classification: row[11],
1264
+ retrievalStatus: row[12],
1265
+ sourceLocation: row[13],
1266
+ supersededBy: row[14],
1267
+ supersedes: row[15],
1268
+ clusterId: row[16],
1269
+ extractedAt: row[17],
1270
+ approvedAt: row[18],
1271
+ approvedByUserId: row[19],
1272
+ edited: row[20],
1273
+ metadata: row[21]
1274
+ };
1275
+ });
1276
+ }
1277
+ exports.listThreadsByDocumentQuery = `-- name: ListThreadsByDocument :many
1278
+ SELECT
1279
+ t.id,
1280
+ t.organization_id,
1281
+ t.document_id,
1282
+ d.filename AS document_name,
1283
+ t.ingestion_run_id,
1284
+ t.text,
1285
+ t.text_original,
1286
+ t.knowledge_type,
1287
+ t.facet_fields,
1288
+ t.confidence,
1289
+ t.temporal_validity,
1290
+ t.classification,
1291
+ t.retrieval_status,
1292
+ t.source_location,
1293
+ t.superseded_by,
1294
+ t.supersedes,
1295
+ t.cluster_id,
1296
+ t.extracted_at,
1297
+ t.approved_at,
1298
+ t.approved_by_user_id,
1299
+ t.edited,
1300
+ t.metadata
1301
+ FROM weave.threads t
1302
+ JOIN weave.documents d ON d.id = t.document_id
1303
+ WHERE t.organization_id = $1
1304
+ AND t.document_id = $2
1305
+ ORDER BY t.extracted_at ASC, t.id ASC`;
1306
+ async function listThreadsByDocument(client, args) {
1307
+ const result = await client.query({
1308
+ text: exports.listThreadsByDocumentQuery,
1309
+ values: [args.organizationId, args.documentId],
1310
+ rowMode: "array"
1311
+ });
1312
+ return result.rows.map(row => {
1313
+ return {
1314
+ id: row[0],
1315
+ organizationId: row[1],
1316
+ documentId: row[2],
1317
+ documentName: row[3],
1318
+ ingestionRunId: row[4],
1319
+ text: row[5],
1320
+ textOriginal: row[6],
1321
+ knowledgeType: row[7],
1322
+ facetFields: row[8],
1323
+ confidence: row[9],
1324
+ temporalValidity: row[10],
1325
+ classification: row[11],
1326
+ retrievalStatus: row[12],
1327
+ sourceLocation: row[13],
1328
+ supersededBy: row[14],
1329
+ supersedes: row[15],
1330
+ clusterId: row[16],
1331
+ extractedAt: row[17],
1332
+ approvedAt: row[18],
1333
+ approvedByUserId: row[19],
1334
+ edited: row[20],
1335
+ metadata: row[21]
1336
+ };
1337
+ });
1338
+ }
1339
+ exports.listPendingThreadsByRunQuery = `-- name: ListPendingThreadsByRun :many
1340
+ SELECT
1341
+ id,
1342
+ organization_id,
1343
+ document_id,
1344
+ ingestion_run_id,
1345
+ text,
1346
+ text_original,
1347
+ knowledge_type,
1348
+ facet_fields,
1349
+ confidence,
1350
+ temporal_validity,
1351
+ classification,
1352
+ retrieval_status,
1353
+ source_location,
1354
+ superseded_by,
1355
+ supersedes,
1356
+ cluster_id,
1357
+ extracted_at,
1358
+ approved_at,
1359
+ approved_by_user_id,
1360
+ edited,
1361
+ metadata
1362
+ FROM weave.threads
1363
+ WHERE organization_id = $1
1364
+ AND ingestion_run_id = $2
1365
+ AND retrieval_status = 'THREAD_RETRIEVAL_STATUS_PENDING'
1366
+ ORDER BY extracted_at ASC, id ASC`;
1367
+ async function listPendingThreadsByRun(client, args) {
1368
+ const result = await client.query({
1369
+ text: exports.listPendingThreadsByRunQuery,
1370
+ values: [args.organizationId, args.ingestionRunId],
1371
+ rowMode: "array"
1372
+ });
1373
+ return result.rows.map(row => {
1374
+ return {
1375
+ id: row[0],
1376
+ organizationId: row[1],
1377
+ documentId: row[2],
1378
+ ingestionRunId: row[3],
1379
+ text: row[4],
1380
+ textOriginal: row[5],
1381
+ knowledgeType: row[6],
1382
+ facetFields: row[7],
1383
+ confidence: row[8],
1384
+ temporalValidity: row[9],
1385
+ classification: row[10],
1386
+ retrievalStatus: row[11],
1387
+ sourceLocation: row[12],
1388
+ supersededBy: row[13],
1389
+ supersedes: row[14],
1390
+ clusterId: row[15],
1391
+ extractedAt: row[16],
1392
+ approvedAt: row[17],
1393
+ approvedByUserId: row[18],
1394
+ edited: row[19],
1395
+ metadata: row[20]
1396
+ };
1397
+ });
1398
+ }
1399
+ exports.listPendingThreadsByOrganizationQuery = `-- name: ListPendingThreadsByOrganization :many
1400
+ SELECT
1401
+ t.id,
1402
+ t.organization_id,
1403
+ t.document_id,
1404
+ d.filename AS document_name,
1405
+ t.ingestion_run_id,
1406
+ t.text,
1407
+ t.text_original,
1408
+ t.knowledge_type,
1409
+ t.facet_fields,
1410
+ t.confidence,
1411
+ t.temporal_validity,
1412
+ t.classification,
1413
+ t.retrieval_status,
1414
+ t.source_location,
1415
+ t.superseded_by,
1416
+ t.supersedes,
1417
+ t.cluster_id,
1418
+ t.extracted_at,
1419
+ t.approved_at,
1420
+ t.approved_by_user_id,
1421
+ t.edited,
1422
+ t.metadata
1423
+ FROM weave.threads t
1424
+ JOIN weave.documents d ON d.id = t.document_id
1425
+ WHERE t.organization_id = $1
1426
+ AND t.retrieval_status = 'THREAD_RETRIEVAL_STATUS_PENDING'
1427
+ ORDER BY t.extracted_at DESC, t.id DESC
1428
+ LIMIT $3 OFFSET $2`;
1429
+ async function listPendingThreadsByOrganization(client, args) {
1430
+ const result = await client.query({
1431
+ text: exports.listPendingThreadsByOrganizationQuery,
1432
+ values: [args.organizationId, args.pageOffset, args.pageSize],
1433
+ rowMode: "array"
1434
+ });
1435
+ return result.rows.map(row => {
1436
+ return {
1437
+ id: row[0],
1438
+ organizationId: row[1],
1439
+ documentId: row[2],
1440
+ documentName: row[3],
1441
+ ingestionRunId: row[4],
1442
+ text: row[5],
1443
+ textOriginal: row[6],
1444
+ knowledgeType: row[7],
1445
+ facetFields: row[8],
1446
+ confidence: row[9],
1447
+ temporalValidity: row[10],
1448
+ classification: row[11],
1449
+ retrievalStatus: row[12],
1450
+ sourceLocation: row[13],
1451
+ supersededBy: row[14],
1452
+ supersedes: row[15],
1453
+ clusterId: row[16],
1454
+ extractedAt: row[17],
1455
+ approvedAt: row[18],
1456
+ approvedByUserId: row[19],
1457
+ edited: row[20],
1458
+ metadata: row[21]
1459
+ };
1460
+ });
1461
+ }
1462
+ exports.updateThreadEmbeddingQuery = `-- name: UpdateThreadEmbedding :one
1463
+ UPDATE weave.threads
1464
+ SET
1465
+ embedding = $1::vector
1466
+ WHERE organization_id = $2
1467
+ AND id = $3
1468
+ AND retrieval_status = 'THREAD_RETRIEVAL_STATUS_PENDING'
1469
+ RETURNING
1470
+ id,
1471
+ organization_id,
1472
+ document_id,
1473
+ ingestion_run_id,
1474
+ text,
1475
+ text_original,
1476
+ knowledge_type,
1477
+ facet_fields,
1478
+ confidence,
1479
+ temporal_validity,
1480
+ classification,
1481
+ retrieval_status,
1482
+ source_location,
1483
+ superseded_by,
1484
+ supersedes,
1485
+ cluster_id,
1486
+ extracted_at,
1487
+ approved_at,
1488
+ approved_by_user_id,
1489
+ edited,
1490
+ metadata`;
1491
+ async function updateThreadEmbedding(client, args) {
1492
+ const result = await client.query({
1493
+ text: exports.updateThreadEmbeddingQuery,
1494
+ values: [args.embedding, args.organizationId, args.id],
1495
+ rowMode: "array"
1496
+ });
1497
+ if (result.rows.length !== 1) {
1498
+ return null;
1499
+ }
1500
+ const row = result.rows[0];
1501
+ return {
1502
+ id: row[0],
1503
+ organizationId: row[1],
1504
+ documentId: row[2],
1505
+ ingestionRunId: row[3],
1506
+ text: row[4],
1507
+ textOriginal: row[5],
1508
+ knowledgeType: row[6],
1509
+ facetFields: row[7],
1510
+ confidence: row[8],
1511
+ temporalValidity: row[9],
1512
+ classification: row[10],
1513
+ retrievalStatus: row[11],
1514
+ sourceLocation: row[12],
1515
+ supersededBy: row[13],
1516
+ supersedes: row[14],
1517
+ clusterId: row[15],
1518
+ extractedAt: row[16],
1519
+ approvedAt: row[17],
1520
+ approvedByUserId: row[18],
1521
+ edited: row[19],
1522
+ metadata: row[20]
1523
+ };
1524
+ }
1525
+ exports.setThreadNextEmbeddingQuery = `-- name: SetThreadNextEmbedding :one
1526
+ UPDATE weave.threads
1527
+ SET
1528
+ embedding_next = $1::vector
1529
+ WHERE organization_id = $2
1530
+ AND id = $3
1531
+ AND retrieval_status = 'THREAD_RETRIEVAL_STATUS_PENDING'
1532
+ RETURNING
1533
+ id,
1534
+ organization_id,
1535
+ document_id,
1536
+ ingestion_run_id,
1537
+ text,
1538
+ text_original,
1539
+ knowledge_type,
1540
+ facet_fields,
1541
+ confidence,
1542
+ temporal_validity,
1543
+ classification,
1544
+ retrieval_status,
1545
+ source_location,
1546
+ superseded_by,
1547
+ supersedes,
1548
+ cluster_id,
1549
+ extracted_at,
1550
+ approved_at,
1551
+ approved_by_user_id,
1552
+ edited,
1553
+ metadata`;
1554
+ async function setThreadNextEmbedding(client, args) {
1555
+ const result = await client.query({
1556
+ text: exports.setThreadNextEmbeddingQuery,
1557
+ values: [args.embedding, args.organizationId, args.id],
1558
+ rowMode: "array"
1559
+ });
1560
+ if (result.rows.length !== 1) {
1561
+ return null;
1562
+ }
1563
+ const row = result.rows[0];
1564
+ return {
1565
+ id: row[0],
1566
+ organizationId: row[1],
1567
+ documentId: row[2],
1568
+ ingestionRunId: row[3],
1569
+ text: row[4],
1570
+ textOriginal: row[5],
1571
+ knowledgeType: row[6],
1572
+ facetFields: row[7],
1573
+ confidence: row[8],
1574
+ temporalValidity: row[9],
1575
+ classification: row[10],
1576
+ retrievalStatus: row[11],
1577
+ sourceLocation: row[12],
1578
+ supersededBy: row[13],
1579
+ supersedes: row[14],
1580
+ clusterId: row[15],
1581
+ extractedAt: row[16],
1582
+ approvedAt: row[17],
1583
+ approvedByUserId: row[18],
1584
+ edited: row[19],
1585
+ metadata: row[20]
1586
+ };
1587
+ }
1588
+ exports.promoteThreadNextEmbeddingsByOrganizationQuery = `-- name: PromoteThreadNextEmbeddingsByOrganization :execrows
1589
+ UPDATE weave.threads
1590
+ SET
1591
+ embedding = embedding_next,
1592
+ embedding_next = NULL
1593
+ WHERE organization_id = $1
1594
+ AND embedding_next IS NOT NULL`;
1595
+ exports.updateThreadClassificationQuery = `-- name: UpdateThreadClassification :one
1596
+ UPDATE weave.threads
1597
+ SET
1598
+ classification = $1,
1599
+ supersedes = $2
1600
+ WHERE organization_id = $3
1601
+ AND id = $4
1602
+ RETURNING
1603
+ id,
1604
+ organization_id,
1605
+ document_id,
1606
+ ingestion_run_id,
1607
+ text,
1608
+ text_original,
1609
+ knowledge_type,
1610
+ facet_fields,
1611
+ confidence,
1612
+ temporal_validity,
1613
+ classification,
1614
+ retrieval_status,
1615
+ source_location,
1616
+ superseded_by,
1617
+ supersedes,
1618
+ cluster_id,
1619
+ extracted_at,
1620
+ approved_at,
1621
+ approved_by_user_id,
1622
+ edited,
1623
+ metadata`;
1624
+ async function updateThreadClassification(client, args) {
1625
+ const result = await client.query({
1626
+ text: exports.updateThreadClassificationQuery,
1627
+ values: [args.classification, args.supersedes, args.organizationId, args.id],
1628
+ rowMode: "array"
1629
+ });
1630
+ if (result.rows.length !== 1) {
1631
+ return null;
1632
+ }
1633
+ const row = result.rows[0];
1634
+ return {
1635
+ id: row[0],
1636
+ organizationId: row[1],
1637
+ documentId: row[2],
1638
+ ingestionRunId: row[3],
1639
+ text: row[4],
1640
+ textOriginal: row[5],
1641
+ knowledgeType: row[6],
1642
+ facetFields: row[7],
1643
+ confidence: row[8],
1644
+ temporalValidity: row[9],
1645
+ classification: row[10],
1646
+ retrievalStatus: row[11],
1647
+ sourceLocation: row[12],
1648
+ supersededBy: row[13],
1649
+ supersedes: row[14],
1650
+ clusterId: row[15],
1651
+ extractedAt: row[16],
1652
+ approvedAt: row[17],
1653
+ approvedByUserId: row[18],
1654
+ edited: row[19],
1655
+ metadata: row[20]
1656
+ };
1657
+ }
1658
+ exports.editPendingThreadQuery = `-- name: EditPendingThread :one
1659
+ UPDATE weave.threads
1660
+ SET
1661
+ text_original = CASE
1662
+ WHEN text_original IS NULL OR text_original = '' THEN text
1663
+ ELSE text_original
1664
+ END,
1665
+ text = $1,
1666
+ edited = TRUE
1667
+ WHERE id = $2
1668
+ AND organization_id = $3
1669
+ AND retrieval_status = 'THREAD_RETRIEVAL_STATUS_PENDING'
1670
+ RETURNING
1671
+ id,
1672
+ organization_id,
1673
+ document_id,
1674
+ ingestion_run_id,
1675
+ text,
1676
+ text_original,
1677
+ knowledge_type,
1678
+ facet_fields,
1679
+ confidence,
1680
+ temporal_validity,
1681
+ classification,
1682
+ retrieval_status,
1683
+ source_location,
1684
+ superseded_by,
1685
+ supersedes,
1686
+ cluster_id,
1687
+ extracted_at,
1688
+ approved_at,
1689
+ approved_by_user_id,
1690
+ edited,
1691
+ metadata`;
1692
+ async function editPendingThread(client, args) {
1693
+ const result = await client.query({
1694
+ text: exports.editPendingThreadQuery,
1695
+ values: [args.text, args.id, args.organizationId],
1696
+ rowMode: "array"
1697
+ });
1698
+ if (result.rows.length !== 1) {
1699
+ return null;
1700
+ }
1701
+ const row = result.rows[0];
1702
+ return {
1703
+ id: row[0],
1704
+ organizationId: row[1],
1705
+ documentId: row[2],
1706
+ ingestionRunId: row[3],
1707
+ text: row[4],
1708
+ textOriginal: row[5],
1709
+ knowledgeType: row[6],
1710
+ facetFields: row[7],
1711
+ confidence: row[8],
1712
+ temporalValidity: row[9],
1713
+ classification: row[10],
1714
+ retrievalStatus: row[11],
1715
+ sourceLocation: row[12],
1716
+ supersededBy: row[13],
1717
+ supersedes: row[14],
1718
+ clusterId: row[15],
1719
+ extractedAt: row[16],
1720
+ approvedAt: row[17],
1721
+ approvedByUserId: row[18],
1722
+ edited: row[19],
1723
+ metadata: row[20]
1724
+ };
1725
+ }
1726
+ exports.editDocumentThreadQuery = `-- name: EditDocumentThread :one
1727
+ WITH updated AS (
1728
+ UPDATE weave.threads AS t
1729
+ SET
1730
+ text_original = CASE
1731
+ WHEN t.text_original IS NULL OR t.text_original = '' THEN t.text
1732
+ ELSE t.text_original
1733
+ END,
1734
+ text = $1,
1735
+ source_location = COALESCE($2::jsonb, t.source_location),
1736
+ metadata = t.metadata || COALESCE($3::jsonb, '{}'::jsonb),
1737
+ edited = TRUE
1738
+ WHERE t.id = $4
1739
+ AND t.organization_id = $5
1740
+ AND t.document_id = $6
1741
+ AND t.retrieval_status = 'THREAD_RETRIEVAL_STATUS_PENDING'
1742
+ RETURNING
1743
+ id,
1744
+ organization_id,
1745
+ document_id,
1746
+ ingestion_run_id,
1747
+ text,
1748
+ text_original,
1749
+ knowledge_type,
1750
+ facet_fields,
1751
+ confidence,
1752
+ temporal_validity,
1753
+ classification,
1754
+ retrieval_status,
1755
+ source_location,
1756
+ superseded_by,
1757
+ supersedes,
1758
+ cluster_id,
1759
+ extracted_at,
1760
+ approved_at,
1761
+ approved_by_user_id,
1762
+ edited,
1763
+ metadata
1764
+ )
1765
+ SELECT
1766
+ updated.id,
1767
+ updated.organization_id,
1768
+ updated.document_id,
1769
+ d.filename AS document_name,
1770
+ updated.ingestion_run_id,
1771
+ updated.text,
1772
+ updated.text_original,
1773
+ updated.knowledge_type,
1774
+ updated.facet_fields,
1775
+ updated.confidence,
1776
+ updated.temporal_validity,
1777
+ updated.classification,
1778
+ updated.retrieval_status,
1779
+ updated.source_location,
1780
+ updated.superseded_by,
1781
+ updated.supersedes,
1782
+ updated.cluster_id,
1783
+ updated.extracted_at,
1784
+ updated.approved_at,
1785
+ updated.approved_by_user_id,
1786
+ updated.edited,
1787
+ updated.metadata
1788
+ FROM updated
1789
+ JOIN weave.documents d ON d.id = updated.document_id`;
1790
+ async function editDocumentThread(client, args) {
1791
+ const result = await client.query({
1792
+ text: exports.editDocumentThreadQuery,
1793
+ values: [args.text, args.sourceLocation, args.metadata, args.id, args.organizationId, args.documentId],
1794
+ rowMode: "array"
1795
+ });
1796
+ if (result.rows.length !== 1) {
1797
+ return null;
1798
+ }
1799
+ const row = result.rows[0];
1800
+ return {
1801
+ id: row[0],
1802
+ organizationId: row[1],
1803
+ documentId: row[2],
1804
+ documentName: row[3],
1805
+ ingestionRunId: row[4],
1806
+ text: row[5],
1807
+ textOriginal: row[6],
1808
+ knowledgeType: row[7],
1809
+ facetFields: row[8],
1810
+ confidence: row[9],
1811
+ temporalValidity: row[10],
1812
+ classification: row[11],
1813
+ retrievalStatus: row[12],
1814
+ sourceLocation: row[13],
1815
+ supersededBy: row[14],
1816
+ supersedes: row[15],
1817
+ clusterId: row[16],
1818
+ extractedAt: row[17],
1819
+ approvedAt: row[18],
1820
+ approvedByUserId: row[19],
1821
+ edited: row[20],
1822
+ metadata: row[21]
1823
+ };
1824
+ }
1825
+ exports.deleteDocumentThreadByOrganizationAndIDQuery = `-- name: DeleteDocumentThreadByOrganizationAndID :execrows
1826
+ DELETE FROM weave.threads
1827
+ WHERE organization_id = $1
1828
+ AND document_id = $2
1829
+ AND id = $3
1830
+ AND retrieval_status = 'THREAD_RETRIEVAL_STATUS_PENDING'`;
1831
+ exports.approveThreadQuery = `-- name: ApproveThread :one
1832
+ UPDATE weave.threads
1833
+ SET
1834
+ retrieval_status = 'THREAD_RETRIEVAL_STATUS_APPROVED',
1835
+ approved_at = now(),
1836
+ approved_by_user_id = $1,
1837
+ embedding = COALESCE($2::vector, embedding),
1838
+ embedding_next = NULL
1839
+ WHERE id = $3
1840
+ AND organization_id = $4
1841
+ AND retrieval_status = 'THREAD_RETRIEVAL_STATUS_PENDING'
1842
+ RETURNING
1843
+ id,
1844
+ organization_id,
1845
+ document_id,
1846
+ ingestion_run_id,
1847
+ text,
1848
+ text_original,
1849
+ knowledge_type,
1850
+ facet_fields,
1851
+ confidence,
1852
+ temporal_validity,
1853
+ classification,
1854
+ retrieval_status,
1855
+ source_location,
1856
+ superseded_by,
1857
+ supersedes,
1858
+ cluster_id,
1859
+ extracted_at,
1860
+ approved_at,
1861
+ approved_by_user_id,
1862
+ edited,
1863
+ metadata`;
1864
+ async function approveThread(client, args) {
1865
+ const result = await client.query({
1866
+ text: exports.approveThreadQuery,
1867
+ values: [args.approvedByUserId, args.embedding, args.id, args.organizationId],
1868
+ rowMode: "array"
1869
+ });
1870
+ if (result.rows.length !== 1) {
1871
+ return null;
1872
+ }
1873
+ const row = result.rows[0];
1874
+ return {
1875
+ id: row[0],
1876
+ organizationId: row[1],
1877
+ documentId: row[2],
1878
+ ingestionRunId: row[3],
1879
+ text: row[4],
1880
+ textOriginal: row[5],
1881
+ knowledgeType: row[6],
1882
+ facetFields: row[7],
1883
+ confidence: row[8],
1884
+ temporalValidity: row[9],
1885
+ classification: row[10],
1886
+ retrievalStatus: row[11],
1887
+ sourceLocation: row[12],
1888
+ supersededBy: row[13],
1889
+ supersedes: row[14],
1890
+ clusterId: row[15],
1891
+ extractedAt: row[16],
1892
+ approvedAt: row[17],
1893
+ approvedByUserId: row[18],
1894
+ edited: row[19],
1895
+ metadata: row[20]
1896
+ };
1897
+ }
1898
+ exports.bulkApproveThreadsQuery = `-- name: BulkApproveThreads :many
1899
+ UPDATE weave.threads
1900
+ SET
1901
+ retrieval_status = 'THREAD_RETRIEVAL_STATUS_APPROVED',
1902
+ approved_at = now(),
1903
+ approved_by_user_id = $1,
1904
+ embedding_next = NULL
1905
+ WHERE organization_id = $2
1906
+ AND ingestion_run_id = $3
1907
+ AND id = ANY($4::uuid[])
1908
+ AND retrieval_status = 'THREAD_RETRIEVAL_STATUS_PENDING'
1909
+ RETURNING
1910
+ id,
1911
+ organization_id,
1912
+ document_id,
1913
+ ingestion_run_id,
1914
+ text,
1915
+ text_original,
1916
+ knowledge_type,
1917
+ facet_fields,
1918
+ confidence,
1919
+ temporal_validity,
1920
+ classification,
1921
+ retrieval_status,
1922
+ source_location,
1923
+ superseded_by,
1924
+ supersedes,
1925
+ cluster_id,
1926
+ extracted_at,
1927
+ approved_at,
1928
+ approved_by_user_id,
1929
+ edited,
1930
+ metadata`;
1931
+ async function bulkApproveThreads(client, args) {
1932
+ const result = await client.query({
1933
+ text: exports.bulkApproveThreadsQuery,
1934
+ values: [args.approvedByUserId, args.organizationId, args.ingestionRunId, args.threadIds],
1935
+ rowMode: "array"
1936
+ });
1937
+ return result.rows.map(row => {
1938
+ return {
1939
+ id: row[0],
1940
+ organizationId: row[1],
1941
+ documentId: row[2],
1942
+ ingestionRunId: row[3],
1943
+ text: row[4],
1944
+ textOriginal: row[5],
1945
+ knowledgeType: row[6],
1946
+ facetFields: row[7],
1947
+ confidence: row[8],
1948
+ temporalValidity: row[9],
1949
+ classification: row[10],
1950
+ retrievalStatus: row[11],
1951
+ sourceLocation: row[12],
1952
+ supersededBy: row[13],
1953
+ supersedes: row[14],
1954
+ clusterId: row[15],
1955
+ extractedAt: row[16],
1956
+ approvedAt: row[17],
1957
+ approvedByUserId: row[18],
1958
+ edited: row[19],
1959
+ metadata: row[20]
1960
+ };
1961
+ });
1962
+ }
1963
+ exports.rejectThreadQuery = `-- name: RejectThread :one
1964
+ UPDATE weave.threads
1965
+ SET
1966
+ retrieval_status = 'THREAD_RETRIEVAL_STATUS_REJECTED'
1967
+ WHERE organization_id = $1
1968
+ AND id = $2
1969
+ AND retrieval_status = 'THREAD_RETRIEVAL_STATUS_PENDING'
1970
+ RETURNING
1971
+ id,
1972
+ organization_id,
1973
+ document_id,
1974
+ ingestion_run_id,
1975
+ text,
1976
+ text_original,
1977
+ knowledge_type,
1978
+ facet_fields,
1979
+ confidence,
1980
+ temporal_validity,
1981
+ classification,
1982
+ retrieval_status,
1983
+ source_location,
1984
+ superseded_by,
1985
+ supersedes,
1986
+ cluster_id,
1987
+ extracted_at,
1988
+ approved_at,
1989
+ approved_by_user_id,
1990
+ edited,
1991
+ metadata`;
1992
+ async function rejectThread(client, args) {
1993
+ const result = await client.query({
1994
+ text: exports.rejectThreadQuery,
1995
+ values: [args.organizationId, args.id],
1996
+ rowMode: "array"
1997
+ });
1998
+ if (result.rows.length !== 1) {
1999
+ return null;
2000
+ }
2001
+ const row = result.rows[0];
2002
+ return {
2003
+ id: row[0],
2004
+ organizationId: row[1],
2005
+ documentId: row[2],
2006
+ ingestionRunId: row[3],
2007
+ text: row[4],
2008
+ textOriginal: row[5],
2009
+ knowledgeType: row[6],
2010
+ facetFields: row[7],
2011
+ confidence: row[8],
2012
+ temporalValidity: row[9],
2013
+ classification: row[10],
2014
+ retrievalStatus: row[11],
2015
+ sourceLocation: row[12],
2016
+ supersededBy: row[13],
2017
+ supersedes: row[14],
2018
+ clusterId: row[15],
2019
+ extractedAt: row[16],
2020
+ approvedAt: row[17],
2021
+ approvedByUserId: row[18],
2022
+ edited: row[19],
2023
+ metadata: row[20]
2024
+ };
2025
+ }
2026
+ exports.bulkRejectThreadsQuery = `-- name: BulkRejectThreads :many
2027
+ UPDATE weave.threads
2028
+ SET
2029
+ retrieval_status = 'THREAD_RETRIEVAL_STATUS_REJECTED'
2030
+ WHERE organization_id = $1
2031
+ AND ingestion_run_id = $2
2032
+ AND id = ANY($3::uuid[])
2033
+ AND retrieval_status = 'THREAD_RETRIEVAL_STATUS_PENDING'
2034
+ RETURNING
2035
+ id,
2036
+ organization_id,
2037
+ document_id,
2038
+ ingestion_run_id,
2039
+ text,
2040
+ text_original,
2041
+ knowledge_type,
2042
+ facet_fields,
2043
+ confidence,
2044
+ temporal_validity,
2045
+ classification,
2046
+ retrieval_status,
2047
+ source_location,
2048
+ superseded_by,
2049
+ supersedes,
2050
+ cluster_id,
2051
+ extracted_at,
2052
+ approved_at,
2053
+ approved_by_user_id,
2054
+ edited,
2055
+ metadata`;
2056
+ async function bulkRejectThreads(client, args) {
2057
+ const result = await client.query({
2058
+ text: exports.bulkRejectThreadsQuery,
2059
+ values: [args.organizationId, args.ingestionRunId, args.threadIds],
2060
+ rowMode: "array"
2061
+ });
2062
+ return result.rows.map(row => {
2063
+ return {
2064
+ id: row[0],
2065
+ organizationId: row[1],
2066
+ documentId: row[2],
2067
+ ingestionRunId: row[3],
2068
+ text: row[4],
2069
+ textOriginal: row[5],
2070
+ knowledgeType: row[6],
2071
+ facetFields: row[7],
2072
+ confidence: row[8],
2073
+ temporalValidity: row[9],
2074
+ classification: row[10],
2075
+ retrievalStatus: row[11],
2076
+ sourceLocation: row[12],
2077
+ supersededBy: row[13],
2078
+ supersedes: row[14],
2079
+ clusterId: row[15],
2080
+ extractedAt: row[16],
2081
+ approvedAt: row[17],
2082
+ approvedByUserId: row[18],
2083
+ edited: row[19],
2084
+ metadata: row[20]
2085
+ };
2086
+ });
2087
+ }
2088
+ exports.markThreadsSupersededQuery = `-- name: MarkThreadsSuperseded :execrows
2089
+ UPDATE weave.threads
2090
+ SET
2091
+ retrieval_status = 'THREAD_RETRIEVAL_STATUS_SUPERSEDED',
2092
+ superseded_by = $1
2093
+ WHERE organization_id = $2
2094
+ AND id = ANY($3::uuid[])`;
2095
+ exports.listThreadsBySupersedesQuery = `-- name: ListThreadsBySupersedes :many
2096
+ SELECT
2097
+ id,
2098
+ organization_id,
2099
+ document_id,
2100
+ ingestion_run_id,
2101
+ text,
2102
+ text_original,
2103
+ knowledge_type,
2104
+ facet_fields,
2105
+ confidence,
2106
+ temporal_validity,
2107
+ classification,
2108
+ retrieval_status,
2109
+ source_location,
2110
+ superseded_by,
2111
+ supersedes,
2112
+ cluster_id,
2113
+ extracted_at,
2114
+ approved_at,
2115
+ approved_by_user_id,
2116
+ edited,
2117
+ metadata
2118
+ FROM weave.threads
2119
+ WHERE organization_id = $1
2120
+ AND $2 = ANY(supersedes)
2121
+ ORDER BY approved_at DESC NULLS LAST, extracted_at DESC, id DESC`;
2122
+ async function listThreadsBySupersedes(client, args) {
2123
+ const result = await client.query({
2124
+ text: exports.listThreadsBySupersedesQuery,
2125
+ values: [args.organizationId, args.threadId],
2126
+ rowMode: "array"
2127
+ });
2128
+ return result.rows.map(row => {
2129
+ return {
2130
+ id: row[0],
2131
+ organizationId: row[1],
2132
+ documentId: row[2],
2133
+ ingestionRunId: row[3],
2134
+ text: row[4],
2135
+ textOriginal: row[5],
2136
+ knowledgeType: row[6],
2137
+ facetFields: row[7],
2138
+ confidence: row[8],
2139
+ temporalValidity: row[9],
2140
+ classification: row[10],
2141
+ retrievalStatus: row[11],
2142
+ sourceLocation: row[12],
2143
+ supersededBy: row[13],
2144
+ supersedes: row[14],
2145
+ clusterId: row[15],
2146
+ extractedAt: row[16],
2147
+ approvedAt: row[17],
2148
+ approvedByUserId: row[18],
2149
+ edited: row[19],
2150
+ metadata: row[20]
2151
+ };
2152
+ });
2153
+ }
2154
+ exports.listThreadsByIDsQuery = `-- name: ListThreadsByIDs :many
2155
+ SELECT
2156
+ id,
2157
+ organization_id,
2158
+ document_id,
2159
+ ingestion_run_id,
2160
+ text,
2161
+ text_original,
2162
+ knowledge_type,
2163
+ facet_fields,
2164
+ confidence,
2165
+ temporal_validity,
2166
+ classification,
2167
+ retrieval_status,
2168
+ source_location,
2169
+ superseded_by,
2170
+ supersedes,
2171
+ cluster_id,
2172
+ extracted_at,
2173
+ approved_at,
2174
+ approved_by_user_id,
2175
+ edited,
2176
+ metadata
2177
+ FROM weave.threads
2178
+ WHERE organization_id = $1
2179
+ AND id = ANY($2::uuid[])
2180
+ ORDER BY extracted_at ASC, id ASC`;
2181
+ async function listThreadsByIDs(client, args) {
2182
+ const result = await client.query({
2183
+ text: exports.listThreadsByIDsQuery,
2184
+ values: [args.organizationId, args.threadIds],
2185
+ rowMode: "array"
2186
+ });
2187
+ return result.rows.map(row => {
2188
+ return {
2189
+ id: row[0],
2190
+ organizationId: row[1],
2191
+ documentId: row[2],
2192
+ ingestionRunId: row[3],
2193
+ text: row[4],
2194
+ textOriginal: row[5],
2195
+ knowledgeType: row[6],
2196
+ facetFields: row[7],
2197
+ confidence: row[8],
2198
+ temporalValidity: row[9],
2199
+ classification: row[10],
2200
+ retrievalStatus: row[11],
2201
+ sourceLocation: row[12],
2202
+ supersededBy: row[13],
2203
+ supersedes: row[14],
2204
+ clusterId: row[15],
2205
+ extractedAt: row[16],
2206
+ approvedAt: row[17],
2207
+ approvedByUserId: row[18],
2208
+ edited: row[19],
2209
+ metadata: row[20]
2210
+ };
2211
+ });
2212
+ }
2213
+ exports.getIngestionRunThreadCountsQuery = `-- name: GetIngestionRunThreadCounts :one
2214
+ SELECT
2215
+ COUNT(*)::int AS thread_count,
2216
+ COUNT(*) FILTER (
2217
+ WHERE retrieval_status = 'THREAD_RETRIEVAL_STATUS_PENDING'
2218
+ )::int AS pending_count,
2219
+ COUNT(*) FILTER (
2220
+ WHERE retrieval_status = 'THREAD_RETRIEVAL_STATUS_APPROVED'
2221
+ )::int AS approved_count,
2222
+ COUNT(*) FILTER (
2223
+ WHERE retrieval_status = 'THREAD_RETRIEVAL_STATUS_REJECTED'
2224
+ )::int AS rejected_count
2225
+ FROM weave.threads
2226
+ WHERE organization_id = $1
2227
+ AND ingestion_run_id = $2`;
2228
+ async function getIngestionRunThreadCounts(client, args) {
2229
+ const result = await client.query({
2230
+ text: exports.getIngestionRunThreadCountsQuery,
2231
+ values: [args.organizationId, args.ingestionRunId],
2232
+ rowMode: "array"
2233
+ });
2234
+ if (result.rows.length !== 1) {
2235
+ return null;
2236
+ }
2237
+ const row = result.rows[0];
2238
+ return {
2239
+ threadCount: row[0],
2240
+ pendingCount: row[1],
2241
+ approvedCount: row[2],
2242
+ rejectedCount: row[3]
2243
+ };
2244
+ }
2245
+ exports.deleteThreadReconciliationByPendingThreadQuery = `-- name: DeleteThreadReconciliationByPendingThread :exec
2246
+ DELETE FROM weave.thread_reconciliation tr
2247
+ USING weave.threads t
2248
+ WHERE tr.pending_thread_id = t.id
2249
+ AND t.organization_id = $1
2250
+ AND tr.pending_thread_id = $2`;
2251
+ async function deleteThreadReconciliationByPendingThread(client, args) {
2252
+ await client.query({
2253
+ text: exports.deleteThreadReconciliationByPendingThreadQuery,
2254
+ values: [args.organizationId, args.pendingThreadId],
2255
+ rowMode: "array"
2256
+ });
2257
+ }
2258
+ exports.upsertThreadReconciliationQuery = `-- name: UpsertThreadReconciliation :one
2259
+ INSERT INTO weave.thread_reconciliation (
2260
+ pending_thread_id,
2261
+ existing_thread_id,
2262
+ similarity,
2263
+ entity_overlap
2264
+ ) VALUES (
2265
+ $1,
2266
+ $2,
2267
+ $3,
2268
+ $4
2269
+ )
2270
+ ON CONFLICT (pending_thread_id, existing_thread_id) DO UPDATE
2271
+ SET
2272
+ similarity = EXCLUDED.similarity,
2273
+ entity_overlap = EXCLUDED.entity_overlap
2274
+ RETURNING
2275
+ pending_thread_id,
2276
+ existing_thread_id,
2277
+ similarity,
2278
+ entity_overlap`;
2279
+ async function upsertThreadReconciliation(client, args) {
2280
+ const result = await client.query({
2281
+ text: exports.upsertThreadReconciliationQuery,
2282
+ values: [args.pendingThreadId, args.existingThreadId, args.similarity, args.entityOverlap],
2283
+ rowMode: "array"
2284
+ });
2285
+ if (result.rows.length !== 1) {
2286
+ return null;
2287
+ }
2288
+ const row = result.rows[0];
2289
+ return {
2290
+ pendingThreadId: row[0],
2291
+ existingThreadId: row[1],
2292
+ similarity: row[2],
2293
+ entityOverlap: row[3]
2294
+ };
2295
+ }
2296
+ exports.listThreadReconciliationByPendingThreadQuery = `-- name: ListThreadReconciliationByPendingThread :many
2297
+ SELECT
2298
+ pending_thread_id,
2299
+ existing_thread_id,
2300
+ similarity,
2301
+ entity_overlap
2302
+ FROM weave.thread_reconciliation
2303
+ WHERE pending_thread_id IN (
2304
+ SELECT id
2305
+ FROM weave.threads
2306
+ WHERE organization_id = $1
2307
+ AND id = $2
2308
+ )
2309
+ ORDER BY similarity DESC, entity_overlap DESC, existing_thread_id ASC`;
2310
+ async function listThreadReconciliationByPendingThread(client, args) {
2311
+ const result = await client.query({
2312
+ text: exports.listThreadReconciliationByPendingThreadQuery,
2313
+ values: [args.organizationId, args.pendingThreadId],
2314
+ rowMode: "array"
2315
+ });
2316
+ return result.rows.map(row => {
2317
+ return {
2318
+ pendingThreadId: row[0],
2319
+ existingThreadId: row[1],
2320
+ similarity: row[2],
2321
+ entityOverlap: row[3]
2322
+ };
2323
+ });
2324
+ }
2325
+ exports.createThreadActivityQuery = `-- name: CreateThreadActivity :one
2326
+ INSERT INTO weave.thread_activity (
2327
+ id,
2328
+ thread_id,
2329
+ action,
2330
+ actor_id,
2331
+ metadata
2332
+ ) VALUES (
2333
+ $1,
2334
+ $2,
2335
+ $3,
2336
+ $4,
2337
+ $5
2338
+ )
2339
+ RETURNING
2340
+ id,
2341
+ thread_id,
2342
+ action,
2343
+ actor_id,
2344
+ metadata,
2345
+ created_at`;
2346
+ async function createThreadActivity(client, args) {
2347
+ const result = await client.query({
2348
+ text: exports.createThreadActivityQuery,
2349
+ values: [args.id, args.threadId, args.action, args.actorId, args.metadata],
2350
+ rowMode: "array"
2351
+ });
2352
+ if (result.rows.length !== 1) {
2353
+ return null;
2354
+ }
2355
+ const row = result.rows[0];
2356
+ return {
2357
+ id: row[0],
2358
+ threadId: row[1],
2359
+ action: row[2],
2360
+ actorId: row[3],
2361
+ metadata: row[4],
2362
+ createdAt: row[5]
2363
+ };
2364
+ }
2365
+ exports.listThreadActivityByThreadQuery = `-- name: ListThreadActivityByThread :many
2366
+ SELECT
2367
+ id,
2368
+ thread_id,
2369
+ action,
2370
+ actor_id,
2371
+ metadata,
2372
+ created_at
2373
+ FROM weave.thread_activity
2374
+ WHERE thread_id IN (
2375
+ SELECT t.id
2376
+ FROM weave.threads t
2377
+ WHERE t.organization_id = $1
2378
+ AND t.id = $2
2379
+ )
2380
+ ORDER BY created_at DESC`;
2381
+ async function listThreadActivityByThread(client, args) {
2382
+ const result = await client.query({
2383
+ text: exports.listThreadActivityByThreadQuery,
2384
+ values: [args.organizationId, args.threadId],
2385
+ rowMode: "array"
2386
+ });
2387
+ return result.rows.map(row => {
2388
+ return {
2389
+ id: row[0],
2390
+ threadId: row[1],
2391
+ action: row[2],
2392
+ actorId: row[3],
2393
+ metadata: row[4],
2394
+ createdAt: row[5]
2395
+ };
2396
+ });
2397
+ }
2398
+ exports.upsertEntityQuery = `-- name: UpsertEntity :one
2399
+ INSERT INTO weave.entities (
2400
+ id,
2401
+ organization_id,
2402
+ name,
2403
+ type,
2404
+ canonical,
2405
+ metadata
2406
+ ) VALUES (
2407
+ $1,
2408
+ $2,
2409
+ $3,
2410
+ $4,
2411
+ $5,
2412
+ $6
2413
+ )
2414
+ ON CONFLICT (organization_id, type, canonical) DO UPDATE
2415
+ SET
2416
+ name = EXCLUDED.name,
2417
+ metadata = EXCLUDED.metadata,
2418
+ updated_at = now()
2419
+ RETURNING
2420
+ id,
2421
+ organization_id,
2422
+ name,
2423
+ type,
2424
+ canonical,
2425
+ metadata,
2426
+ created_at,
2427
+ updated_at`;
2428
+ async function upsertEntity(client, args) {
2429
+ const result = await client.query({
2430
+ text: exports.upsertEntityQuery,
2431
+ values: [args.id, args.organizationId, args.name, args.type, args.canonical, args.metadata],
2432
+ rowMode: "array"
2433
+ });
2434
+ if (result.rows.length !== 1) {
2435
+ return null;
2436
+ }
2437
+ const row = result.rows[0];
2438
+ return {
2439
+ id: row[0],
2440
+ organizationId: row[1],
2441
+ name: row[2],
2442
+ type: row[3],
2443
+ canonical: row[4],
2444
+ metadata: row[5],
2445
+ createdAt: row[6],
2446
+ updatedAt: row[7]
2447
+ };
2448
+ }
2449
+ exports.upsertThreadEntityQuery = `-- name: UpsertThreadEntity :one
2450
+ INSERT INTO weave.thread_entities (
2451
+ thread_id,
2452
+ entity_id,
2453
+ role,
2454
+ confidence
2455
+ ) VALUES (
2456
+ $1,
2457
+ $2,
2458
+ $3,
2459
+ $4
2460
+ )
2461
+ ON CONFLICT (thread_id, entity_id) DO UPDATE
2462
+ SET
2463
+ role = EXCLUDED.role,
2464
+ confidence = EXCLUDED.confidence
2465
+ RETURNING
2466
+ thread_id,
2467
+ entity_id,
2468
+ role,
2469
+ confidence`;
2470
+ async function upsertThreadEntity(client, args) {
2471
+ const result = await client.query({
2472
+ text: exports.upsertThreadEntityQuery,
2473
+ values: [args.threadId, args.entityId, args.role, args.confidence],
2474
+ rowMode: "array"
2475
+ });
2476
+ if (result.rows.length !== 1) {
2477
+ return null;
2478
+ }
2479
+ const row = result.rows[0];
2480
+ return {
2481
+ threadId: row[0],
2482
+ entityId: row[1],
2483
+ role: row[2],
2484
+ confidence: row[3]
2485
+ };
2486
+ }
2487
+ exports.upsertEntityRelationshipQuery = `-- name: UpsertEntityRelationship :one
2488
+ INSERT INTO weave.entity_relationships (
2489
+ id,
2490
+ organization_id,
2491
+ source_entity_id,
2492
+ target_entity_id,
2493
+ relationship,
2494
+ source_thread_id,
2495
+ confidence
2496
+ ) VALUES (
2497
+ $1,
2498
+ $2,
2499
+ $3,
2500
+ $4,
2501
+ $5,
2502
+ $6,
2503
+ $7
2504
+ )
2505
+ ON CONFLICT (source_entity_id, target_entity_id, relationship, source_thread_id) DO UPDATE
2506
+ SET
2507
+ confidence = EXCLUDED.confidence
2508
+ RETURNING
2509
+ id,
2510
+ organization_id,
2511
+ source_entity_id,
2512
+ target_entity_id,
2513
+ relationship,
2514
+ source_thread_id,
2515
+ confidence,
2516
+ created_at`;
2517
+ async function upsertEntityRelationship(client, args) {
2518
+ const result = await client.query({
2519
+ text: exports.upsertEntityRelationshipQuery,
2520
+ values: [args.id, args.organizationId, args.sourceEntityId, args.targetEntityId, args.relationship, args.sourceThreadId, args.confidence],
2521
+ rowMode: "array"
2522
+ });
2523
+ if (result.rows.length !== 1) {
2524
+ return null;
2525
+ }
2526
+ const row = result.rows[0];
2527
+ return {
2528
+ id: row[0],
2529
+ organizationId: row[1],
2530
+ sourceEntityId: row[2],
2531
+ targetEntityId: row[3],
2532
+ relationship: row[4],
2533
+ sourceThreadId: row[5],
2534
+ confidence: row[6],
2535
+ createdAt: row[7]
2536
+ };
2537
+ }
2538
+ exports.listEntitiesByThreadQuery = `-- name: ListEntitiesByThread :many
2539
+ SELECT
2540
+ e.id,
2541
+ e.organization_id,
2542
+ e.name,
2543
+ e.type,
2544
+ e.canonical,
2545
+ e.metadata,
2546
+ e.created_at,
2547
+ e.updated_at,
2548
+ te.role,
2549
+ te.confidence AS relationship_confidence
2550
+ FROM weave.thread_entities te
2551
+ JOIN weave.entities e ON e.id = te.entity_id
2552
+ WHERE te.thread_id IN (
2553
+ SELECT t.id
2554
+ FROM weave.threads t
2555
+ WHERE t.organization_id = $1
2556
+ AND t.id = $2
2557
+ )
2558
+ ORDER BY e.type ASC, e.canonical ASC`;
2559
+ async function listEntitiesByThread(client, args) {
2560
+ const result = await client.query({
2561
+ text: exports.listEntitiesByThreadQuery,
2562
+ values: [args.organizationId, args.threadId],
2563
+ rowMode: "array"
2564
+ });
2565
+ return result.rows.map(row => {
2566
+ return {
2567
+ id: row[0],
2568
+ organizationId: row[1],
2569
+ name: row[2],
2570
+ type: row[3],
2571
+ canonical: row[4],
2572
+ metadata: row[5],
2573
+ createdAt: row[6],
2574
+ updatedAt: row[7],
2575
+ role: row[8],
2576
+ relationshipConfidence: row[9]
2577
+ };
2578
+ });
2579
+ }
2580
+ exports.ensureOrganizationIngestionSettingsQuery = `-- name: EnsureOrganizationIngestionSettings :one
2581
+ WITH upsert AS (
2582
+ INSERT INTO weave.org_ingestion_settings (organization_id)
2583
+ VALUES ($1)
2584
+ ON CONFLICT (organization_id) DO UPDATE
2585
+ SET organization_id = EXCLUDED.organization_id
2586
+ RETURNING
2587
+ organization_id,
2588
+ reasoning_model_id,
2589
+ reasoning_provider_configuration_id,
2590
+ embedding_model_id,
2591
+ embedding_provider_configuration_id,
2592
+ updated_at
2593
+ )
2594
+ SELECT
2595
+ upsert.organization_id,
2596
+ upsert.reasoning_model_id,
2597
+ upsert.reasoning_provider_configuration_id,
2598
+ upsert.embedding_model_id,
2599
+ upsert.embedding_provider_configuration_id,
2600
+ cfg.embedding_dimension AS embedding_dimensions,
2601
+ upsert.updated_at
2602
+ FROM upsert
2603
+ JOIN weave.database_config cfg
2604
+ ON cfg.id = 1`;
2605
+ async function ensureOrganizationIngestionSettings(client, args) {
2606
+ const result = await client.query({
2607
+ text: exports.ensureOrganizationIngestionSettingsQuery,
2608
+ values: [args.organizationId],
2609
+ rowMode: "array"
2610
+ });
2611
+ if (result.rows.length !== 1) {
2612
+ return null;
2613
+ }
2614
+ const row = result.rows[0];
2615
+ return {
2616
+ organizationId: row[0],
2617
+ reasoningModelId: row[1],
2618
+ reasoningProviderConfigurationId: row[2],
2619
+ embeddingModelId: row[3],
2620
+ embeddingProviderConfigurationId: row[4],
2621
+ embeddingDimensions: row[5],
2622
+ updatedAt: row[6]
2623
+ };
2624
+ }
2625
+ exports.getOrganizationIngestionSettingsQuery = `-- name: GetOrganizationIngestionSettings :one
2626
+ SELECT
2627
+ settings.organization_id,
2628
+ settings.reasoning_model_id,
2629
+ settings.reasoning_provider_configuration_id,
2630
+ settings.embedding_model_id,
2631
+ settings.embedding_provider_configuration_id,
2632
+ cfg.embedding_dimension AS embedding_dimensions,
2633
+ settings.updated_at
2634
+ FROM weave.org_ingestion_settings settings
2635
+ JOIN weave.database_config cfg
2636
+ ON cfg.id = 1
2637
+ WHERE settings.organization_id = $1`;
2638
+ async function getOrganizationIngestionSettings(client, args) {
2639
+ const result = await client.query({
2640
+ text: exports.getOrganizationIngestionSettingsQuery,
2641
+ values: [args.organizationId],
2642
+ rowMode: "array"
2643
+ });
2644
+ if (result.rows.length !== 1) {
2645
+ return null;
2646
+ }
2647
+ const row = result.rows[0];
2648
+ return {
2649
+ organizationId: row[0],
2650
+ reasoningModelId: row[1],
2651
+ reasoningProviderConfigurationId: row[2],
2652
+ embeddingModelId: row[3],
2653
+ embeddingProviderConfigurationId: row[4],
2654
+ embeddingDimensions: row[5],
2655
+ updatedAt: row[6]
2656
+ };
2657
+ }
2658
+ exports.upsertOrganizationIngestionSettingsQuery = `-- name: UpsertOrganizationIngestionSettings :one
2659
+ WITH cfg AS (
2660
+ SELECT embedding_dimension
2661
+ FROM weave.database_config
2662
+ WHERE id = 1
2663
+ AND ($1 = 0 OR $1 = embedding_dimension)
2664
+ ), upsert AS (
2665
+ INSERT INTO weave.org_ingestion_settings (
2666
+ organization_id,
2667
+ reasoning_model_id,
2668
+ reasoning_provider_configuration_id,
2669
+ embedding_model_id,
2670
+ embedding_provider_configuration_id
2671
+ )
2672
+ SELECT
2673
+ $2,
2674
+ $3,
2675
+ $4,
2676
+ $5,
2677
+ $6
2678
+ FROM cfg
2679
+ ON CONFLICT (organization_id) DO UPDATE
2680
+ SET
2681
+ reasoning_model_id = EXCLUDED.reasoning_model_id,
2682
+ reasoning_provider_configuration_id = EXCLUDED.reasoning_provider_configuration_id,
2683
+ embedding_model_id = EXCLUDED.embedding_model_id,
2684
+ embedding_provider_configuration_id = EXCLUDED.embedding_provider_configuration_id,
2685
+ updated_at = now()
2686
+ RETURNING
2687
+ organization_id,
2688
+ reasoning_model_id,
2689
+ reasoning_provider_configuration_id,
2690
+ embedding_model_id,
2691
+ embedding_provider_configuration_id,
2692
+ updated_at
2693
+ )
2694
+ SELECT
2695
+ upsert.organization_id,
2696
+ upsert.reasoning_model_id,
2697
+ upsert.reasoning_provider_configuration_id,
2698
+ upsert.embedding_model_id,
2699
+ upsert.embedding_provider_configuration_id,
2700
+ cfg.embedding_dimension AS embedding_dimensions,
2701
+ upsert.updated_at
2702
+ FROM upsert
2703
+ JOIN cfg
2704
+ ON TRUE`;
2705
+ async function upsertOrganizationIngestionSettings(client, args) {
2706
+ const result = await client.query({
2707
+ text: exports.upsertOrganizationIngestionSettingsQuery,
2708
+ values: [args.embeddingDimensions, args.organizationId, args.reasoningModelId, args.reasoningProviderConfigurationId, args.embeddingModelId, args.embeddingProviderConfigurationId],
2709
+ rowMode: "array"
2710
+ });
2711
+ if (result.rows.length !== 1) {
2712
+ return null;
2713
+ }
2714
+ const row = result.rows[0];
2715
+ return {
2716
+ organizationId: row[0],
2717
+ reasoningModelId: row[1],
2718
+ reasoningProviderConfigurationId: row[2],
2719
+ embeddingModelId: row[3],
2720
+ embeddingProviderConfigurationId: row[4],
2721
+ embeddingDimensions: row[5],
2722
+ updatedAt: row[6]
2723
+ };
2724
+ }
2725
+ exports.syncOrganizationIngestionReasoningDefaultsQuery = `-- name: SyncOrganizationIngestionReasoningDefaults :one
2726
+ WITH cfg AS (
2727
+ SELECT embedding_dimension
2728
+ FROM weave.database_config
2729
+ WHERE id = 1
2730
+ ), upsert AS (
2731
+ INSERT INTO weave.org_ingestion_settings (
2732
+ organization_id,
2733
+ reasoning_model_id,
2734
+ reasoning_provider_configuration_id
2735
+ )
2736
+ SELECT
2737
+ cs.organization_id,
2738
+ cs.default_chat_model_id,
2739
+ cs.default_provider_configuration_id
2740
+ FROM weave.organization_chat_settings cs
2741
+ WHERE cs.organization_id = $1
2742
+ ON CONFLICT (organization_id) DO UPDATE
2743
+ SET
2744
+ reasoning_model_id = COALESCE(weave.org_ingestion_settings.reasoning_model_id, EXCLUDED.reasoning_model_id),
2745
+ reasoning_provider_configuration_id = COALESCE(
2746
+ weave.org_ingestion_settings.reasoning_provider_configuration_id,
2747
+ EXCLUDED.reasoning_provider_configuration_id
2748
+ ),
2749
+ updated_at = now()
2750
+ RETURNING
2751
+ organization_id,
2752
+ reasoning_model_id,
2753
+ reasoning_provider_configuration_id,
2754
+ embedding_model_id,
2755
+ embedding_provider_configuration_id,
2756
+ updated_at
2757
+ )
2758
+ SELECT
2759
+ upsert.organization_id,
2760
+ upsert.reasoning_model_id,
2761
+ upsert.reasoning_provider_configuration_id,
2762
+ upsert.embedding_model_id,
2763
+ upsert.embedding_provider_configuration_id,
2764
+ cfg.embedding_dimension AS embedding_dimensions,
2765
+ upsert.updated_at
2766
+ FROM upsert
2767
+ JOIN cfg
2768
+ ON TRUE`;
2769
+ async function syncOrganizationIngestionReasoningDefaults(client, args) {
2770
+ const result = await client.query({
2771
+ text: exports.syncOrganizationIngestionReasoningDefaultsQuery,
2772
+ values: [args.organizationId],
2773
+ rowMode: "array"
2774
+ });
2775
+ if (result.rows.length !== 1) {
2776
+ return null;
2777
+ }
2778
+ const row = result.rows[0];
2779
+ return {
2780
+ organizationId: row[0],
2781
+ reasoningModelId: row[1],
2782
+ reasoningProviderConfigurationId: row[2],
2783
+ embeddingModelId: row[3],
2784
+ embeddingProviderConfigurationId: row[4],
2785
+ embeddingDimensions: row[5],
2786
+ updatedAt: row[6]
2787
+ };
2788
+ }
2789
+ exports.listFacetConfigsQuery = `-- name: ListFacetConfigs :many
2790
+ SELECT
2791
+ organization_id,
2792
+ knowledge_type,
2793
+ label,
2794
+ extraction_hint,
2795
+ required_fields,
2796
+ active
2797
+ FROM weave.org_facet_config
2798
+ WHERE organization_id = $1
2799
+ ORDER BY knowledge_type ASC`;
2800
+ async function listFacetConfigs(client, args) {
2801
+ const result = await client.query({
2802
+ text: exports.listFacetConfigsQuery,
2803
+ values: [args.organizationId],
2804
+ rowMode: "array"
2805
+ });
2806
+ return result.rows.map(row => {
2807
+ return {
2808
+ organizationId: row[0],
2809
+ knowledgeType: row[1],
2810
+ label: row[2],
2811
+ extractionHint: row[3],
2812
+ requiredFields: row[4],
2813
+ active: row[5]
2814
+ };
2815
+ });
2816
+ }
2817
+ exports.listActiveFacetConfigsQuery = `-- name: ListActiveFacetConfigs :many
2818
+ SELECT
2819
+ organization_id,
2820
+ knowledge_type,
2821
+ label,
2822
+ extraction_hint,
2823
+ required_fields,
2824
+ active
2825
+ FROM weave.org_facet_config
2826
+ WHERE organization_id = $1
2827
+ AND active = TRUE
2828
+ ORDER BY knowledge_type ASC`;
2829
+ async function listActiveFacetConfigs(client, args) {
2830
+ const result = await client.query({
2831
+ text: exports.listActiveFacetConfigsQuery,
2832
+ values: [args.organizationId],
2833
+ rowMode: "array"
2834
+ });
2835
+ return result.rows.map(row => {
2836
+ return {
2837
+ organizationId: row[0],
2838
+ knowledgeType: row[1],
2839
+ label: row[2],
2840
+ extractionHint: row[3],
2841
+ requiredFields: row[4],
2842
+ active: row[5]
2843
+ };
2844
+ });
2845
+ }
2846
+ exports.upsertFacetConfigQuery = `-- name: UpsertFacetConfig :one
2847
+ INSERT INTO weave.org_facet_config (
2848
+ organization_id,
2849
+ knowledge_type,
2850
+ label,
2851
+ extraction_hint,
2852
+ required_fields,
2853
+ active
2854
+ ) VALUES (
2855
+ $1,
2856
+ $2,
2857
+ $3,
2858
+ $4,
2859
+ $5,
2860
+ $6
2861
+ )
2862
+ ON CONFLICT (organization_id, knowledge_type) DO UPDATE
2863
+ SET
2864
+ label = EXCLUDED.label,
2865
+ extraction_hint = EXCLUDED.extraction_hint,
2866
+ required_fields = EXCLUDED.required_fields,
2867
+ active = EXCLUDED.active
2868
+ RETURNING
2869
+ organization_id,
2870
+ knowledge_type,
2871
+ label,
2872
+ extraction_hint,
2873
+ required_fields,
2874
+ active`;
2875
+ async function upsertFacetConfig(client, args) {
2876
+ const result = await client.query({
2877
+ text: exports.upsertFacetConfigQuery,
2878
+ values: [args.organizationId, args.knowledgeType, args.label, args.extractionHint, args.requiredFields, args.active],
2879
+ rowMode: "array"
2880
+ });
2881
+ if (result.rows.length !== 1) {
2882
+ return null;
2883
+ }
2884
+ const row = result.rows[0];
2885
+ return {
2886
+ organizationId: row[0],
2887
+ knowledgeType: row[1],
2888
+ label: row[2],
2889
+ extractionHint: row[3],
2890
+ requiredFields: row[4],
2891
+ active: row[5]
2892
+ };
2893
+ }
2894
+ exports.deactivateFacetConfigQuery = `-- name: DeactivateFacetConfig :one
2895
+ UPDATE weave.org_facet_config
2896
+ SET active = FALSE
2897
+ WHERE organization_id = $1
2898
+ AND knowledge_type = $2
2899
+ RETURNING
2900
+ organization_id,
2901
+ knowledge_type,
2902
+ label,
2903
+ extraction_hint,
2904
+ required_fields,
2905
+ active`;
2906
+ async function deactivateFacetConfig(client, args) {
2907
+ const result = await client.query({
2908
+ text: exports.deactivateFacetConfigQuery,
2909
+ values: [args.organizationId, args.knowledgeType],
2910
+ rowMode: "array"
2911
+ });
2912
+ if (result.rows.length !== 1) {
2913
+ return null;
2914
+ }
2915
+ const row = result.rows[0];
2916
+ return {
2917
+ organizationId: row[0],
2918
+ knowledgeType: row[1],
2919
+ label: row[2],
2920
+ extractionHint: row[3],
2921
+ requiredFields: row[4],
2922
+ active: row[5]
2923
+ };
2924
+ }