@capybara-hq/kernel 0.1.0-rc.80 → 0.1.0-rc.82

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 (65) hide show
  1. package/bootstrap.json +29 -29
  2. package/dist/admin/outbox-dead.service.js +133 -120
  3. package/dist/background/store.js +78 -67
  4. package/dist/background/tasks.service.d.ts +6 -0
  5. package/dist/background/tasks.service.js +3 -0
  6. package/dist/catalog/marketplaces.service.d.ts +1 -1
  7. package/dist/catalog/plugin-import.js +45 -40
  8. package/dist/catalog/scope-sync-workers.js +3 -0
  9. package/dist/channels/inbound.d.ts +6 -1
  10. package/dist/channels/inbound.js +18 -1
  11. package/dist/client/client-reports.service.js +9 -6
  12. package/dist/config/schema.d.ts +5 -0
  13. package/dist/config/schema.js +6 -0
  14. package/dist/conversations/attachments.service.js +101 -96
  15. package/dist/conversations/events.d.ts +7 -0
  16. package/dist/conversations/events.js +9 -0
  17. package/dist/ctx/bus.js +5 -3
  18. package/dist/ctx/queue.js +4 -2
  19. package/dist/db/pool.d.ts +6 -0
  20. package/dist/db/pool.js +3 -2
  21. package/dist/devices/legacy-cleanup.job.js +73 -70
  22. package/dist/dial-in/gateway.d.ts +8 -0
  23. package/dist/dial-in/gateway.js +22 -2
  24. package/dist/extensions/admin-ops.js +22 -19
  25. package/dist/extensions/lifecycle-hooks.js +3 -1
  26. package/dist/http/app.js +3 -1
  27. package/dist/http/plugin-dispatch.js +8 -0
  28. package/dist/identity/auth.guard.js +13 -3
  29. package/dist/index.d.ts +2 -0
  30. package/dist/index.js +1 -0
  31. package/dist/infra/database/database.module.js +1 -0
  32. package/dist/infra/database/org-scope.d.ts +59 -0
  33. package/dist/infra/database/org-scope.js +68 -0
  34. package/dist/infra/database/rls-role.d.ts +11 -0
  35. package/dist/infra/database/rls-role.js +33 -0
  36. package/dist/infra/database/scoped-dialect.d.ts +18 -0
  37. package/dist/infra/database/scoped-dialect.js +245 -0
  38. package/dist/infra/outbox/outbox.dispatcher.js +98 -90
  39. package/dist/infra/outbox/outbox.service.js +29 -26
  40. package/dist/infra/queue/run-job.d.ts +8 -2
  41. package/dist/infra/queue/run-job.js +16 -3
  42. package/dist/infra/schedule/locked-tick.js +12 -4
  43. package/dist/infra/schedule/scheduled-runs.js +3 -1
  44. package/dist/lifecycle/kernel-lifecycle.d.ts +1 -0
  45. package/dist/lifecycle/kernel-lifecycle.js +16 -1
  46. package/dist/orgs/org.guard.js +4 -0
  47. package/dist/platform/sealed-reveals.js +9 -6
  48. package/dist/runtime/maintenance.js +6 -1
  49. package/dist/runtime/run-execution.d.ts +1 -0
  50. package/dist/runtime/run-execution.js +5 -0
  51. package/dist/runtime/run-orphan-check.job.js +20 -15
  52. package/dist/sandbox/legacy-retirement.js +438 -397
  53. package/dist/sandbox/modes.d.ts +10 -0
  54. package/dist/sandbox/modes.js +23 -0
  55. package/dist/sandbox/operation-reconcile.job.d.ts +14 -1
  56. package/dist/sandbox/operation-reconcile.job.js +35 -3
  57. package/dist/sandbox/permission-config-publication.js +83 -77
  58. package/dist/sandbox/sandbox.service.d.ts +24 -0
  59. package/dist/sandbox/sandbox.service.js +159 -62
  60. package/dist/schedules/store.js +17 -14
  61. package/dist/tools/builtins/sandbox/bash.js +16 -1
  62. package/dist/tools/drift.js +31 -24
  63. package/dist/tools/outputs.js +20 -17
  64. package/package.json +2 -2
  65. package/src/migrations/0182_rls_policies.sql +202 -0
@@ -12,6 +12,7 @@ import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { ModuleRef } from "@nestjs/core";
13
13
  import { sql } from "kysely";
14
14
  import { KernelDb } from "../database/kernel-db.js";
15
+ import { asPlatform } from "../database/org-scope.js";
15
16
  import { TransactionHost } from "../database/transaction-host.js";
