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

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 (64) hide show
  1. package/dist/admin/outbox-dead.service.js +133 -120
  2. package/dist/background/store.js +78 -67
  3. package/dist/background/tasks.service.d.ts +6 -0
  4. package/dist/background/tasks.service.js +3 -0
  5. package/dist/catalog/marketplaces.service.d.ts +1 -1
  6. package/dist/catalog/plugin-import.js +45 -40
  7. package/dist/catalog/scope-sync-workers.js +3 -0
  8. package/dist/channels/inbound.d.ts +6 -1
  9. package/dist/channels/inbound.js +18 -1
  10. package/dist/client/client-reports.service.js +9 -6
  11. package/dist/config/schema.d.ts +5 -0
  12. package/dist/config/schema.js +6 -0
  13. package/dist/conversations/attachments.service.js +101 -96
  14. package/dist/conversations/events.d.ts +7 -0
  15. package/dist/conversations/events.js +9 -0
  16. package/dist/ctx/bus.js +5 -3
  17. package/dist/ctx/queue.js +4 -2
  18. package/dist/db/pool.d.ts +6 -0
  19. package/dist/db/pool.js +3 -2
  20. package/dist/devices/legacy-cleanup.job.js +73 -70
  21. package/dist/dial-in/gateway.d.ts +8 -0
  22. package/dist/dial-in/gateway.js +22 -2
  23. package/dist/extensions/admin-ops.js +22 -19
  24. package/dist/extensions/lifecycle-hooks.js +3 -1
  25. package/dist/http/app.js +3 -1
  26. package/dist/http/plugin-dispatch.js +8 -0
  27. package/dist/identity/auth.guard.js +13 -3
  28. package/dist/index.d.ts +2 -0
  29. package/dist/index.js +1 -0
  30. package/dist/infra/database/database.module.js +1 -0
  31. package/dist/infra/database/org-scope.d.ts +59 -0
  32. package/dist/infra/database/org-scope.js +68 -0
  33. package/dist/infra/database/rls-role.d.ts +11 -0
  34. package/dist/infra/database/rls-role.js +33 -0
  35. package/dist/infra/database/scoped-dialect.d.ts +18 -0
  36. package/dist/infra/database/scoped-dialect.js +245 -0
  37. package/dist/infra/outbox/outbox.dispatcher.js +98 -90
  38. package/dist/infra/outbox/outbox.service.js +29 -26
  39. package/dist/infra/queue/run-job.d.ts +8 -2
  40. package/dist/infra/queue/run-job.js +16 -3
  41. package/dist/infra/schedule/locked-tick.js +12 -4
  42. package/dist/infra/schedule/scheduled-runs.js +3 -1
  43. package/dist/lifecycle/kernel-lifecycle.d.ts +1 -0
  44. package/dist/lifecycle/kernel-lifecycle.js +16 -1
  45. package/dist/orgs/org.guard.js +4 -0
  46. package/dist/platform/sealed-reveals.js +9 -6
  47. package/dist/runtime/maintenance.js +6 -1
  48. package/dist/runtime/run-execution.d.ts +1 -0
  49. package/dist/runtime/run-execution.js +5 -0
  50. package/dist/runtime/run-orphan-check.job.js +20 -15
  51. package/dist/sandbox/legacy-retirement.js +438 -397
  52. package/dist/sandbox/modes.d.ts +10 -0
  53. package/dist/sandbox/modes.js +23 -0
  54. package/dist/sandbox/operation-reconcile.job.d.ts +14 -1
  55. package/dist/sandbox/operation-reconcile.job.js +35 -3
  56. package/dist/sandbox/permission-config-publication.js +83 -77
  57. package/dist/sandbox/sandbox.service.d.ts +24 -0
  58. package/dist/sandbox/sandbox.service.js +159 -62
  59. package/dist/schedules/store.js +17 -14
  60. package/dist/tools/builtins/sandbox/bash.js +16 -1
  61. package/dist/tools/drift.js +31 -24
  62. package/dist/tools/outputs.js +20 -17
  63. package/package.json +2 -2
  64. package/src/migrations/0182_rls_policies.sql +202 -0
