@opengeni/db 4.4.0-canary.0 → 4.4.0-canary.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/dist/canonical-human-identities.js +4 -3
  2. package/dist/{chunk-2ZMTQVTR.js → chunk-2KOLL33E.js} +2 -2
  3. package/dist/chunk-45CP2YKY.js +1062 -0
  4. package/dist/chunk-45CP2YKY.js.map +1 -0
  5. package/dist/{chunk-6TKL3GQO.js → chunk-5UUWZDAV.js} +6531 -6480
  6. package/dist/chunk-5UUWZDAV.js.map +1 -0
  7. package/dist/{chunk-QLA3UQNX.js → chunk-6IJD3XXF.js} +17 -3
  8. package/dist/chunk-6IJD3XXF.js.map +1 -0
  9. package/dist/{chunk-232VC2LW.js → chunk-6V3HDEMR.js} +2 -2
  10. package/dist/{chunk-M7PSMVFF.js → chunk-CHBLBEU6.js} +2 -2
  11. package/dist/chunk-M4PKBJRS.js +20318 -0
  12. package/dist/chunk-M4PKBJRS.js.map +1 -0
  13. package/dist/chunk-S2TZ3F4L.js +237 -0
  14. package/dist/chunk-S2TZ3F4L.js.map +1 -0
  15. package/dist/{chunk-UK57QA2H.js → chunk-UOXWVP3T.js} +2 -2
  16. package/dist/{chunk-GVZJ7XSR.js → chunk-WFU6PS54.js} +11 -4
  17. package/dist/chunk-WFU6PS54.js.map +1 -0
  18. package/dist/{chunk-THJGMEK5.js → chunk-XJP7KJ6U.js} +121 -66
  19. package/dist/chunk-XJP7KJ6U.js.map +1 -0
  20. package/dist/connection-token-resolver.d.ts +2 -0
  21. package/dist/database.d.ts +2 -0
  22. package/dist/editable-artifact-durable-export.js +3 -2
  23. package/dist/editable-artifact-durable-export.js.map +1 -1
  24. package/dist/editable-artifacts.js +4 -3
  25. package/dist/external-identities.d.ts +1 -0
  26. package/dist/external-membership-operations.d.ts +44 -0
  27. package/dist/governed-learning-evaluator.d.ts +1 -14
  28. package/dist/host-mcp-bindings.d.ts +4 -0
  29. package/dist/host-mcp-resolvers.d.ts +47 -0
  30. package/dist/host-mcp-task-authority.d.ts +2 -6
  31. package/dist/index.d.ts +29 -31
  32. package/dist/index.js +8616 -8321
  33. package/dist/index.js.map +1 -1
  34. package/dist/knowledge-document-preparation.d.ts +56 -0
  35. package/dist/knowledge-entries-schema.d.ts +2479 -0
  36. package/dist/knowledge-entries.d.ts +421 -0
  37. package/dist/knowledge-indexing.d.ts +99 -0
  38. package/dist/knowledge-migration.d.ts +6 -0
  39. package/dist/managed-auth-session-sets.js +4 -3
  40. package/dist/mcp-operations.js +3 -2
  41. package/dist/mcp-operations.js.map +1 -1
  42. package/dist/migrate.js +2 -1
  43. package/dist/provision-roles.js +1 -1
  44. package/dist/retained-provider-commands.js +3 -2
  45. package/dist/retained-provider-commands.js.map +1 -1
  46. package/dist/runtime-posture.d.ts +7 -7
  47. package/dist/schema.d.ts +115 -12
  48. package/dist/schema.js +26 -1
  49. package/dist/session-background-commands.js +5 -4
  50. package/dist/session-command-output.js +8 -6
  51. package/dist/session-command-output.js.map +1 -1
  52. package/dist/session-event-slices.js +6 -4
  53. package/dist/session-event-slices.js.map +1 -1
  54. package/dist/session-mcp-credential-rotation.js +5 -4
  55. package/dist/session-mcp-credential-rotation.js.map +1 -1
  56. package/dist/session-tenancy.js +4 -3
  57. package/dist/video-generation.js +4 -3
  58. package/dist/workspace-artifacts.d.ts +1 -0
  59. package/dist/workspace-instruction-policies-schema.d.ts +21 -2
  60. package/dist/workspace-instruction-policies.d.ts +1 -1
  61. package/dist/workspace-membership-access.d.ts +11 -0
  62. package/dist/workspace-tool-defaults.js +5 -4
  63. package/dist/workspace-tool-defaults.js.map +1 -1
  64. package/drizzle/0461_unified_knowledge.sql +2859 -0
  65. package/drizzle/0462_agent_instruction_non_destructive_edits.sql +212 -0
  66. package/drizzle/0463_host_mcp_resolver_registration.sql +111 -0
  67. package/drizzle/0464_external_workspace_membership_operations.sql +166 -0
  68. package/package.json +6 -6
  69. package/src/connection-token-resolver.ts +75 -6
  70. package/src/database.ts +12 -1
  71. package/src/external-identities.ts +1 -0
  72. package/src/external-membership-operations.ts +134 -0
  73. package/src/governed-learning-evaluator.ts +0 -69
  74. package/src/host-mcp-binding-match.ts +1 -0
  75. package/src/host-mcp-bindings.ts +24 -1
  76. package/src/host-mcp-resolvers.ts +266 -0
  77. package/src/host-mcp-task-authority.ts +11 -10
  78. package/src/index.ts +307 -128
  79. package/src/knowledge-document-preparation.ts +90 -0
  80. package/src/knowledge-entries-schema.ts +264 -0
  81. package/src/knowledge-entries.ts +860 -0
  82. package/src/knowledge-indexing.ts +126 -0
  83. package/src/knowledge-migration.ts +761 -0
  84. package/src/knowledge-source-sync.ts +46 -7
  85. package/src/migrate.ts +19 -0
  86. package/src/provision-roles.ts +23 -57
  87. package/src/runtime-posture.ts +103 -7
  88. package/src/schema.ts +15 -3
  89. package/src/skills.ts +4 -0
  90. package/src/video-generation.ts +14 -0
  91. package/src/workspace-artifacts.ts +2 -0
  92. package/src/workspace-instruction-policies-schema.ts +1 -0
  93. package/src/workspace-membership-access.ts +61 -0
  94. package/dist/chunk-6TKL3GQO.js.map +0 -1
  95. package/dist/chunk-EYF6MH6C.js +0 -4772
  96. package/dist/chunk-EYF6MH6C.js.map +0 -1
  97. package/dist/chunk-GSBONN55.js +0 -533
  98. package/dist/chunk-GSBONN55.js.map +0 -1
  99. package/dist/chunk-GVZJ7XSR.js.map +0 -1
  100. package/dist/chunk-QLA3UQNX.js.map +0 -1
  101. package/dist/chunk-THJGMEK5.js.map +0 -1
  102. /package/dist/{chunk-2ZMTQVTR.js.map → chunk-2KOLL33E.js.map} +0 -0
  103. /package/dist/{chunk-232VC2LW.js.map → chunk-6V3HDEMR.js.map} +0 -0
  104. /package/dist/{chunk-M7PSMVFF.js.map → chunk-CHBLBEU6.js.map} +0 -0
  105. /package/dist/{chunk-UK57QA2H.js.map → chunk-UOXWVP3T.js.map} +0 -0
