kimaki 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/dist/agent-model.e2e.test.js +25 -122
  2. package/dist/anthropic-account-identity.js +1 -0
  3. package/dist/anthropic-auth-plugin.js +1 -0
  4. package/dist/anthropic-auth-state.js +1 -0
  5. package/dist/bin.js +73 -19
  6. package/dist/cli-commands/maintenance.js +46 -7
  7. package/dist/cli-commands/send.js +24 -0
  8. package/dist/cli-commands/session.js +183 -8
  9. package/dist/cli-commands/task.js +13 -1
  10. package/dist/cli-parsing.test.js +59 -3
  11. package/dist/cli-runner.js +28 -4
  12. package/dist/cli-runner.test.js +27 -0
  13. package/dist/cli-send-thread.e2e.test.js +1 -1
  14. package/dist/cli.js +32 -0
  15. package/dist/commands/abort.js +5 -1
  16. package/dist/commands/agent.js +6 -8
  17. package/dist/commands/ask-question.js +21 -32
  18. package/dist/commands/ask-question.test.js +43 -1
  19. package/dist/commands/login.js +6 -0
  20. package/dist/commands/merge-worktree.js +36 -10
  21. package/dist/commands/model-variant.js +7 -1
  22. package/dist/commands/model.js +14 -8
  23. package/dist/commands/multioauth.js +1 -0
  24. package/dist/commands/new-worktree.js +170 -102
  25. package/dist/commands/user-command.js +6 -8
  26. package/dist/commands/worktrees.js +5 -13
  27. package/dist/config.js +16 -1
  28. package/dist/database.js +124 -3
  29. package/dist/db.js +22 -0
  30. package/dist/db.test.js +167 -1
  31. package/dist/discord-bot.js +34 -32
  32. package/dist/discord-command-registration.js +9 -1
  33. package/dist/discord-utils.js +13 -5
  34. package/dist/discord-utils.test.js +17 -1
  35. package/dist/errors.js +5 -0
  36. package/dist/exec-async.js +17 -5
  37. package/dist/external-directory-permissions.e2e.test.js +2 -2
  38. package/dist/file-edit-log.js +197 -0
  39. package/dist/file-edit-log.test.js +258 -0
  40. package/dist/format-tables.js +52 -0
  41. package/dist/format-tables.test.js +93 -0
  42. package/dist/gateway-proxy-reconnect.e2e.test.js +28 -8
  43. package/dist/gateway-proxy.e2e.test.js +5 -5
  44. package/dist/git-worktree-core.js +182 -17
  45. package/dist/ipc-tools-plugin.js +63 -3
  46. package/dist/kimaki-opencode-plugin-loading.e2e.test.js +122 -58
  47. package/dist/kimaki-opencode-plugin.js +7 -3
  48. package/dist/kimaki-workspace-adaptor.js +33 -10
  49. package/dist/logger.js +10 -1
  50. package/dist/markdown.js +3 -1
  51. package/dist/markdown.test.js +11 -3
  52. package/dist/message-formatting.js +18 -7
  53. package/dist/message-formatting.test.js +56 -9
  54. package/dist/oauth-rotation-shared.js +10 -0
  55. package/dist/openai-auth-plugin.js +1 -0
  56. package/dist/openai-auth-state.js +1 -0
  57. package/dist/opencode-command.test.js +60 -0
  58. package/dist/opencode.js +53 -12
  59. package/dist/question-abort-clears-dropdown.e2e.test.js +89 -0
  60. package/dist/question-text-before-dropdown.e2e.test.js +52 -0
  61. package/dist/queue-advanced-abort.e2e.test.js +1 -1
  62. package/dist/queue-advanced-action-buttons.e2e.test.js +3 -3
  63. package/dist/queue-advanced-e2e-setup.js +78 -5
  64. package/dist/queue-advanced-footer.e2e.test.js +40 -246
  65. package/dist/queue-advanced-model-switch.e2e.test.js +2 -2
  66. package/dist/queue-advanced-permissions-typing.e2e.test.js +7 -9
  67. package/dist/queue-advanced-question.e2e.test.js +31 -26
  68. package/dist/queue-advanced-typing-interrupt.e2e.test.js +2 -2
  69. package/dist/queue-delete-message.e2e.test.js +1 -1
  70. package/dist/queue-drain-after-interactive-ui.e2e.test.js +2 -2
  71. package/dist/queue-interrupt-drain.e2e.test.js +112 -2
  72. package/dist/queue-question-select-drain.e2e.test.js +30 -128
  73. package/dist/runtime-lifecycle.e2e.test.js +10 -37
  74. package/dist/schema.js +34 -0
  75. package/dist/session-handler/event-stream-state.js +267 -50
  76. package/dist/session-handler/event-stream-state.test.js +415 -8
  77. package/dist/session-handler/model-utils.js +159 -5
  78. package/dist/session-handler/model-utils.test.js +345 -0
  79. package/dist/session-handler/thread-session-runtime.js +252 -182
  80. package/dist/session-sleep.test.js +224 -0
  81. package/dist/session-title-rename.test.js +7 -39
  82. package/dist/sleep.e2e.test.js +491 -0
  83. package/dist/startup-time.e2e.test.js +2 -1
  84. package/dist/store.js +3 -0
  85. package/dist/system-message.js +59 -6
  86. package/dist/system-message.test.js +76 -6
  87. package/dist/task-runner.js +94 -4
  88. package/dist/task-schedule.js +56 -0
  89. package/dist/task-schedule.test.js +71 -1
  90. package/dist/thread-message-queue.e2e.test.js +10 -169
  91. package/dist/undo-redo.e2e.test.js +2 -2
  92. package/dist/voice-attachment.js +23 -1
  93. package/dist/voice-message.e2e.test.js +10 -10
  94. package/dist/voice.test.js +55 -29
  95. package/dist/worktree-clone-isolation.e2e.test.js +188 -0
  96. package/dist/worktree-lifecycle.e2e.test.js +29 -10
  97. package/dist/worktrees.js +226 -443
  98. package/dist/worktrees.test.js +435 -58
  99. package/dist/xai-auth-plugin.js +1 -0
  100. package/dist/xai-auth-state.js +1 -0
  101. package/package.json +8 -6
  102. package/skills/errore/SKILL.md +18 -0
  103. package/skills/goke/SKILL.md +150 -10
  104. package/skills/holocron/SKILL.md +37 -0
  105. package/skills/npm-package/SKILL.md +55 -35
  106. package/skills/profano/SKILL.md +17 -2
  107. package/skills/spiceflow/SKILL.md +39 -3
  108. package/skills/strada/SKILL.md +39 -0
  109. package/skills/zele/SKILL.md +19 -0
  110. package/src/agent-model.e2e.test.ts +25 -151
  111. package/src/anthropic-account-identity.ts +1 -0
  112. package/src/anthropic-auth-plugin.ts +1 -0
  113. package/src/anthropic-auth-state.ts +1 -0
  114. package/src/bin.ts +78 -26
  115. package/src/cli-commands/maintenance.ts +59 -13
  116. package/src/cli-commands/send.ts +25 -0
  117. package/src/cli-commands/session.ts +203 -9
  118. package/src/cli-commands/task.ts +13 -1
  119. package/src/cli-parsing.test.ts +69 -3
  120. package/src/cli-runner.test.ts +49 -0
  121. package/src/cli-runner.ts +28 -4
  122. package/src/cli-send-thread.e2e.test.ts +1 -1
  123. package/src/cli.ts +53 -0
  124. package/src/commands/abort.ts +6 -1
  125. package/src/commands/agent.ts +6 -6
  126. package/src/commands/ask-question.test.ts +48 -1
  127. package/src/commands/ask-question.ts +21 -32
  128. package/src/commands/login.ts +6 -0
  129. package/src/commands/merge-worktree.ts +43 -12
  130. package/src/commands/model-variant.ts +8 -1
  131. package/src/commands/model.ts +18 -8
  132. package/src/commands/multioauth.ts +1 -0
  133. package/src/commands/new-worktree.ts +138 -55
  134. package/src/commands/user-command.ts +6 -6
  135. package/src/commands/worktrees.ts +5 -12
  136. package/src/config.ts +18 -1
  137. package/src/database.ts +195 -3
  138. package/src/db.test.ts +188 -0
  139. package/src/db.ts +26 -0
  140. package/src/discord-bot.ts +35 -29
  141. package/src/discord-command-registration.ts +15 -1
  142. package/src/discord-utils.test.ts +19 -0
  143. package/src/discord-utils.ts +21 -6
  144. package/src/errors.ts +5 -0
  145. package/src/exec-async.ts +20 -11
  146. package/src/external-directory-permissions.e2e.test.ts +2 -2
  147. package/src/file-edit-log.test.ts +287 -0
  148. package/src/file-edit-log.ts +283 -0
  149. package/src/format-tables.test.ts +101 -0
  150. package/src/format-tables.ts +75 -0
  151. package/src/gateway-proxy-reconnect.e2e.test.ts +38 -8
  152. package/src/gateway-proxy.e2e.test.ts +5 -5
  153. package/src/git-worktree-core.ts +247 -20
  154. package/src/ipc-tools-plugin.ts +75 -5
  155. package/src/kimaki-opencode-plugin-loading.e2e.test.ts +188 -97
  156. package/src/kimaki-opencode-plugin.ts +7 -3
  157. package/src/kimaki-workspace-adaptor.ts +40 -11
  158. package/src/logger.ts +13 -4
  159. package/src/markdown.test.ts +13 -3
  160. package/src/markdown.ts +4 -1
  161. package/src/message-formatting.test.ts +86 -12
  162. package/src/message-formatting.ts +19 -7
  163. package/src/oauth-rotation-shared.ts +10 -0
  164. package/src/openai-auth-plugin.ts +1 -0
  165. package/src/openai-auth-state.ts +1 -0
  166. package/src/opencode-command.test.ts +81 -0
  167. package/src/opencode.ts +71 -11
  168. package/src/question-abort-clears-dropdown.e2e.test.ts +109 -0
  169. package/src/question-text-before-dropdown.e2e.test.ts +67 -0
  170. package/src/queue-advanced-abort.e2e.test.ts +1 -1
  171. package/src/queue-advanced-action-buttons.e2e.test.ts +3 -3
  172. package/src/queue-advanced-e2e-setup.ts +83 -4
  173. package/src/queue-advanced-footer.e2e.test.ts +47 -294
  174. package/src/queue-advanced-model-switch.e2e.test.ts +2 -2
  175. package/src/queue-advanced-permissions-typing.e2e.test.ts +7 -9
  176. package/src/queue-advanced-question.e2e.test.ts +35 -29
  177. package/src/queue-advanced-typing-interrupt.e2e.test.ts +2 -2
  178. package/src/queue-delete-message.e2e.test.ts +1 -1
  179. package/src/queue-drain-after-interactive-ui.e2e.test.ts +2 -2
  180. package/src/queue-interrupt-drain.e2e.test.ts +123 -2
  181. package/src/queue-question-select-drain.e2e.test.ts +32 -157
  182. package/src/runtime-lifecycle.e2e.test.ts +10 -41
  183. package/src/schema.sql +14 -1
  184. package/src/schema.ts +36 -0
  185. package/src/session-handler/event-stream-state.test.ts +437 -7
  186. package/src/session-handler/event-stream-state.ts +389 -53
  187. package/src/session-handler/model-utils.test.ts +415 -0
  188. package/src/session-handler/model-utils.ts +249 -5
  189. package/src/session-handler/thread-session-runtime.ts +300 -215
  190. package/src/session-sleep.test.ts +294 -0
  191. package/src/session-title-rename.test.ts +9 -48
  192. package/src/sleep.e2e.test.ts +562 -0
  193. package/src/startup-time.e2e.test.ts +5 -1
  194. package/src/store.ts +21 -0
  195. package/src/system-message.test.ts +86 -6
  196. package/src/system-message.ts +66 -7
  197. package/src/task-runner.ts +136 -2
  198. package/src/task-schedule.test.ts +76 -0
  199. package/src/task-schedule.ts +95 -0
  200. package/src/thread-message-queue.e2e.test.ts +10 -202
  201. package/src/undo-redo.e2e.test.ts +2 -2
  202. package/src/voice-attachment.ts +29 -1
  203. package/src/voice-message.e2e.test.ts +10 -10
  204. package/src/voice.test.ts +63 -29
  205. package/src/worktree-clone-isolation.e2e.test.ts +213 -0
  206. package/src/worktree-lifecycle.e2e.test.ts +29 -9
  207. package/src/worktrees.test.ts +505 -64
  208. package/src/worktrees.ts +257 -603
  209. package/src/xai-auth-plugin.ts +1 -0
  210. package/src/xai-auth-state.ts +1 -0
  211. package/dist/message-finish-field.e2e.test.js +0 -169
  212. package/dist/subagent-rate-limit-plugin.js +0 -184
  213. package/src/message-finish-field.e2e.test.ts +0 -196
  214. package/src/subagent-rate-limit-plugin.ts +0 -228