@@ -14,6 +14,7 @@ import { audit } from "../identity/audit.js";
14
14
  import { SuperAdminLock } from "../identity/super-admin.js";
15
15
  import { afterCommit } from "../infra/database/after-commit.js";
16
16
  import { KernelDb } from "../infra/database/kernel-db.js";
17
+ import { asPlatform } from "../infra/database/org-scope.js";
17
18
  import { TransactionHost } from "../infra/database/transaction-host.js";
18
19
  import { Transactional } from "../infra/database/transactional.decorator.js";
19
20
  import { OUTBOX_FAST_PATH } from "../infra/outbox/outbox.service.js";
@@ -48,62 +49,66 @@ let OutboxDeadService = class OutboxDeadService {
48
49
  * first by `(dead_at, id)`; one extra row tells `next`. A malformed cursor is a validation error.
49
50
  */
50
51
  async list(q = {}) {
51
- const limit = Math.min(q.limit ?? OUTBOX_DEAD_LIST_MAX, OUTBOX_DEAD_LIST_MAX);
52
- const cursor = q.after === undefined ? null : decodeOutboxDeadCursor(q.after);
53
- if (q.after !== undefined && cursor === null) {
54
- throw new ApiError("validation_failed", "after must be a cursor from a previous page");
55
- }
56
- let query = this.db.db
57
- .selectFrom("outbox")
58
- .select([
59
- "id",
60
- "queue",
61
- "job_name",
62
- "job_id",
63
- "org_id",
64
- "attempts",
65
- "last_error",
66
- "dead_at",
67
- "created_at",
68
- // PG's own text keeps the microseconds a JS Date would cut
69
- sql `dead_at::text`.as("dead_at_text"),
70
- ])
71
- .where("dead_at", "is not", null);
72
- if (cursor !== null) {
73
- query = query.where(sql `(dead_at, id) > (${cursor.deadAt}::timestamptz, ${cursor.id}::bigint)`);
74
- }
75
- const rows = await query
76
- .orderBy("dead_at")
77
- .orderBy("id")
78
- .limit(limit + 1)
79
- .execute();
80
- const page = rows.slice(0, limit);
81
- const last = page.at(-1);
82
- return {
83
- next: rows.length > limit && last !== undefined
84
- ? encodeOutboxDeadCursor({ deadAt: last.dead_at_text, id: String(last.id) })
85
- : null,
86
- items: page.map((r) => ({
87
- id: String(r.id),
88
- queue: r.queue,
89
- jobName: r.job_name,
90
- jobId: r.job_id,
91
- orgId: r.org_id,
92
- attempts: r.attempts,
93
- lastError: r.last_error,
94
- deadAt: r.dead_at.toISOString(),
95
- createdAt: r.created_at.toISOString(),
96
- })),
97
- };
52
+ return asPlatform("super admin: the dead outbox rows of every org", async () => {
53
+ const limit = Math.min(q.limit ?? OUTBOX_DEAD_LIST_MAX, OUTBOX_DEAD_LIST_MAX);
54
+ const cursor = q.after === undefined ? null : decodeOutboxDeadCursor(q.after);
55
+ if (q.after !== undefined && cursor === null) {
56
+ throw new ApiError("validation_failed", "after must be a cursor from a previous page");
57
+ }
58
+ let query = this.db.db
59
+ .selectFrom("outbox")
60
+ .select([
61
+ "id",
62
+ "queue",
63
+ "job_name",
64
+ "job_id",
65
+ "org_id",
66
+ "attempts",
67
+ "last_error",
68
+ "dead_at",
69
+ "created_at",
70
+ // PG's own text keeps the microseconds a JS Date would cut
71
+ sql `dead_at::text`.as("dead_at_text"),
72
+ ])
73
+ .where("dead_at", "is not", null);
74
+ if (cursor !== null) {
75
+ query = query.where(sql `(dead_at, id) > (${cursor.deadAt}::timestamptz, ${cursor.id}::bigint)`);
76
+ }
77
+ const rows = await query
78
+ .orderBy("dead_at")
79
+ .orderBy("id")
80
+ .limit(limit + 1)
81
+ .execute();
82
+ const page = rows.slice(0, limit);
83
+ const last = page.at(-1);
84
+ return {
85
+ next: rows.length > limit && last !== undefined
86
+ ? encodeOutboxDeadCursor({ deadAt: last.dead_at_text, id: String(last.id) })
87
+ : null,
88
+ items: page.map((r) => ({
89
+ id: String(r.id),
90
+ queue: r.queue,
91
+ jobName: r.job_name,
92
+ jobId: r.job_id,
93
+ orgId: r.org_id,
94
+ attempts: r.attempts,
95
+ lastError: r.last_error,
96
+ deadAt: r.dead_at.toISOString(),
97
+ createdAt: r.created_at.toISOString(),
98
+ })),
99
+ };
100
+ });
98
101
  }
99
102
  /** How many rows are dead, and the oldest one's `dead_at`. */
100
103
  async summary() {
101
- const row = await this.db.db
102
- .selectFrom("outbox")
103
- .select([sql `count(*)`.as("count"), sql `min(dead_at)`.as("oldest")])
104
- .where("dead_at", "is not", null)
105
- .executeTakeFirstOrThrow();
106
- return { count: Number(row.count), oldestAt: row.oldest };
104
+ return asPlatform("super admin: the dead outbox rows of every org", async () => {
105
+ const row = await this.db.db
106
+ .selectFrom("outbox")
107
+ .select([sql `count(*)`.as("count"), sql `min(dead_at)`.as("oldest")])
108
+ .where("dead_at", "is not", null)
109
+ .executeTakeFirstOrThrow();
110
+ return { count: Number(row.count), oldestAt: row.oldest };
111
+ });
107
112
  }
108
113
  /**
109
114
  * Makes a dead row due again (`dead_at` cleared, no attempts, next attempt now) and hands it to
@@ -132,82 +137,90 @@ let OutboxDeadService = class OutboxDeadService {
132
137
  }
133
138
  }
134
139
  async retryOnce(id, actor, detail) {
135
- await this.adminLock.lockAndAuthorize(actor.accountId);
136
- await this.lockRunRetryIn(id);
137
- const row = await this.lockDead(id);
138
- const owed = await this.db.db
139
- .selectFrom("outbox")
140
- .select("id")
141
- .where("queue", "=", row.queue)
142
- .where("job_id", "=", row.job_id)
143
- .where("dead_at", "is", null)
144
- .executeTakeFirst();
145
- let outcome;
146
- if (owed) {
147
- await this.db.db.deleteFrom("outbox").where("id", "=", id).execute();
148
- outcome = "already_owed";
149
- }
150
- else {
151
- await this.db.db
152
- .updateTable("outbox")
153
- .set({ dead_at: null, attempts: 0, next_attempt_at: sql `now()` })
154
- .where("id", "=", id)
155
- .execute();
156
- outcome = "retried";
157
- afterCommit(() => this.fastPath([id]));
158
- }
159
- await this.audit("outbox.retried", id, row, actor, { ...detail, outcome });
160
- return { outcome };
140
+ return asPlatform("super admin: the dead outbox rows of every org", async () => {
141
+ await this.adminLock.lockAndAuthorize(actor.accountId);
142
+ await this.lockRunRetryIn(id);
143
+ const row = await this.lockDead(id);
144
+ const owed = await this.db.db
145
+ .selectFrom("outbox")
146
+ .select("id")
147
+ .where("queue", "=", row.queue)
148
+ .where("job_id", "=", row.job_id)
149
+ .where("dead_at", "is", null)
150
+ .executeTakeFirst();
151
+ let outcome;
152
+ if (owed) {
153
+ await this.db.db.deleteFrom("outbox").where("id", "=", id).execute();
154
+ outcome = "already_owed";
155
+ }
156
+ else {
157
+ await this.db.db
158
+ .updateTable("outbox")
159
+ .set({ dead_at: null, attempts: 0, next_attempt_at: sql `now()` })
160
+ .where("id", "=", id)
161
+ .execute();
162
+ outcome = "retried";
163
+ afterCommit(() => this.fastPath([id]));
164
+ }
165
+ await this.audit("outbox.retried", id, row, actor, { ...detail, outcome });
166
+ return { outcome };
167
+ });
161
168
  }
162
169
  /** A run-job retry is a new delivery generation, serialized with its terminal transition. */
163
170
  async lockRunRetryIn(id) {
164
- // Read before taking any outbox lock: the lock order is conversation, then outbox. The
165
- // subsequent lockDead rechecks this row, so a concurrent discard/retry rolls this back.
166
- const row = await this.db
167
- .selectFrom("outbox")
168
- .select(["job_name", "job_id", "data"])
169
- .where("id", "=", id)
170
- .where("dead_at", "is not", null)
171
- .executeTakeFirst();
172
- if (row?.job_name !== "run" || row.data === null || typeof row.data !== "object")
173
- return;
174
- const data = row.data;
175
- if (typeof data.conversationId !== "string" || typeof data.runId !== "string")
176
- return;
177
- await this.db
178
- .selectFrom("conversations")
179
- .select("id")
180
- .where("id", "=", data.conversationId)
181
- .forUpdate()
182
- .execute();
183
- await this.db
184
- .updateTable("runs")
185
- .set({ queued_at: sql `clock_timestamp()` })
186
- .where("id", "=", data.runId)
187
- .where("conversation_id", "=", data.conversationId)
188
- .where("status", "=", "queued")
189
- .where(sql `COALESCE(job_id, 'run-' || conversation_id || '-' || trigger_seq::text) = ${row.job_id}`)
190
- .execute();
171
+ return asPlatform("super admin: the dead outbox rows of every org", async () => {
172
+ // Read before taking any outbox lock: the lock order is conversation, then outbox. The
173
+ // subsequent lockDead rechecks this row, so a concurrent discard/retry rolls this back.
174
+ const row = await this.db
175
+ .selectFrom("outbox")
176
+ .select(["job_name", "job_id", "data"])
177
+ .where("id", "=", id)
178
+ .where("dead_at", "is not", null)
179
+ .executeTakeFirst();
180
+ if (row?.job_name !== "run" || row.data === null || typeof row.data !== "object")
181
+ return;
182
+ const data = row.data;
183
+ if (typeof data.conversationId !== "string" || typeof data.runId !== "string")
184
+ return;
185
+ await this.db
186
+ .selectFrom("conversations")
187
+ .select("id")
188
+ .where("id", "=", data.conversationId)
189
+ .forUpdate()
190
+ .execute();
191
+ await this.db
192
+ .updateTable("runs")
193
+ .set({ queued_at: sql `clock_timestamp()` })
194
+ .where("id", "=", data.runId)
195
+ .where("conversation_id", "=", data.conversationId)
196
+ .where("status", "=", "queued")
197
+ .where(sql `COALESCE(job_id, 'run-' || conversation_id || '-' || trigger_seq::text) = ${row.job_id}`)
198
+ .execute();
199
+ });
191
200
  }
192
201
  /** Deletes a dead row: its job is never delivered. `outbox.not_found` (404) when none. */
193
202
  async discard(id, actor, detail = {}) {
194
- await this.adminLock.lockAndAuthorize(actor.accountId);
195
- const row = await this.lockDead(id);
196
- await this.db.db.deleteFrom("outbox").where("id", "=", id).execute();
197
- await this.audit("outbox.discarded", id, row, actor, detail);
203
+ return asPlatform("super admin: the dead outbox rows of every org", async () => {
204
+ await this.adminLock.lockAndAuthorize(actor.accountId);
205
+ const row = await this.lockDead(id);
206
+ await this.db.db.deleteFrom("outbox").where("id", "=", id).execute();
207
+ await this.audit("outbox.discarded", id, row, actor, detail);
208
+ });
198
209
  }
199
210
  /** The dead row `id`, locked for the transaction; `outbox.not_found` when it is not dead. */
200
211
  async lockDead(id) {
201
- const row = await this.db.db
202
- .selectFrom("outbox")
203
- .select(["queue", "job_name", "job_id", "org_id", "attempts", "last_error"])
204
- .where("id", "=", id)
205
- .where("dead_at", "is not", null)
206
- .forUpdate()
207
- .executeTakeFirst();
208
- if (!row)
209
- throw notFound(id);
210
- return row;
212
+ return asPlatform("super admin: the dead outbox rows of every org", async () => {
213
+ const row = await this.db.db
214
+ .selectFrom("outbox")
215
+ .select(["queue", "job_name", "job_id", "org_id", "attempts", "last_error"])
216
+ .where("id", "=", id)
217
+ .where("dead_at", "is not", null)
218
+ .forUpdate()
219
+ .executeTakeFirst();
220
+ if (!row)
221
+ throw notFound(id);
222
+ return row;
223
+ });
211
224
  }
212
225
  /**
213
226
  * A platform-level audit event (no org: the outbox is the deployment's), naming the job. The
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
12
  import { KernelDb } from "../infra/database/kernel-db.js";
13
+ import { asPlatform } from "../infra/database/org-scope.js";
13
14
  import { TransactionHost } from "../infra/database/transaction-host.js";
14
15
  import { Transactional } from "../infra/database/transactional.decorator.js";
15
16
  import { BackgroundLaunchLock } from "./launch-lock.js";
@@ -196,30 +197,32 @@ let BackgroundTaskStore = class BackgroundTaskStore {
196
197
  // org-filter: deployment-wide background-task poller sweep across all orgs; each row is
197
198
  // handled in its own org
198
199
  async failAbandonedLaunches(before) {
199
- const r = await this.db
200
- .updateTable("background_tasks")
201
- .set({
202
- status: "failed",
203
- finished_at: sql `now()`,
204
- lost_reason: "launch_abandoned",
205
- stopping_at: null,
206
- // a managed reservation that never dispatched settles; dispatch is conditional on
207
- // `pending`, so a launch racing this update either wins or is refused before effects
208
- launch_state: sql `CASE WHEN launch_state = 'pending' THEN 'terminal' ELSE launch_state END`,
209
- })
210
- .where("status", "=", "running")
211
- .where("sid", "is", null)
212
- // never a dispatched, acknowledged or cancel-pending managed task
213
- .where("launch_state", "in", ["legacy", "pending"])
214
- .where(unclaimed)
215
- .where("started_at", "<", before)
216
- .returning(["id", "conversation_id", "sandbox_conversation_id"])
217
- .execute();
218
- return r.map((x) => ({
219
- id: x.id,
220
- conversationId: x.conversation_id,
221
- sandboxConversationId: x.sandbox_conversation_id,
222
- }));
200
+ return asPlatform("deployment-wide background-task poller sweep across all orgs", async () => {
201
+ const r = await this.db
202
+ .updateTable("background_tasks")
203
+ .set({
204
+ status: "failed",
205
+ finished_at: sql `now()`,
206
+ lost_reason: "launch_abandoned",
207
+ stopping_at: null,
208
+ // a managed reservation that never dispatched settles; dispatch is conditional on
209
+ // `pending`, so a launch racing this update either wins or is refused before effects
210
+ launch_state: sql `CASE WHEN launch_state = 'pending' THEN 'terminal' ELSE launch_state END`,
211
+ })
212
+ .where("status", "=", "running")
213
+ .where("sid", "is", null)
214
+ // never a dispatched, acknowledged or cancel-pending managed task
215
+ .where("launch_state", "in", ["legacy", "pending"])
216
+ .where(unclaimed)
217
+ .where("started_at", "<", before)
218
+ .returning(["id", "conversation_id", "sandbox_conversation_id"])
219
+ .execute();
220
+ return r.map((x) => ({
221
+ id: x.id,
222
+ conversationId: x.conversation_id,
223
+ sandboxConversationId: x.sandbox_conversation_id,
224
+ }));
225
+ });
223
226
  }
224
227
  /**
225
228
  * Inserts a legacy row: no launch writes one any more; only rows from before (and tests of their
@@ -308,17 +311,19 @@ let BackgroundTaskStore = class BackgroundTaskStore {
308
311
  // org-filter: deployment-wide background-task poller sweep across all orgs; each row is
309
312
  // handled in its own org
310
313
  async runningLegacy() {
311
- const rows = await this.db
312
- .selectFrom("background_tasks")
313
- .selectAll()
314
- .where("status", "=", "running")
315
- .where("launch_state", "=", "legacy")
316
- .where("sandbox_created_at", "is not", null)
317
- .where(unclaimed)
318
- .orderBy("started_at", "asc")
319
- .orderBy("id", "asc")
320
- .execute();
321
- return rows.map(toRow);
314
+ return asPlatform("deployment-wide background-task poller sweep across all orgs", async () => {
315
+ const rows = await this.db
316
+ .selectFrom("background_tasks")
317
+ .selectAll()
318
+ .where("status", "=", "running")
319
+ .where("launch_state", "=", "legacy")
320
+ .where("sandbox_created_at", "is not", null)
321
+ .where(unclaimed)
322
+ .orderBy("started_at", "asc")
323
+ .orderBy("id", "asc")
324
+ .execute();
325
+ return rows.map(toRow);
326
+ });
322
327
  }
323
328
  /**
324
329
  * Every running acknowledged managed task with no live stop claim, oldest first: what the
@@ -327,17 +332,19 @@ let BackgroundTaskStore = class BackgroundTaskStore {
327
332
  // org-filter: deployment-wide background-task poller sweep across all orgs; each row is
328
333
  // handled in its own org
329
334
  async runningManaged() {
330
- const rows = await this.db
331
- .selectFrom("background_tasks")
332
- .selectAll()
333
- .where("status", "=", "running")
334
- .where("launch_state", "=", "acknowledged")
335
- .where("execution_ref", "is not", null)
336
- .where(unclaimed)
337
- .orderBy("started_at", "asc")
338
- .orderBy("id", "asc")
339
- .execute();
340
- return rows.map(toRow);
335
+ return asPlatform("deployment-wide background-task poller sweep across all orgs", async () => {
336
+ const rows = await this.db
337
+ .selectFrom("background_tasks")
338
+ .selectAll()
339
+ .where("status", "=", "running")
340
+ .where("launch_state", "=", "acknowledged")
341
+ .where("execution_ref", "is not", null)
342
+ .where(unclaimed)
343
+ .orderBy("started_at", "asc")
344
+ .orderBy("id", "asc")
345
+ .execute();
346
+ return rows.map(toRow);
347
+ });
341
348
  }
342
349
  /**
343
350
  * The running managed tasks that owe an exact stop (`cancel-pending` with a ref, no live stop
@@ -347,20 +354,22 @@ let BackgroundTaskStore = class BackgroundTaskStore {
347
354
  // org-filter: deployment-wide background-task poller sweep across all orgs; each row is
348
355
  // handled in its own org
349
356
  async owedCancels() {
350
- const rows = await this.db
351
- .selectFrom("background_tasks")
352
- .selectAll("background_tasks")
353
- .leftJoin("device_instances", "device_instances.device_id", "background_tasks.device_id")
354
- .where("background_tasks.status", "=", "running")
355
- .where("background_tasks.launch_state", "=", "cancel-pending")
356
- .where("background_tasks.execution_ref", "is not", null)
357
- .where(sql `(background_tasks.stopping_at IS NULL OR background_tasks.stopping_at < now() - ${STOP_CLAIM_TTL_MS}::integer * interval '1 millisecond')`)
358
- .where(sql `NOT (device_instances.status IS NOT DISTINCT FROM 'suspended' AND floor(extract(epoch from device_instances.created_at) * 1000)::bigint::text = background_tasks.instance_generation)`)
359
- .orderBy(sql `background_tasks.cancel_attempted_at ASC NULLS FIRST`)
360
- .orderBy("background_tasks.started_at", "asc")
361
- .orderBy("background_tasks.id", "asc")
362
- .execute();
363
- return rows.map(toRow);
357
+ return asPlatform("deployment-wide background-task poller sweep across all orgs", async () => {
358
+ const rows = await this.db
359
+ .selectFrom("background_tasks")
360
+ .selectAll("background_tasks")
361
+ .leftJoin("device_instances", "device_instances.device_id", "background_tasks.device_id")
362
+ .where("background_tasks.status", "=", "running")
363
+ .where("background_tasks.launch_state", "=", "cancel-pending")
364
+ .where("background_tasks.execution_ref", "is not", null)
365
+ .where(sql `(background_tasks.stopping_at IS NULL OR background_tasks.stopping_at < now() - ${STOP_CLAIM_TTL_MS}::integer * interval '1 millisecond')`)
366
+ .where(sql `NOT (device_instances.status IS NOT DISTINCT FROM 'suspended' AND floor(extract(epoch from device_instances.created_at) * 1000)::bigint::text = background_tasks.instance_generation)`)
367
+ .orderBy(sql `background_tasks.cancel_attempted_at ASC NULLS FIRST`)
368
+ .orderBy("background_tasks.started_at", "asc")
369
+ .orderBy("background_tasks.id", "asc")
370
+ .execute();
371
+ return rows.map(toRow);
372
+ });
364
373
  }
365
374
  /** Records that an exact stop of the task is being attempted now (its owed-stop turn moves back). */
366
375
  // org-filter: by task id: callers check ownership first (ownedTask: the calling conversation;
@@ -524,13 +533,15 @@ let BackgroundTaskStore = class BackgroundTaskStore {
524
533
  */
525
534
  // org-filter: deployment-wide retention sweep across all orgs (finished rows past their age)
526
535
  async pruneFinished(before) {
527
- const r = await this.db
528
- .deleteFrom("background_tasks")
529
- .where("status", "<>", "running")
530
- .where("launch_state", "in", ["legacy", "terminal"])
531
- .where("finished_at", "<", before)
532
- .executeTakeFirst();
533
- return Number(r.numDeletedRows);
536
+ return asPlatform("deployment-wide retention sweep across all orgs", async () => {
537
+ const r = await this.db
538
+ .deleteFrom("background_tasks")
539
+ .where("status", "<>", "running")
540
+ .where("launch_state", "in", ["legacy", "terminal"])
541
+ .where("finished_at", "<", before)
542
+ .executeTakeFirst();
543
+ return Number(r.numDeletedRows);
544
+ });
534
545
  }
535
546
  };
536
547
  __decorate([
@@ -26,6 +26,12 @@ export interface BackgroundTaskView {
26
26
  finishedAt: string | null;
27
27
  /** True while a stop has claimed the task and it is still running. */
28
28
  stopping: boolean;
29
+ /**
30
+ * True while the task's start was sent but not yet confirmed (a managed launch without its
31
+ * exact ref, still `running`): the kernel is reconciling it under its original identity, and it
32
+ * either becomes a confirmed running task or ends (`lost` when given up).
33
+ */
34
+ starting: boolean;
29
35
  }
30
36
  /**
31
37
  * Why a task's output cannot be read live: `starting` (the start has not been acknowledged with
@@ -90,6 +90,9 @@ let BackgroundTasks = class BackgroundTasks {
90
90
  // a managed task's owed cancellation is a stop in progress too
91
91
  stopping: task.status === "running" &&
92
92
  (task.stoppingAt !== null || task.launchState === "cancel-pending"),
93
+ starting: task.status === "running" &&
94
+ task.executionRef === null &&
95
+ (task.launchState === "pending" || task.launchState === "dispatched"),
93
96
  };
94
97
  }
95
98
  async owned(orgId, conversationId, accountId, taskId) {
@@ -208,7 +208,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
208
208
  /** The host versions (an entry's `minKernel` is judged against them). */
209
209
  export declare const HOST_VERSIONS: {
210
210
  readonly kernel: string;
211
- readonly sdk: "0.1.0-rc.66";
211
+ readonly sdk: "0.1.0-rc.67";
212
212
  };
213
213
  /** Whether this deployment satisfies the entry's `minKernel`. */
214
214
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;