package/src/index.ts CHANGED
@@ -1,5 +1,12 @@
1
+ import { grantWorkspaceAccess } from "./workspace-membership-access";
2
+ export { grantWorkspaceAccess, listWorkspaceMembers } from "./workspace-membership-access";
1
3
  import { codexSelectionDiagnostics } from "./codex-selection-diagnostics";
2
4
  export { codexSelectionDiagnostics } from "./codex-selection-diagnostics";
5
+ import {
6
+ scheduledTaskKnowledgeSource,
7
+ requireScheduledTaskKnowledgeSource,
8
+ } from "@opengeni/contracts";
9
+ import { z } from "zod";
3
10
  import {
4
11
  latestStartedSessionTurnQuery,
5
12
  withLatestStartedSessionPolicy,
@@ -59,6 +66,7 @@ import {
59
66
  getExternalLinkTurnAuthorization,
60
67
  } from "./external-link-work";
61
68
  export * from "./host-mcp-bindings";
69
+ export * from "./host-mcp-resolvers";
62
70
  import {
63
71
  inheritCausalHostMcpTurnAuthorities,
64
72
  inheritChildHostMcpTurnAuthorities,
@@ -164,7 +172,6 @@ import type {
164
172
  ScheduledTask,
165
173
  ScheduledTaskAction,
166
174
  ScheduledTaskActionKind,
167
- KnowledgeSourceSyncAction,
168
175
  ScheduledTaskAgentConfig,
169
176
  ScheduledTaskOverlapPolicy,
170
177
  ScheduledTaskRun,
@@ -220,11 +227,11 @@ import type {
220
227
  ReasoningEffort,
221
228
  UsageEvent,
222
229
  Workspace,
230
+ WorkspaceMember,
223
231
  WorkspaceControlEvent,
224
232
  VariableSet,
225
233
  VariableSetSecret,
226
234
  VariableSetVariableMetadata,
227
- WorkspaceMember,
228
235
  WorkspaceMemoryPromptMode,
229
236
  WorkspaceRegisteredPack,
230
237
  Channel,
@@ -295,7 +302,6 @@ import {
295
302
  approvalIdentifier,
296
303
  boundWorkspaceControlEvent,
297
304
  workspaceControlUtf8Bytes,
298
- WORKSPACE_STATE_MEMORY_SAMPLE_LIMIT,
299
305
  SESSION_EVENT_RAW_DELTA_TYPES,
300
306
  SESSION_EVENT_CLIENT_EVENT_ID_MAX_BYTES,
301
307
  SESSION_EVENT_DUPLICATE_REASON_MAX_BYTES,
@@ -636,6 +642,7 @@ import {
636
642
  withRestoredSessionActivityRlsContext,
637
643
  withSessionActivityRlsContext,
638
644
  withSessionActivitySavepoint,
645
+ withSessionRlsActorContext,
639
646
  withWorkspaceRls,
640
647
  withWorkspaceSessionActivityRls,
641
648
  withWorkspaceSubjectRls,
@@ -2676,38 +2683,6 @@ export async function createOrganizationSharedWorkspace(
2676
2683
  });
2677
2684
  }
2678
2685
 
2679
- export async function grantWorkspaceAccess(
2680
- db: Database,
2681
- input: {
2682
- accountId: string;
2683
- workspaceId: string;
2684
- subjectId: string;
2685
- subjectLabel?: string;
2686
- role?: string;
2687
- permissions: Permission[];
2688
- },
2689
- ): Promise<void> {
2690
- await db
2691
- .insert(schema.workspaceMemberships)
2692
- .values({
2693
- accountId: input.accountId,
2694
- workspaceId: input.workspaceId,
2695
- subjectId: input.subjectId,
2696
- subjectLabel: input.subjectLabel ?? null,
2697
- role: input.role ?? "member",
2698
- permissions: input.permissions,
2699
- })
2700
- .onConflictDoUpdate({
2701
- target: [schema.workspaceMemberships.subjectId, schema.workspaceMemberships.workspaceId],
2702
- set: {
2703
- subjectLabel: input.subjectLabel ?? null,
2704
- role: input.role ?? "member",
2705
- permissions: input.permissions,
2706
- updatedAt: new Date(),
2707
- },
2708
- });
2709
- }
2710
-
2711
2686
  export class WorkspaceMemberManagementError extends Error {
2712
2687
  constructor(
2713
2688
  readonly code:
@@ -3123,20 +3098,6 @@ export async function getWorkspaceGrant(
3123
3098
  : null;
3124
3099
  }
3125
3100
 
3126
- export async function listWorkspaceMembers(
3127
- db: Database,
3128
- workspaceId: string,
3129
- ): Promise<WorkspaceMember[]> {
3130
- return await withWorkspaceRls(db, workspaceId, async (scopedDb) => {
3131
- const rows = await scopedDb
3132
- .select()
3133
- .from(schema.workspaceMemberships)
3134
- .where(eq(schema.workspaceMemberships.workspaceId, workspaceId))
3135
- .orderBy(asc(schema.workspaceMemberships.createdAt));
3136
- return rows.map(mapWorkspaceMember);
3137
- });
3138
- }
3139
-
3140
3101
  // removeWorkspaceMember moved to ./organization-membership-lifecycle: removal is
3141
3102
  // now the fenced SECURITY DEFINER teardown from migration 0278.
3142
3103
 
@@ -5593,18 +5554,6 @@ export type ListKnowledgeMemoryOptions = {
5593
5554
  agentScope?: MemoryAgentScope | undefined;
5594
5555
  };
5595
5556
 
5596
- /**
5597
- * Sanitized row shape used only by Workspace State's bounded read-only
5598
- * inventory. The stable id is retained solely for deterministic ordering; no
5599
- * memory body, provenance, metadata, or vector field crosses this query seam.
5600
- */
5601
- export type WorkspaceStateMemoryRecord = {
5602
- id: string;
5603
- status: KnowledgeMemoryStatus;
5604
- kind: KnowledgeMemoryKind;
5605
- updatedAt: string;
5606
- };
5607
-
5608
5557
  export type CreateSocialConnectionInput = {
5609
5558
  accountId: string;
5610
5559
  workspaceId: string;
@@ -6340,6 +6289,7 @@ export async function createFileUpload(
6340
6289
  accountId: string;
6341
6290
  workspaceId: string;
6342
6291
  fileId: string;
6292
+ privateOwnerSubjectId?: string | null;
6343
6293
  filename: string;
6344
6294
  safeFilename: string;
6345
6295
  contentType: string;
@@ -6359,6 +6309,9 @@ export async function createFileUpload(
6359
6309
  .insert(schema.files)
6360
6310
  .values({
6361
6311
  id: input.fileId,
6312
+ privateOwnerSubjectIds: input.privateOwnerSubjectId
6313
+ ? [input.privateOwnerSubjectId]
6314
+ : null,
6362
6315
  accountId: input.accountId,
6363
6316
  workspaceId: input.workspaceId,
6364
6317
  filename: input.filename,
@@ -6380,6 +6333,7 @@ export async function createFileUpload(
6380
6333
  accountId: input.accountId,
6381
6334
  workspaceId: input.workspaceId,
6382
6335
  fileId: fileRow.id,
6336
+ privateFileOwnerSubjectId: input.privateOwnerSubjectId ?? null,
6383
6337
  status: "pending",
6384
6338
  expiresAt: input.expiresAt,
6385
6339
  })
@@ -6437,6 +6391,13 @@ export async function prepareGeneratedWorkspaceFile(
6437
6391
  await tx.execute(
6438
6392
  sql`select pg_advisory_xact_lock(hashtextextended(${`generated-workspace-file:${input.workspaceId}:${input.fileId}`}, 0))`,
6439
6393
  );
6394
+ // Callers scope this to the source session before retaining generated bytes.
6395
+ // This is a host-owned context value, never inferred from the file name.
6396
+ const [ownership] = await rawRows<{ owner: string | null }>(
6397
+ tx as unknown as Database,
6398
+ sql`SELECT nullif(current_setting('opengeni.private_file_owner',true),'') AS owner`,
6399
+ );
6400
+ const privateOwner = ownership?.owner ?? null;
6440
6401
  const [existing] = await tx
6441
6402
  .select({ file: schema.files, upload: schema.fileUploads })
6442
6403
  .from(schema.files)
@@ -6455,6 +6416,11 @@ export async function prepareGeneratedWorkspaceFile(
6455
6416
  .limit(1);
6456
6417
  if (existing) {
6457
6418
  assertGeneratedWorkspaceFileMatches(existing.file, existing.upload, input);
6419
+ if (
6420
+ JSON.stringify(existing.file.privateOwnerSubjectIds) !==
6421
+ JSON.stringify(privateOwner ? [privateOwner] : null)
6422
+ )
6423
+ throw new Error("Generated file ownership changed");
6458
6424
  return {
6459
6425
  file: mapFile(existing.file),
6460
6426
  uploadId: existing.upload.id,
@@ -6466,6 +6432,7 @@ export async function prepareGeneratedWorkspaceFile(
6466
6432
  .insert(schema.files)
6467
6433
  .values({
6468
6434
  id: input.fileId,
6435
+ privateOwnerSubjectIds: privateOwner ? [privateOwner] : null,
6469
6436
  accountId: input.accountId,
6470
6437
  workspaceId: input.workspaceId,
6471
6438
  status: "pending_upload",
@@ -6579,7 +6546,10 @@ export async function requireFileForSubject(
6579
6546
  .where(
6580
6547
  and(
6581
6548
  eq(schema.files.accountId, input.accountId),
6582
- eq(schema.files.workspaceId, input.workspaceId),
6549
+ or(
6550
+ eq(schema.files.workspaceId, input.workspaceId),
6551
+ isNotNull(schema.files.privateOwnerSubjectIds),
6552
+ ),
6583
6553
  eq(schema.files.id, input.fileId),
6584
6554
  sql`google_drive_file_authorized(
6585
6555
  ${input.accountId}::uuid,
@@ -6645,6 +6615,79 @@ export async function resolveDocumentOriginalFileForSubject(
6645
6615
  }
6646
6616
 
6647
6617
  /** Batch form of requireFileForSubject; unauthorized or missing ids are omitted. */
6618
+ /** Ready originals, filtered by owner RLS and provider ACL before pagination. */
6619
+ export async function listFilesForSubject(
6620
+ db: Database,
6621
+ input: {
6622
+ accountId: string;
6623
+ workspaceId: string;
6624
+ subjectId: string | null;
6625
+ scope?: "all" | "workspace" | "personal";
6626
+ limit?: number;
6627
+ cursor?: string | undefined;
6628
+ },
6629
+ ): Promise<{ files: FileAsset[]; nextCursor: string | null }> {
6630
+ const limit = input.limit ?? 30;
6631
+ if (!Number.isInteger(limit) || limit < 1 || limit > 50)
6632
+ throw new RangeError("Invalid file page size");
6633
+ let after: { id: string; at: string } | null = null;
6634
+ if (input.cursor) {
6635
+ try {
6636
+ after = z
6637
+ .object({ id: z.uuid(), at: z.string().datetime({ offset: true }) })
6638
+ .strict()
6639
+ .parse(JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8")));
6640
+ } catch {
6641
+ throw new z.ZodError([{ code: "custom", path: ["cursor"], message: "Invalid file cursor" }]);
6642
+ }
6643
+ }
6644
+ return withRlsContext(
6645
+ db,
6646
+ { accountId: input.accountId, workspaceId: input.workspaceId },
6647
+ async (tx) => {
6648
+ if (input.subjectId) await setSubjectRlsContext(tx, input.subjectId);
6649
+ const rows = await tx
6650
+ .select({
6651
+ file: schema.files,
6652
+ position: sql<string>`to_char(${schema.files.createdAt} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,
6653
+ })
6654
+ .from(schema.files)
6655
+ .where(
6656
+ and(
6657
+ eq(schema.files.accountId, input.accountId),
6658
+ eq(schema.files.status, "ready"),
6659
+ or(
6660
+ eq(schema.files.workspaceId, input.workspaceId),
6661
+ isNotNull(schema.files.privateOwnerSubjectIds),
6662
+ ),
6663
+ input.scope === "workspace"
6664
+ ? isNull(schema.files.privateOwnerSubjectIds)
6665
+ : input.scope === "personal"
6666
+ ? isNotNull(schema.files.privateOwnerSubjectIds)
6667
+ : undefined,
6668
+ sql`google_drive_file_authorized(${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.subjectId}::text, ${schema.files.id})`,
6669
+ after
6670
+ ? sql`(${schema.files.createdAt}, ${schema.files.id}) < (${after.at}::text::timestamptz, ${after.id}::uuid)`
6671
+ : undefined,
6672
+ ),
6673
+ )
6674
+ .orderBy(desc(schema.files.createdAt), desc(schema.files.id))
6675
+ .limit(limit + 1);
6676
+ const page = rows.slice(0, limit),
6677
+ last = page.at(-1);
6678
+ return {
6679
+ files: page.map((row) => mapFile(row.file)),
6680
+ nextCursor:
6681
+ rows.length > limit && last
6682
+ ? Buffer.from(JSON.stringify({ id: last.file.id, at: last.position })).toString(
6683
+ "base64url",
6684
+ )
6685
+ : null,
6686
+ };
6687
+ },
6688
+ );
6689
+ }
6690
+
6648
6691
  export async function getFilesForSubject(
6649
6692
  db: Database,
6650
6693
  input: {
@@ -6668,7 +6711,10 @@ export async function getFilesForSubject(
6668
6711
  .where(
6669
6712
  and(
6670
6713
  eq(schema.files.accountId, input.accountId),
6671
- eq(schema.files.workspaceId, input.workspaceId),
6714
+ or(
6715
+ eq(schema.files.workspaceId, input.workspaceId),
6716
+ isNotNull(schema.files.privateOwnerSubjectIds),
6717
+ ),
6672
6718
  inArray(schema.files.id, ids),
6673
6719
  sql`google_drive_file_authorized(
6674
6720
  ${input.accountId}::uuid,
@@ -6928,6 +6974,7 @@ export async function prepareRetainedScreenshotArtifact(
6928
6974
  .insert(schema.files)
6929
6975
  .values({
6930
6976
  id: input.artifactId,
6977
+ privateOwnerSubjectIds: sql`CASE WHEN nullif(current_setting('opengeni.private_file_owner',true),'') IS NULL THEN NULL ELSE ARRAY[current_setting('opengeni.private_file_owner',true)] END`,
6931
6978
  accountId: input.accountId,
6932
6979
  workspaceId: input.workspaceId,
6933
6980
  status: "pending_upload",
@@ -7268,6 +7315,46 @@ export async function promoteRetainedScreenshotMaintenanceCleanup(
7268
7315
  * bucket. A lost response is idempotent on the requested terminal state.
7269
7316
  */
7270
7317
  export async function completeRetainedScreenshotMaintenance(
7318
+ db: Database,
7319
+ input: Parameters<typeof completeRetainedScreenshotMaintenanceInOwnerScope>[1],
7320
+ ): Promise<boolean> {
7321
+ return withRlsContext(
7322
+ db,
7323
+ { accountId: input.accountId, workspaceId: input.workspaceId },
7324
+ async (tx) => {
7325
+ const [claim] = await tx
7326
+ .select({
7327
+ owner: schema.retainedScreenshotArtifacts.privateFileOwnerSubjectId,
7328
+ claimId: schema.retainedScreenshotArtifacts.maintenanceClaimId,
7329
+ status: schema.retainedScreenshotArtifacts.status,
7330
+ })
7331
+ .from(schema.retainedScreenshotArtifacts)
7332
+ .where(
7333
+ and(
7334
+ eq(schema.retainedScreenshotArtifacts.accountId, input.accountId),
7335
+ eq(schema.retainedScreenshotArtifacts.workspaceId, input.workspaceId),
7336
+ eq(schema.retainedScreenshotArtifacts.artifactId, input.artifactId),
7337
+ ),
7338
+ )
7339
+ .limit(1);
7340
+ if (
7341
+ claim &&
7342
+ claim.claimId !== input.claimId &&
7343
+ !(claim.claimId === null && claim.status === input.outcome)
7344
+ )
7345
+ return false;
7346
+ return withSessionRlsActorContext(
7347
+ {
7348
+ subjectId: "service:retained-screenshot-maintenance",
7349
+ privateFileOwnerSubjectId: claim?.owner ?? null,
7350
+ },
7351
+ () => completeRetainedScreenshotMaintenanceInOwnerScope(tx, input),
7352
+ );
7353
+ },
7354
+ );
7355
+ }
7356
+
7357
+ async function completeRetainedScreenshotMaintenanceInOwnerScope(
7271
7358
  db: Database,
7272
7359
  input: {
7273
7360
  accountId: string;
@@ -7795,6 +7882,44 @@ export async function completeFileUploadCleanup(
7795
7882
  fileId: string;
7796
7883
  terminalStatus: "failed" | "expired";
7797
7884
  },
7885
+ ): Promise<boolean> {
7886
+ return withRlsContext(
7887
+ db,
7888
+ { accountId: input.accountId, workspaceId: input.workspaceId },
7889
+ async (tx) => {
7890
+ const [upload] = await tx
7891
+ .select({
7892
+ owner: schema.fileUploads.privateFileOwnerSubjectId,
7893
+ fileId: schema.fileUploads.fileId,
7894
+ status: schema.fileUploads.status,
7895
+ })
7896
+ .from(schema.fileUploads)
7897
+ .where(
7898
+ and(
7899
+ eq(schema.fileUploads.accountId, input.accountId),
7900
+ eq(schema.fileUploads.workspaceId, input.workspaceId),
7901
+ eq(schema.fileUploads.id, input.uploadId),
7902
+ ),
7903
+ )
7904
+ .for("update")
7905
+ .limit(1);
7906
+ if (
7907
+ !upload ||
7908
+ upload.fileId !== input.fileId ||
7909
+ (upload.status !== "cleanup_pending" && upload.status !== input.terminalStatus)
7910
+ )
7911
+ return false;
7912
+ return withSessionRlsActorContext(
7913
+ { subjectId: "service:file-upload-cleanup", privateFileOwnerSubjectId: upload.owner },
7914
+ () => completeFileUploadCleanupInOwnerScope(tx, input),
7915
+ );
7916
+ },
7917
+ );
7918
+ }
7919
+
7920
+ async function completeFileUploadCleanupInOwnerScope(
7921
+ db: Database,
7922
+ input: Parameters<typeof completeFileUploadCleanup>[1],
7798
7923
  ): Promise<boolean> {
7799
7924
  return await withRlsContext(
7800
7925
  db,
@@ -15161,36 +15286,6 @@ export async function listKnowledgeMemories(
15161
15286
  );
15162
15287
  }
15163
15288
 
15164
- /**
15165
- * Return Workspace State's fixed-limit Memory projection without materializing
15166
- * general Memory rows. Equal timestamps use the stable UUID as a deterministic
15167
- * tie-breaker so repeated read-time projections are reproducible.
15168
- */
15169
- export async function listWorkspaceStateMemoryRecords(
15170
- db: Database,
15171
- workspaceId: string,
15172
- ): Promise<WorkspaceStateMemoryRecord[]> {
15173
- return await withWorkspaceRls(db, workspaceId, async (scopedDb) => {
15174
- const rows = await scopedDb
15175
- .select({
15176
- id: schema.knowledgeMemories.id,
15177
- status: schema.knowledgeMemories.status,
15178
- kind: schema.knowledgeMemories.kind,
15179
- updatedAt: schema.knowledgeMemories.updatedAt,
15180
- })
15181
- .from(schema.knowledgeMemories)
15182
- .where(eq(schema.knowledgeMemories.workspaceId, workspaceId))
15183
- .orderBy(desc(schema.knowledgeMemories.updatedAt), asc(schema.knowledgeMemories.id))
15184
- .limit(WORKSPACE_STATE_MEMORY_SAMPLE_LIMIT);
15185
- return rows.map((row) => ({
15186
- id: row.id,
15187
- status: row.status as KnowledgeMemoryStatus,
15188
- kind: row.kind as KnowledgeMemoryKind,
15189
- updatedAt: row.updatedAt.toISOString(),
15190
- }));
15191
- });
15192
- }
15193
-
15194
15289
  // ===========================================================================
15195
15290
  // Workspace Memory V1 — agent-writable, hybrid-searchable memory over
15196
15291
  // knowledge_memories. saveWorkspaceMemory is the single write gate; every write
@@ -17234,13 +17329,13 @@ export async function listKnowledgeSourceSyncTasksForConnection(
17234
17329
  workspaceId: string,
17235
17330
  connectionId: string,
17236
17331
  pageSize = 500,
17237
- ): Promise<Array<ScheduledTask & { action: KnowledgeSourceSyncAction }>> {
17332
+ ): Promise<Array<ScheduledTask>> {
17238
17333
  const boundedPageSize = Math.max(1, Math.min(1_000, Math.trunc(pageSize)));
17239
17334
  return await withWorkspaceRls(
17240
17335
  db,
17241
17336
  workspaceId,
17242
17337
  async (scopedDb) => {
17243
- const tasks: Array<ScheduledTask & { action: KnowledgeSourceSyncAction }> = [];
17338
+ const tasks: Array<ScheduledTask> = [];
17244
17339
  let cursor: { createdAt: Date; id: string } | null = null;
17245
17340
  for (;;) {
17246
17341
  const rows: Array<typeof schema.scheduledTasks.$inferSelect> = await scopedDb
@@ -17250,8 +17345,8 @@ export async function listKnowledgeSourceSyncTasksForConnection(
17250
17345
  and(
17251
17346
  eq(schema.scheduledTasks.workspaceId, workspaceId),
17252
17347
  isNull(schema.scheduledTasks.deletedAt),
17253
- sql`${schema.scheduledTasks.action}->>'kind' = 'knowledge_source_sync'`,
17254
- sql`${schema.scheduledTasks.action}->'connection'->>'connectionId' = ${connectionId}`,
17348
+ sql`coalesce(${schema.scheduledTasks.agentConfig}->'knowledgeSource',
17349
+ CASE WHEN ${schema.scheduledTasks.action}->>'kind'='knowledge_source_sync' THEN ${schema.scheduledTasks.action} END)->'connection'->>'connectionId' = ${connectionId}`,
17255
17350
  cursor
17256
17351
  ? or(
17257
17352
  gt(schema.scheduledTasks.createdAt, cursor.createdAt),
@@ -17267,10 +17362,10 @@ export async function listKnowledgeSourceSyncTasksForConnection(
17267
17362
  .limit(boundedPageSize);
17268
17363
  for (const row of rows) {
17269
17364
  const task = mapScheduledTask(row);
17270
- if (task.action.kind !== "knowledge_source_sync") {
17365
+ if (!scheduledTaskKnowledgeSource(task)) {
17271
17366
  throw new Error("Knowledge source task query returned a non-sync action");
17272
17367
  }
17273
- tasks.push(task as ScheduledTask & { action: KnowledgeSourceSyncAction });
17368
+ tasks.push(task);
17274
17369
  }
17275
17370
  const last: typeof schema.scheduledTasks.$inferSelect | undefined = rows.at(-1);
17276
17371
  if (!last || rows.length < boundedPageSize) return tasks;
@@ -17330,9 +17425,11 @@ export async function deleteScheduledTask(
17330
17425
  throw new Error("scheduled task changed after connector cleanup preflight");
17331
17426
  }
17332
17427
  if (
17333
- mappedTask.action.kind !== "knowledge_source_sync" ||
17334
- mappedTask.action.initiatingSubjectId !== connectorCleanupSubjectId ||
17335
- mappedTask.action.connection.ownerSubjectId !== connectorCleanupSubjectId
17428
+ !scheduledTaskKnowledgeSource(mappedTask) ||
17429
+ requireScheduledTaskKnowledgeSource(mappedTask).initiatingSubjectId !==
17430
+ connectorCleanupSubjectId ||
17431
+ requireScheduledTaskKnowledgeSource(mappedTask).connection.ownerSubjectId !==
17432
+ connectorCleanupSubjectId
17336
17433
  ) {
17337
17434
  throw new Error("scheduled task connector cleanup requires the exact causal subject");
17338
17435
  }
@@ -17365,18 +17462,22 @@ export async function deleteScheduledTask(
17365
17462
  scheduledTaskId: connectorCleanupSubjectId ? task.id : null,
17366
17463
  connectorCleanupSubjectId,
17367
17464
  connectorCleanupSnapshot:
17368
- connectorCleanupSubjectId && mappedTask.action.kind === "knowledge_source_sync"
17465
+ connectorCleanupSubjectId && Boolean(scheduledTaskKnowledgeSource(mappedTask))
17369
17466
  ? {
17370
17467
  version: 1,
17371
17468
  taskId: mappedTask.id,
17372
17469
  accountId: mappedTask.accountId,
17373
17470
  workspaceId: mappedTask.workspaceId,
17374
17471
  connectorKind: mappedTask.metadata.connectorKind,
17375
- connectionId: mappedTask.action.connection.connectionId,
17376
- connectionVersion: mappedTask.action.connection.connectionVersion,
17377
- sourceId: mappedTask.action.sourceId,
17378
- sourceLifecycleGeneration: mappedTask.action.sourceLifecycleGeneration,
17379
- sourceConfigGeneration: mappedTask.action.sourceConfigGeneration,
17472
+ connectionId:
17473
+ requireScheduledTaskKnowledgeSource(mappedTask).connection.connectionId,
17474
+ connectionVersion:
17475
+ requireScheduledTaskKnowledgeSource(mappedTask).connection.connectionVersion,
17476
+ sourceId: requireScheduledTaskKnowledgeSource(mappedTask).sourceId,
17477
+ sourceLifecycleGeneration:
17478
+ requireScheduledTaskKnowledgeSource(mappedTask).sourceLifecycleGeneration,
17479
+ sourceConfigGeneration:
17480
+ requireScheduledTaskKnowledgeSource(mappedTask).sourceConfigGeneration,
17380
17481
  externalSourceId: mappedTask.metadata.externalSourceId,
17381
17482
  subjectId: connectorCleanupSubjectId,
17382
17483
  }
@@ -17405,7 +17506,7 @@ export async function deleteScheduledTask(
17405
17506
  if (
17406
17507
  !cleanup &&
17407
17508
  connectorCleanupSubjectId &&
17408
- mappedTask.action.kind === "knowledge_source_sync"
17509
+ Boolean(scheduledTaskKnowledgeSource(mappedTask))
17409
17510
  ) {
17410
17511
  const connectorCleanupSnapshot = {
17411
17512
  version: 1,
@@ -17413,11 +17514,14 @@ export async function deleteScheduledTask(
17413
17514
  accountId: mappedTask.accountId,
17414
17515
  workspaceId: mappedTask.workspaceId,
17415
17516
  connectorKind: mappedTask.metadata.connectorKind,
17416
- connectionId: mappedTask.action.connection.connectionId,
17417
- connectionVersion: mappedTask.action.connection.connectionVersion,
17418
- sourceId: mappedTask.action.sourceId,
17419
- sourceLifecycleGeneration: mappedTask.action.sourceLifecycleGeneration,
17420
- sourceConfigGeneration: mappedTask.action.sourceConfigGeneration,
17517
+ connectionId: requireScheduledTaskKnowledgeSource(mappedTask).connection.connectionId,
17518
+ connectionVersion:
17519
+ requireScheduledTaskKnowledgeSource(mappedTask).connection.connectionVersion,
17520
+ sourceId: requireScheduledTaskKnowledgeSource(mappedTask).sourceId,
17521
+ sourceLifecycleGeneration:
17522
+ requireScheduledTaskKnowledgeSource(mappedTask).sourceLifecycleGeneration,
17523
+ sourceConfigGeneration:
17524
+ requireScheduledTaskKnowledgeSource(mappedTask).sourceConfigGeneration,
17421
17525
  externalSourceId: mappedTask.metadata.externalSourceId,
17422
17526
  subjectId: connectorCleanupSubjectId,
17423
17527
  };
@@ -31693,8 +31797,11 @@ async function setScheduledTaskAuthorityRlsContext(
31693
31797
  }
31694
31798
 
31695
31799
  export type SessionCreateInput = {
31800
+ initialAgentLearning?: import("@opengeni/contracts").AgentLearningOverrides | undefined;
31696
31801
  bundledSkillIds?: BundledSkillId[] | undefined;
31697
31802
  requestedSessionId?: string;
31803
+ /** Internal ordinary source-run proof; never accepted from session HTTP input. */
31804
+ scheduledSourceRunId?: string;
31698
31805
  accountId: string;
31699
31806
  workspaceId: string;
31700
31807
  visibility?: "user_private" | "workspace_shared";
@@ -32021,6 +32128,7 @@ async function existingSessionForCreateKey(
32021
32128
  }
32022
32129
 
32023
32130
  type SessionCreateReplayIdentity = {
32131
+ initialAgentLearning?: import("@opengeni/contracts").AgentLearningOverrides | undefined;
32024
32132
  bundledSkillIds?: BundledSkillId[] | undefined;
32025
32133
  requestedSessionId?: string;
32026
32134
  visibility?: "user_private" | "workspace_shared";
@@ -32038,6 +32146,19 @@ type SessionCreateReplayIdentity = {
32038
32146
  // every historical schema fixture. Keep this reserved request-identity fact
32039
32147
  // there instead of making current code require a post-fixture sessions column.
32040
32148
  // Create admission always replaces a caller-supplied value for this key.
32149
+ const SESSION_CREATE_AGENT_LEARNING_METADATA_KEY = "_opengeni_session_create_agent_learning_v1";
32150
+
32151
+ function metadataWithAgentLearningCreateIdentity(
32152
+ metadata: Record<string, unknown>,
32153
+ settings: import("@opengeni/contracts").AgentLearningOverrides | undefined,
32154
+ ): Record<string, unknown> {
32155
+ const next = { ...metadata };
32156
+ delete next[SESSION_CREATE_AGENT_LEARNING_METADATA_KEY];
32157
+ if (settings && Object.keys(settings).length)
32158
+ next[SESSION_CREATE_AGENT_LEARNING_METADATA_KEY] = settings;
32159
+ return next;
32160
+ }
32161
+
32041
32162
  const SESSION_CREATE_SELECTED_INSTALLED_SKILL_IDS_METADATA_KEY =
32042
32163
  "_opengeni_session_create_selected_installed_skill_ids_v1";
32043
32164
 
@@ -32065,6 +32186,11 @@ function assertSessionCreateReplayIdentity(
32065
32186
  existing: typeof schema.sessions.$inferSelect,
32066
32187
  input: SessionCreateReplayIdentity,
32067
32188
  ): void {
32189
+ if (
32190
+ stableJson(existing.metadata?.[SESSION_CREATE_AGENT_LEARNING_METADATA_KEY] ?? {}) !==
32191
+ stableJson(input.initialAgentLearning ?? {})
32192
+ )
32193
+ throw new SessionCreateIdempotencyConflictError();
32068
32194
  if (
32069
32195
  stableJson(hostCreateSelectionFromMetadata(existing.metadata)) !==
32070
32196
  stableJson(normalizeHostCreateSelection(input.selectedHostMcpDelegations))
@@ -32202,7 +32328,10 @@ async function createSessionInTransaction(
32202
32328
  const selectedInstalledSkillIds = input.selectedInstalledSkillIds ?? [];
32203
32329
  const sessionMetadata = metadataWithSelectedInstalledSkillCreateIdentity(
32204
32330
  metadataWithHostCreateSelection(
32205
- withBundledSkillSelectionMetadata(input.metadata, input.bundledSkillIds),
32331
+ withBundledSkillSelectionMetadata(
32332
+ metadataWithAgentLearningCreateIdentity(input.metadata, input.initialAgentLearning),
32333
+ input.bundledSkillIds,
32334
+ ),
32206
32335
  input.selectedHostMcpDelegations,
32207
32336
  ),
32208
32337
  selectedInstalledSkillIds,
@@ -32254,6 +32383,7 @@ async function createSessionInTransaction(
32254
32383
  // before any first-turn repair so a retry cannot hide a requested-ID
32255
32384
  // conflict behind an apparently successful replay.
32256
32385
  assertSessionCreateReplayIdentity(existing, {
32386
+ initialAgentLearning: input.initialAgentLearning,
32257
32387
  bundledSkillIds: input.bundledSkillIds,
32258
32388
  ...(input.requestedSessionId ? { requestedSessionId: input.requestedSessionId } : {}),
32259
32389
  visibility: createRequestedVisibility,
@@ -32277,6 +32407,13 @@ async function createSessionInTransaction(
32277
32407
  if (!canonicalExisting) {
32278
32408
  throw new Error(`Session event cursor missing for session ${existing.id}`);
32279
32409
  }
32410
+ if (input.scheduledSourceRunId)
32411
+ await bindScheduledTaskRunSessionInTransaction(tx, {
32412
+ accountId: input.accountId,
32413
+ workspaceId: input.workspaceId,
32414
+ runId: input.scheduledSourceRunId,
32415
+ sessionId: existing.id,
32416
+ });
32280
32417
  await input.beforeCreateCommit?.(tx, existing.id, { created: false });
32281
32418
  return {
32282
32419
  session: await mapSessionWithControl(tx, canonicalExisting, grouped.get(existing.id) ?? []),
@@ -32356,18 +32493,45 @@ async function createSessionInTransaction(
32356
32493
  privateCreateOwnerMembershipId = capability.ownerMembershipId;
32357
32494
  privateCreateOwnerSubjectId = capability.ownerSubjectId;
32358
32495
  } else {
32359
- if (frozenCreator.initiator.kind !== "subject" || !input.subjectId || input.sandboxGroupId) {
32496
+ let owner = input.subjectId;
32497
+ if (input.scheduledSourceRunId) {
32498
+ const accepted = await getScheduledTaskRunAcceptedExecution(tx, {
32499
+ workspaceId: input.workspaceId,
32500
+ runId: input.scheduledSourceRunId,
32501
+ });
32502
+ const source = accepted?.task.agentConfig.knowledgeSource;
32503
+ if (
32504
+ !accepted ||
32505
+ !source ||
32506
+ accepted.task.accountId !== input.accountId ||
32507
+ accepted.task.runMode !== "new_session_per_run" ||
32508
+ source.destination.kind !== "personal" ||
32509
+ source.destination.subjectId !== source.initiatingSubjectId ||
32510
+ source.connection.ownerSubjectId !== source.initiatingSubjectId ||
32511
+ accepted.causalHumanSubjectId !== source.initiatingSubjectId ||
32512
+ accepted.causalHumanAuthority?.subjectId !== source.initiatingSubjectId ||
32513
+ accepted.generatedSessionBinding?.createIdempotencyKey !== input.createIdempotencyKey ||
32514
+ frozenCreator.initiator.kind !== "service" ||
32515
+ frozenCreator.initiator.subjectId !== "scheduler" ||
32516
+ input.sandboxGroupId
32517
+ ) {
32518
+ throw new Error("Private source session requires its accepted owning-human run");
32519
+ }
32520
+ owner = source.initiatingSubjectId;
32521
+ await setSubjectRlsContext(tx, owner);
32522
+ } else if (frozenCreator.initiator.kind !== "subject" || !owner || input.sandboxGroupId) {
32360
32523
  throw new Error("Private session creation requires a top-level managed-human singleton");
32361
32524
  }
32525
+ if (!owner) throw new Error("Private session owner is unavailable");
32362
32526
  const capability = await openPrivateSessionCreateCapability(tx, {
32363
32527
  accountId: input.accountId,
32364
32528
  workspaceId: input.workspaceId,
32365
32529
  sessionId: id,
32366
- actorSubjectId: input.subjectId,
32530
+ actorSubjectId: owner,
32367
32531
  });
32368
32532
  privateCreateCapabilityId = capability.capabilityId;
32369
32533
  privateCreateOwnerMembershipId = capability.ownerMembershipId;
32370
- privateCreateOwnerSubjectId = input.subjectId;
32534
+ privateCreateOwnerSubjectId = owner;
32371
32535
  }
32372
32536
  }
32373
32537
  try {
@@ -32478,6 +32642,7 @@ async function createSessionInTransaction(
32478
32642
  );
32479
32643
  if (existing) {
32480
32644
  assertSessionCreateReplayIdentity(existing, {
32645
+ initialAgentLearning: input.initialAgentLearning,
32481
32646
  bundledSkillIds: input.bundledSkillIds,
32482
32647
  ...(input.requestedSessionId ? { requestedSessionId: input.requestedSessionId } : {}),
32483
32648
  visibility: createRequestedVisibility,
@@ -32501,6 +32666,13 @@ async function createSessionInTransaction(
32501
32666
  if (!canonicalExisting) {
32502
32667
  throw new Error(`Session event cursor missing for session ${existing.id}`);
32503
32668
  }
32669
+ if (input.scheduledSourceRunId)
32670
+ await bindScheduledTaskRunSessionInTransaction(tx, {
32671
+ accountId: input.accountId,
32672
+ workspaceId: input.workspaceId,
32673
+ runId: input.scheduledSourceRunId,
32674
+ sessionId: existing.id,
32675
+ });
32504
32676
  await input.beforeCreateCommit?.(tx, existing.id, { created: false });
32505
32677
  return {
32506
32678
  session: await mapSessionWithControl(
@@ -32538,6 +32710,13 @@ async function createSessionInTransaction(
32538
32710
  sessionId: inserted.id,
32539
32711
  servers: input.mcpServers ?? [],
32540
32712
  });
32713
+ if (input.scheduledSourceRunId)
32714
+ await bindScheduledTaskRunSessionInTransaction(tx, {
32715
+ accountId: input.accountId,
32716
+ workspaceId: input.workspaceId,
32717
+ runId: input.scheduledSourceRunId,
32718
+ sessionId: inserted.id,
32719
+ });
32541
32720
  await input.beforeCreateCommit?.(tx, inserted.id, { created: true });
32542
32721
  return {
32543
32722
  session: await mapSessionWithControl(tx, inserted, mcpServers),
@@ -32669,6 +32848,10 @@ export type InitializedSessionCreateReplay =
32669
32848
  export async function getInitializedSessionCreateReplay(
32670
32849
  db: Database,
32671
32850
  input: {
32851
+ initialAgentLearning?: import("@opengeni/contracts").AgentLearningOverrides | undefined;
32852
+ agentAccess?: SessionAgentAccess;
32853
+ scopeSubjectId?: SessionScopeSubjectId | null;
32854
+ memoryScope?: SessionMemoryScope;
32672
32855
  bundledSkillIds?: BundledSkillId[] | undefined;
32673
32856
  accountId: string;
32674
32857
  workspaceId: string;
@@ -77516,6 +77699,7 @@ async function latestStartedSessionTurnRow(
77516
77699
 
77517
77700
  function mapFile(row: typeof schema.files.$inferSelect): FileAsset {
77518
77701
  return {
77702
+ scope: row.privateOwnerSubjectIds ? "personal" : "workspace",
77519
77703
  id: row.id,
77520
77704
  workspaceId: row.workspaceId,
77521
77705
  status: row.status as FileStatus,
@@ -77893,16 +78077,6 @@ function mapWorkspace(
77893
78077
  };
77894
78078
  }
77895
78079
 
77896
- function mapWorkspaceMember(row: typeof schema.workspaceMemberships.$inferSelect): WorkspaceMember {
77897
- return {
77898
- subjectId: row.subjectId,
77899
- subjectLabel: row.subjectLabel,
77900
- role: row.role,
77901
- permissions: normalizeWorkspaceMembershipPermissions(row.permissions),
77902
- createdAt: row.createdAt.toISOString(),
77903
- };
77904
- }
77905
-
77906
78080
  function mapCapabilityInstallation(
77907
78081
  row: typeof schema.capabilityInstallations.$inferSelect,
77908
78082
  ): CapabilityInstallation {
@@ -78590,3 +78764,8 @@ export async function listDueWorkspacePauseTimers(db: Database, limit = 100) {
78590
78764
  }
78591
78765
 
78592
78766
  export * from "./feedback";
78767
+ export * from "./knowledge-entries";
78768
+
78769
+ export * from "./knowledge-indexing";
78770
+
78771
+ export * from "./knowledge-document-preparation";