@thready-web/dsh-bot-plugin 0.1.0-beta.1 → 0.1.0-beta.10

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 (144) hide show
  1. package/README.md +109 -1
  2. package/client.js +646 -621
  3. package/dist/approvals.js +160 -0
  4. package/dist/authorization.js +225 -0
  5. package/dist/cli.js +32 -12
  6. package/dist/context.js +59 -17
  7. package/dist/cron.js +1 -1
  8. package/dist/cua-access.js +79 -0
  9. package/dist/desk.js +314 -37
  10. package/dist/engine.js +178 -84
  11. package/dist/fs-safe.js +1 -1
  12. package/dist/host.js +1 -0
  13. package/dist/http-plugin.js +14 -4
  14. package/dist/http.js +383 -85
  15. package/dist/inbox.js +51 -40
  16. package/dist/index.js +190 -47
  17. package/dist/live-diff.js +3 -1
  18. package/dist/live-snapshot.js +2 -13
  19. package/dist/log/canonical.js +37 -0
  20. package/dist/log/plan.js +62 -0
  21. package/dist/log/routes.js +144 -0
  22. package/dist/log/snapshot-service.js +76 -0
  23. package/dist/log/source.js +173 -0
  24. package/dist/memory-catalog.js +798 -0
  25. package/dist/permissions.js +86 -0
  26. package/dist/provision.js +2 -0
  27. package/dist/questions.js +407 -0
  28. package/dist/runtime-registry.js +4 -4
  29. package/dist/session-files.js +2 -2
  30. package/dist/session-previews.js +5 -1
  31. package/dist/store.js +20 -5
  32. package/dist/tools.js +150 -32
  33. package/dist/triggers.js +83 -39
  34. package/dist/work-admit.js +222 -25
  35. package/dist/work-child.js +17 -9
  36. package/dist/work-http.js +33 -2
  37. package/dist/work-ledger.js +256 -16
  38. package/dist/work-mock-host.js +9 -6
  39. package/dist/work-mock.js +29 -19
  40. package/dist/work-tickets.js +423 -96
  41. package/dist/work-tools.js +43 -6
  42. package/dist/work-worker.js +1028 -207
  43. package/dist/workspace-files.js +319 -0
  44. package/dist/workspace-image.js +91 -0
  45. package/fixtures/mock-llm.mjs +17 -2
  46. package/package.json +15 -5
  47. package/public/assets/SourceEditor-BEQaScgR.js +669 -0
  48. package/public/assets/SourceEditor-CJwK846Z.css +1 -0
  49. package/public/assets/abap-CRCWOmpq.js +1 -0
  50. package/public/assets/apex-DnsZk_dE.js +1 -0
  51. package/public/assets/azcli-1IWB1ccx.js +1 -0
  52. package/public/assets/bat-DPkNLes8.js +1 -0
  53. package/public/assets/bicep-Corcdgou.js +2 -0
  54. package/public/assets/cameligo-CGrWLZr3.js +1 -0
  55. package/public/assets/clojure-D9WOWImG.js +1 -0
  56. package/public/assets/codicon-DCmgc-ay.ttf +0 -0
  57. package/public/assets/coffee-B7EJu28W.js +1 -0
  58. package/public/assets/cpp-SEyurbux.js +1 -0
  59. package/public/assets/csharp-BoL64M5l.js +1 -0
  60. package/public/assets/csp-C46ZqvIl.js +1 -0
  61. package/public/assets/css-DQU6DXDx.js +3 -0
  62. package/public/assets/css.worker-DYpkewsP.js +79 -0
  63. package/public/assets/cssMode-gpcjCFFS.js +4 -0
  64. package/public/assets/cypher-D84EuPTj.js +1 -0
  65. package/public/assets/dart-D8lhlL1r.js +1 -0
  66. package/public/assets/dockerfile-DLk6rpji.js +1 -0
  67. package/public/assets/ecl-BO6FnfXk.js +1 -0
  68. package/public/assets/editor.worker-B4pQIWZD.js +12 -0
  69. package/public/assets/elixir-BRjLKONM.js +1 -0
  70. package/public/assets/flow9-Cac8vKd7.js +1 -0
  71. package/public/assets/freemarker2-C1qemGIt.js +3 -0
  72. package/public/assets/fsharp-fd1GTHhf.js +1 -0
  73. package/public/assets/go-O9LJTZXk.js +1 -0
  74. package/public/assets/graphql-LQdxqEYJ.js +1 -0
  75. package/public/assets/handlebars-sZqIfAlP.js +1 -0
  76. package/public/assets/hcl-DxDQ3s82.js +1 -0
  77. package/public/assets/html-Bn1WXB8L.js +1 -0
  78. package/public/assets/html.worker-tnXziJOq.js +456 -0
  79. package/public/assets/htmlMode-CvQyXnaW.js +4 -0
  80. package/public/assets/index-DRNkUrer.css +1 -0
  81. package/public/assets/index-DhL5Kdlz.js +63 -0
  82. package/public/assets/ini-BvajGCUy.js +1 -0
  83. package/public/assets/java-SYsfObOQ.js +1 -0
  84. package/public/assets/javascript-Ox4Jg12j.js +1 -0
  85. package/public/assets/json.worker-aFakAbRR.js +44 -0
  86. package/public/assets/jsonMode-DMR7R2dQ.js +10 -0
  87. package/public/assets/julia-DQXNmw_w.js +1 -0
  88. package/public/assets/kotlin-qQ0MG-9I.js +1 -0
  89. package/public/assets/less-GGFNNJHn.js +2 -0
  90. package/public/assets/lexon-Canl7DCW.js +1 -0
  91. package/public/assets/liquid-B6HxtpBd.js +1 -0
  92. package/public/assets/lua-D28Ae8-K.js +1 -0
  93. package/public/assets/m3-DPitgjJI.js +1 -0
  94. package/public/assets/markdown-B811l8j2.js +1 -0
  95. package/public/assets/mdx--jDhmrXq.js +1 -0
  96. package/public/assets/mips-CdjsipkG.js +1 -0
  97. package/public/assets/msdax-CYqgjx_P.js +1 -0
  98. package/public/assets/mysql-BHd6q0vd.js +1 -0
  99. package/public/assets/objective-c-B1aVtJYH.js +1 -0
  100. package/public/assets/pascal-BhNW15KB.js +1 -0
  101. package/public/assets/pascaligo-5jv8CcQD.js +1 -0
  102. package/public/assets/perl-DlYyT36c.js +1 -0
  103. package/public/assets/pgsql-Dy0bjov7.js +1 -0
  104. package/public/assets/php-120yhfDK.js +1 -0
  105. package/public/assets/pla-CjnFlu4u.js +1 -0
  106. package/public/assets/postiats-CQpG440k.js +1 -0
  107. package/public/assets/powerquery-DdJtto1Z.js +1 -0
  108. package/public/assets/powershell-Bu_VLpJB.js +1 -0
  109. package/public/assets/protobuf-IBS6jZEB.js +2 -0
  110. package/public/assets/pug-kFxLfcjb.js +1 -0
  111. package/public/assets/python-YjG50skX.js +1 -0
  112. package/public/assets/qsharp-q7JyzKFN.js +1 -0
  113. package/public/assets/r-BIFz-_sK.js +1 -0
  114. package/public/assets/razor-CEcFE3UK.js +1 -0
  115. package/public/assets/redis-CHOsPHWR.js +1 -0
  116. package/public/assets/redshift-CBifECDb.js +1 -0
  117. package/public/assets/restructuredtext-CghPJEOS.js +1 -0
  118. package/public/assets/ruby-CYWGW-b1.js +1 -0
  119. package/public/assets/rust-DMDD0SHb.js +1 -0
  120. package/public/assets/sb-BYAiYHFx.js +1 -0
  121. package/public/assets/scala-Bqvq8jcR.js +1 -0
  122. package/public/assets/scheme-Dhb-2j9p.js +1 -0
  123. package/public/assets/scss-CTwUZ5N7.js +3 -0
  124. package/public/assets/shell-CsDZo4DB.js +1 -0
  125. package/public/assets/solidity-CME5AdoB.js +1 -0
  126. package/public/assets/sophia-RYC1BQQz.js +1 -0
  127. package/public/assets/sparql-KEyrF7De.js +1 -0
  128. package/public/assets/sql-BdTr02Mf.js +1 -0
  129. package/public/assets/st-C7iG7M4S.js +1 -0
  130. package/public/assets/swift-D7IUmUK8.js +1 -0
  131. package/public/assets/systemverilog-DgMryOEJ.js +1 -0
  132. package/public/assets/tcl-PloMZuKG.js +1 -0
  133. package/public/assets/ts.worker-Bij5J2kb.js +51316 -0
  134. package/public/assets/tsMode-g4kTQl09.js +11 -0
  135. package/public/assets/twig-BfRIq3la.js +1 -0
  136. package/public/assets/typescript-CnHeFmPW.js +1 -0
  137. package/public/assets/typespec-CzxlYoT_.js +1 -0
  138. package/public/assets/vb-BwAE3J76.js +1 -0
  139. package/public/assets/wgsl-B_1kOXbF.js +298 -0
  140. package/public/assets/xml-BFXMY9nb.js +1 -0
  141. package/public/assets/yaml-DNm87nSf.js +1 -0
  142. package/public/index.html +2 -2
  143. package/public/assets/index-Be82iGwe.css +0 -1
  144. package/public/assets/index-ByU9a3Lh.js +0 -61