package/src/database.ts CHANGED
@@ -42,6 +42,7 @@ export type ScheduledTaskScheduleKind = typeof schema.scheduled_tasks.$inferSele
42
42
  export type ScheduledTask = typeof schema.scheduled_tasks.$inferSelect
43
43
  export type ScheduledTaskRun = typeof schema.scheduled_task_runs.$inferSelect
44
44
  export type SessionStartSource = typeof schema.session_start_sources.$inferSelect
45
+ export type SessionSleep = typeof schema.session_sleeps.$inferSelect
45
46
  export type ModelPreference = { modelId: string; variant: string | null }
46
47
  export type { BotMode }
47
48
 
@@ -367,6 +368,172 @@ export async function setSessionStartSource({ sessionId, scheduleKind, scheduled
367
368
  })
368
369
  }
369
370
 
371
+ export async function upsertSessionSleep({
372
+ sessionId,
373
+ wakeAt,
374
+ reason,
375
+ }: {
376
+ sessionId: string
377
+ wakeAt: Date
378
+ reason?: string | null
379
+ }) {
380
+ const db = await getDb()
381
+ // A new occurrence gets a fresh delivery_id, which invalidates any in-flight
382
+ // wake for the previous occurrence: every delivery write is guarded on it.
383
+ const deliveryId = crypto.randomUUID()
384
+ await db.insert(schema.session_sleeps)
385
+ .values({
386
+ session_id: sessionId,
387
+ wake_at: wakeAt,
388
+ reason: reason ?? null,
389
+ status: 'planned',
390
+ delivery_id: deliveryId,
391
+ })
392
+ .onConflictDoUpdate({
393
+ target: schema.session_sleeps.session_id,
394
+ set: {
395
+ wake_at: wakeAt,
396
+ reason: reason ?? null,
397
+ status: 'planned',
398
+ delivery_id: deliveryId,
399
+ attempts: 0,
400
+ last_attempt_at: null,
401
+ created_at: new Date(),
402
+ },
403
+ })
404
+ return deliveryId
405
+ }
406
+
407
+ export async function getSessionSleep({ sessionId }: { sessionId: string }) {
408
+ const db = await getDb()
409
+ return await db.query.session_sleeps.findFirst({
410
+ where: { session_id: sessionId },
411
+ }) ?? null
412
+ }
413
+
414
+ /** Rows that are due and not attempted too recently. Status stays `planned`. */
415
+ export async function getDueSessionSleeps({
416
+ now,
417
+ retryAfterMs,
418
+ limit,
419
+ }: {
420
+ now: Date
421
+ retryAfterMs: number
422
+ limit: number
423
+ }) {
424
+ const db = await getDb()
425
+ const retryBefore = new Date(now.getTime() - retryAfterMs)
426
+ return db.select()
427
+ .from(schema.session_sleeps)
428
+ .where(orm.and(
429
+ orm.eq(schema.session_sleeps.status, 'planned'),
430
+ orm.lte(schema.session_sleeps.wake_at, now),
431
+ orm.or(
432
+ orm.isNull(schema.session_sleeps.last_attempt_at),
433
+ orm.lte(schema.session_sleeps.last_attempt_at, retryBefore),
434
+ ),
435
+ ))
436
+ .orderBy(orm.asc(schema.session_sleeps.wake_at))
437
+ .limit(limit)
438
+ }
439
+
440
+ /**
441
+ * Reserve one delivery attempt. The row never leaves `planned` here.
442
+ *
443
+ * Only `last_attempt_at` moves, which keeps concurrent ticks off the same row
444
+ * for retryAfterMs. Because posting does not change the status either, one
445
+ * retry path covers every loss: dying before the post, dying after it, or
446
+ * never receiving the gateway event for the message we posted.
447
+ */
448
+ export async function claimSessionSleepAttempt({
449
+ sessionId,
450
+ deliveryId,
451
+ now,
452
+ retryAfterMs,
453
+ }: {
454
+ sessionId: string
455
+ deliveryId: string
456
+ now: Date
457
+ retryAfterMs: number
458
+ }) {
459
+ const db = await getDb()
460
+ const retryBefore = new Date(now.getTime() - retryAfterMs)
461
+ const rows = await db.update(schema.session_sleeps)
462
+ .set({ last_attempt_at: now, attempts: orm.sql`${schema.session_sleeps.attempts} + 1` })
463
+ .where(orm.and(
464
+ orm.eq(schema.session_sleeps.session_id, sessionId),
465
+ orm.eq(schema.session_sleeps.delivery_id, deliveryId),
466
+ orm.eq(schema.session_sleeps.status, 'planned'),
467
+ orm.lte(schema.session_sleeps.wake_at, now),
468
+ orm.or(
469
+ orm.isNull(schema.session_sleeps.last_attempt_at),
470
+ orm.lte(schema.session_sleeps.last_attempt_at, retryBefore),
471
+ ),
472
+ ))
473
+ .returning()
474
+ return rows[0] ?? null
475
+ }
476
+
477
+ export async function markSessionSleepFailed({
478
+ sessionId,
479
+ deliveryId,
480
+ }: {
481
+ sessionId: string
482
+ deliveryId: string
483
+ }) {
484
+ const db = await getDb()
485
+ const rows = await db.update(schema.session_sleeps)
486
+ .set({ status: 'failed' })
487
+ .where(orm.and(
488
+ orm.eq(schema.session_sleeps.session_id, sessionId),
489
+ orm.eq(schema.session_sleeps.delivery_id, deliveryId),
490
+ orm.eq(schema.session_sleeps.status, 'planned'),
491
+ ))
492
+ .returning({ session_id: schema.session_sleeps.session_id })
493
+ return countRows(rows) > 0
494
+ }
495
+
496
+ /**
497
+ * Ingress commit point. Marks the wake as delivered to the session.
498
+ *
499
+ * Returns false when the row is missing or no longer `planned`, which is how a
500
+ * wake that raced a user cancellation, or a duplicate of one already delivered,
501
+ * gets dropped instead of starting a turn.
502
+ */
503
+ export async function consumeSessionSleepWake({ deliveryId }: { deliveryId: string }) {
504
+ const db = await getDb()
505
+ const rows = await db.update(schema.session_sleeps)
506
+ .set({ status: 'consumed' })
507
+ .where(orm.and(
508
+ orm.eq(schema.session_sleeps.delivery_id, deliveryId),
509
+ orm.eq(schema.session_sleeps.status, 'planned'),
510
+ ))
511
+ .returning({ session_id: schema.session_sleeps.session_id })
512
+ return countRows(rows) > 0
513
+ }
514
+
515
+ /**
516
+ * Cancel the pending sleep of the session currently bound to a thread.
517
+ *
518
+ * Runs on every ingress, so the binding is resolved with a correlated subquery
519
+ * rather than a second round trip. thread_id is the primary key of
520
+ * thread_sessions, so it yields at most one session.
521
+ */
522
+ export async function cancelSessionSleepForThread({ threadId }: { threadId: string }) {
523
+ const db = await getDb()
524
+ const rows = await db.update(schema.session_sleeps)
525
+ .set({ status: 'cancelled' })
526
+ .where(orm.and(
527
+ orm.eq(schema.session_sleeps.status, 'planned'),
528
+ orm.eq(
529
+ schema.session_sleeps.session_id,
530
+ orm.sql`(SELECT ${schema.thread_sessions.session_id} FROM ${schema.thread_sessions} WHERE ${schema.thread_sessions.thread_id} = ${threadId})`,
531
+ ),
532
+ ))
533
+ .returning({ session_id: schema.session_sleeps.session_id })
534
+ return countRows(rows) > 0
535
+ }
536
+
370
537
  export async function getSessionStartSourcesBySessionIds(sessionIds: string[]) {
371
538
  if (sessionIds.length === 0) return new Map<string, SessionStartSource>()
372
539
  const db = await getDb()
@@ -652,9 +819,18 @@ export async function setThreadSession(threadId: string, sessionId: string) {
652
819
 
653
820
  export async function upsertThreadSession({ threadId, sessionId, source }: { threadId: string; sessionId: string; source: ThreadSessionSource }) {
654
821
  const db = await getDb()
822
+ // updated_at is written explicitly on BOTH paths, never left to the column's
823
+ // CURRENT_TIMESTAMP default. The default stores "YYYY-MM-DD HH:MM:SS" while
824
+ // Date values store ISO with a "T", and those two text formats do not sort
825
+ // against each other correctly. Writing ISO everywhere keeps the ordering in
826
+ // getThreadIdBySessionId honest and gives it millisecond resolution.
827
+ const boundAt = new Date()
655
828
  await db.insert(schema.thread_sessions)
656
- .values({ thread_id: threadId, session_id: sessionId, source })
657
- .onConflictDoUpdate({ target: schema.thread_sessions.thread_id, set: { session_id: sessionId, source } })
829
+ .values({ thread_id: threadId, session_id: sessionId, source, updated_at: boundAt })
830
+ .onConflictDoUpdate({
831
+ target: schema.thread_sessions.thread_id,
832
+ set: { session_id: sessionId, source, updated_at: boundAt },
833
+ })
658
834
  }
659
835
 
660
836
  export async function getThreadParentSessionId(threadId: string) {
@@ -686,9 +862,25 @@ export async function getThreadSessionSource(threadId: string) {
686
862
  return (await db.query.thread_sessions.findFirst({ where: { thread_id: threadId }, columns: { source: true } }))?.source
687
863
  }
688
864
 
865
+ /**
866
+ * Reverse lookup of the Discord thread that currently owns an OpenCode session.
867
+ *
868
+ * `thread_sessions.session_id` is NOT unique: /resume binds an existing session
869
+ * to a brand new thread without clearing the old row. An unordered findFirst
870
+ * therefore returns an arbitrary (often dead) thread, which made plugin tools
871
+ * post into the wrong conversation. Order by the most recent binding instead,
872
+ * falling back to created_at for rows written before updated_at existed.
873
+ */
689
874
  export async function getThreadIdBySessionId(sessionId: string) {
690
875
  const db = await getDb()
691
- return (await db.query.thread_sessions.findFirst({ where: { session_id: sessionId } }))?.thread_id
876
+ const rows = await db.select({ thread_id: schema.thread_sessions.thread_id })
877
+ .from(schema.thread_sessions)
878
+ .where(orm.eq(schema.thread_sessions.session_id, sessionId))
879
+ .orderBy(
880
+ orm.desc(orm.sql`COALESCE(${schema.thread_sessions.updated_at}, ${schema.thread_sessions.created_at})`),
881
+ )
882
+ .limit(1)
883
+ return rows[0]?.thread_id
692
884
  }
693
885
 
694
886
  export async function getAllThreadSessionIds() {
package/src/db.test.ts CHANGED
@@ -11,10 +11,14 @@ import * as schema from './schema.js'
11
11
  import {
12
12
  appendSessionEventsSinceLastTimestamp,
13
13
  createPendingWorkspace,
14
+ getDueSessionSleeps,
14
15
  getSessionEventSnapshot,
15
16
  getSessionModel,
17
+ getSessionSleep,
16
18
  setSessionModel,
19
+ upsertSessionSleep,
17
20
  } from './database.js'
21
+ import { createClient } from '@libsql/client'
18
22
  import { startHranaServer, stopHranaServer } from './hrana-server.js'
19
23
  import { chooseLockPort } from './test-utils.js'
20
24
  import { copyCurrentSessionModel } from './commands/model.js'
@@ -25,6 +29,190 @@ afterAll(async () => {
25
29
  })
26
30
 
27
31
  describe('getDb', () => {
32
+ test('schema.sql creates every drizzle table', () => {
33
+ const schemaTs = fs.readFileSync(
34
+ path.join(import.meta.dirname, 'schema.ts'),
35
+ 'utf8',
36
+ )
37
+ const schemaSql = fs.readFileSync(
38
+ path.join(import.meta.dirname, 'schema.sql'),
39
+ 'utf8',
40
+ )
41
+ const tablesFromTs = [
42
+ ...schemaTs.matchAll(/sqliteTable\('([^']+)'/g),
43
+ ].map((match) => match[1])
44
+ const tablesFromSql = [
45
+ ...schemaSql.matchAll(/CREATE TABLE IF NOT EXISTS `([^`]+)`/g),
46
+ ].map((match) => match[1])
47
+ expect(new Set(tablesFromSql)).toEqual(new Set(tablesFromTs))
48
+ expect(tablesFromSql).toContain('session_sleeps')
49
+ })
50
+
51
+ test('adds session_sleeps delivery columns on databases created before that schema', async () => {
52
+ await closeDb()
53
+
54
+ const previousDbUrl = process.env['KIMAKI_DB_URL']
55
+ const dbPath = path.join(
56
+ process.cwd(),
57
+ `tmp/test-db-legacy-sleeps-${crypto.randomUUID().slice(0, 8)}.db`,
58
+ )
59
+
60
+ try {
61
+ const client = createClient({ url: `file:${dbPath}` })
62
+ await client.execute(`
63
+ CREATE TABLE thread_sessions (
64
+ thread_id text PRIMARY KEY,
65
+ session_id text NOT NULL
66
+ )
67
+ `)
68
+ await client.execute(`
69
+ CREATE TABLE session_sleeps (
70
+ session_id text PRIMARY KEY,
71
+ thread_id text NOT NULL,
72
+ wake_at datetime NOT NULL,
73
+ reason text,
74
+ status text DEFAULT 'planned' NOT NULL,
75
+ created_at datetime DEFAULT CURRENT_TIMESTAMP
76
+ )
77
+ `)
78
+ await client.execute(`
79
+ INSERT INTO thread_sessions (thread_id, session_id)
80
+ VALUES ('thr-legacy', 'ses-legacy')
81
+ `)
82
+ await client.execute(`
83
+ INSERT INTO session_sleeps (session_id, thread_id, wake_at, status)
84
+ VALUES ('ses-legacy', 'thr-legacy', '2020-01-01T00:00:00.000Z', 'planned')
85
+ `)
86
+ client.close()
87
+
88
+ process.env['KIMAKI_DB_URL'] = `file:${dbPath}`
89
+ await getDb()
90
+
91
+ const due = await getDueSessionSleeps({
92
+ now: new Date('2026-08-21T00:00:00Z'),
93
+ retryAfterMs: 30_000,
94
+ limit: 10,
95
+ })
96
+ const legacy = due.find((row) => row.session_id === 'ses-legacy')
97
+ expect(legacy?.delivery_id).toBeTruthy()
98
+ expect(legacy?.attempts).toBe(0)
99
+
100
+ // The first table required thread_id. After the column was dropped from
101
+ // the schema, inserts that omit it must still work on existing databases.
102
+ await upsertSessionSleep({
103
+ sessionId: 'ses-legacy-new',
104
+ wakeAt: new Date('2026-08-26T00:00:00Z'),
105
+ reason: 'check the reply',
106
+ })
107
+ const created = await getSessionSleep({ sessionId: 'ses-legacy-new' })
108
+ expect(created?.status).toBe('planned')
109
+ expect(created?.reason).toBe('check the reply')
110
+ expect(created?.delivery_id).toBeTruthy()
111
+ } finally {
112
+ await closeDb()
113
+ if (previousDbUrl === undefined) {
114
+ delete process.env['KIMAKI_DB_URL']
115
+ } else {
116
+ process.env['KIMAKI_DB_URL'] = previousDbUrl
117
+ }
118
+ for (const file of [dbPath, `${dbPath}-wal`, `${dbPath}-shm`]) {
119
+ try {
120
+ fs.unlinkSync(file)
121
+ } catch {
122
+ // Test cleanup best effort.
123
+ }
124
+ }
125
+ }
126
+ })
127
+
128
+ test('rebuilds session_sleeps that still have posted_at from the intermediate schema', async () => {
129
+ await closeDb()
130
+
131
+ const previousDbUrl = process.env['KIMAKI_DB_URL']
132
+ const dbPath = path.join(
133
+ process.cwd(),
134
+ `tmp/test-db-posted-sleeps-${crypto.randomUUID().slice(0, 8)}.db`,
135
+ )
136
+
137
+ try {
138
+ const client = createClient({ url: `file:${dbPath}` })
139
+ await client.execute(`
140
+ CREATE TABLE thread_sessions (
141
+ thread_id text PRIMARY KEY,
142
+ session_id text NOT NULL
143
+ )
144
+ `)
145
+ await client.execute(`
146
+ CREATE TABLE session_sleeps (
147
+ session_id text PRIMARY KEY,
148
+ thread_id text NOT NULL,
149
+ wake_at datetime NOT NULL,
150
+ reason text,
151
+ status text DEFAULT 'planned' NOT NULL,
152
+ delivery_id text NOT NULL,
153
+ attempts integer DEFAULT 0 NOT NULL,
154
+ last_attempt_at datetime,
155
+ posted_at datetime,
156
+ created_at datetime DEFAULT CURRENT_TIMESTAMP
157
+ )
158
+ `)
159
+ await client.execute(`
160
+ INSERT INTO thread_sessions (thread_id, session_id)
161
+ VALUES ('thr-posted', 'ses-posted')
162
+ `)
163
+ await client.execute(`
164
+ INSERT INTO session_sleeps (
165
+ session_id, thread_id, wake_at, status, delivery_id, posted_at
166
+ )
167
+ VALUES (
168
+ 'ses-posted',
169
+ 'thr-posted',
170
+ '2020-01-01T00:00:00.000Z',
171
+ 'posted',
172
+ 'del-posted',
173
+ '2020-01-01T00:00:01.000Z'
174
+ )
175
+ `)
176
+ client.close()
177
+
178
+ process.env['KIMAKI_DB_URL'] = `file:${dbPath}`
179
+ await getDb()
180
+
181
+ const due = await getDueSessionSleeps({
182
+ now: new Date('2026-08-21T00:00:00Z'),
183
+ retryAfterMs: 30_000,
184
+ limit: 10,
185
+ })
186
+ const posted = due.find((row) => row.session_id === 'ses-posted')
187
+ expect(posted?.status).toBe('planned')
188
+ expect(posted?.delivery_id).toBe('del-posted')
189
+
190
+ await upsertSessionSleep({
191
+ sessionId: 'ses-posted',
192
+ wakeAt: new Date('2026-08-26T00:00:00Z'),
193
+ reason: 'retry after schema change',
194
+ })
195
+ const updated = await getSessionSleep({ sessionId: 'ses-posted' })
196
+ expect(updated?.status).toBe('planned')
197
+ expect(updated?.reason).toBe('retry after schema change')
198
+ expect(updated?.delivery_id).not.toBe('del-posted')
199
+ } finally {
200
+ await closeDb()
201
+ if (previousDbUrl === undefined) {
202
+ delete process.env['KIMAKI_DB_URL']
203
+ } else {
204
+ process.env['KIMAKI_DB_URL'] = previousDbUrl
205
+ }
206
+ for (const file of [dbPath, `${dbPath}-wal`, `${dbPath}-shm`]) {
207
+ try {
208
+ fs.unlinkSync(file)
209
+ } catch {
210
+ // Test cleanup best effort.
211
+ }
212
+ }
213
+ }
214
+ })
215
+
28
216
  test('creates sqlite file and migrates schema automatically', async () => {
29
217
  const db = await getDb()
30
218
 
package/src/db.ts CHANGED
@@ -111,6 +111,23 @@ async function initializeDb(): Promise<KimakiDb> {
111
111
  return db
112
112
  }
113
113
 
114
+ // CREATE TABLE IF NOT EXISTS cannot drop columns. The first two session_sleeps
115
+ // shapes kept thread_id NOT NULL and posted_at. Inserts now omit thread_id, so
116
+ // existing DBs fail with SQLITE_CONSTRAINT_NOTNULL until those columns go away.
117
+ async function dropLegacySessionSleepsColumns(client: Client) {
118
+ const info = await client.execute('PRAGMA table_info(session_sleeps)')
119
+ const columns = new Set(info.rows.map((row) => String(row.name)))
120
+ if (columns.has('thread_id')) {
121
+ await client.execute('ALTER TABLE session_sleeps DROP COLUMN thread_id')
122
+ }
123
+ if (columns.has('posted_at')) {
124
+ await client.execute('ALTER TABLE session_sleeps DROP COLUMN posted_at')
125
+ }
126
+ await client.execute(
127
+ "UPDATE session_sleeps SET status = 'planned' WHERE status = 'posted'",
128
+ )
129
+ }
130
+
114
131
  async function migrateSchema({
115
132
  db,
116
133
  client,
@@ -159,7 +176,12 @@ async function migrateSchema({
159
176
  "ALTER TABLE thread_sessions ADD COLUMN source TEXT DEFAULT 'kimaki'",
160
177
  'ALTER TABLE thread_sessions ADD COLUMN last_synced_name TEXT',
161
178
  'ALTER TABLE thread_sessions ADD COLUMN parent_session_id TEXT',
179
+ 'ALTER TABLE thread_sessions ADD COLUMN updated_at DATETIME',
162
180
  'ALTER TABLE channel_directories ADD COLUMN guild_id TEXT',
181
+ // First session_sleeps shape had thread_id only. Later ticks query these.
182
+ 'ALTER TABLE session_sleeps ADD COLUMN delivery_id TEXT',
183
+ 'ALTER TABLE session_sleeps ADD COLUMN attempts INTEGER DEFAULT 0',
184
+ 'ALTER TABLE session_sleeps ADD COLUMN last_attempt_at DATETIME',
163
185
  ]
164
186
  for (const stmt of alterStatements) {
165
187
  await client.execute(stmt).catch(() => undefined)
@@ -180,11 +202,15 @@ async function migrateSchema({
180
202
  "UPDATE bot_tokens SET bot_mode = 'self_hosted' WHERE bot_mode = 'self-hosted'",
181
203
  "UPDATE bot_tokens SET proxy_url = REPLACE(proxy_url, 'discord-gateway.kimaki.xyz', 'discord-gateway.kimaki.dev') WHERE bot_mode = 'gateway' AND proxy_url LIKE '%discord-gateway.kimaki.xyz%'",
182
204
  "UPDATE thread_worktrees SET status = 'pending' WHERE status IS NULL",
205
+ "UPDATE session_sleeps SET delivery_id = lower(hex(randomblob(16))) WHERE delivery_id IS NULL",
206
+ 'UPDATE session_sleeps SET attempts = 0 WHERE attempts IS NULL',
183
207
  ]
184
208
  for (const stmt of migrationStatements) {
185
209
  await client.execute(stmt).catch(() => undefined)
186
210
  }
187
211
 
212
+ await dropLegacySessionSleepsColumns(client)
213
+
188
214
  // Migrate legacy thread_worktrees rows into thread_workspaces.
189
215
  // Rows that already exist in thread_workspaces (by thread_id) are skipped.
190
216
  await client.execute(`
@@ -23,6 +23,7 @@ import {
23
23
  getChannelMentionMode,
24
24
  getChannelDirectory,
25
25
  cancelAllPendingIpcRequests,
26
+ consumeSessionSleepWake,
26
27
  deleteChannelDirectoryById,
27
28
  createPendingWorkspace,
28
29
  setWorkspaceReady,
@@ -435,8 +436,8 @@ export async function startDiscordBot({
435
436
  discordLogger.error(
436
437
  `[GATEWAY] Shard ${shardId} exceeded ${MAX_RECONNECT_ATTEMPTS} reconnect attempts, self-restarting`,
437
438
  )
438
- // Self-restart: cleanup, then exit non-zero so the bin.ts wrapper
439
- // restarts us. Without the wrapper this exits after logging a warning.
439
+ // Self-restart: cleanup, then SIGKILL so the bin.ts wrapper
440
+ // restarts us. Without the wrapper this dies after logging a warning.
440
441
  void selfRestart('gateway-reconnect-limit')
441
442
  }
442
443
  })
@@ -840,6 +841,24 @@ export async function startDiscordBot({
840
841
  void cancelPendingFileUpload(thread.id)
841
842
  }
842
843
 
844
+ // A sleep wake only becomes a turn if it can still claim its own row.
845
+ // The claim fails when the user cancelled the sleep while the wake was
846
+ // being posted, so the superseded wake is dropped instead of starting a
847
+ // turn the user already replaced. Cancellation for every other kind of
848
+ // message happens inside runtime.enqueueIncoming().
849
+ const isSleepWake = Boolean(promptMarker?.sleepWake)
850
+ if (isSleepWake) {
851
+ const claimedWake = promptMarker?.sleepId
852
+ ? await consumeSessionSleepWake({ deliveryId: promptMarker.sleepId })
853
+ : false
854
+ if (!claimedWake) {
855
+ discordLogger.log(
856
+ `[SLEEP] ignoring superseded wake in thread ${thread.id}`,
857
+ )
858
+ return
859
+ }
860
+ }
861
+
843
862
  // Expensive pre-processing (voice transcription, context fetch,
844
863
  // attachment download) runs inside the runtime's serialized
845
864
  // preprocess chain, preserving Discord arrival order without
@@ -859,6 +878,7 @@ export async function startDiscordBot({
859
878
  permissions: cliInjectedPermissions,
860
879
  injectionGuardPatterns: cliInjectedInjectionGuardPatterns,
861
880
  parentSessionId: cliInjectedParentSessionId,
881
+ isSleepWake: isSleepWake || undefined,
862
882
  noReply: isLeadingMentionToOtherUser || undefined,
863
883
  sessionStartSource: sessionStartSource
864
884
  ? {
@@ -1038,14 +1058,9 @@ export async function startDiscordBot({
1038
1058
  })
1039
1059
  }
1040
1060
 
1041
- const sessionDirectory = await (async () => {
1042
- if (!worktreePromise) {
1043
- return projectDirectory
1044
- }
1045
- const result = await worktreePromise
1046
- if (result instanceof Error) return projectDirectory
1047
- return result
1048
- })()
1061
+ const worktreeResult = worktreePromise ? await worktreePromise : projectDirectory
1062
+ if (worktreeResult instanceof Error) return
1063
+ const sessionDirectory = worktreeResult
1049
1064
 
1050
1065
  const channelRuntime = getOrCreateRuntime({
1051
1066
  threadId: thread.id,
@@ -1392,17 +1407,9 @@ export async function startDiscordBot({
1392
1407
 
1393
1408
  const botThreadStartSource = parseSessionStartSourceFromMarker(marker)
1394
1409
 
1395
- const sessionDirectory = await (async () => {
1396
- if (cwdDirectory) {
1397
- return cwdDirectory
1398
- }
1399
- if (!worktreePromise) {
1400
- return projectDirectory
1401
- }
1402
- const result = await worktreePromise
1403
- if (result instanceof Error) return projectDirectory
1404
- return result
1405
- })()
1410
+ const worktreeResult = worktreePromise ? await worktreePromise : undefined
1411
+ if (worktreeResult instanceof Error) return
1412
+ const sessionDirectory = cwdDirectory ?? worktreeResult ?? projectDirectory
1406
1413
 
1407
1414
  const runtime = getOrCreateRuntime({
1408
1415
  threadId: thread.id,
@@ -1626,13 +1633,11 @@ export async function startDiscordBot({
1626
1633
  })
1627
1634
  })
1628
1635
 
1629
- // Self-restart: exit with code 1 so the bin.ts wrapper restarts us with
1630
- // exponential backoff and crash-loop detection. When running without the
1631
- // wrapper (e.g. `tsx src/cli.ts`), the process just exits and the user
1632
- // sees the non-zero exit code — they should use `tsx src/bin.ts` instead
1633
- // for auto-restart support. The previous detached-spawn fallback was
1634
- // unreliable: process.exit(0) could kill the child before it started,
1635
- // there was no backoff between restarts, and spawn failures were silent.
1636
+ // Self-restart: die so the bin.ts wrapper restarts us with exponential
1637
+ // backoff and crash-loop detection. process.exit() can hang joining native
1638
+ // worker threads after Discord gateway failures, so SIGKILL instead.
1639
+ // When running without the wrapper (e.g. `tsx src/cli.ts`), the process
1640
+ // just dies — use `tsx src/bin.ts` for auto-restart support.
1636
1641
  let selfRestarting = false
1637
1642
  async function selfRestart(reason: string) {
1638
1643
  if (selfRestarting) {
@@ -1641,6 +1646,7 @@ export async function startDiscordBot({
1641
1646
  }
1642
1647
  selfRestarting = true
1643
1648
  discordLogger.log(`Self-restarting (reason: ${reason})...`)
1649
+ setTimeout(() => process.kill(process.pid, 'SIGKILL'), 15_000)
1644
1650
  try {
1645
1651
  await handleShutdown(reason, { skipExit: true })
1646
1652
  } catch (error) {
@@ -1652,7 +1658,7 @@ export async function startDiscordBot({
1652
1658
  'No restart wrapper detected. Run via `tsx src/bin.ts` (dev) or `kimaki` (npm) for auto-restart on crash.',
1653
1659
  )
1654
1660
  }
1655
- process.exit(1)
1661
+ process.kill(process.pid, 'SIGKILL')
1656
1662
  }
1657
1663
 
1658
1664
  process.on('SIGUSR2', () => {
@@ -156,8 +156,22 @@ export async function registerCommands({
156
156
  new SlashCommandBuilder()
157
157
  .setName('merge-worktree')
158
158
  .setDescription(
159
- truncateCommandDescription('Squash-merge worktree into default branch. Aborts if main has uncommitted changes.'),
159
+ truncateCommandDescription('Merge worktree commits into the default branch'),
160
160
  )
161
+ .addStringOption((option) => {
162
+ option
163
+ .setName('strategy')
164
+ .setDescription(
165
+ truncateCommandDescription('How to merge commits (default: keep commits)'),
166
+ )
167
+ .setRequired(false)
168
+ .addChoices(
169
+ { name: 'Keep commits (rebase)', value: 'rebase' },
170
+ { name: 'Squash into one commit', value: 'squash' },
171
+ )
172
+
173
+ return option
174
+ })
161
175
  .addStringOption((option) => {
162
176
  option
163
177
  .setName('target-branch')
@@ -3,6 +3,7 @@ import { afterEach, describe, expect, test } from 'vitest'
3
3
  import {
4
4
  hasKimakiAdminPermission,
5
5
  hasKimakiBotPermission,
6
+ raceDiscordRename,
6
7
  resolveGuildMessageMember,
7
8
  splitMarkdownForDiscord,
8
9
  } from './discord-utils.js'
@@ -292,3 +293,21 @@ describe('resolveGuildMessageMember', () => {
292
293
  await expect(resolveGuildMessageMember(message)).resolves.toBe(null)
293
294
  })
294
295
  })
296
+
297
+ describe('raceDiscordRename', () => {
298
+ test('returns timeout when rename hangs', async () => {
299
+ const result = await raceDiscordRename({
300
+ rename: new Promise(() => {}),
301
+ timeoutMs: 20,
302
+ })
303
+ expect(result).toBe('timeout')
304
+ })
305
+
306
+ test('returns rename result when it finishes first', async () => {
307
+ const result = await raceDiscordRename({
308
+ rename: Promise.resolve('ok'),
309
+ timeoutMs: 1000,
310
+ })
311
+ expect(result).toBe('ok')
312
+ })
313
+ })