16
17
  import { Transactional } from "../database/transactional.decorator.js";
17
18
  import { QUEUE_JOB_DEFAULTS } from "../queue/queue.module.js";
@@ -193,74 +194,76 @@ let OutboxDispatcher = class OutboxDispatcher {
193
194
  * bounded by {@link OUTBOX_REDIS_TIMEOUT_MS}.
194
195
  */
195
196
  async claimAndSend(claim) {
196
- const queues = new Map(this.reachable());
197
- if (queues.size === 0)
198
- return { sent: 0, failed: [] };
199
- // rows of a queue this process cannot reach are left for a process that can
200
- let query = this.db
201
- .selectFrom("outbox")
202
- .select(["id", "queue", "job_name", "job_id", "data", "run_at"])
203
- .where("dead_at", "is", null)
204
- .where("queue", "in", [...queues.keys()]);
205
- query =
206
- "ids" in claim
207
- ? query.where("id", "in", [...claim.ids])
208
- : query.where("next_attempt_at", "<=", sql `now()`).limit(claim.limit);
209
- const rows = await query.orderBy("id").forUpdate().skipLocked().execute();
210
- if (rows.length === 0)
211
- return { sent: 0, failed: [] };
212
- const byQueue = new Map();
213
- for (const row of rows) {
214
- const group = byQueue.get(row.queue);
215
- if (group)
216
- group.push(row);
217
- else
218
- byQueue.set(row.queue, [row]);
219
- }
220
- const now = Date.now();
221
- const deadline = now + OUTBOX_REDIS_TIMEOUT_MS;
222
- const delivered = [];
223
- const failed = [];
224
- // after the first failure the queues left are failed without a try: Redis is likely down
225
- let firstError;
226
- for (const [name, group] of byQueue) {
227
- const ids = group.map((r) => r.id);
228
- if (firstError !== undefined) {
229
- failed.push({
230
- ids,
231
- error: `not tried after an earlier queue failed: ${firstError}`.slice(0, MAX_ERROR_LENGTH),
232
- });
233
- continue;
234
- }
235
- try {
236
- if (this.dispatchFails(name))
237
- throw new Error("outbox dispatch failure (test seam)");
238
- const queue = queues.get(name);
239
- if (!queue)
240
- throw new Error(`"${name}" is not a kernel queue`);
241
- const left = deadline - Date.now();
242
- if (left <= 0)
243
- throw new Error(`no time left of the pass's ${OUTBOX_REDIS_TIMEOUT_MS} ms`);
244
- await withTimeout(queue.addBulk(group.map((r) => ({
245
- name: r.job_name,
246
- data: r.data,
247
- opts: {
248
- ...QUEUE_JOB_DEFAULTS,
249
- ...outboxJobOptions(r.job_name),
250
- jobId: r.job_id,
251
- delay: r.run_at ? Math.max(0, r.run_at.getTime() - now) : 0,
252
- },
253
- }))), left, `addBulk to ${name}`);
254
- delivered.push(...ids);
197
+ return asPlatform("deployment-wide relay", async () => {
198
+ const queues = new Map(this.reachable());
199
+ if (queues.size === 0)
200
+ return { sent: 0, failed: [] };
201
+ // rows of a queue this process cannot reach are left for a process that can
202
+ let query = this.db
203
+ .selectFrom("outbox")
204
+ .select(["id", "queue", "job_name", "job_id", "data", "run_at"])
205
+ .where("dead_at", "is", null)
206
+ .where("queue", "in", [...queues.keys()]);
207
+ query =
208
+ "ids" in claim
209
+ ? query.where("id", "in", [...claim.ids])
210
+ : query.where("next_attempt_at", "<=", sql `now()`).limit(claim.limit);
211
+ const rows = await query.orderBy("id").forUpdate().skipLocked().execute();
212
+ if (rows.length === 0)
213
+ return { sent: 0, failed: [] };
214
+ const byQueue = new Map();
215
+ for (const row of rows) {
216
+ const group = byQueue.get(row.queue);
217
+ if (group)
218
+ group.push(row);
219
+ else
220
+ byQueue.set(row.queue, [row]);
255
221
  }
256
- catch (e) {
257
- firstError = errMsg(e);
258
- failed.push({ ids, error: firstError.slice(0, MAX_ERROR_LENGTH) });
222
+ const now = Date.now();
223
+ const deadline = now + OUTBOX_REDIS_TIMEOUT_MS;
224
+ const delivered = [];
225
+ const failed = [];
226
+ // after the first failure the queues left are failed without a try: Redis is likely down
227
+ let firstError;
228
+ for (const [name, group] of byQueue) {
229
+ const ids = group.map((r) => r.id);
230
+ if (firstError !== undefined) {
231
+ failed.push({
232
+ ids,
233
+ error: `not tried after an earlier queue failed: ${firstError}`.slice(0, MAX_ERROR_LENGTH),
234
+ });
235
+ continue;
236
+ }
237
+ try {
238
+ if (this.dispatchFails(name))
239
+ throw new Error("outbox dispatch failure (test seam)");
240
+ const queue = queues.get(name);
241
+ if (!queue)
242
+ throw new Error(`"${name}" is not a kernel queue`);
243
+ const left = deadline - Date.now();
244
+ if (left <= 0)
245
+ throw new Error(`no time left of the pass's ${OUTBOX_REDIS_TIMEOUT_MS} ms`);
246
+ await withTimeout(queue.addBulk(group.map((r) => ({
247
+ name: r.job_name,
248
+ data: r.data,
249
+ opts: {
250
+ ...QUEUE_JOB_DEFAULTS,
251
+ ...outboxJobOptions(r.job_name),
252
+ jobId: r.job_id,
253
+ delay: r.run_at ? Math.max(0, r.run_at.getTime() - now) : 0,
254
+ },
255
+ }))), left, `addBulk to ${name}`);
256
+ delivered.push(...ids);
257
+ }
258
+ catch (e) {
259
+ firstError = errMsg(e);
260
+ failed.push({ ids, error: firstError.slice(0, MAX_ERROR_LENGTH) });
261
+ }
259
262
  }
260
- }
261
- if (delivered.length > 0)
262
- await this.db.deleteFrom("outbox").where("id", "in", delivered).execute();
263
- return { sent: delivered.length, failed };
263
+ if (delivered.length > 0)
264
+ await this.db.deleteFrom("outbox").where("id", "in", delivered).execute();
265
+ return { sent: delivered.length, failed };
266
+ });
264
267
  }
265
268
  /**
266
269
  * Records a failed add on its rows (after the claim transaction, so the attempt is kept whatever
@@ -268,31 +271,36 @@ let OutboxDispatcher = class OutboxDispatcher {
268
271
  * and `dead_at` at the last attempt. Returns how many rows it made dead.
269
272
  */
270
273
  async recordFailure(group) {
271
- const { baseMs, capMs, maxAttempts } = OUTBOX_BACKOFF;
272
- // the right-hand sides read the row before the update: the first failure waits baseMs
273
- const backoffMs = sql `least(${capMs}::float8, ${baseMs}::float8 * power(2, attempts))`;
274
- const updated = await this.db
275
- .updateTable("outbox")
276
- .set({
277
- attempts: sql `attempts + 1`,
278
- last_error: group.error,
279
- next_attempt_at: sql `now() + ${backoffMs} * interval '1 millisecond'`,
280
- dead_at: sql `case when attempts + 1 >= ${maxAttempts}::int then now() end`,
281
- })
282
- .where("id", "in", group.ids)
283
- .where("dead_at", "is", null)
284
- .returning(["dead_at"])
285
- .execute();
286
- const dead = updated.filter((r) => r.dead_at !== null).length;
287
- this.log.warn("outbox delivery failed; retrying with backoff", {
288
- rows: group.ids.length,
289
- dead,
290
- error: group.error,
274
+ return asPlatform("deployment-wide relay", async () => {
275
+ const { baseMs, capMs, maxAttempts } = OUTBOX_BACKOFF;
276
+ // the right-hand sides read the row before the update: the first failure waits baseMs
277
+ const backoffMs = sql `least(${capMs}::float8, ${baseMs}::float8 * power(2, attempts))`;
278
+ const updated = await this.db
279
+ .updateTable("outbox")
280
+ .set({
281
+ attempts: sql `attempts + 1`,
282
+ last_error: group.error,
283
+ next_attempt_at: sql `now() + ${backoffMs} * interval '1 millisecond'`,
284
+ dead_at: sql `case when attempts + 1 >= ${maxAttempts}::int then now() end`,
285
+ })
286
+ .where("id", "in", group.ids)
287
+ .where("dead_at", "is", null)
288
+ .returning(["dead_at"])
289
+ .execute();
290
+ const dead = updated.filter((r) => r.dead_at !== null).length;
291
+ this.log.warn("outbox delivery failed; retrying with backoff", {
292
+ rows: group.ids.length,
293
+ dead,
294
+ error: group.error,
295
+ });
296
+ if (dead > 0) {
297
+ this.log.error("outbox rows dead after the last attempt", {
298
+ rows: dead,
299
+ error: group.error,
300
+ });
301
+ }
302
+ return dead;
291
303
  });
292
- if (dead > 0) {
293
- this.log.error("outbox rows dead after the last attempt", { rows: dead, error: group.error });
294
- }
295
- return dead;
296
304
  }
297
305
  };
298
306
  __decorate([
@@ -11,6 +11,7 @@ import { isDeepStrictEqual } from "node:util";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { afterCommit } from "../database/after-commit.js";
13
13
  import { KernelDb } from "../database/kernel-db.js";
14
+ import { asPlatform } from "../database/org-scope.js";
14
15
  import { currentStore, TransactionHost } from "../database/transaction-host.js";
15
16
  import { Transactional } from "../database/transactional.decorator.js";
16
17
  /** The fast path `add` hands each committed transaction's rows to (`OutboxModule` provides it). */
@@ -82,32 +83,34 @@ let OutboxService = class OutboxService {
82
83
  * {@link OutboxConflictError}, so the caller's transaction fails. Undefined data is stored as JSON null.
83
84
  */
84
85
  async add(job) {
85
- const json = JSON.stringify(job.data ?? null);
86
- const row = await this.db
87
- .insertInto("outbox")
88
- .values(rowOf(job))
89
- .onConflict((oc) => oc.columns(["queue", "job_id"]).where("dead_at", "is", null).doNothing())
90
- .returning("id")
91
- .executeTakeFirst();
92
- if (row) {
93
- if (dueNow(job))
94
- this.deliverAfterCommit(row.id);
95
- return true;
96
- }
97
- // org-filter: by the unique (queue, job_id) of the conflicting insert just above; job ids are
98
- // kernel-built and the outbox is deployment-wide
99
- const stored = await this.db
100
- .selectFrom("outbox")
101
- .select(["job_name", "data"])
102
- .where("queue", "=", job.queue)
103
- .where("job_id", "=", job.jobId)
104
- .where("dead_at", "is", null)
105
- .executeTakeFirst();
106
- // no row: the owed one was delivered (and deleted) since the conflict; BullMQ dedupes the id
107
- if (stored && !isDeepStrictEqual(stored.data, JSON.parse(json))) {
108
- throw new OutboxConflictError(job.queue, job.jobId, job.name, stored.job_name);
109
- }
110
- return false;
86
+ return asPlatform("the outbox is a deployment-wide table", async () => {
87
+ const json = JSON.stringify(job.data ?? null);
88
+ const row = await this.db
89
+ .insertInto("outbox")
90
+ .values(rowOf(job))
91
+ .onConflict((oc) => oc.columns(["queue", "job_id"]).where("dead_at", "is", null).doNothing())
92
+ .returning("id")
93
+ .executeTakeFirst();
94
+ if (row) {
95
+ if (dueNow(job))
96
+ this.deliverAfterCommit(row.id);
97
+ return true;
98
+ }
99
+ // org-filter: by the unique (queue, job_id) of the conflicting insert just above; job ids are
100
+ // kernel-built and the outbox is deployment-wide
101
+ const stored = await this.db
102
+ .selectFrom("outbox")
103
+ .select(["job_name", "data"])
104
+ .where("queue", "=", job.queue)
105
+ .where("job_id", "=", job.jobId)
106
+ .where("dead_at", "is", null)
107
+ .executeTakeFirst();
108
+ // no row: the owed one was delivered (and deleted) since the conflict; BullMQ dedupes the id
109
+ if (stored && !isDeepStrictEqual(stored.data, JSON.parse(json))) {
110
+ throw new OutboxConflictError(job.queue, job.jobId, job.name, stored.job_name);
111
+ }
112
+ return false;
113
+ });
111
114
  }
112
115
  /**
113
116
  * {@link add} for many jobs in one multi-row insert per {@link ADD_MANY_CHUNK} jobs (an eval
@@ -2,7 +2,11 @@ import { type ContextJob } from "../../log-context.js";
2
2
  /**
3
3
  * The wrapper every queue processor runs its job in: a fresh async context (no transaction of
4
4
  * whoever enqueued the job or started the worker is visible), `queue` / `jobId` / `runId` in the
5
- * log context, and the tracing span when tracing is on (`withJobContext`).
5
+ * log context, and the tracing span when tracing is on (`withJobContext`). The org scope (RLS spec
6
+ * §5.3, §10) is the job's org when its data carries a string `orgId`; else the platform scope when
7
+ * the queue's work is deployment-wide (`opts.platform`, the reason); else none, never inherited
8
+ * from whoever started the worker (a missing org fails closed once RLS is enforced, and the
9
+ * unscoped-query check reports it).
6
10
  *
7
11
  * ```ts
8
12
  * @Processor("cap-kernel-titles")
@@ -13,4 +17,6 @@ import { type ContextJob } from "../../log-context.js";
13
17
  * }
14
18
  * ```
15
19
  */
16
- export declare function runJob<T>(queue: string, job: ContextJob, fn: () => Promise<T>): Promise<T>;
20
+ export declare function runJob<T>(queue: string, job: ContextJob, fn: () => Promise<T>, opts?: {
21
+ platform?: string;
22
+ }): Promise<T>;
@@ -1,9 +1,14 @@
1
1
  import { withJobContext } from "../../log-context.js";
2
+ import { asPlatform, withOrgScope, withoutOrgScope } from "../database/org-scope.js";
2
3
  import { runOutsideTransaction } from "../database/transaction-host.js";
3
4
  /**
4
5
  * The wrapper every queue processor runs its job in: a fresh async context (no transaction of
5
6
  * whoever enqueued the job or started the worker is visible), `queue` / `jobId` / `runId` in the
6
- * log context, and the tracing span when tracing is on (`withJobContext`).
7
+ * log context, and the tracing span when tracing is on (`withJobContext`). The org scope (RLS spec
8
+ * §5.3, §10) is the job's org when its data carries a string `orgId`; else the platform scope when
9
+ * the queue's work is deployment-wide (`opts.platform`, the reason); else none, never inherited
10
+ * from whoever started the worker (a missing org fails closed once RLS is enforced, and the
11
+ * unscoped-query check reports it).
7
12
  *
8
13
  * ```ts
9
14
  * @Processor("cap-kernel-titles")
@@ -14,6 +19,14 @@ import { runOutsideTransaction } from "../database/transaction-host.js";
14
19
  * }
15
20
  * ```
16
21
  */
17
- export function runJob(queue, job, fn) {
18
- return runOutsideTransaction(() => withJobContext(queue, job, fn));
22
+ export function runJob(queue, job, fn, opts = {}) {
23
+ const orgId = job.data?.orgId;
24
+ const run = () => withJobContext(queue, job, fn);
25
+ return runOutsideTransaction(() => {
26
+ if (typeof orgId === "string" && orgId !== "")
27
+ return withOrgScope(orgId, run);
28
+ if (opts.platform !== undefined)
29
+ return asPlatform(opts.platform, run);
30
+ return withoutOrgScope(run);
31
+ });
19
32
  }
@@ -1,4 +1,5 @@
1
1
  import { withLogContext } from "../../log-context.js";
2
+ import { asPlatform } from "../database/org-scope.js";
2
3
  import { runOutsideTransaction } from "../database/transaction-host.js";
3
4
  /** Marks a method wrapped by `@LockedCron` / `@LockedInterval` (read by `ScheduledRuns`). */
4
5
  export const LOCKED_JOB = Symbol("LOCKED_JOB");
@@ -61,13 +62,17 @@ export async function runLockedTick(host, o) {
61
62
  const signal = scope?.signal;
62
63
  /** Errors during the stop are expected (the job aborted, Redis closing): WARN, not ERROR. */
63
64
  const logFailure = (msg, fields) => signal?.aborted ? log.warn(msg, fields) : log.error(msg, fields);
64
- const run = runOutsideTransaction(() => withLogContext({ cron: o.name }, async () => {
65
+ // a periodic sweep is deployment-wide work (RLS spec §5.1); one that handles each org in turn
66
+ // enters that org's scope itself
67
+ const run = runOutsideTransaction(() => asPlatform(`cron ${o.name}`, () => withLogContext({ cron: o.name }, async () => {
65
68
  let tick;
66
69
  try {
67
70
  if (o.start) {
68
71
  tick = "start";
69
72
  if (!(await lockService.lease(`cron:${o.name}:start`, "start", o.start.ttlMs))) {
70
- log.info("cron skipped: start run already taken by another replica", { cron: o.name });
73
+ log.info("cron skipped: start run already taken by another replica", {
74
+ cron: o.name,
75
+ });
71
76
  return;
72
77
  }
73
78
  }
@@ -115,7 +120,10 @@ export async function runLockedTick(host, o) {
115
120
  log.info("cron run stopped by the shutdown", { cron: o.name, error: errMsg(err) });
116
121
  }
117
122
  else if (handle.lost.aborted) {
118
- log.warn("cron run stopped: its run lock was lost", { cron: o.name, error: errMsg(err) });
123
+ log.warn("cron run stopped: its run lock was lost", {
124
+ cron: o.name,
125
+ error: errMsg(err),
126
+ });
119
127
  }
120
128
  else {
121
129
  log.error("cron job failed", { cron: o.name, error: errMsg(err), err });
@@ -126,7 +134,7 @@ export async function runLockedTick(host, o) {
126
134
  .release()
127
135
  .catch((err) => logFailure("cron lock release failed", { cron: o.name, err }));
128
136
  }
129
- }));
137
+ })));
130
138
  try {
131
139
  await (scope ? scope.track(run) : run);
132
140
  }
@@ -11,6 +11,7 @@ import { Inject, Injectable, } from "@nestjs/common";
11
11
  import { DiscoveryService, MetadataScanner } from "@nestjs/core";
12
12
  import { SchedulerRegistry } from "@nestjs/schedule";
13
13
  import { waitWithin } from "../close-within.js";
14
+ import { asPlatform } from "../database/org-scope.js";
14
15
  import { runOutsideTransaction } from "../database/transaction-host.js";
15
16
  import { GracefulShutdown } from "../lifecycle/graceful-shutdown.service.js";
16
17
  import { KERNEL_LOGGER } from "../tokens.js";
@@ -88,7 +89,8 @@ let ScheduledRuns = class ScheduledRuns {
88
89
  const body = this.bodies.get(name);
89
90
  if (!body)
90
91
  return false;
91
- await runOutsideTransaction(() => Promise.resolve(body(this.abort.signal)));
92
+ // deployment-wide like the tick itself (RLS spec §5.1)
93
+ await runOutsideTransaction(() => asPlatform(`cron ${name}`, () => Promise.resolve(body(this.abort.signal))));
92
94
  return true;
93
95
  }
94
96
  /** The start gate is open: ticks and start runs may run. */
@@ -123,6 +123,7 @@ export declare class KernelLifecycle implements OnApplicationBootstrap, BeforeAp
123
123
  releaseOnly(): void;
124
124
  private checkpoint;
125
125
  onApplicationBootstrap(): Promise<void>;
126
+ private startSequence;
126
127
  /**
127
128
  * Listens on `port` (0.0.0.0; every role listens: worker-only serves only `/healthz` and
128
129
  * `/readyz`) after the start sequence; returns the actual port.
@@ -34,6 +34,8 @@ import { insecurePublicUrlWarning } from "../identity/cookies.js";
34
34
  import { waitWithin } from "../infra/close-within.js";
35
35
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
36
36
  import { KernelDb } from "../infra/database/kernel-db.js";
37
+ import { asPlatform } from "../infra/database/org-scope.js";
38
+ import { rlsEnforceProblem } from "../infra/database/rls-role.js";
37
39
  import { GracefulShutdown } from "../infra/lifecycle/graceful-shutdown.service.js";
38
40
  import { ReplicaPresence } from "../infra/presence/replica-presence.js";
39
41
  import { KERNEL_BUS, KERNEL_LOGGER, KERNEL_POOL, REDIS } from "../infra/tokens.js";
@@ -199,7 +201,13 @@ let KernelLifecycle = class KernelLifecycle {
199
201
  if (this.shutdown.isShuttingDown())
200
202
  throw new Error("kernel stopped during start");
201
203
  }
202
- async onApplicationBootstrap() {
204
+ onApplicationBootstrap() {
205
+ // the start sequence (migrations, bootstrap, extension load, the gateway's connections) is
206
+ // deployment-wide work (RLS spec §5.1); what it starts keeps this scope until an entry point
207
+ // (a request, a job, a run, an event) enters its own
208
+ return asPlatform("kernel start sequence", () => this.startSequence());
209
+ }
210
+ async startSequence() {
203
211
  if (this.shutdown.isShuttingDown())
204
212
  throw new Error("kernel is stopped");
205
213
  const { config, options: opts } = this;
@@ -215,6 +223,13 @@ let KernelLifecycle = class KernelLifecycle {
215
223
  this.checkpoint();
216
224
  await sql `select 1`.execute(this.pool);
217
225
  this.checkpoint();
226
+ if (cfg().db.rls === "enforce") {
227
+ // never fails the start: enforcement is a backstop, and the operator decides
228
+ const problem = await rlsEnforceProblem(this.pool);
229
+ if (problem !== undefined) {
230
+ this.log.error(`db.rls is enforce, but ${problem}: PostgreSQL filters nothing by the org scope there`);
231
+ }
232
+ }
218
233
  // In flight for the stop: aborted when the shutdown begins, which then waits for its session to end
219
234
  await this.shutdown.trackInFlight(migrate(config.db.url, { schema: KERNEL_SCHEMA, dir: KERNEL_MIGRATIONS_DIR }, { connectTimeoutMs: config.db.connectTimeoutMs, signal: this.shutdown.signal }));
220
235
  this.checkpoint();
@@ -12,6 +12,7 @@ import { Reflector } from "@nestjs/core";
12
12
  import { ApiError } from "../errors.js";
13
13
  import { AllowService } from "../identity/principal.js";
14
14
  import { KernelDb } from "../infra/database/kernel-db.js";
15
+ import { bindRequestScope } from "../infra/database/org-scope.js";
15
16
  import { can, HUMAN_ONLY } from "./roles.js";
16
17
  export const ORG_ACTION_KEY = "capybara:org:action";
17
18
  /**
@@ -93,6 +94,9 @@ let OrgGuard = class OrgGuard {
93
94
  const orgId = req.params.orgId;
94
95
  if (!orgId)
95
96
  throw new Error("OrgGuard: route has no :orgId parameter");
97
+ // the request works in this org from here on (RLS spec §5.1), the role check included: it
98
+ // reads only this org's membership; a refused check ends the request
99
+ bindRequestScope({ kind: "org", orgId });
96
100
  const role = await authorizeOrgAction(this.db.db, p, orgId, action);
97
101
  req.org = { orgId, role };
98
102
  return true;
@@ -15,6 +15,7 @@ import { ApiError } from "../errors.js";
15
15
  import { audit } from "../identity/audit.js";
16
16
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
17
17
  import { KernelDb } from "../infra/database/kernel-db.js";
18
+ import { asPlatform } from "../infra/database/org-scope.js";
18
19
  import { TransactionHost } from "../infra/database/transaction-host.js";
19
20
  import { Transactional } from "../infra/database/transactional.decorator.js";
20
21
  import { KEYRING } from "../infra/tokens.js";
@@ -143,10 +144,12 @@ SealedReveals = __decorate([
143
144
  export { SealedReveals };
144
145
  /** Deletes the sealed reveals past `expires_at`; returns how many. */
145
146
  export async function deleteExpiredSealedReveals(db) {
146
- // org-filter: deployment-wide expiry sweep over every org's sealed reveals (maintenance job)
147
- const r = await db
148
- .deleteFrom("platform_sealed_reveals")
149
- .where("expires_at", "<=", sql `now()`)
150
- .executeTakeFirst();
151
- return Number(r.numDeletedRows);
147
+ return asPlatform("deployment-wide expiry sweep over every org's sealed reveals", async () => {
148
+ // org-filter: deployment-wide expiry sweep over every org's sealed reveals (maintenance job)
149
+ const r = await db
150
+ .deleteFrom("platform_sealed_reveals")
151
+ .where("expires_at", "<=", sql `now()`)
152
+ .executeTakeFirst();
153
+ return Number(r.numDeletedRows);
154
+ });
152
155
  }
@@ -13,6 +13,7 @@ import { BackgroundModule } from "../background/background.module.js";
13
13
  import { BG_WAKE_JOB } from "../background/wake-rules.js";
14
14
  import { OWNED_PLUGIN_CLEANUP_JOB } from "../catalog/job-ids.js";
15
15
  import { OwnedPluginCleanup, OwnedPluginCleanupModule } from "../catalog/owned-plugin-cleanup.js";
16
+ import { EventLogModule } from "../conversations/event-log.js";
16
17
  import { configuredProcessor } from "../infra/queue/configured-processor.js";
17
18
  import { QueueModule } from "../infra/queue/queue.module.js";
18
19
  import { runJob } from "../infra/queue/run-job.js";
@@ -97,7 +98,9 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
97
98
  this.snapshots = snapshots;
98
99
  }
99
100
  process(job, token) {
100
- return runJob(MAINTENANCE_QUEUE_NAME, job, () => this.dispatch(job, token));
101
+ return runJob(MAINTENANCE_QUEUE_NAME, job, () => this.dispatch(job, token), {
102
+ platform: "maintenance job (deployment-wide sweeps)",
103
+ });
101
104
  }
102
105
  /** Starts consuming (worker role, after the extensions loaded; built with `autorun: false`). */
103
106
  start() {
@@ -253,6 +256,8 @@ MaintenanceModule = __decorate([
253
256
  KernelScheduleModule,
254
257
  // the exact stop a revoked background start owes (SandboxOperationReconcileJob)
255
258
  BackgroundModule,
259
+ // the background list hint after reconciling a start (SandboxOperationReconcileJob)
260
+ EventLogModule,
256
261
  RuntimeModule,
257
262
  SandboxModule,
258
263
  ToolsModule,
@@ -68,6 +68,7 @@ export declare class RunExecution {
68
68
  constructor(db: KernelDb, xactLock: XactLock, txHost: TransactionHost);
69
69
  claim(conversationId: string, runId: string, executionId: string, live?: () => boolean): Promise<ExecutionClaim | null>;
70
70
  withClaim<T>(claim: ExecutionClaim, live: () => boolean, fn: () => Promise<T>): Promise<T>;
71
+ private claimed;
71
72
  /**
72
73
  * The admission (see the class), then the root and the current conversation; NO KEY UPDATE
73
74
  * allows foreign key references while excluding deletion and other writers. The root stays
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { AsyncLocalStorage } from "node:async_hooks";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { KernelDb } from "../infra/database/kernel-db.js";
13
+ import { withOrgScope } from "../infra/database/org-scope.js";
13
14
  import { TransactionHost, withTransactionFence } from "../infra/database/transaction-host.js";
14
15
  import { Transactional } from "../infra/database/transactional.decorator.js";
15
16
  import { XactLock } from "../infra/database/xact-lock.js";
@@ -113,6 +114,10 @@ let RunExecution = class RunExecution {
113
114
  return run ? claim : null;
114
115
  }
115
116
  withClaim(claim, live, fn) {
117
+ // the run works in its org (RLS spec §5.1): every query of the claimed run carries that scope
118
+ return withOrgScope(claim.orgId, () => this.claimed(claim, live, fn));
119
+ }
120
+ claimed(claim, live, fn) {
116
121
  return invocationClaim.run(Object.freeze({ ...claim }), () => withTransactionFence(async ({ shared, prelude }) => {
117
122
  const admitShared = shared && !exclusiveScope.getStore();
118
123
  if (prelude && admitShared)
@@ -12,6 +12,7 @@ import { sql } from "kysely";
12
12
  import { EventLog } from "../conversations/event-log.js";
13
13
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
14
  import { KernelDb } from "../infra/database/kernel-db.js";
15
+ import { asPlatform } from "../infra/database/org-scope.js";
15
16
  import { TransactionHost } from "../infra/database/transaction-host.js";
16
17
  import { Transactional } from "../infra/database/transactional.decorator.js";
17
18
  import { KernelEvents } from "../infra/events/kernel-events.js";
@@ -95,14 +96,16 @@ export async function orphanCandidates(db, statuses, minAgeMs, limit, after) {
95
96
  // org-filter: outbox rows looked up by queue and deterministic kernel job id (unique across the
96
97
  // deployment) in the deployment-wide orphan check; outbox.org_id is nullable
97
98
  export async function jobInOutbox(db, queue, jobId) {
98
- const row = await db
99
- .selectFrom("outbox")
100
- .select("id")
101
- .where("queue", "=", queue)
102
- .where("job_id", "=", jobId)
103
- .where("dead_at", "is", null)
104
- .executeTakeFirst();
105
- return row !== undefined;
99
+ return asPlatform("orphan check: outbox rows by kernel job id", async () => {
100
+ const row = await db
101
+ .selectFrom("outbox")
102
+ .select("id")
103
+ .where("queue", "=", queue)
104
+ .where("job_id", "=", jobId)
105
+ .where("dead_at", "is", null)
106
+ .executeTakeFirst();
107
+ return row !== undefined;
108
+ });
106
109
  }
107
110
  /** Every page of {@link orphanCandidates}, at most {@link RUN_ORPHAN_CHECK_MAX_PAGES}. */
108
111
  async function* candidatePages(db, statuses, minAgeMs, after) {
@@ -271,13 +274,15 @@ let RunOrphanCheck = class RunOrphanCheck {
271
274
  // org-filter: outbox rows looked up by queue and deterministic kernel job id (unique across the
272
275
  // deployment) in the deployment-wide orphan check; outbox.org_id is nullable
273
276
  async hasDeadDelivery(c) {
274
- return ((await this.db
275
- .selectFrom("outbox")
276
- .select("id")
277
- .where("queue", "=", c.queue)
278
- .where("job_id", "=", c.jobId)
279
- .where("dead_at", ">=", sql `${c.since}::timestamptz`)
280
- .executeTakeFirst()) !== undefined);
277
+ return asPlatform("orphan check: outbox rows by kernel job id", async () => {
278
+ return ((await this.db
279
+ .selectFrom("outbox")
280
+ .select("id")
281
+ .where("queue", "=", c.queue)
282
+ .where("job_id", "=", c.jobId)
283
+ .where("dead_at", ">=", sql `${c.since}::timestamptz`)
284
+ .executeTakeFirst()) !== undefined);
285
+ });
281
286
  }
282
287
  /**
283
288
  * Neither a conversation lock holder nor the run's job in BullMQ (nor, queued, in the outbox: an