@@ -3,6 +3,10 @@ import { join } from 'node:path';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import { sha256 } from "./fs-safe.js";
5
5
  export const ACTIVE_TICKET = Object.freeze(['accepted', 'enqueued', 'started', 'needs_user']);
6
+ /** Tickets that occupy a running execution slot, plus reserved starts stored as slot=held. */
7
+ export const SLOT_TICKET = Object.freeze(['enqueued', 'started']);
8
+ /** Cap on how long an accepted/needs_user ticket may occupy a reserved start slot. */
9
+ export const RESERVE_WALL_MS = 10 * 60 * 1000;
6
10
  const TERMINAL_KIND = new Set(['question', 'result', 'failure']);
7
11
  const OPEN_NOTICE_FLUSH = new Set(['intent', 'flushing', 'ambiguous']);
8
12
  /**
@@ -14,10 +18,23 @@ const OPEN_NOTICE_FLUSH = new Set(['intent', 'flushing', 'ambiguous']);
14
18
  */
15
19
  export function createTicketBook(db, root, now = () => new Date()) {
16
20
  const iso = () => now().toISOString();
21
+ const SLOT_SQL = `status IN ('enqueued','started')
22
+ OR (status IN ('accepted','needs_user') AND json_extract(budget_json, '$.slot') = 'held')`;
23
+ const QUEUE_SQL = `status = 'accepted'
24
+ AND (json_extract(budget_json, '$.slot') IS NULL OR json_extract(budget_json, '$.slot') != 'held')`;
17
25
  return {
18
26
  iso,
19
27
  countActive,
20
28
  countGlobal,
29
+ countSlots,
30
+ countGlobalSlots,
31
+ countQueued,
32
+ countGlobalQueued,
33
+ slotHeld,
34
+ reserveSlot,
35
+ releaseSlot,
36
+ nextPromotable,
37
+ heldStarts,
21
38
  ticket: (id) => row('SELECT * FROM work_tickets WHERE id = ?', id),
22
39
  attempt: (id) => row('SELECT * FROM work_attempts WHERE id = ?', id),
23
40
  byIdempotency,
@@ -71,6 +88,8 @@ export function createTicketBook(db, root, now = () => new Date()) {
71
88
  attemptsOf,
72
89
  ownerIds,
73
90
  childIds,
91
+ ownerIdsForReconcile,
92
+ childIdsForReconcile,
74
93
  };
75
94
  /**
76
95
  * @param {string} sql
@@ -83,16 +102,112 @@ export function createTicketBook(db, root, now = () => new Date()) {
83
102
  * @param {string} owner
84
103
  */
85
104
  function countActive(owner) {
86
- return db.prepare(`
105
+ return db
106
+ .prepare(`
87
107
  SELECT COUNT(*) AS n FROM work_tickets
88
108
  WHERE owner_session_id = ? AND status IN ('accepted','enqueued','started','needs_user')
89
- `).get(owner).n;
109
+ `)
110
+ .get(owner).n;
90
111
  }
91
112
  function countGlobal() {
92
- return db.prepare(`
113
+ return db
114
+ .prepare(`
93
115
  SELECT COUNT(*) AS n FROM work_tickets
94
116
  WHERE status IN ('accepted','enqueued','started','needs_user')
95
- `).get().n;
117
+ `)
118
+ .get().n;
119
+ }
120
+ /**
121
+ * Running execution slots for one bot. needs_user does not count unless a
122
+ * resume has already reserved a slot.
123
+ * @param {string} owner
124
+ */
125
+ function countSlots(owner) {
126
+ return db.prepare(`SELECT COUNT(*) AS n FROM work_tickets WHERE owner_session_id = ? AND (${SLOT_SQL})`).get(owner)
127
+ .n;
128
+ }
129
+ function countGlobalSlots() {
130
+ return db.prepare(`SELECT COUNT(*) AS n FROM work_tickets WHERE ${SLOT_SQL}`).get().n;
131
+ }
132
+ /**
133
+ * Accepted tickets waiting for a slot. A reserved start is not queued.
134
+ * @param {string} owner
135
+ */
136
+ function countQueued(owner) {
137
+ return db.prepare(`SELECT COUNT(*) AS n FROM work_tickets WHERE owner_session_id = ? AND ${QUEUE_SQL}`).get(owner).n;
138
+ }
139
+ function countGlobalQueued() {
140
+ return db.prepare(`SELECT COUNT(*) AS n FROM work_tickets WHERE ${QUEUE_SQL}`).get().n;
141
+ }
142
+ /**
143
+ * @param {{ budget_json?: string } | null | undefined} ticket
144
+ */
145
+ function slotHeld(ticket) {
146
+ return budgetObject(ticket ?? {}).slot === 'held';
147
+ }
148
+ /**
149
+ * Reserve a running slot on an accepted or needs_user ticket. Returns null
150
+ * when the ticket is missing or already terminal.
151
+ * @param {string} ticketId
152
+ */
153
+ function reserveSlot(ticketId) {
154
+ const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
155
+ if (!ticket)
156
+ return null;
157
+ if (ticket.status === 'cancelled' || ticket.status === 'failed' || ticket.status === 'delivered')
158
+ return ticket;
159
+ if (ticket.status === 'enqueued' || ticket.status === 'started' || slotHeld(ticket))
160
+ return ticket;
161
+ const budget = { ...budgetObject(ticket), slot: 'held' };
162
+ db.prepare(`UPDATE work_tickets SET budget_json = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(budget), iso(), ticketId);
163
+ return row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
164
+ }
165
+ /**
166
+ * @param {string} ticketId
167
+ */
168
+ function releaseSlot(ticketId) {
169
+ const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
170
+ if (!ticket || !slotHeld(ticket))
171
+ return ticket;
172
+ const budget = budgetObject(ticket);
173
+ delete budget.slot;
174
+ db.prepare(`UPDATE work_tickets SET budget_json = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(budget), iso(), ticketId);
175
+ return row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
176
+ }
177
+ /**
178
+ * Oldest ticket that can take a newly freed slot: a queued accept, a reserved
179
+ * start that has not reached enqueued, or a needs_user resume with unflushed input.
180
+ * FIFO is created_at, then SQLite rowid (insertion order), not ticket id.
181
+ * The caller still checks per-bot and global slot caps before reserveSlot.
182
+ */
183
+ function nextPromotable() {
184
+ return db
185
+ .prepare(`
186
+ SELECT t.* FROM work_tickets t
187
+ LEFT JOIN work_attempts a ON a.id = t.active_attempt_id
188
+ LEFT JOIN work_inputs i ON i.id = a.current_input_id
189
+ WHERE t.status = 'accepted'
190
+ OR (t.status IN ('accepted','needs_user') AND json_extract(t.budget_json, '$.slot') = 'held')
191
+ OR (
192
+ t.status = 'needs_user'
193
+ AND t.child_session_id IS NOT NULL
194
+ AND i.flush_status IN ('intent','ambiguous')
195
+ )
196
+ ORDER BY t.created_at ASC, t.rowid ASC
197
+ `)
198
+ .all();
199
+ }
200
+ /**
201
+ * Reserved starts that still need create/flush after a crash or a mid-start return.
202
+ */
203
+ function heldStarts() {
204
+ return db
205
+ .prepare(`
206
+ SELECT * FROM work_tickets
207
+ WHERE status IN ('accepted','needs_user') AND json_extract(budget_json, '$.slot') = 'held'
208
+ ORDER BY created_at ASC, rowid ASC
209
+ `)
210
+ .all();
96
211
  }
97
212
  /**
98
213
  * @param {string} owner
@@ -101,17 +216,21 @@ export function createTicketBook(db, root, now = () => new Date()) {
101
216
  function byIdempotency(owner, key) {
102
217
  if (key == null)
103
218
  return null;
104
- return db.prepare(`
219
+ return (db
220
+ .prepare(`
105
221
  SELECT * FROM work_tickets WHERE owner_session_id = ? AND idempotency_key = ?
106
- `).get(owner, key) ?? null;
222
+ `)
223
+ .get(owner, key) ?? null);
107
224
  }
108
225
  /**
109
226
  * @param {string} sessionId
110
227
  */
111
228
  function attemptForChild(sessionId) {
112
- return db.prepare(`
229
+ return (db
230
+ .prepare(`
113
231
  SELECT * FROM work_attempts WHERE child_session_id = ? ORDER BY fencing_token DESC LIMIT 1
114
- `).get(sessionId) ?? null;
232
+ `)
233
+ .get(sessionId) ?? null);
115
234
  }
116
235
  /**
117
236
  * @param {string} nativeId
@@ -175,23 +294,43 @@ export function createTicketBook(db, root, now = () => new Date()) {
175
294
  cancel_requested_revision, created_at, updated_at
176
295
  ) VALUES (?, ?, NULL, 1, 1, 'accepted', 'none', ?, ?, ?, ?, NULL, ?, NULL, ?, ?)
177
296
  `).run(ticketId, input.owner, attemptId, hash, input.correlationId ?? '', input.idempotencyKey, JSON.stringify(input.budget), stamp, stamp);
178
- return { ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId), attempt: row('SELECT * FROM work_attempts WHERE id = ?', attemptId) };
297
+ return {
298
+ ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId),
299
+ attempt: row('SELECT * FROM work_attempts WHERE id = ?', attemptId),
300
+ };
179
301
  }
180
302
  /**
181
303
  * @param {string} ticketId
182
304
  * @param {string} childSessionId
183
305
  */
184
- function setChildIfEmpty(ticketId, childSessionId) {
306
+ function setChildIfEmpty(ticketId, childSessionId, expected) {
185
307
  const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
186
- if (!ticket || ticket.child_session_id)
187
- return ticket;
308
+ if (!ticket)
309
+ return { ticket: null, attached: false };
310
+ if (ticket.status === 'cancelled' || ticket.status === 'failed' || ticket.status === 'delivered') {
311
+ return { ticket, attached: false };
312
+ }
313
+ if (ticket.child_session_id) {
314
+ return { ticket, attached: ticket.child_session_id === childSessionId };
315
+ }
316
+ const attempt = ticket.active_attempt_id
317
+ ? row('SELECT * FROM work_attempts WHERE id = ?', ticket.active_attempt_id)
318
+ : null;
319
+ if (expected?.attemptId && attempt?.id !== expected.attemptId)
320
+ return { ticket, attached: false };
321
+ if (expected?.fencingToken != null && attempt && attempt.fencing_token !== expected.fencingToken) {
322
+ return { ticket, attached: false };
323
+ }
188
324
  db.prepare(`
189
325
  UPDATE work_tickets SET child_session_id = ?, updated_at = ? WHERE id = ? AND child_session_id IS NULL
190
326
  `).run(childSessionId, iso(), ticketId);
191
- db.prepare(`
192
- UPDATE work_attempts SET child_session_id = ? WHERE id = ? AND child_session_id IS NULL
193
- `).run(childSessionId, ticket.active_attempt_id);
194
- return row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
327
+ if (ticket.active_attempt_id) {
328
+ db.prepare(`
329
+ UPDATE work_attempts SET child_session_id = ? WHERE id = ? AND child_session_id IS NULL
330
+ `).run(childSessionId, ticket.active_attempt_id);
331
+ }
332
+ const fresh = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
333
+ return { ticket: fresh, attached: fresh?.child_session_id === childSessionId };
195
334
  }
196
335
  /**
197
336
  * @param {{
@@ -276,22 +415,34 @@ export function createTicketBook(db, root, now = () => new Date()) {
276
415
  return { error: 'NOT_FOUND' };
277
416
  const allowed = kind === 'supply'
278
417
  ? ticket.status === 'needs_user' || ticket.status === 'enqueued'
279
- : ticket.status === 'accepted' || ticket.status === 'enqueued' || ticket.status === 'started' || ticket.status === 'needs_user' || ticket.status === 'ready';
418
+ : ticket.status === 'accepted' ||
419
+ ticket.status === 'enqueued' ||
420
+ ticket.status === 'started' ||
421
+ ticket.status === 'needs_user' ||
422
+ ticket.status === 'ready';
280
423
  if (!allowed)
281
- return { error: 'VALIDATION', message: `Ticket status ${ticket.status} cannot ${kind === 'supply' ? 'supply' : 'redirect'}.` };
424
+ return {
425
+ error: 'VALIDATION',
426
+ message: `Ticket status ${ticket.status} cannot ${kind === 'supply' ? 'supply' : 'redirect'}.`,
427
+ };
282
428
  if (!ticket.child_session_id)
283
- return { error: 'VALIDATION', message: 'The worker session does not exist yet, so this generation cannot be changed.' };
429
+ return {
430
+ error: 'VALIDATION',
431
+ message: 'The worker session does not exist yet, so this generation cannot be changed.',
432
+ };
284
433
  const expected = expectedRevision == null ? ticket.revision : expectedRevision;
285
434
  if (expected !== ticket.revision)
286
435
  return { error: 'CAS_CONFLICT' };
287
436
  const nextRevision = ticket.revision + 1;
288
437
  const nextBrief = ticket.briefing_revision + 1;
289
438
  const hash = writeBriefing(text);
290
- const info = db.prepare(`
439
+ const info = db
440
+ .prepare(`
291
441
  UPDATE work_tickets
292
442
  SET revision = ?, briefing_revision = ?, briefing_hash = ?, review_status = 'none', updated_at = ?
293
443
  WHERE id = ? AND revision = ?
294
- `).run(nextRevision, nextBrief, hash, iso(), ticketId, expected);
444
+ `)
445
+ .run(nextRevision, nextBrief, hash, iso(), ticketId, expected);
295
446
  if (info.changes !== 1)
296
447
  return { error: 'CAS_CONFLICT' };
297
448
  abandonOpenDeliveries(ticketId, nextBrief);
@@ -325,11 +476,13 @@ export function createTicketBook(db, root, now = () => new Date()) {
325
476
  if (expected !== ticket.revision)
326
477
  return { error: 'CAS_CONFLICT' };
327
478
  const next = ticket.revision + 1;
328
- const info = db.prepare(`
479
+ const info = db
480
+ .prepare(`
329
481
  UPDATE work_tickets
330
482
  SET revision = ?, status = 'cancelled', cancel_requested_revision = ?, updated_at = ?
331
483
  WHERE id = ? AND revision = ?
332
- `).run(next, next, iso(), ticketId, expected);
484
+ `)
485
+ .run(next, next, iso(), ticketId, expected);
333
486
  if (info.changes !== 1)
334
487
  return { error: 'CAS_CONFLICT' };
335
488
  db.prepare(`
@@ -371,12 +524,17 @@ export function createTicketBook(db, root, now = () => new Date()) {
371
524
  const token = (previous?.fencing_token ?? 0) + 1;
372
525
  const attemptId = randomUUID();
373
526
  const next = ticket.revision + 1;
374
- const info = db.prepare(`
527
+ const retryBudget = budgetObject(ticket);
528
+ delete retryBudget.quota;
529
+ delete retryBudget.extension;
530
+ const info = db
531
+ .prepare(`
375
532
  UPDATE work_tickets
376
- SET revision = ?, briefing_revision = 1, status = 'accepted', review_status = 'none',
533
+ SET budget_json = ?, revision = ?, briefing_revision = 1, status = 'accepted', review_status = 'none',
377
534
  active_attempt_id = ?, cancel_requested_revision = NULL, updated_at = ?
378
535
  WHERE id = ? AND revision = ?
379
- `).run(next, attemptId, iso(), ticketId, expected);
536
+ `)
537
+ .run(JSON.stringify(retryBudget), next, attemptId, iso(), ticketId, expected);
380
538
  if (info.changes !== 1)
381
539
  return { error: 'CAS_CONFLICT' };
382
540
  if (previous) {
@@ -396,7 +554,11 @@ export function createTicketBook(db, root, now = () => new Date()) {
396
554
  kind: 'briefing',
397
555
  text: briefing,
398
556
  });
399
- return { ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId), attempt: row('SELECT * FROM work_attempts WHERE id = ?', attemptId), input };
557
+ return {
558
+ ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId),
559
+ attempt: row('SELECT * FROM work_attempts WHERE id = ?', attemptId),
560
+ input,
561
+ };
400
562
  }
401
563
  /**
402
564
  * @param {{
@@ -442,13 +604,14 @@ export function createTicketBook(db, root, now = () => new Date()) {
442
604
  }
443
605
  const ticket = row('SELECT * FROM work_tickets WHERE id = ?', found.ticket_id);
444
606
  const attempt = row('SELECT * FROM work_attempts WHERE id = ?', found.attempt_id);
445
- const matches = Boolean(ticket && attempt
446
- && ticket.active_attempt_id === found.attempt_id
447
- && attempt.fencing_token === found.fencing_token
448
- && ticket.briefing_revision === found.briefing_revision
449
- && ticket.status !== 'cancelled'
450
- && ticket.status !== 'failed'
451
- && ticket.status !== 'delivered');
607
+ const matches = Boolean(ticket &&
608
+ attempt &&
609
+ ticket.active_attempt_id === found.attempt_id &&
610
+ attempt.fencing_token === found.fencing_token &&
611
+ ticket.briefing_revision === found.briefing_revision &&
612
+ ticket.status !== 'cancelled' &&
613
+ ticket.status !== 'failed' &&
614
+ ticket.status !== 'delivered');
452
615
  if (!matches || reasonKind !== 'completed') {
453
616
  db.prepare(`UPDATE work_events SET apply_status = 'stale', turn_end_reason = ? WHERE event_id = ?`).run(reasonKind || '', eventId);
454
617
  return row('SELECT * FROM work_events WHERE event_id = ?', eventId);
@@ -456,7 +619,9 @@ export function createTicketBook(db, root, now = () => new Date()) {
456
619
  db.prepare(`UPDATE work_events SET apply_status = 'applied', turn_end_reason = ? WHERE event_id = ?`).run(reasonKind, eventId);
457
620
  const stamp = iso();
458
621
  if (found.kind === 'question') {
459
- db.prepare(`UPDATE work_tickets SET status = 'needs_user', updated_at = ? WHERE id = ?`).run(stamp, ticket.id);
622
+ const budget = budgetObject(ticket);
623
+ delete budget.slot;
624
+ db.prepare(`UPDATE work_tickets SET status = 'needs_user', budget_json = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(budget), stamp, ticket.id);
460
625
  }
461
626
  else if (found.kind === 'result') {
462
627
  const review = ticket.review_status === 'rejected' ? 'rejected' : 'candidate';
@@ -499,12 +664,13 @@ export function createTicketBook(db, root, now = () => new Date()) {
499
664
  return { ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId), already: false };
500
665
  }
501
666
  /**
502
- * Add granted runtime or tokens, capped by the host ceiling, and close the request.
667
+ * Add granted runtime or tokens and close the request when the new totals
668
+ * exceed current usage. There is no cumulative ceiling and no grant-count cap.
503
669
  * @param {string} ticketId
504
670
  * @param {{ wallMs?: number, maxTokens?: number }} add
505
- * @param {{ wallMs: number, maxTokens: number }} ceilings
671
+ * @param {{ wallMs: number, maxTokens: number }} [baseline]
506
672
  */
507
- function extendBudget(ticketId, add, ceilings) {
673
+ function extendBudget(ticketId, add, baseline) {
508
674
  const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
509
675
  if (!ticket)
510
676
  return { error: 'NOT_FOUND', message: 'No such ticket.' };
@@ -512,20 +678,25 @@ export function createTicketBook(db, root, now = () => new Date()) {
512
678
  return { error: 'VALIDATION', message: 'This ticket has finished and cannot be granted more budget.' };
513
679
  }
514
680
  const budget = budgetObject(ticket);
515
- const beforeWall = Number(budget.wallMs) || ceilings.wallMs;
516
- const beforeTokens = Number(budget.maxTokens) || ceilings.maxTokens;
681
+ const beforeWall = Number(budget.wallMs) || baseline?.wallMs || 0;
682
+ const beforeTokens = Number(budget.maxTokens) || baseline?.maxTokens || 0;
517
683
  const wallAdd = Number(add.wallMs);
518
684
  const tokenAdd = Number(add.maxTokens);
519
- const wallMs = Number.isFinite(wallAdd) && wallAdd > 0
520
- ? Math.min(ceilings.wallMs, beforeWall + Math.floor(wallAdd))
521
- : beforeWall;
522
- const maxTokens = Number.isFinite(tokenAdd) && tokenAdd > 0
523
- ? Math.min(ceilings.maxTokens, beforeTokens + Math.floor(tokenAdd))
524
- : beforeTokens;
685
+ const wallMs = Number.isFinite(wallAdd) && wallAdd > 0 ? beforeWall + Math.floor(wallAdd) : beforeWall;
686
+ const maxTokens = Number.isFinite(tokenAdd) && tokenAdd > 0 ? beforeTokens + Math.floor(tokenAdd) : beforeTokens;
525
687
  if (wallMs === beforeWall && maxTokens === beforeTokens) {
526
- return { error: 'VALIDATION', message: 'Nothing more can be granted. The host ceiling is already used.' };
688
+ return { error: 'VALIDATION', message: 'Pass wallMs or maxTokens to add.' };
527
689
  }
528
- const next = { ...budget, wallMs, maxTokens, extension: null };
690
+ const quota = budget.quota;
691
+ const enough = !quota?.waiting || (maxTokens > quota.tokens && wallMs > quota.activeMs);
692
+ const next = {
693
+ ...budget,
694
+ wallMs,
695
+ maxTokens,
696
+ extension: enough ? null : 'open',
697
+ // Only actual loop admission clears durable waiting. A crash after this
698
+ // grant transaction must not remove expiry protection before resumption.
699
+ };
529
700
  db.prepare(`UPDATE work_tickets SET budget_json = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(next), iso(), ticketId);
530
701
  return { ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId), budget: next };
531
702
  }
@@ -575,19 +746,38 @@ export function createTicketBook(db, root, now = () => new Date()) {
575
746
  }
576
747
  return row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
577
748
  }
749
+ function extensionIsOpen(budgetJson) {
750
+ try {
751
+ return JSON.parse(budgetJson ?? '')?.extension === 'open';
752
+ }
753
+ catch {
754
+ return false;
755
+ }
756
+ }
578
757
  function expireQuiet() {
579
758
  const failed = [];
580
- const running = db.prepare(`
581
- SELECT t.id AS ticket_id, t.budget_json, t.status AS ticket_status, a.id AS attempt_id, a.status AS attempt_status,
759
+ const running = db
760
+ .prepare(`
761
+ SELECT t.id AS ticket_id, t.budget_json, t.status AS ticket_status, t.child_session_id,
762
+ a.id AS attempt_id, a.status AS attempt_status,
582
763
  a.lease_until, a.current_input_id
583
764
  FROM work_tickets t
584
765
  JOIN work_attempts a ON a.id = t.active_attempt_id
585
766
  WHERE t.status IN ('enqueued','started')
586
- `).all();
767
+ `)
768
+ .all();
587
769
  for (const item of running) {
588
- if (item.ticket_status === 'started' && item.attempt_status === 'started' && item.lease_until && Date.parse(item.lease_until) <= now().getTime()) {
770
+ if (budgetObject(item).quota?.waiting)
771
+ continue;
772
+ if (item.ticket_status === 'started' &&
773
+ item.attempt_status === 'started' &&
774
+ item.lease_until &&
775
+ Date.parse(item.lease_until) <= now().getTime()) {
776
+ // The host already asked main to grant, not to mark the ticket failed.
777
+ if (extensionIsOpen(item.budget_json))
778
+ continue;
589
779
  failRunning(item.ticket_id, 'lease');
590
- failed.push(item.ticket_id);
780
+ failed.push({ ticketId: item.ticket_id, reason: 'lease', childSessionId: item.child_session_id ?? null });
591
781
  continue;
592
782
  }
593
783
  if (item.ticket_status === 'enqueued' && item.attempt_status === 'enqueued' && item.current_input_id) {
@@ -596,13 +786,47 @@ export function createTicketBook(db, root, now = () => new Date()) {
596
786
  try {
597
787
  wall = JSON.parse(item.budget_json).wallMs ?? wall;
598
788
  }
599
- catch { /* host default */ }
789
+ catch {
790
+ /* host default */
791
+ }
600
792
  if (input && input.flush_status === 'accepted' && Date.parse(input.updated_at) + wall <= now().getTime()) {
601
793
  failRunning(item.ticket_id, 'enqueue-wall');
602
- failed.push(item.ticket_id);
794
+ failed.push({
795
+ ticketId: item.ticket_id,
796
+ reason: 'enqueue-wall',
797
+ childSessionId: item.child_session_id ?? null,
798
+ });
603
799
  }
604
800
  }
605
801
  }
802
+ const reserved = db
803
+ .prepare(`
804
+ SELECT t.id AS ticket_id, t.budget_json, t.updated_at, t.child_session_id
805
+ FROM work_tickets t
806
+ WHERE t.status IN ('accepted','needs_user')
807
+ AND json_extract(t.budget_json, '$.slot') = 'held'
808
+ `)
809
+ .all();
810
+ for (const item of reserved) {
811
+ let wall = RESERVE_WALL_MS;
812
+ try {
813
+ const parsed = JSON.parse(item.budget_json);
814
+ const ticketWall = Number(parsed?.wallMs);
815
+ if (Number.isFinite(ticketWall) && ticketWall > 0)
816
+ wall = Math.min(ticketWall, RESERVE_WALL_MS);
817
+ }
818
+ catch {
819
+ /* host default */
820
+ }
821
+ if (Date.parse(item.updated_at) + wall <= now().getTime()) {
822
+ failRunning(item.ticket_id, 'reserve-wall');
823
+ failed.push({
824
+ ticketId: item.ticket_id,
825
+ reason: 'reserve-wall',
826
+ childSessionId: item.child_session_id ?? null,
827
+ });
828
+ }
829
+ }
606
830
  return failed;
607
831
  }
608
832
  /**
@@ -618,9 +842,11 @@ export function createTicketBook(db, root, now = () => new Date()) {
618
842
  * }} input
619
843
  */
620
844
  function insertDelivery(input) {
621
- const existing = db.prepare(`
845
+ const existing = db
846
+ .prepare(`
622
847
  SELECT * FROM user_deliveries WHERE ticket_id = ? AND result_event_id = ?
623
- `).get(input.ticketId, input.eventId);
848
+ `)
849
+ .get(input.ticketId, input.eventId);
624
850
  if (existing)
625
851
  return { row: existing, already: true };
626
852
  const id = randomUUID();
@@ -637,9 +863,11 @@ export function createTicketBook(db, root, now = () => new Date()) {
637
863
  * @param {string} eventId
638
864
  */
639
865
  function deliveryForEvent(ticketId, eventId) {
640
- return db.prepare(`
866
+ return (db
867
+ .prepare(`
641
868
  SELECT * FROM user_deliveries WHERE ticket_id = ? AND result_event_id = ?
642
- `).get(ticketId, eventId) ?? null;
869
+ `)
870
+ .get(ticketId, eventId) ?? null);
643
871
  }
644
872
  /**
645
873
  * @param {string} ticketId
@@ -680,9 +908,11 @@ export function createTicketBook(db, root, now = () => new Date()) {
680
908
  * @param {string} owner
681
909
  */
682
910
  function visibleTickets(owner) {
683
- const rows = db.prepare(`
911
+ const rows = db
912
+ .prepare(`
684
913
  SELECT * FROM work_tickets WHERE owner_session_id = ? ORDER BY updated_at DESC
685
- `).all(owner);
914
+ `)
915
+ .all(owner);
686
916
  const open = rows.filter(item => item.status !== 'delivered' && item.status !== 'cancelled' && item.status !== 'failed');
687
917
  const closed = rows.filter(item => !open.includes(item)).slice(0, 8);
688
918
  return [...open, ...closed];
@@ -694,6 +924,7 @@ export function createTicketBook(db, root, now = () => new Date()) {
694
924
  return visibleTickets(owner).map(item => ({
695
925
  id: item.id,
696
926
  status: item.status,
927
+ waiting_budget: (item.status === 'started' || item.status === 'enqueued') && budgetObject(item).quota?.waiting === true,
697
928
  briefing_revision: item.briefing_revision,
698
929
  child_session_id: item.child_session_id,
699
930
  summary: readBriefing(item.briefing_hash).replace(/\s+/g, ' ').trim().slice(0, 80),
@@ -701,32 +932,42 @@ export function createTicketBook(db, root, now = () => new Date()) {
701
932
  }
702
933
  /** Stable across unchanged rows. Lease touches are not part of it. */
703
934
  function liveStamp() {
704
- const tickets = db.prepare(`
935
+ const tickets = db
936
+ .prepare(`
705
937
  SELECT id, status, briefing_revision, IFNULL(child_session_id, '') AS child_session_id,
706
938
  IFNULL(active_attempt_id, '') AS active_attempt_id, briefing_hash, updated_at
707
939
  FROM work_tickets ORDER BY id
708
- `).all();
709
- const events = db.prepare(`
940
+ `)
941
+ .all();
942
+ const events = db
943
+ .prepare(`
710
944
  SELECT event_id, apply_status, payload_hash FROM work_events ORDER BY event_id
711
- `).all();
712
- const attempts = db.prepare(`
945
+ `)
946
+ .all();
947
+ const attempts = db
948
+ .prepare(`
713
949
  SELECT id, IFNULL(started_at, '') AS started_at FROM work_attempts ORDER BY id
714
- `).all();
950
+ `)
951
+ .all();
715
952
  return JSON.stringify([tickets, events, attempts]);
716
953
  }
717
954
  /** Delivered and cancelled tickets do not light a bot, so they stay out of signals. */
718
955
  function signalMap() {
719
- const rows = db.prepare(`
720
- SELECT owner_session_id, status FROM work_tickets
956
+ const rows = db
957
+ .prepare(`
958
+ SELECT owner_session_id, status, budget_json FROM work_tickets
721
959
  WHERE status != 'delivered' AND status != 'cancelled'
722
960
  ORDER BY updated_at DESC
723
- `).all();
961
+ `)
962
+ .all();
724
963
  /** @type {Record<string, string[]>} */
725
964
  const signals = {};
726
965
  for (const item of rows) {
727
966
  const owner = item.owner_session_id;
728
967
  const list = signals[owner] ?? [];
729
- list.push(item.status);
968
+ list.push((item.status === 'started' || item.status === 'enqueued') && budgetObject(item).quota?.waiting
969
+ ? 'waiting_budget'
970
+ : item.status);
730
971
  signals[owner] = list;
731
972
  }
732
973
  return signals;
@@ -763,12 +1004,16 @@ export function createTicketBook(db, root, now = () => new Date()) {
763
1004
  return [];
764
1005
  const ids = picked.map(item => item.id);
765
1006
  const marks = ids.map(() => '?').join(',');
766
- const attempts = db.prepare(`
1007
+ const attempts = db
1008
+ .prepare(`
767
1009
  SELECT id, ticket_id, started_at FROM work_attempts WHERE ticket_id IN (${marks})
768
- `).all(...ids);
769
- const events = db.prepare(`
1010
+ `)
1011
+ .all(...ids);
1012
+ const events = db
1013
+ .prepare(`
770
1014
  SELECT * FROM work_events WHERE ticket_id IN (${marks}) ORDER BY created_at
771
- `).all(...ids);
1015
+ `)
1016
+ .all(...ids);
772
1017
  /** @type {Map<string, Array<{ id: string, started_at: string | null }>>} */
773
1018
  const byAttempt = new Map();
774
1019
  for (const attempt of attempts) {
@@ -794,6 +1039,7 @@ export function createTicketBook(db, root, now = () => new Date()) {
794
1039
  ticket: {
795
1040
  id: item.id,
796
1041
  status: item.status,
1042
+ waiting_budget: (item.status === 'started' || item.status === 'enqueued') && budgetObject(item).quota?.waiting === true,
797
1043
  briefing_revision: item.briefing_revision,
798
1044
  child_session_id: item.child_session_id,
799
1045
  active_attempt_id: item.active_attempt_id,
@@ -813,7 +1059,10 @@ export function createTicketBook(db, root, now = () => new Date()) {
813
1059
  ticket: found,
814
1060
  attempts: db.prepare('SELECT * FROM work_attempts WHERE ticket_id = ? ORDER BY fencing_token').all(id),
815
1061
  inputs: db.prepare('SELECT * FROM work_inputs WHERE ticket_id = ? ORDER BY created_at').all(id),
816
- events: db.prepare('SELECT * FROM work_events WHERE ticket_id = ? ORDER BY created_at').all(id).map(event => ({
1062
+ events: db
1063
+ .prepare('SELECT * FROM work_events WHERE ticket_id = ? ORDER BY created_at')
1064
+ .all(id)
1065
+ .map(event => ({
817
1066
  ...event,
818
1067
  text: readBriefing(event.payload_hash),
819
1068
  })),
@@ -825,45 +1074,54 @@ export function createTicketBook(db, root, now = () => new Date()) {
825
1074
  * @param {string} owner
826
1075
  */
827
1076
  function eventsWithoutNotice(owner) {
828
- return db.prepare(`
1077
+ return db
1078
+ .prepare(`
829
1079
  SELECT e.* FROM work_events e
830
1080
  JOIN work_tickets t ON t.id = e.ticket_id
831
1081
  WHERE t.owner_session_id = ? AND e.notice_id IS NULL AND e.apply_status != 'stale'
832
1082
  ORDER BY e.created_at
833
- `).all(owner);
1083
+ `)
1084
+ .all(owner);
834
1085
  }
835
1086
  /**
836
1087
  * @param {string} owner
837
1088
  */
838
1089
  function pendingWake(owner) {
839
1090
  const events = eventsWithoutNotice(owner);
840
- const cancels = db.prepare(`
1091
+ const cancels = db
1092
+ .prepare(`
841
1093
  SELECT * FROM work_tickets t
842
1094
  WHERE t.owner_session_id = ? AND t.status = 'cancelled' AND t.cancel_requested_revision IS NOT NULL
843
1095
  AND NOT EXISTS (
844
1096
  SELECT 1 FROM work_notices n
845
1097
  WHERE n.ticket_id = t.id AND n.event_id = 'cancel:' || t.cancel_requested_revision
846
1098
  )
847
- `).all(owner);
1099
+ `)
1100
+ .all(owner);
848
1101
  return { events, cancels };
849
1102
  }
850
1103
  /**
851
1104
  * @param {string} owner
852
1105
  */
853
1106
  function openNotice(owner) {
854
- const rows = db.prepare(`SELECT flush_status, observe_status FROM work_notices WHERE owner_session_id = ?`).all(owner);
855
- return rows.some(item => OPEN_NOTICE_FLUSH.has(item.flush_status) || (item.flush_status === 'accepted' && item.observe_status !== 'completed'));
1107
+ const rows = db
1108
+ .prepare(`SELECT flush_status, observe_status FROM work_notices WHERE owner_session_id = ?`)
1109
+ .all(owner);
1110
+ return rows.some(item => OPEN_NOTICE_FLUSH.has(item.flush_status) ||
1111
+ (item.flush_status === 'accepted' && item.observe_status !== 'completed'));
856
1112
  }
857
1113
  /**
858
1114
  * @param {string} owner
859
1115
  */
860
1116
  function openDelivery(owner) {
861
- const found = db.prepare(`
1117
+ const found = db
1118
+ .prepare(`
862
1119
  SELECT 1 AS ok FROM deliveries
863
1120
  WHERE target_session_id = ? AND kind IN ('message','timer','webhook')
864
1121
  AND status IN ('intent','flushing','accepted','claimed','started')
865
1122
  LIMIT 1
866
- `).get(owner);
1123
+ `)
1124
+ .get(owner);
867
1125
  return found != null;
868
1126
  }
869
1127
  /**
@@ -878,20 +1136,26 @@ export function createTicketBook(db, root, now = () => new Date()) {
878
1136
  * @param {string} owner
879
1137
  */
880
1138
  function latestNoticeAt(owner) {
881
- const found = db.prepare(`
1139
+ const found = db
1140
+ .prepare(`
882
1141
  SELECT created_at FROM work_notices WHERE owner_session_id = ? ORDER BY created_at DESC LIMIT 1
883
- `).get(owner);
1142
+ `)
1143
+ .get(owner);
884
1144
  return found ? Date.parse(found.created_at) : null;
885
1145
  }
886
1146
  function flushInputs() {
887
- return db.prepare(`
1147
+ return db
1148
+ .prepare(`
888
1149
  SELECT * FROM work_inputs WHERE flush_status IN ('intent','flushing','ambiguous') ORDER BY created_at
889
- `).all();
1150
+ `)
1151
+ .all();
890
1152
  }
891
1153
  function flushNotices() {
892
- return db.prepare(`
1154
+ return db
1155
+ .prepare(`
893
1156
  SELECT * FROM work_notices WHERE flush_status IN ('intent','flushing','ambiguous') ORDER BY created_at
894
- `).all();
1157
+ `)
1158
+ .all();
895
1159
  }
896
1160
  /**
897
1161
  * @param {string} id
@@ -974,9 +1238,11 @@ export function createTicketBook(db, root, now = () => new Date()) {
974
1238
  * @param {string} owner
975
1239
  */
976
1240
  function intentsFor(owner) {
977
- return db.prepare(`
1241
+ return db
1242
+ .prepare(`
978
1243
  SELECT * FROM user_deliveries WHERE owner_session_id = ? AND status = 'intent' ORDER BY created_at
979
- `).all(owner);
1244
+ `)
1245
+ .all(owner);
980
1246
  }
981
1247
  /**
982
1248
  * One native wake id shared by every event in the merged notice.
@@ -1007,19 +1273,78 @@ export function createTicketBook(db, root, now = () => new Date()) {
1007
1273
  return db.prepare('SELECT * FROM work_attempts WHERE ticket_id = ? ORDER BY fencing_token').all(ticketId);
1008
1274
  }
1009
1275
  function ownerIds() {
1010
- return db.prepare(`SELECT DISTINCT owner_session_id AS id FROM work_tickets`).all().map(item => item.id);
1276
+ return db
1277
+ .prepare(`SELECT DISTINCT owner_session_id AS id FROM work_tickets`)
1278
+ .all()
1279
+ .map(item => item.id);
1011
1280
  }
1012
1281
  function childIds() {
1013
- return db.prepare(`
1282
+ return db
1283
+ .prepare(`
1014
1284
  SELECT DISTINCT child_session_id AS id FROM work_attempts
1015
1285
  WHERE child_session_id IS NOT NULL
1016
- `).all().map(item => item.id);
1286
+ `)
1287
+ .all()
1288
+ .map(item => item.id);
1289
+ }
1290
+ /**
1291
+ * Owners whose log can still bind a publish intent to an assistant seq.
1292
+ * Delivered, abandoned, and absent rows have nothing left to read.
1293
+ */
1294
+ function ownerIdsForReconcile() {
1295
+ return db
1296
+ .prepare(`
1297
+ SELECT DISTINCT owner_session_id AS id FROM user_deliveries
1298
+ WHERE status = 'intent'
1299
+ `)
1300
+ .all()
1301
+ .map(item => item.id);
1302
+ }
1303
+ /**
1304
+ * Child logs that can still move a ticket.
1305
+ * A running attempt is included. A needs_user attempt is not, once its
1306
+ * question/result/failure is applied, because that log no longer changes
1307
+ * the ledger until a supply or retry enqueues the attempt again.
1308
+ * A terminal attempt is included only while a terminal report for the
1309
+ * active attempt is still pending_completion, so the final turn/end is
1310
+ * applied or staled once and then the closed log is left alone.
1311
+ */
1312
+ function childIdsForReconcile() {
1313
+ return db
1314
+ .prepare(`
1315
+ SELECT DISTINCT a.child_session_id AS id
1316
+ FROM work_attempts a
1317
+ JOIN work_tickets t ON t.id = a.ticket_id
1318
+ WHERE a.child_session_id IS NOT NULL
1319
+ AND (
1320
+ a.status IN ('starting', 'enqueued')
1321
+ OR (
1322
+ a.status = 'started'
1323
+ AND t.status IN ('accepted', 'enqueued', 'started')
1324
+ )
1325
+ OR (
1326
+ t.active_attempt_id = a.id
1327
+ AND EXISTS (
1328
+ SELECT 1 FROM work_events e
1329
+ WHERE e.attempt_id = a.id
1330
+ AND e.briefing_revision = t.briefing_revision
1331
+ AND e.apply_status = 'pending_completion'
1332
+ AND e.kind IN ('question', 'result', 'failure')
1333
+ )
1334
+ )
1335
+ )
1336
+ `)
1337
+ .all()
1338
+ .map(item => item.id);
1017
1339
  }
1018
1340
  /**
1019
1341
  * @param {string} owner
1020
1342
  */
1021
1343
  function noticeIds(owner) {
1022
- return new Set(db.prepare(`SELECT native_message_id FROM work_notices WHERE owner_session_id = ?`).all(owner).map(item => item.native_message_id));
1344
+ return new Set(db
1345
+ .prepare(`SELECT native_message_id FROM work_notices WHERE owner_session_id = ?`)
1346
+ .all(owner)
1347
+ .map(item => item.native_message_id));
1023
1348
  }
1024
1349
  }
1025
1350
  /**
@@ -1036,6 +1361,8 @@ function hostFailureText(reason) {
1036
1361
  return 'The worker lease expired and this round has stopped.';
1037
1362
  if (reason === 'enqueue-wall')
1038
1363
  return 'The task entered the queue and did not start before the time limit.';
1364
+ if (reason === 'reserve-wall')
1365
+ return 'The reserved start did not create a worker before the time limit, so the slot was released.';
1039
1366
  if (reason === 'steps')
1040
1367
  return 'The worker hit its step limit and this round has stopped.';
1041
1368
  return 'The worker has stopped.';