@goah/cli 0.13.0 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/dist/LICENSE +201 -0
  2. package/dist/THIRD-PARTY-NOTICES.md +2319 -0
  3. package/dist/anthropic-messages-WBFOHES5.js +7214 -0
  4. package/dist/azure-openai-responses-NZFH3PO6.js +253 -0
  5. package/dist/chunk-25XSBFX6.js +639 -0
  6. package/dist/chunk-2QBQZGXF.js +110 -0
  7. package/dist/chunk-2ZP2NBW3.js +345 -0
  8. package/dist/chunk-4KA63VNZ.js +2 -0
  9. package/dist/chunk-4M6TXTT5.js +86 -0
  10. package/dist/chunk-4US7ZHT3.js +20 -0
  11. package/dist/chunk-6M3OOCKO.js +11809 -0
  12. package/dist/chunk-7AXAFDPG.js +17 -0
  13. package/dist/chunk-7E7V6OIU.js +920 -0
  14. package/dist/chunk-BXA47DTF.js +548 -0
  15. package/dist/chunk-D2DVAH37.js +25 -0
  16. package/dist/chunk-FSBUS2BI.js +26 -0
  17. package/dist/chunk-GKDRAHLI.js +4787 -0
  18. package/dist/chunk-H462EFJP.js +89 -0
  19. package/dist/chunk-IIJQ3DW4.js +35 -0
  20. package/dist/chunk-JQD5EWJY.js +34 -0
  21. package/dist/chunk-K26BVR6O.js +61 -0
  22. package/dist/chunk-KAO7WIXG.js +31 -0
  23. package/dist/chunk-KJ4HJCTK.js +1178 -0
  24. package/dist/chunk-LBKI23CC.js +9810 -0
  25. package/dist/chunk-LKBKZEHT.js +41 -0
  26. package/dist/chunk-MD7TLTXZ.js +18 -0
  27. package/dist/chunk-MPXK7QBL.js +868 -0
  28. package/dist/chunk-NRLGWZJC.js +11 -0
  29. package/dist/chunk-QBD6EJ2Z.js +1746 -0
  30. package/dist/chunk-R6I3VKME.js +132 -0
  31. package/dist/chunk-TJON22J4.js +87 -0
  32. package/dist/chunk-ULY36ME4.js +33097 -0
  33. package/dist/chunk-XALZLRYK.js +9221 -0
  34. package/dist/chunk-XPQKM3L7.js +57 -0
  35. package/dist/chunk-YH6YJ2IB.js +1773 -0
  36. package/dist/cli.d.ts +0 -2
  37. package/dist/cli.js +13716 -580
  38. package/dist/console/assets/{index-Rtc_B7cs.js → index-B1vGMXKr.js} +11 -11
  39. package/dist/console/assets/{index-Rtc_B7cs.js.map → index-B1vGMXKr.js.map} +1 -1
  40. package/dist/console/index.html +1 -1
  41. package/dist/dist-65MDQA4Q.js +1126 -0
  42. package/dist/dist-KNR2XL6J.js +39 -0
  43. package/dist/execution.d.ts +557 -2
  44. package/dist/execution.js +37 -2
  45. package/dist/faux-runner-worker.js +128 -0
  46. package/dist/google-generative-ai-YMHXZSFE.js +422 -0
  47. package/dist/google-vertex-X6DB3ZQ6.js +471 -0
  48. package/dist/index.d.ts +853 -25
  49. package/dist/index.js +84 -385
  50. package/dist/kernel.d.ts +39 -2
  51. package/dist/kernel.js +21 -2
  52. package/dist/mistral-conversations-TY3MMD6G.js +718 -0
  53. package/dist/multipart-parser-F6M4NJZU.js +373 -0
  54. package/dist/openai-codex-responses-BRDUMLN5.js +1374 -0
  55. package/dist/openai-completions-CX634XN3.js +1139 -0
  56. package/dist/openai-responses-HMCXJIHT.js +300 -0
  57. package/dist/openrouter-images-KTWET2H2.js +148 -0
  58. package/dist/pi-messages-XL5OEC4K.js +307 -0
  59. package/dist/pi-worker.js +671 -0
  60. package/dist/runner-pi.d.ts +342 -2
  61. package/dist/runner-pi.js +46 -2
  62. package/dist/runner-registry-GD4BYCQC.js +22 -0
  63. package/dist/sqlite.d.ts +446 -2
  64. package/dist/sqlite.js +15 -2
  65. package/dist/src-F2KBSV4T.js +1398 -0
  66. package/dist/supervisor.d.ts +625 -2
  67. package/dist/supervisor.js +39 -2
  68. package/dist/testkit.d.ts +564 -2
  69. package/dist/testkit.js +127 -2
  70. package/dist/transcript.d.ts +84 -2
  71. package/dist/transcript.js +25 -2
  72. package/dist/verification-worker.js +72 -0
  73. package/package.json +2 -26
  74. package/dist/cli.d.ts.map +0 -1
  75. package/dist/cli.js.map +0 -1
  76. package/dist/control.d.ts +0 -106
  77. package/dist/control.d.ts.map +0 -1
  78. package/dist/control.js +0 -242
  79. package/dist/control.js.map +0 -1
  80. package/dist/execution.d.ts.map +0 -1
  81. package/dist/execution.js.map +0 -1
  82. package/dist/index.d.ts.map +0 -1
  83. package/dist/index.js.map +0 -1
  84. package/dist/kernel.d.ts.map +0 -1
  85. package/dist/kernel.js.map +0 -1
  86. package/dist/live-config.d.ts +0 -10
  87. package/dist/live-config.d.ts.map +0 -1
  88. package/dist/live-config.js +0 -44
  89. package/dist/live-config.js.map +0 -1
  90. package/dist/prompt-queue.d.ts +0 -13
  91. package/dist/prompt-queue.d.ts.map +0 -1
  92. package/dist/prompt-queue.js +0 -35
  93. package/dist/prompt-queue.js.map +0 -1
  94. package/dist/runner-pi.d.ts.map +0 -1
  95. package/dist/runner-pi.js.map +0 -1
  96. package/dist/runner-registry.d.ts +0 -8
  97. package/dist/runner-registry.d.ts.map +0 -1
  98. package/dist/runner-registry.js +0 -12
  99. package/dist/runner-registry.js.map +0 -1
  100. package/dist/searchable-select.d.ts +0 -24
  101. package/dist/searchable-select.d.ts.map +0 -1
  102. package/dist/searchable-select.js +0 -61
  103. package/dist/searchable-select.js.map +0 -1
  104. package/dist/secret-input.d.ts +0 -8
  105. package/dist/secret-input.d.ts.map +0 -1
  106. package/dist/secret-input.js +0 -14
  107. package/dist/secret-input.js.map +0 -1
  108. package/dist/setup-wizard.d.ts +0 -22
  109. package/dist/setup-wizard.d.ts.map +0 -1
  110. package/dist/setup-wizard.js +0 -154
  111. package/dist/setup-wizard.js.map +0 -1
  112. package/dist/sqlite.d.ts.map +0 -1
  113. package/dist/sqlite.js.map +0 -1
  114. package/dist/supervisor.d.ts.map +0 -1
  115. package/dist/supervisor.js.map +0 -1
  116. package/dist/testkit.d.ts.map +0 -1
  117. package/dist/testkit.js.map +0 -1
  118. package/dist/thread-inspect.d.ts +0 -47
  119. package/dist/thread-inspect.d.ts.map +0 -1
  120. package/dist/thread-inspect.js +0 -78
  121. package/dist/thread-inspect.js.map +0 -1
  122. package/dist/transcript.d.ts.map +0 -1
  123. package/dist/transcript.js.map +0 -1
  124. package/dist/tui-theme.d.ts +0 -17
  125. package/dist/tui-theme.d.ts.map +0 -1
  126. package/dist/tui-theme.js +0 -19
  127. package/dist/tui-theme.js.map +0 -1
  128. package/dist/tui.d.ts +0 -24
  129. package/dist/tui.d.ts.map +0 -1
  130. package/dist/tui.js +0 -784
  131. package/dist/tui.js.map +0 -1
  132. package/dist/update.d.ts +0 -16
  133. package/dist/update.d.ts.map +0 -1
  134. package/dist/update.js +0 -67
  135. package/dist/update.js.map +0 -1
  136. package/dist/web-console.d.ts +0 -33
  137. package/dist/web-console.d.ts.map +0 -1
  138. package/dist/web-console.js +0 -242
  139. package/dist/web-console.js.map +0 -1
  140. package/dist/welcome.d.ts +0 -30
  141. package/dist/welcome.d.ts.map +0 -1
  142. package/dist/welcome.js +0 -69
  143. package/dist/welcome.js.map +0 -1
  144. package/node_modules/goah-ledger-contract/dist/execution.d.ts +0 -544
  145. package/node_modules/goah-ledger-contract/dist/execution.d.ts.map +0 -1
  146. package/node_modules/goah-ledger-contract/dist/execution.js +0 -52
  147. package/node_modules/goah-ledger-contract/dist/execution.js.map +0 -1
  148. package/node_modules/goah-ledger-contract/dist/index.d.ts +0 -4
  149. package/node_modules/goah-ledger-contract/dist/index.d.ts.map +0 -1
  150. package/node_modules/goah-ledger-contract/dist/index.js +0 -4
  151. package/node_modules/goah-ledger-contract/dist/index.js.map +0 -1
  152. package/node_modules/goah-ledger-contract/dist/kernel.d.ts +0 -37
  153. package/node_modules/goah-ledger-contract/dist/kernel.d.ts.map +0 -1
  154. package/node_modules/goah-ledger-contract/dist/kernel.js +0 -8
  155. package/node_modules/goah-ledger-contract/dist/kernel.js.map +0 -1
  156. package/node_modules/goah-ledger-contract/dist/transcript.d.ts +0 -63
  157. package/node_modules/goah-ledger-contract/dist/transcript.d.ts.map +0 -1
  158. package/node_modules/goah-ledger-contract/dist/transcript.js +0 -115
  159. package/node_modules/goah-ledger-contract/dist/transcript.js.map +0 -1
  160. package/node_modules/goah-ledger-contract/package.json +0 -28
  161. package/node_modules/goah-ledger-sqlite/dist/index.d.ts +0 -86
  162. package/node_modules/goah-ledger-sqlite/dist/index.d.ts.map +0 -1
  163. package/node_modules/goah-ledger-sqlite/dist/index.js +0 -1254
  164. package/node_modules/goah-ledger-sqlite/dist/index.js.map +0 -1
  165. package/node_modules/goah-ledger-sqlite/package.json +0 -26
  166. package/node_modules/goah-runner-pi/dist/configurator.d.ts +0 -20
  167. package/node_modules/goah-runner-pi/dist/configurator.d.ts.map +0 -1
  168. package/node_modules/goah-runner-pi/dist/configurator.js +0 -423
  169. package/node_modules/goah-runner-pi/dist/configurator.js.map +0 -1
  170. package/node_modules/goah-runner-pi/dist/credential-store.d.ts +0 -14
  171. package/node_modules/goah-runner-pi/dist/credential-store.d.ts.map +0 -1
  172. package/node_modules/goah-runner-pi/dist/credential-store.js +0 -163
  173. package/node_modules/goah-runner-pi/dist/credential-store.js.map +0 -1
  174. package/node_modules/goah-runner-pi/dist/env-spec.d.ts +0 -17
  175. package/node_modules/goah-runner-pi/dist/env-spec.d.ts.map +0 -1
  176. package/node_modules/goah-runner-pi/dist/env-spec.js +0 -95
  177. package/node_modules/goah-runner-pi/dist/env-spec.js.map +0 -1
  178. package/node_modules/goah-runner-pi/dist/index.d.ts +0 -76
  179. package/node_modules/goah-runner-pi/dist/index.d.ts.map +0 -1
  180. package/node_modules/goah-runner-pi/dist/index.js +0 -326
  181. package/node_modules/goah-runner-pi/dist/index.js.map +0 -1
  182. package/node_modules/goah-runner-pi/dist/model-provider.d.ts +0 -30
  183. package/node_modules/goah-runner-pi/dist/model-provider.d.ts.map +0 -1
  184. package/node_modules/goah-runner-pi/dist/model-provider.js +0 -96
  185. package/node_modules/goah-runner-pi/dist/model-provider.js.map +0 -1
  186. package/node_modules/goah-runner-pi/dist/pi-worker.d.ts +0 -31
  187. package/node_modules/goah-runner-pi/dist/pi-worker.d.ts.map +0 -1
  188. package/node_modules/goah-runner-pi/dist/pi-worker.js +0 -579
  189. package/node_modules/goah-runner-pi/dist/pi-worker.js.map +0 -1
  190. package/node_modules/goah-runner-pi/dist/steering-no-ack.test-fixture.d.ts +0 -2
  191. package/node_modules/goah-runner-pi/dist/steering-no-ack.test-fixture.d.ts.map +0 -1
  192. package/node_modules/goah-runner-pi/dist/steering-no-ack.test-fixture.js +0 -3
  193. package/node_modules/goah-runner-pi/dist/steering-no-ack.test-fixture.js.map +0 -1
  194. package/node_modules/goah-runner-pi/dist/steering-reject.test-fixture.d.ts +0 -2
  195. package/node_modules/goah-runner-pi/dist/steering-reject.test-fixture.d.ts.map +0 -1
  196. package/node_modules/goah-runner-pi/dist/steering-reject.test-fixture.js +0 -5
  197. package/node_modules/goah-runner-pi/dist/steering-reject.test-fixture.js.map +0 -1
  198. package/node_modules/goah-runner-pi/dist/steering-worker.test-fixture.d.ts +0 -2
  199. package/node_modules/goah-runner-pi/dist/steering-worker.test-fixture.d.ts.map +0 -1
  200. package/node_modules/goah-runner-pi/dist/steering-worker.test-fixture.js +0 -5
  201. package/node_modules/goah-runner-pi/dist/steering-worker.test-fixture.js.map +0 -1
  202. package/node_modules/goah-runner-pi/dist/test-helpers.d.ts +0 -4
  203. package/node_modules/goah-runner-pi/dist/test-helpers.d.ts.map +0 -1
  204. package/node_modules/goah-runner-pi/dist/test-helpers.js +0 -13
  205. package/node_modules/goah-runner-pi/dist/test-helpers.js.map +0 -1
  206. package/node_modules/goah-runner-pi/dist/verification-worker.d.ts +0 -2
  207. package/node_modules/goah-runner-pi/dist/verification-worker.d.ts.map +0 -1
  208. package/node_modules/goah-runner-pi/dist/verification-worker.js +0 -46
  209. package/node_modules/goah-runner-pi/dist/verification-worker.js.map +0 -1
  210. package/node_modules/goah-runner-pi/package.json +0 -28
  211. package/node_modules/goah-supervisor/dist/context-view.d.ts +0 -30
  212. package/node_modules/goah-supervisor/dist/context-view.d.ts.map +0 -1
  213. package/node_modules/goah-supervisor/dist/context-view.js +0 -58
  214. package/node_modules/goah-supervisor/dist/context-view.js.map +0 -1
  215. package/node_modules/goah-supervisor/dist/index.d.ts +0 -96
  216. package/node_modules/goah-supervisor/dist/index.d.ts.map +0 -1
  217. package/node_modules/goah-supervisor/dist/index.js +0 -1075
  218. package/node_modules/goah-supervisor/dist/index.js.map +0 -1
  219. package/node_modules/goah-supervisor/dist/roles.d.ts +0 -4
  220. package/node_modules/goah-supervisor/dist/roles.d.ts.map +0 -1
  221. package/node_modules/goah-supervisor/dist/roles.js +0 -29
  222. package/node_modules/goah-supervisor/dist/roles.js.map +0 -1
  223. package/node_modules/goah-supervisor/dist/verification.d.ts +0 -61
  224. package/node_modules/goah-supervisor/dist/verification.d.ts.map +0 -1
  225. package/node_modules/goah-supervisor/dist/verification.js +0 -135
  226. package/node_modules/goah-supervisor/dist/verification.js.map +0 -1
  227. package/node_modules/goah-supervisor/package.json +0 -26
  228. package/node_modules/goah-testkit/dist/faux-runner-worker.d.ts +0 -2
  229. package/node_modules/goah-testkit/dist/faux-runner-worker.d.ts.map +0 -1
  230. package/node_modules/goah-testkit/dist/faux-runner-worker.js +0 -82
  231. package/node_modules/goah-testkit/dist/faux-runner-worker.js.map +0 -1
  232. package/node_modules/goah-testkit/dist/index.d.ts +0 -49
  233. package/node_modules/goah-testkit/dist/index.d.ts.map +0 -1
  234. package/node_modules/goah-testkit/dist/index.js +0 -96
  235. package/node_modules/goah-testkit/dist/index.js.map +0 -1
  236. package/node_modules/goah-testkit/package.json +0 -29
@@ -1,1254 +0,0 @@
1
- import { DatabaseSync } from "node:sqlite";
2
- import { isDeepStrictEqual } from "node:util";
3
- import { assertHandoff, assertGoalSnapshot, assertGoalTransition, controlStream, goalStream, goalRoute, goalExecutionBinding, wakeStream, workRecordStream, } from "goah-ledger-contract";
4
- export const SQLITE_SCHEMA_VERSION = 24;
5
- const createThreads = `CREATE TABLE IF NOT EXISTS threads (
6
- id TEXT PRIMARY KEY,
7
- agent TEXT NOT NULL,
8
- parent_thread_id TEXT REFERENCES threads(id),
9
- created_at TEXT NOT NULL,
10
- updated_at TEXT NOT NULL,
11
- UNIQUE(agent)
12
- ) STRICT;`;
13
- const createTurns = `CREATE TABLE IF NOT EXISTS turns (
14
- id TEXT PRIMARY KEY,
15
- thread_id TEXT NOT NULL REFERENCES threads(id) ON DELETE CASCADE,
16
- source TEXT NOT NULL CHECK(source IN ('human','goal','system')),
17
- binding_kind TEXT NOT NULL CHECK(binding_kind IN ('human','goal','specialist')),
18
- specialist_role TEXT CHECK(specialist_role IS NULL OR specialist_role IN ('verifier','audit')),
19
- goal_id TEXT REFERENCES goals(id),
20
- goal_revision INTEGER CHECK(goal_revision IS NULL OR goal_revision >= 0),
21
- status TEXT NOT NULL CHECK(status IN ('in_progress','completed','failed','interrupted')),
22
- attempt INTEGER NOT NULL CHECK(attempt > 0),
23
- error TEXT CHECK(error IS NULL OR json_valid(error)),
24
- started_at TEXT NOT NULL,
25
- ended_at TEXT,
26
- lease_until TEXT,
27
- lease_token TEXT,
28
- runner_pid INTEGER,
29
- runner_profile_id TEXT,
30
- CHECK((goal_id IS NULL) = (goal_revision IS NULL)),
31
- CHECK((binding_kind='human' AND goal_id IS NULL AND specialist_role IS NULL) OR (binding_kind='goal' AND goal_id IS NOT NULL AND specialist_role IS NULL) OR (binding_kind='specialist' AND goal_id IS NULL AND specialist_role IS NOT NULL)),
32
- CHECK((binding_kind='human' AND source='human') OR (binding_kind='goal' AND source IN ('human','goal')) OR (binding_kind='specialist' AND source='system')),
33
- CHECK((status='in_progress' AND ended_at IS NULL AND lease_until IS NOT NULL AND lease_token IS NOT NULL) OR (status<>'in_progress' AND ended_at IS NOT NULL AND lease_until IS NULL AND lease_token IS NULL AND runner_pid IS NULL))
34
- ) STRICT;`;
35
- const createTurnItems = `CREATE TABLE IF NOT EXISTS turn_items (
36
- id TEXT PRIMARY KEY,
37
- turn_id TEXT NOT NULL REFERENCES turns(id) ON DELETE CASCADE,
38
- ordinal INTEGER NOT NULL CHECK(ordinal > 0),
39
- type TEXT NOT NULL CHECK(type IN ('user_message','assistant_message','reasoning','tool_call','tool_result','plan','handoff')),
40
- status TEXT NOT NULL CHECK(status IN ('in_progress','completed','failed')),
41
- data TEXT NOT NULL CHECK(json_valid(data)),
42
- created_at TEXT NOT NULL,
43
- completed_at TEXT,
44
- UNIQUE(turn_id, ordinal),
45
- CHECK((status='in_progress' AND completed_at IS NULL) OR (status<>'in_progress' AND completed_at IS NOT NULL))
46
- ) STRICT;`;
47
- const createGoals = `CREATE TABLE IF NOT EXISTS goals (
48
- id TEXT PRIMARY KEY,
49
- parent_id TEXT REFERENCES goals(id),
50
- objective TEXT NOT NULL,
51
- observation_method TEXT CHECK(observation_method IS NULL OR length(trim(observation_method)) > 0),
52
- verification_method TEXT CHECK(verification_method IS NULL OR length(trim(verification_method)) > 0),
53
- owner TEXT NOT NULL,
54
- phase TEXT NOT NULL CHECK(phase IN ('active','paused','blocked','complete')),
55
- revision INTEGER NOT NULL CHECK(revision >= 0)
56
- ) STRICT;`;
57
- const createWorkRecords = `CREATE TABLE IF NOT EXISTS work_records (
58
- goal_id TEXT PRIMARY KEY REFERENCES goals(id),
59
- record_revision INTEGER NOT NULL CHECK(record_revision >= 0),
60
- goal_revision INTEGER NOT NULL CHECK(goal_revision >= 0),
61
- content TEXT NOT NULL CHECK(length(trim(content)) > 0),
62
- updated_by TEXT NOT NULL,
63
- updated_in_turn TEXT NOT NULL,
64
- source_wake_id TEXT,
65
- updated_at TEXT NOT NULL,
66
- reason TEXT NOT NULL CHECK(length(trim(reason)) > 0),
67
- evidence TEXT NOT NULL CHECK(json_valid(evidence)),
68
- last_event_seq INTEGER NOT NULL REFERENCES events(seq)
69
- ) STRICT;`;
70
- const createWakes = `CREATE TABLE IF NOT EXISTS wakes (
71
- id TEXT PRIMARY KEY,
72
- binding_kind TEXT NOT NULL CHECK(binding_kind IN ('human','goal','specialist')),
73
- agent TEXT NOT NULL,
74
- specialist_role TEXT CHECK(specialist_role IS NULL OR specialist_role IN ('verifier','audit')),
75
- trigger_ref TEXT NOT NULL,
76
- status TEXT NOT NULL CHECK(status IN ('queued','claimed','consumed','cancelled')),
77
- attempt INTEGER NOT NULL CHECK(attempt >= 0),
78
- enqueued_seq INTEGER NOT NULL CHECK(enqueued_seq > 0),
79
- claimed_at TEXT,
80
- consumed_at TEXT,
81
- turn_id TEXT REFERENCES turns(id),
82
- goal_id TEXT REFERENCES goals(id),
83
- UNIQUE(agent, trigger_ref),
84
- UNIQUE(turn_id),
85
- CHECK((status='claimed' AND claimed_at IS NOT NULL) OR status<>'claimed'),
86
- CHECK((status='consumed' AND consumed_at IS NOT NULL AND turn_id IS NOT NULL) OR status<>'consumed'),
87
- CHECK((binding_kind='human' AND agent='ceo' AND goal_id IS NULL AND specialist_role IS NULL) OR (binding_kind='goal' AND goal_id IS NOT NULL AND specialist_role IS NULL) OR (binding_kind='specialist' AND goal_id IS NULL AND specialist_role IS NOT NULL))
88
- ) STRICT;`;
89
- const createWakeTriggers = `CREATE TABLE IF NOT EXISTS wake_triggers (
90
- wake_id TEXT NOT NULL REFERENCES wakes(id) ON DELETE CASCADE,
91
- agent TEXT NOT NULL,
92
- trigger_ref TEXT NOT NULL,
93
- source TEXT NOT NULL CHECK(source IN ('human','goal','system')),
94
- status TEXT NOT NULL CHECK(status IN ('pending','resolved')),
95
- added_at TEXT NOT NULL,
96
- resolved_at TEXT,
97
- PRIMARY KEY(wake_id,trigger_ref),
98
- UNIQUE(agent,trigger_ref),
99
- CHECK((status='pending' AND resolved_at IS NULL) OR (status='resolved' AND resolved_at IS NOT NULL))
100
- ) STRICT;`;
101
- const indexesAndTriggers = `
102
- CREATE UNIQUE INDEX IF NOT EXISTS turns_one_active_thread ON turns(thread_id) WHERE status='in_progress';
103
- CREATE INDEX IF NOT EXISTS turns_thread_started ON turns(thread_id,started_at,id);
104
- CREATE INDEX IF NOT EXISTS turn_items_turn_ordinal ON turn_items(turn_id,ordinal);
105
- CREATE UNIQUE INDEX IF NOT EXISTS wakes_one_claimed_agent ON wakes(agent) WHERE status='claimed';
106
- CREATE INDEX IF NOT EXISTS wakes_queue_order ON wakes(status, enqueued_seq);
107
- CREATE INDEX IF NOT EXISTS wake_triggers_pending ON wake_triggers(wake_id,status);
108
- CREATE INDEX IF NOT EXISTS schedule_due ON schedule(status,next_wake_at);
109
- CREATE INDEX IF NOT EXISTS events_actor_type_seq ON events(actor, type, seq DESC);
110
- CREATE INDEX IF NOT EXISTS events_stream_seq ON events(stream_id, stream_seq);
111
- CREATE VIRTUAL TABLE IF NOT EXISTS events_fts USING fts5(actor, type, data, content='events', content_rowid='seq');
112
-
113
- CREATE TRIGGER IF NOT EXISTS events_no_update BEFORE UPDATE ON events
114
- BEGIN SELECT RAISE(ABORT, 'events are append-only'); END;
115
- CREATE TRIGGER IF NOT EXISTS events_no_delete BEFORE DELETE ON events
116
- BEGIN SELECT RAISE(ABORT, 'events are append-only'); END;
117
- CREATE TRIGGER IF NOT EXISTS events_fts_insert AFTER INSERT ON events
118
- BEGIN INSERT INTO events_fts(rowid,actor,type,data) VALUES (new.seq,new.actor,new.type,new.data); END;
119
-
120
- CREATE TRIGGER IF NOT EXISTS wakes_valid_transition BEFORE UPDATE OF status ON wakes
121
- WHEN OLD.status <> NEW.status AND NOT (
122
- (OLD.status = 'queued' AND NEW.status IN ('claimed','cancelled')) OR
123
- (OLD.status = 'claimed' AND NEW.status IN ('queued','consumed','cancelled'))
124
- )
125
- BEGIN SELECT RAISE(ABORT, 'invalid wake transition'); END;
126
-
127
- CREATE TRIGGER IF NOT EXISTS schedule_valid_transition BEFORE UPDATE OF status ON schedule
128
- WHEN OLD.status <> NEW.status AND NOT (
129
- OLD.status = 'pending' AND NEW.status IN ('consumed','cancelled','superseded')
130
- )
131
- BEGIN SELECT RAISE(ABORT, 'invalid schedule transition'); END;
132
-
133
- CREATE TRIGGER IF NOT EXISTS wake_triggers_valid_transition BEFORE UPDATE OF status ON wake_triggers
134
- WHEN OLD.status <> NEW.status AND NOT (OLD.status='pending' AND NEW.status='resolved')
135
- BEGIN SELECT RAISE(ABORT, 'invalid Wake trigger transition'); END;
136
-
137
- CREATE TRIGGER IF NOT EXISTS goals_valid_transition BEFORE UPDATE OF phase ON goals
138
- WHEN OLD.phase <> NEW.phase AND NOT (
139
- (OLD.phase = 'active' AND NEW.phase IN ('paused','blocked','complete')) OR
140
- (OLD.phase = 'paused' AND NEW.phase IN ('active','complete')) OR
141
- (OLD.phase = 'blocked' AND NEW.phase IN ('active','complete'))
142
- )
143
- BEGIN SELECT RAISE(ABORT, 'invalid goal transition'); END;
144
- `;
145
- const schema = `
146
- CREATE TABLE IF NOT EXISTS events (
147
- seq INTEGER PRIMARY KEY AUTOINCREMENT,
148
- stream_id TEXT NOT NULL,
149
- stream_seq INTEGER NOT NULL CHECK(stream_seq > 0),
150
- ts TEXT NOT NULL,
151
- actor TEXT NOT NULL,
152
- type TEXT NOT NULL,
153
- data TEXT NOT NULL CHECK(json_valid(data)),
154
- projection_name TEXT,
155
- ignorable INTEGER CHECK(ignorable IS NULL OR ignorable = 1),
156
- UNIQUE(stream_id, stream_seq)
157
- ) STRICT;
158
- ${createGoals}
159
- ${createWorkRecords}
160
- ${createThreads}
161
- ${createTurns}
162
- ${createTurnItems}
163
- CREATE TABLE IF NOT EXISTS schedule (
164
- id TEXT PRIMARY KEY,
165
- binding_kind TEXT NOT NULL CHECK(binding_kind IN ('goal','specialist')),
166
- agent TEXT NOT NULL,
167
- specialist_role TEXT CHECK(specialist_role IS NULL OR specialist_role IN ('verifier','audit')),
168
- next_wake_at TEXT NOT NULL,
169
- reason TEXT NOT NULL,
170
- set_by TEXT NOT NULL,
171
- status TEXT NOT NULL CHECK(status IN ('pending','consumed','cancelled','superseded')),
172
- resolved_at TEXT,
173
- goal_id TEXT REFERENCES goals(id),
174
- CHECK((status='pending' AND resolved_at IS NULL) OR (status<>'pending' AND resolved_at IS NOT NULL)),
175
- CHECK((binding_kind='goal' AND goal_id IS NOT NULL AND specialist_role IS NULL) OR (binding_kind='specialist' AND goal_id IS NULL AND specialist_role IS NOT NULL))
176
- ) STRICT;
177
- ${createWakes}
178
- ${createWakeTriggers}
179
- CREATE TABLE IF NOT EXISTS mailbox (
180
- id TEXT PRIMARY KEY,
181
- route_kind TEXT NOT NULL CHECK(route_kind IN ('goal','human_inbox','human_request','specialist_inbox')),
182
- to_agent TEXT NOT NULL,
183
- from_agent TEXT NOT NULL,
184
- specialist_role TEXT CHECK(specialist_role IS NULL OR specialist_role IN ('verifier','audit')),
185
- level TEXT NOT NULL CHECK(level IN ('fyi','decision','emergency')),
186
- goal_id TEXT REFERENCES goals(id),
187
- body TEXT NOT NULL CHECK(json_valid(body)),
188
- read_at TEXT,
189
- CHECK((route_kind='goal' AND goal_id IS NOT NULL AND specialist_role IS NULL) OR (route_kind='human_inbox' AND to_agent='ceo' AND from_agent IN ('human','verifier','audit','supervisor') AND goal_id IS NULL AND specialist_role IS NULL) OR (route_kind='human_request' AND to_agent='human' AND from_agent='ceo' AND goal_id IS NULL AND specialist_role IS NULL) OR (route_kind='specialist_inbox' AND goal_id IS NULL AND specialist_role IS NOT NULL))
190
- ) STRICT;
191
- ${indexesAndTriggers}`;
192
- class SystemClock {
193
- now() { return new Date(); }
194
- }
195
- export class SqliteLedger {
196
- db;
197
- #faultInjector;
198
- #clock;
199
- constructor(path = ":memory:", options = {}) {
200
- this.db = new DatabaseSync(path);
201
- this.db.exec(`PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = ${options.busyTimeoutMs ?? 5_000};`);
202
- this.#faultInjector = options.faultInjector;
203
- this.#clock = options.clock ?? new SystemClock();
204
- const version = Number(this.db.prepare("PRAGMA user_version").get().user_version);
205
- if (version > SQLITE_SCHEMA_VERSION) {
206
- this.db.close();
207
- throw new Error(`ledger schema ${version} is newer than supported schema ${SQLITE_SCHEMA_VERSION}`);
208
- }
209
- if (version > 0 && version < SQLITE_SCHEMA_VERSION) {
210
- this.db.close();
211
- throw new Error(`ledger schema ${version} predates runtime schema ${SQLITE_SCHEMA_VERSION}; recreate this development workspace`);
212
- }
213
- if (version === 0) {
214
- this.db.exec(schema);
215
- this.db.exec(`PRAGMA user_version = ${SQLITE_SCHEMA_VERSION}`);
216
- }
217
- else {
218
- this.db.exec(schema);
219
- }
220
- }
221
- close() { this.db.close(); }
222
- appendEvent(input) { this.#assertRawEvent(input); return this.#transaction(() => this.#insertEvent(input)); }
223
- appendEvents(inputs) { for (const input of inputs)
224
- this.#assertRawEvent(input); return this.#transaction(() => inputs.map((input) => this.#insertEvent(input))); }
225
- readStream(streamId, fromStreamSeq = 1) {
226
- return this.db.prepare("SELECT * FROM events WHERE stream_id=? AND stream_seq>=? ORDER BY stream_seq").all(streamId, fromStreamSeq).map(mapEvent);
227
- }
228
- putThread(thread, actor) {
229
- if (!thread.id.trim() || !thread.agent.trim())
230
- throw new Error("thread id and agent are required");
231
- const current = this.thread(thread.id);
232
- const agentThread = this.threads().find((candidate) => candidate.agent === thread.agent);
233
- if (agentThread && agentThread.id !== thread.id)
234
- throw new Error("agent already owns a Thread");
235
- if (current && (current.agent !== thread.agent || current.parentThreadId !== thread.parentThreadId || current.createdAt !== thread.createdAt))
236
- throw new Error("thread identity cannot change");
237
- return this.#project("threads", thread, actor, "thread.put", undefined, thread.updatedAt, `thread:${thread.id}`);
238
- }
239
- putTurn(turn, actor) {
240
- if (!turn.id.trim() || !turn.threadId.trim())
241
- throw new Error("turn id and thread are required");
242
- this.#assertTurnBinding(turn);
243
- if (turn.status === "in_progress" && (!turn.leaseUntil || !turn.leaseToken) || turn.status !== "in_progress" && (turn.leaseUntil !== null || turn.leaseToken !== null || turn.runnerPid !== null))
244
- throw new Error("Turn execution ownership does not match status");
245
- const thread = this.thread(turn.threadId);
246
- if (!thread)
247
- throw new Error("Turn Thread does not exist");
248
- const current = this.turn(turn.id);
249
- if (current) {
250
- if (turn.status !== "in_progress")
251
- throw new Error("terminal Turn state must be committed through finishTurn or commitHandoff");
252
- if (current.threadId !== turn.threadId || current.source !== turn.source)
253
- throw new Error("turn identity cannot change");
254
- if (current.runnerProfileId !== turn.runnerProfileId)
255
- throw new Error("turn Runner Profile cannot change");
256
- if (current.status !== "in_progress")
257
- throw new Error("terminal turn cannot change");
258
- const bindsGoal = actor === "supervisor" && current.bindingKind === "human" && turn.bindingKind === "goal" && current.source === "human";
259
- if (current.bindingKind !== turn.bindingKind && !bindsGoal || current.bindingKind === turn.bindingKind && (current.goalId !== turn.goalId || current.goalRevision !== turn.goalRevision || current.specialistRole !== turn.specialistRole))
260
- throw new Error("turn execution binding cannot change");
261
- if (bindsGoal) {
262
- const goal = this.#getGoal(turn.goalId);
263
- if (thread.agent !== "ceo" || !goal || goal.parentId !== null || goal.owner !== "ceo" || goal.phase !== "active" || goal.revision !== turn.goalRevision)
264
- throw new Error("Human Turn may bind only the current active CEO Root Goal");
265
- }
266
- if (turn.attempt !== current.attempt && turn.attempt !== current.attempt + 1)
267
- throw new Error("turn attempt must stay current or increment by one");
268
- if (turn.status === "in_progress" && turn.endedAt !== null || turn.status !== "in_progress" && turn.endedAt === null)
269
- throw new Error("turn terminal time does not match status");
270
- }
271
- else {
272
- if (turn.status !== "in_progress" || turn.attempt !== 1)
273
- throw new Error("new turn must start in progress at attempt one");
274
- if (actor !== "human" || thread.agent !== "ceo" || turn.bindingKind !== "human")
275
- throw new Error("new automatic Turns must start from a claimed Wake");
276
- }
277
- return this.#project("turns", turn, actor, current ? `turn.${turn.status}` : "turn.started", undefined, undefined, `turn:${turn.id}`);
278
- }
279
- putTurnItem(item, actor) {
280
- return this.#transaction(() => this.#admitTurnItem(item, actor));
281
- }
282
- thread(id) { const row = this.db.prepare("SELECT * FROM threads WHERE id=?").get(id); return row ? mapThread(row) : null; }
283
- threads() { return this.db.prepare("SELECT * FROM threads ORDER BY created_at,id").all().map(mapThread); }
284
- turn(id) { const row = this.db.prepare("SELECT * FROM turns WHERE id=?").get(id); return row ? mapTurn(row) : null; }
285
- turns(threadId) { return (threadId ? this.db.prepare("SELECT * FROM turns WHERE thread_id=? ORDER BY rowid").all(threadId) : this.db.prepare("SELECT * FROM turns ORDER BY rowid").all()).map(mapTurn); }
286
- turnItems(turnId) { return this.db.prepare("SELECT * FROM turn_items WHERE turn_id=? ORDER BY ordinal").all(turnId).map(mapTurnItem); }
287
- activeTurn(threadId) { const row = this.db.prepare("SELECT * FROM turns WHERE thread_id=? AND status='in_progress'").get(threadId); return row ? mapTurn(row) : null; }
288
- putGoal(goal, actor, wakeId, change) {
289
- const normalized = normalizeGoal(goal);
290
- assertGoalSnapshot(normalized);
291
- if (change?.idempotencyKey) {
292
- const row = this.db.prepare("SELECT * FROM events WHERE type='goal.changed' AND actor=? AND json_extract(data,'$.idempotencyKey')=? ORDER BY seq LIMIT 1").get(actor, change.idempotencyKey);
293
- if (row) {
294
- const event = mapEvent(row);
295
- const data = event.data;
296
- const same = isDeepStrictEqual(data.snapshot, normalized) && data.operation === change.operation && data.reason === change.reason.trim() && isDeepStrictEqual(data.evidence, change.evidence) && (!change.authority || isDeepStrictEqual(data.authority, change.authority));
297
- if (!same)
298
- throw new Error("Goal idempotency key was reused with a different mutation");
299
- return event;
300
- }
301
- }
302
- const current = this.#getGoal(normalized.id);
303
- if (current) {
304
- if (normalized.revision !== current.revision + 1)
305
- throw new Error("goal revision CAS failed");
306
- if (current.phase === "complete")
307
- throw new Error("completed goal cannot be modified");
308
- if (normalized.parentId !== current.parentId)
309
- throw new Error("goal reparenting is not supported");
310
- if (normalized.phase === "complete")
311
- throw new Error("goal completion requires reason and evidence");
312
- const definitionChanged = normalized.objective !== current.objective || normalized.observationMethod !== current.observationMethod || normalized.verificationMethod !== current.verificationMethod;
313
- if (current.phase !== normalized.phase && (current.owner !== normalized.owner || definitionChanged) || current.owner !== normalized.owner && definitionChanged)
314
- throw new Error("Goal mutation must express exactly one lifecycle operation");
315
- if (normalized.objective !== current.objective && ((current.observationMethod !== null && normalized.observationMethod === current.observationMethod) || (current.verificationMethod !== null && normalized.verificationMethod === current.verificationMethod)))
316
- throw new Error("objective revision must replace or invalidate observation and verification methods");
317
- assertGoalTransition(current.phase, normalized.phase);
318
- this.#assertGoalAuthority(current.parentId, actor);
319
- }
320
- else {
321
- if (normalized.revision !== 0)
322
- throw new Error("new goal revision must be 0");
323
- this.#assertGoalAuthority(normalized.parentId, actor);
324
- }
325
- this.#assertOwnerSeparation(normalized.id, normalized.parentId, normalized.owner);
326
- return this.#transaction(() => {
327
- const event = this.#recordGoalChange(normalized, current, actor, wakeId, change);
328
- if (!current)
329
- this.#createWorkRecord(normalized, actor, wakeId ?? `goal:create:${normalized.id}`, wakeId);
330
- return event;
331
- });
332
- }
333
- updateWorkRecord(request, actor) {
334
- if (!request.turnId.trim() || !request.reason.trim() || !request.content.trim())
335
- throw new Error("work record turn, reason and content are required");
336
- this.#assertEvidenceExists(request.evidence);
337
- const goal = this.#getGoal(request.goalId);
338
- if (!goal)
339
- throw new Error("work record goal does not exist");
340
- if (goal.revision !== request.goalRevision)
341
- throw new Error("work record goal revision is stale");
342
- this.#assertWorkRecordAuthority(goal, actor);
343
- const turn = this.turn(request.turnId);
344
- if (!turn || turn.status !== "in_progress" || turn.bindingKind !== "goal" || turn.goalId !== goal.id || turn.goalRevision !== request.goalRevision)
345
- throw new Error("work record update does not match an active Goal-bound Turn");
346
- const current = this.workRecord(goal.id);
347
- if (!current)
348
- throw new Error("work record does not exist");
349
- if (current.recordRevision !== request.expectedRevision)
350
- throw new Error("work record revision CAS failed");
351
- if (current.content === request.content)
352
- throw new Error("work record content is unchanged");
353
- return this.#transaction(() => this.#recordWorkRecord({
354
- ...current,
355
- recordRevision: current.recordRevision + 1,
356
- goalRevision: goal.revision,
357
- content: request.content,
358
- updatedBy: actor,
359
- updatedInTurn: request.turnId,
360
- sourceWakeId: request.sourceWakeId ?? null,
361
- updatedAt: this.#now(),
362
- reason: request.reason,
363
- evidence: request.evidence,
364
- }, "work_record.updated"));
365
- }
366
- commitDelegation(request, actor, wakeId) {
367
- const existing = this.#delegationResult(request.id);
368
- if (existing) {
369
- const event = this.events().find((candidate) => candidate.type === "delegation.created" && candidate.data.delegationId === request.id);
370
- const prior = event?.data?.request;
371
- if (event?.actor !== actor || !isDeepStrictEqual(prior, withoutSourceTurn(request)))
372
- throw new Error("delegation id was reused with a different request");
373
- return existing;
374
- }
375
- if (!request.id.trim() || !request.reason.trim())
376
- throw new Error("delegation id and reason are required");
377
- if (request.childGoal.owner === actor)
378
- throw new Error("delegate to a distinct worker agent; use goal.put for self-owned subgoals");
379
- if (!request.childGoal.id.trim() || !request.childGoal.objective.trim() || !request.childGoal.observationMethod.trim() || !request.childGoal.verificationMethod.trim() || !request.childGoal.owner.trim())
380
- throw new Error("delegation child goal is incomplete");
381
- this.#assertEvidenceExists(request.evidence);
382
- const parent = this.#getGoal(request.parentGoalId);
383
- if (!parent)
384
- throw new Error("delegation parent goal does not exist");
385
- if (parent.revision !== request.expectedParentRevision)
386
- throw new Error("delegation parent Goal revision is stale");
387
- if (parent.owner !== actor)
388
- throw new Error("only the parent goal owner may delegate");
389
- if (parent.phase !== "active")
390
- throw new Error("delegation parent goal must be active");
391
- if (this.#getGoal(request.childGoal.id))
392
- throw new Error("delegation child goal already exists");
393
- return this.#transaction(() => {
394
- const goal = normalizeGoal({ ...request.childGoal, parentId: request.parentGoalId, phase: "active", revision: 0 });
395
- const mail = {
396
- id: `delegation-mail:${request.id}`,
397
- to: goal.owner,
398
- from: actor,
399
- level: "decision",
400
- ...goalRoute(goal.id),
401
- body: { type: "delegation", delegationId: request.id, goalId: goal.id, parentGoalId: request.parentGoalId, objective: goal.objective, observationMethod: goal.observationMethod, verificationMethod: goal.verificationMethod ?? null, brief: request.brief, reason: request.reason, evidence: request.evidence },
402
- readAt: null,
403
- };
404
- const wakeBase = {
405
- id: `delegation-wake:${request.id}`,
406
- ...goalExecutionBinding(goal.owner, goal.id),
407
- triggerRef: `delegation:${request.id}`,
408
- status: "queued",
409
- attempt: 0,
410
- enqueuedSeq: 0,
411
- claimedAt: null,
412
- consumedAt: null,
413
- turnId: null,
414
- };
415
- this.#insertEvent({
416
- streamId: wakeId ? wakeStream(wakeId) : controlStream("delegations"),
417
- ts: this.#now(),
418
- actor,
419
- type: "delegation.created",
420
- data: { delegationId: request.id, parentGoalId: request.parentGoalId, goalId: goal.id, mailId: mail.id, wakeId: wakeBase.id, reason: request.reason, evidence: request.evidence, request: withoutSourceTurn(request) },
421
- });
422
- this.#faultInjector?.("after_delegation_event");
423
- this.#recordGoalChange(goal, null, actor, wakeId, { operation: "create", reason: request.reason, evidence: request.evidence, authority: { kind: "parent_goal", goalId: parent.id, goalRevision: parent.revision }, ...(request.sourceTurnId ? { sourceTurnId: request.sourceTurnId } : {}), ...(wakeId ? { sourceWakeId: wakeId } : {}), idempotencyKey: request.id });
424
- this.#createWorkRecord(goal, actor, wakeId ?? `delegation:${request.id}`, wakeId);
425
- this.#assertNewMail(mail, actor);
426
- this.#recordProjection("mailbox", mail, actor, "mail.put", wakeId);
427
- const wake = this.#admitWake(wakeBase, "supervisor", false).wake;
428
- return { delegationId: request.id, goal, mail, wake };
429
- });
430
- }
431
- commitReassignment(request, actor, wakeId) {
432
- const existing = this.#reassignmentResult(request.id);
433
- if (existing) {
434
- const event = this.events().find((candidate) => candidate.type === "goal.reassigned" && candidate.data.reassignmentId === request.id);
435
- const prior = event?.data?.request;
436
- if (event?.actor !== actor || !isDeepStrictEqual(prior, withoutSourceTurn(request)))
437
- throw new Error("reassignment id was reused with a different request");
438
- return existing;
439
- }
440
- if (!request.id.trim() || !request.newOwner.trim() || !request.reason.trim())
441
- throw new Error("reassignment id, owner and reason are required");
442
- this.#assertEvidenceExists(request.evidence);
443
- const current = this.#getGoal(request.goalId);
444
- if (!current)
445
- throw new Error("reassignment goal does not exist");
446
- if (current.revision !== request.expectedGoalRevision)
447
- throw new Error("reassignment Goal revision is stale");
448
- if (!current.parentId)
449
- throw new Error("root goals cannot be reassigned by CEO");
450
- this.#assertGoalAuthority(current.parentId, actor);
451
- if (current.phase === "complete")
452
- throw new Error("completed goals cannot be reassigned");
453
- if (current.owner === request.newOwner)
454
- throw new Error("reassignment owner is unchanged");
455
- this.#assertOwnerSeparation(current.id, current.parentId, request.newOwner);
456
- return this.#transaction(() => {
457
- const goal = { ...current, owner: request.newOwner, revision: current.revision + 1 };
458
- const mail = [{ id: `reassignment-new-mail:${request.id}`, to: goal.owner, from: actor, level: "decision", ...goalRoute(goal.id), body: { type: "reassignment", reassignmentId: request.id, role: "new_owner", previousOwner: current.owner, brief: request.brief, reason: request.reason, evidence: request.evidence }, readAt: null }];
459
- const wakeBase = goal.phase === "active" ? { id: `reassignment-wake:${request.id}`, ...goalExecutionBinding(goal.owner, goal.id), triggerRef: `reassignment:${request.id}`, status: "queued", attempt: 0, enqueuedSeq: 0, claimedAt: null, consumedAt: null, turnId: null } : null;
460
- this.#insertEvent({ streamId: wakeId ? wakeStream(wakeId) : controlStream("reassignments"), ts: this.#now(), actor, type: "goal.reassigned", data: { reassignmentId: request.id, goalId: goal.id, oldOwner: current.owner, newOwner: goal.owner, mailIds: mail.map((item) => item.id), wakeId: wakeBase?.id ?? null, reason: request.reason, evidence: request.evidence, request: withoutSourceTurn(request) } });
461
- this.#faultInjector?.("after_reassignment_event");
462
- this.#recordGoalChange(goal, current, actor, wakeId, { operation: "reassign", reason: request.reason, evidence: request.evidence, authority: { kind: "parent_goal", goalId: current.parentId, goalRevision: this.#getGoal(current.parentId).revision }, ...(request.sourceTurnId ? { sourceTurnId: request.sourceTurnId } : {}), ...(wakeId ? { sourceWakeId: wakeId } : {}), idempotencyKey: request.id });
463
- for (const item of mail) {
464
- this.#assertNewMail(item, actor);
465
- this.#recordProjection("mailbox", item, actor, "mail.put", wakeId);
466
- }
467
- const wake = wakeBase ? this.#admitWake(wakeBase, "supervisor", false).wake : null;
468
- return { reassignmentId: request.id, goal, mail, wake };
469
- });
470
- }
471
- completeGoal(request, actor, wakeId) {
472
- if (!request.reason.trim())
473
- throw new Error("goal completion reason is required");
474
- this.#assertEvidenceExists(request.evidence);
475
- const current = this.#getGoal(request.goalId);
476
- if (!current)
477
- throw new Error("goal does not exist");
478
- if (current.phase === "complete") {
479
- const decision = this.readStream(goalStream(current.id)).findLast((event) => event.type === "goal.completion_decided");
480
- const data = decision?.data;
481
- if (decision?.actor === actor && data.revision === request.revision && data.reason === request.reason && JSON.stringify(data.evidence) === JSON.stringify(request.evidence))
482
- return current;
483
- throw new Error("completed goal cannot accept a different completion decision");
484
- }
485
- if (request.revision !== current.revision)
486
- throw new Error("goal completion revision is stale");
487
- if (current.observationMethod === null)
488
- throw new Error("goal completion requires an observation method");
489
- if (current.verificationMethod === null || current.verificationMethod === undefined)
490
- throw new Error("goal completion requires a verification method");
491
- this.#assertGoalAuthority(current.parentId, actor);
492
- if (current.parentId === null && this.#hasNonCompleteDescendant(current.id))
493
- throw new Error("root goal cannot complete while descendants remain non-complete");
494
- const source = this.db.prepare("SELECT seq FROM events WHERE stream_id=? AND type='goal.changed' AND json_extract(data,'$.snapshot.revision')=? ORDER BY seq DESC LIMIT 1").get(goalStream(current.id), current.revision);
495
- if (!source)
496
- throw new Error("goal revision has no source event");
497
- if (request.evidence.some((seq) => seq <= source.seq))
498
- throw new Error("goal completion evidence predates the current revision");
499
- return this.#transaction(() => {
500
- this.#insertEvent({ streamId: goalStream(current.id), ts: this.#now(), actor, type: "goal.completion_decided", data: { goalId: current.id, revision: current.revision, observationMethod: current.observationMethod, verificationMethod: current.verificationMethod ?? null, reason: request.reason, evidence: request.evidence } });
501
- const next = { ...current, phase: "complete", revision: current.revision + 1 };
502
- this.#recordGoalChange(next, current, actor, wakeId, { operation: "complete", reason: request.reason, evidence: request.evidence, authority: this.#goalAuthority(current.parentId, actor), ...(request.sourceTurnId ? { sourceTurnId: request.sourceTurnId } : {}), ...(wakeId ? { sourceWakeId: wakeId } : {}) });
503
- return next;
504
- });
505
- }
506
- putSchedule(value, actor, wakeId) {
507
- return this.#transaction(() => this.#admitSchedule(value, actor, wakeId));
508
- }
509
- consumeSchedule(id, wake, now) { const current = this.#requiredSchedule(id); if (current.status !== "pending")
510
- throw new Error("only a pending Schedule may be consumed"); if (wake.bindingKind !== current.bindingKind || wake.agent !== current.agent || wake.specialistRole !== current.specialistRole || wake.triggerRef !== `${current.id}@${current.nextWakeAt}` || wake.goalId !== current.goalId)
511
- throw new Error("scheduled Wake does not match Schedule"); if (wake.status !== "queued" || wake.attempt !== 0 || wake.claimedAt || wake.consumedAt || wake.turnId)
512
- throw new Error("scheduled Wake must be pristine"); return this.#transaction(() => { const exact = this.wakeByTrigger(wake.agent, wake.triggerRef); let stored; if (exact) {
513
- if (exact.status !== "queued" || exact.bindingKind !== wake.bindingKind || exact.specialistRole !== wake.specialistRole || exact.goalId !== wake.goalId)
514
- throw new Error("scheduled Wake trigger is already terminal or bound differently");
515
- stored = exact;
516
- }
517
- else {
518
- const queued = this.wakes().find((candidate) => candidate.agent === wake.agent && candidate.status === "queued" && candidate.bindingKind === wake.bindingKind && candidate.specialistRole === wake.specialistRole && candidate.goalId === wake.goalId);
519
- if (queued) {
520
- stored = queued;
521
- this.#admitWakeTrigger(queued.id, wake.triggerRef, "supervisor", now);
522
- }
523
- else
524
- stored = this.#admitWake(wake, "supervisor", false).wake;
525
- } const schedule = { ...current, status: "consumed", resolvedAt: now }; this.#recordProjection("schedule", schedule, "supervisor", "schedule.consumed", undefined, now); return { schedule, wake: stored }; }); }
526
- cancelSchedule(id, now) { const current = this.#requiredSchedule(id); if (current.status !== "pending")
527
- throw new Error("only a pending Schedule may be cancelled"); const next = { ...current, status: "cancelled", resolvedAt: now }; this.#project("schedule", next, "supervisor", "schedule.cancelled", undefined, now); return next; }
528
- supersedeSchedule(id, now) { const current = this.#requiredSchedule(id); if (current.status !== "pending")
529
- throw new Error("only a pending Schedule may be superseded"); const next = { ...current, status: "superseded", resolvedAt: now }; this.#project("schedule", next, "supervisor", "schedule.superseded", undefined, now); return next; }
530
- enqueueWake(input, actor) {
531
- return this.#transaction(() => { const result = this.#admitWake(input, actor, true); return { event: result.event, created: result.created }; });
532
- }
533
- addWakeTrigger(wakeId, triggerRef, actor) { return this.#transaction(() => this.#admitWakeTrigger(wakeId, triggerRef, actor, this.#now())); }
534
- claimNextWake(now) {
535
- return this.#transaction(() => {
536
- const row = this.db.prepare(`SELECT * FROM wakes w WHERE status='queued' AND NOT EXISTS (
537
- SELECT 1 FROM wakes active WHERE active.agent=w.agent AND active.status='claimed'
538
- ) AND NOT EXISTS (
539
- SELECT 1 FROM turns WHERE source='human' AND status='in_progress'
540
- ) AND NOT EXISTS (
541
- SELECT 1 FROM turns t JOIN threads th ON th.id=t.thread_id WHERE th.agent=w.agent AND t.status='in_progress'
542
- ) ORDER BY enqueued_seq LIMIT 1`).get();
543
- if (!row)
544
- return null;
545
- const current = mapWake(row);
546
- const next = { ...current, status: "claimed", claimedAt: now, attempt: current.attempt + 1 };
547
- this.#recordProjection("wakes", next, "supervisor", "wake.claimed", next.id, now);
548
- return next;
549
- });
550
- }
551
- startTurnFromWake(id, turn, now) { const wake = this.#requiredWake(id); if (wake.status !== "claimed")
552
- throw new Error("only a claimed Wake may start a Turn"); if (this.turn(turn.id))
553
- throw new Error("Wake Turn already exists"); this.#assertTurnBinding(turn); if (turn.status !== "in_progress" || turn.attempt !== 1 || !turn.leaseUntil || !turn.leaseToken)
554
- throw new Error("Wake must start an owned Turn at attempt one"); const thread = this.thread(turn.threadId); if (!thread || thread.agent !== wake.agent)
555
- throw new Error("Wake Turn agent does not match"); if (!sameWakeTurnBinding(wake, turn))
556
- throw new Error("Wake Turn execution binding does not match"); return this.#transaction(() => { if (this.db.prepare("SELECT 1 FROM turns WHERE source='human' AND status='in_progress' LIMIT 1").get())
557
- throw new Error("automatic Wake cannot start while a Human Turn is in progress"); this.#assertCurrentAutomaticTurn(turn, thread.agent); this.#recordProjection("turns", turn, "supervisor", "turn.started", undefined, now, undefined, `turn:${turn.id}`); this.#resolveWakeTriggers(id, now); const next = { ...wake, status: "consumed", consumedAt: now, turnId: turn.id }; this.#recordProjection("wakes", next, "supervisor", "wake.consumed", id, now); return next; }); }
558
- releaseWake(id, now) {
559
- const current = this.#requiredWake(id);
560
- if (current.status !== "claimed")
561
- throw new Error("only a claimed Wake may be released");
562
- const next = { ...current, status: "queued", claimedAt: null };
563
- this.#project("wakes", next, "supervisor", "wake.released", id, now);
564
- return next;
565
- }
566
- cancelWake(id, now) {
567
- const current = this.#requiredWake(id);
568
- return this.#transaction(() => this.#cancelWakeProjection(current, now));
569
- }
570
- attachTurnProcess(id, leaseToken, pid) {
571
- const current = this.#requiredTurn(id);
572
- this.#assertTurnLease(current, leaseToken);
573
- if (current.status !== "in_progress")
574
- throw new Error("runner pid may only be attached to an active Turn");
575
- this.putTurn({ ...current, runnerPid: pid }, "supervisor");
576
- return this.#requiredTurn(id);
577
- }
578
- renewTurnLease(id, leaseToken, leaseUntil, now) {
579
- const current = this.#requiredTurn(id);
580
- this.#assertTurnLease(current, leaseToken);
581
- if (current.status !== "in_progress")
582
- throw new Error("only an active Turn lease may be renewed");
583
- if (leaseUntil <= now)
584
- throw new Error("renewed lease must expire in the future");
585
- this.putTurn({ ...current, leaseUntil }, "supervisor");
586
- return this.#requiredTurn(id);
587
- }
588
- appendTurnEvent(input, leaseToken) {
589
- return this.#transaction(() => {
590
- this.#assertRawEvent(input);
591
- if (!input.streamId.startsWith("turn:"))
592
- throw new Error("runner event requires a Turn stream");
593
- const turn = this.#requiredTurn(input.streamId.slice("turn:".length));
594
- this.#assertTurnLease(turn, leaseToken);
595
- if (turn.status !== "in_progress" || !turn.leaseUntil || input.ts > turn.leaseUntil)
596
- throw new Error("stale runner event rejected");
597
- return this.#insertEvent(input);
598
- });
599
- }
600
- repairTurnAttempt(id, reason, now, actor) { const current = this.#requiredTurn(id); if (current.status !== "in_progress")
601
- throw new Error("only an active Turn attempt may be repaired"); return this.#transaction(() => this.#repairOpenTurnItems(id, reason, now, actor)); }
602
- finishTurn(id, status, error, now, actor, mailIds = []) { const current = this.#requiredTurn(id); if (current.status !== "in_progress")
603
- throw new Error("only an active Turn may finish"); if (status === "completed" && current.bindingKind === "goal")
604
- throw new Error("Goal-bound Turn completion requires commitHandoff"); if (status === "completed" && error !== null || status !== "completed" && error === null)
605
- throw new Error("Turn terminal error does not match status"); return this.#transaction(() => { if (status !== "completed")
606
- this.#repairOpenTurnItems(id, String(error.message ?? "Turn interrupted"), now, actor);
607
- else if (this.turnItems(id).some((item) => item.status === "in_progress"))
608
- throw new Error("successful Turn cannot retain in-progress Items"); const streamId = `turn:${id}`; const thread = this.thread(current.threadId); const delivered = new Set(mailIds); if (status !== "completed" && mailIds.length)
609
- throw new Error("failed Turn cannot acknowledge Mail"); if (status === "completed" && thread)
610
- this.#recordMailReads(this.unreadMail(thread.agent).filter((candidate) => delivered.has(candidate.id)), now, streamId); this.#insertEvent({ streamId, ts: now, actor, type: status === "completed" ? "transcript.completed" : "transcript.interrupted", data: status === "completed" ? {} : { reason: String(error.message ?? "Turn interrupted") } }); const next = { ...current, status, error, endedAt: now, leaseUntil: null, leaseToken: null, runnerPid: null }; this.#recordProjection("turns", next, actor, `turn.${status}`, undefined, now, undefined, streamId); return next; }); }
611
- putMail(mail, actor, wakeId) { return this.putMails([mail], actor, wakeId)[0]; }
612
- putMails(mails, actor, wakeId) { const ids = new Set(); const prior = new Map(); for (const mail of mails) {
613
- this.#assertMailRequest(mail, actor);
614
- if (ids.has(mail.id))
615
- throw new Error("mail batch contains a duplicate id");
616
- ids.add(mail.id);
617
- const row = this.db.prepare("SELECT * FROM mailbox WHERE id=?").get(mail.id);
618
- if (!row)
619
- continue;
620
- const current = mapMail(row);
621
- if (current.routeKind !== mail.routeKind || current.to !== mail.to || current.from !== mail.from || current.specialistRole !== mail.specialistRole || current.level !== mail.level || current.goalId !== mail.goalId || !isDeepStrictEqual(current.body, mail.body))
622
- throw new Error("mail id was reused with different content");
623
- const event = this.db.prepare("SELECT * FROM events WHERE type='mail.put' AND json_extract(data,'$.snapshot.id')=? ORDER BY seq LIMIT 1").get(mail.id);
624
- if (!event)
625
- throw new Error("mail projection has no source event");
626
- prior.set(mail.id, mapEvent(event));
627
- } return this.#transaction(() => mails.map((mail) => prior.get(mail.id) ?? this.#recordProjection("mailbox", mail, actor, "mail.put", wakeId))); }
628
- commitHandoff(commit) {
629
- return this.#transaction(() => {
630
- const turn = this.#requiredTurn(commit.turnId);
631
- const thread = this.thread(turn.threadId);
632
- if (turn.status !== "in_progress" || thread?.agent !== commit.agent)
633
- throw new Error("handoff does not match an active Turn");
634
- if (turn.bindingKind !== "goal")
635
- throw new Error("only a Goal-bound Turn may commit Handoff");
636
- const goal = this.#getGoal(turn.goalId);
637
- if (!goal || goal.owner !== commit.agent || goal.phase !== "active" || goal.revision !== turn.goalRevision)
638
- throw new Error("Handoff Turn Goal binding is stale");
639
- const record = this.workRecord(goal.id);
640
- if (!record || record.updatedInTurn !== turn.id || record.goalRevision !== goal.revision || record.recordRevision < 1)
641
- throw new Error("Goal-bound Turn must update its Work Record before Handoff");
642
- assertHandoff(commit.output.handoff);
643
- if (commit.output.handoff.goalId !== goal.id || commit.output.handoff.goalRevision !== goal.revision || commit.output.handoff.recordRevision !== record.recordRevision)
644
- throw new Error("Goal Handoff does not match the current Goal and Work Record");
645
- this.#assertEvidenceExists(commit.output.handoff.evidence);
646
- const responseItem = this.turnItems(turn.id).find((item) => item.id === commit.responseItemId);
647
- if (!responseItem || responseItem.type !== "assistant_message" || responseItem.status !== "completed" || typeof responseItem.data.text !== "string" || !responseItem.data.text.trim())
648
- throw new Error("Handoff response does not match a readable Turn Item");
649
- const ordinal = this.turnItems(turn.id).length + 1;
650
- if (commit.item.turnId !== turn.id || commit.item.type !== "handoff" || commit.item.status !== "completed" || commit.item.completedAt !== commit.ts || commit.item.createdAt !== commit.ts || commit.item.ordinal !== ordinal || !isDeepStrictEqual(commit.item.data, commit.output.handoff))
651
- throw new Error("handoff Item does not match active TurnOutput");
652
- if (commit.sourceWakeId) {
653
- const wake = this.#requiredWake(commit.sourceWakeId);
654
- if (wake.status !== "consumed" || wake.turnId !== turn.id)
655
- throw new Error("handoff source Wake does not match Turn");
656
- }
657
- const streamId = `turn:${commit.turnId}`;
658
- this.#insertEvent({ streamId, ts: commit.ts, actor: commit.agent, type: "response.committed", data: { messageItemId: responseItem.id, text: responseItem.data.text } });
659
- this.#admitTurnItem(commit.item, commit.agent, streamId);
660
- const event = this.#insertEvent({ streamId, ts: commit.ts, actor: commit.agent, type: "handoff.recorded", data: commit.output.handoff });
661
- const delivered = new Set(commit.mailIds);
662
- this.#recordMailReads(this.unreadMail(commit.agent).filter((candidate) => delivered.has(candidate.id)), commit.ts, streamId);
663
- if (this.turnItems(turn.id).some((item) => item.status === "in_progress"))
664
- throw new Error("successful Turn cannot retain in-progress Items");
665
- this.#insertEvent({ streamId, ts: commit.ts, actor: "supervisor", type: "transcript.completed", data: {} });
666
- this.#recordProjection("turns", { ...turn, status: "completed", error: null, endedAt: commit.ts, leaseUntil: null, leaseToken: null, runnerPid: null }, "supervisor", "turn.completed", undefined, commit.ts, undefined, streamId);
667
- return event;
668
- });
669
- }
670
- dueSchedules(now) { return this.db.prepare("SELECT * FROM schedule WHERE status='pending' AND next_wake_at <= ? ORDER BY next_wake_at,id").all(now).map(mapSchedule); }
671
- unreadMail(agent) { return this.db.prepare("SELECT * FROM mailbox WHERE to_agent=? AND read_at IS NULL ORDER BY rowid").all(agent).map(mapMail); }
672
- lastEvent(actor, type) { const row = this.db.prepare("SELECT * FROM events WHERE actor=? AND type=? ORDER BY seq DESC LIMIT 1").get(actor, type); return row ? mapEvent(row) : null; }
673
- lastGoalHandoff(goalId) { const row = this.db.prepare("SELECT * FROM events WHERE type='handoff.recorded' AND json_extract(data,'$.goalId')=? ORDER BY seq DESC LIMIT 1").get(goalId); return row ? mapEvent(row) : null; }
674
- latestEvent() { const row = this.db.prepare("SELECT * FROM events ORDER BY seq DESC LIMIT 1").get(); return row ? mapEvent(row) : null; }
675
- eventsForWake(wakeId) { return this.readStream(wakeStream(wakeId)); }
676
- wake(id) { const row = this.db.prepare("SELECT * FROM wakes WHERE id=?").get(id); return row ? mapWake(row) : null; }
677
- wakeByTrigger(agent, triggerRef) {
678
- const row = this.db.prepare("SELECT w.* FROM wake_triggers t JOIN wakes w ON w.id=t.wake_id WHERE t.agent=? AND t.trigger_ref=?").get(agent, triggerRef);
679
- return row ? mapWake(row) : null;
680
- }
681
- wakeTriggers(wakeId) { return this.db.prepare("SELECT * FROM wake_triggers WHERE wake_id=? ORDER BY rowid").all(wakeId).map(mapWakeTrigger); }
682
- wakeTriggersForAgent(agent) { return this.db.prepare("SELECT * FROM wake_triggers WHERE agent=? ORDER BY rowid").all(agent).map(mapWakeTrigger); }
683
- queuedWakeForAgent(agent) { const row = this.db.prepare("SELECT * FROM wakes WHERE agent=? AND status='queued' ORDER BY enqueued_seq LIMIT 1").get(agent); return row ? mapWake(row) : null; }
684
- goalsForOwner(owner) { return this.db.prepare("SELECT * FROM goals WHERE owner=? ORDER BY id").all(owner).map(mapGoal); }
685
- goal(id) { return this.#getGoal(id); }
686
- workRecord(goalId) { const row = this.db.prepare("SELECT * FROM work_records WHERE goal_id=?").get(goalId); return row ? mapWorkRecord(row) : null; }
687
- workRecordHistory(goalId) {
688
- return this.readStream(workRecordStream(goalId)).filter((event) => event.type === "work_record.created" || event.type === "work_record.updated").map((event) => mapWorkRecordEvent(event));
689
- }
690
- workRecordDiff(goalId, fromRevision, toRevision) {
691
- const history = this.workRecordHistory(goalId);
692
- const from = history.find((record) => record.recordRevision === fromRevision);
693
- const to = history.find((record) => record.recordRevision === toRevision);
694
- if (!from || !to)
695
- throw new Error("work record diff revision does not exist");
696
- return { goalId, fromRevision, toRevision, text: lineDiff(from.content, to.content) };
697
- }
698
- searchWorkRecords(query, limit = 50) {
699
- return this.db.prepare(`SELECT e.* FROM events_fts f JOIN events e ON e.seq=f.rowid
700
- WHERE events_fts MATCH ? AND e.type IN ('work_record.created','work_record.updated') ORDER BY rank LIMIT ?`).all(query, limit).map((row) => mapWorkRecordEvent(mapEvent(row)));
701
- }
702
- triggeringMail() { return this.db.prepare("SELECT * FROM mailbox WHERE read_at IS NULL AND level IN ('decision','emergency') ORDER BY rowid").all().map(mapMail); }
703
- eventsSince(seq, types) {
704
- const events = this.db.prepare("SELECT * FROM events WHERE seq>? ORDER BY seq").all(seq).map(mapEvent);
705
- return types?.length ? events.filter((event) => types.includes(event.type)) : events;
706
- }
707
- searchEvents(query, limit = 50) {
708
- return this.db.prepare("SELECT e.* FROM events_fts f JOIN events e ON e.seq=f.rowid WHERE events_fts MATCH ? ORDER BY rank LIMIT ?").all(query, limit).map(mapEvent);
709
- }
710
- events() { return this.db.prepare("SELECT * FROM events ORDER BY seq").all().map(mapEvent); }
711
- goals() { return this.db.prepare("SELECT * FROM goals ORDER BY id").all().map(mapGoal); }
712
- workRecords() { return this.db.prepare("SELECT * FROM work_records ORDER BY goal_id").all().map(mapWorkRecord); }
713
- schedules() { return this.db.prepare("SELECT * FROM schedule ORDER BY id").all().map(mapSchedule); }
714
- wakes() { return this.db.prepare("SELECT * FROM wakes ORDER BY enqueued_seq").all().map(mapWake); }
715
- mailbox() { return this.db.prepare("SELECT * FROM mailbox ORDER BY rowid").all().map(mapMail); }
716
- rebuildProjections() {
717
- const source = this.db.prepare("SELECT * FROM events ORDER BY seq").all();
718
- this.#transaction(() => {
719
- this.db.exec("DELETE FROM turn_items; DELETE FROM wake_triggers; DELETE FROM wakes; DELETE FROM turns; DELETE FROM threads; DELETE FROM work_records; DELETE FROM mailbox; DELETE FROM schedule; DELETE FROM goals;");
720
- const goalKeys = new Set();
721
- for (const row of source) {
722
- if (row.projection_name === null)
723
- continue;
724
- const event = mapEvent(row);
725
- const projection = String(row.projection_name);
726
- const expected = projectionForEvent(event.type);
727
- if (expected !== projection)
728
- throw new Error(`event ${event.seq} cannot drive ${projection} projection`);
729
- const data = event.data && typeof event.data === "object" && !Array.isArray(event.data) ? event.data : null;
730
- if (!data || !("snapshot" in data))
731
- throw new Error(`projection event ${event.seq} has no snapshot`);
732
- if (projection === "goals")
733
- this.#replayGoalChange(event, goalKeys);
734
- else
735
- this.#replayProjection(projection, data.snapshot, event);
736
- }
737
- });
738
- }
739
- #delegationResult(id) {
740
- const row = this.db.prepare("SELECT data,actor FROM events WHERE type='delegation.created' AND json_extract(data,'$.delegationId')=? ORDER BY seq LIMIT 1").get(id);
741
- if (!row)
742
- return null;
743
- const data = JSON.parse(row.data);
744
- const goal = this.#goalChangeSnapshot(id, row.actor);
745
- const mail = this.#eventSnapshot("mail.put", data.mailId);
746
- const wake = this.#eventSnapshot("wake.enqueued", data.wakeId);
747
- if (!goal || !mail || !wake)
748
- throw new Error("committed delegation facts are incomplete");
749
- return { delegationId: id, goal, mail, wake };
750
- }
751
- #reassignmentResult(id) {
752
- const row = this.db.prepare("SELECT data,actor FROM events WHERE type='goal.reassigned' AND json_extract(data,'$.reassignmentId')=? ORDER BY seq LIMIT 1").get(id);
753
- if (!row)
754
- return null;
755
- const data = JSON.parse(row.data);
756
- const goal = this.#goalChangeSnapshot(id, row.actor);
757
- const mail = data.mailIds.map((mailId) => { const value = this.#eventSnapshot("mail.put", mailId); if (!value)
758
- throw new Error("committed reassignment mail is missing"); return value; });
759
- const wake = data.wakeId ? this.#eventSnapshot("wake.enqueued", data.wakeId) : null;
760
- if (!goal || data.wakeId && !wake)
761
- throw new Error("committed reassignment facts are incomplete");
762
- return { reassignmentId: id, goal, mail, wake };
763
- }
764
- #goalChangeSnapshot(id, actor) { const row = this.db.prepare("SELECT data FROM events WHERE type='goal.changed' AND actor=? AND json_extract(data,'$.idempotencyKey')=? ORDER BY seq LIMIT 1").get(actor, id); return row ? JSON.parse(row.data).snapshot : null; }
765
- #eventSnapshot(type, id) { const row = this.db.prepare("SELECT data FROM events WHERE type=? AND json_extract(data,'$.snapshot.id')=? ORDER BY seq LIMIT 1").get(type, id); return row ? JSON.parse(row.data).snapshot : null; }
766
- #recordGoalChange(snapshot, previous, actor, wakeId, change) { const derivedOperation = goalOperation(previous, snapshot); if (change && change.operation !== derivedOperation)
767
- throw new Error("Goal change operation does not match its state transition"); const operation = change?.operation ?? derivedOperation; if (change && !change.reason.trim())
768
- throw new Error("Goal change reason is required"); const evidence = change?.evidence ?? []; if (evidence.length)
769
- this.#assertEvidenceExists(evidence); const expectedAuthority = this.#goalAuthority(snapshot.parentId, actor); if (change?.authority && !isDeepStrictEqual(change.authority, expectedAuthority))
770
- throw new Error("Goal change authority does not match the authenticated actor"); const authority = change?.authority ?? expectedAuthority; const sourceWakeId = change?.sourceWakeId ?? wakeId; this.#assertGoalProvenance(snapshot, actor, authority, change?.sourceTurnId, sourceWakeId); if (change?.idempotencyKey && this.db.prepare("SELECT 1 FROM events WHERE type='goal.changed' AND actor=? AND json_extract(data,'$.idempotencyKey')=?").get(actor, change.idempotencyKey))
771
- throw new Error("Goal idempotency key is already committed"); const data = { version: 1, operation, previousRevision: previous?.revision ?? null, snapshot, reason: change?.reason?.trim() || defaultGoalReason(operation), evidence, authority, ...(change?.sourceTurnId ? { sourceTurnId: change.sourceTurnId } : {}), ...(sourceWakeId ? { sourceWakeId } : {}), ...(change?.idempotencyKey ? { idempotencyKey: change.idempotencyKey } : {}) }; const event = this.#insertEvent({ streamId: goalStream(snapshot.id), ts: this.#now(), actor, type: "goal.changed", data: data }, undefined, "goals"); this.#faultInjector?.("after_event_before_projection"); this.#applyProjection("goals", snapshot, event.seq); if (previous && (previous.owner !== snapshot.owner || previous.phase !== snapshot.phase && snapshot.phase !== "active")) {
772
- this.#cancelWakesForGoal(snapshot.id, this.#now());
773
- this.#supersedeSchedulesForGoal(snapshot.id, this.#now());
774
- } return event; }
775
- #replayGoalChange(event, keys) { if (event.type !== "goal.changed")
776
- throw new Error(`event ${event.seq} is not an authoritative Goal change`); const data = event.data; if (data.version !== 1)
777
- throw new Error(`goal.changed ${event.seq} has an unsupported format`); const snapshot = normalizeGoal(data.snapshot); assertGoalSnapshot(snapshot); if (event.streamId !== goalStream(snapshot.id))
778
- throw new Error(`goal.changed ${event.seq} uses the wrong stream`); const previous = this.#getGoal(snapshot.id); if (data.previousRevision !== (previous?.revision ?? null) || snapshot.revision !== (previous ? previous.revision + 1 : 0) || data.operation !== goalOperation(previous, snapshot))
779
- throw new Error(`goal.changed ${event.seq} breaks the Goal revision chain`); if (!data.reason.trim())
780
- throw new Error(`goal.changed ${event.seq} has no reason`); for (const seq of data.evidence)
781
- if (!Number.isInteger(seq) || seq <= 0 || seq >= event.seq)
782
- throw new Error(`goal.changed ${event.seq} has invalid evidence`); const expected = this.#goalAuthority(snapshot.parentId, event.actor); if (!isDeepStrictEqual(data.authority, expected))
783
- throw new Error(`goal.changed ${event.seq} has invalid authority`); this.#assertGoalProvenance(snapshot, event.actor, data.authority, data.sourceTurnId, data.sourceWakeId); if (data.idempotencyKey) {
784
- const key = `${event.actor}\u0000${data.idempotencyKey}`;
785
- if (keys.has(key))
786
- throw new Error(`goal.changed ${event.seq} reuses an idempotency key`);
787
- keys.add(key);
788
- } this.#applyProjection("goals", snapshot, event.seq); }
789
- #assertGoalProvenance(snapshot, actor, authority, sourceTurnId, sourceWakeId) { if (sourceWakeId && !sourceTurnId)
790
- throw new Error("Goal change source Wake requires its source Turn"); const turn = sourceTurnId ? this.turn(sourceTurnId) : null; if (sourceTurnId && !turn)
791
- throw new Error("Goal change source Turn does not exist"); if (turn) {
792
- if (turn.status !== "in_progress")
793
- throw new Error("Goal change source Turn is not active");
794
- const thread = this.thread(turn.threadId);
795
- if (!thread)
796
- throw new Error("Goal change source Turn has no Thread");
797
- if (authority.kind === "human") {
798
- const legalBinding = turn.bindingKind === "human" || turn.bindingKind === "goal" && turn.goalId === snapshot.id;
799
- if (turn.source !== "human" || thread.agent !== "ceo" || !legalBinding)
800
- throw new Error("Goal change source Turn does not carry Human authority");
801
- }
802
- else if (authority.kind === "parent_goal") {
803
- if (thread.agent !== actor || turn.bindingKind !== "goal" || turn.goalId !== authority.goalId || turn.goalRevision !== authority.goalRevision)
804
- throw new Error("Goal change source Turn is not bound to the authorizing parent Goal");
805
- }
806
- else if (thread.agent !== actor)
807
- throw new Error("Goal change source Turn actor does not match");
808
- } if (sourceWakeId) {
809
- const wake = this.wake(sourceWakeId);
810
- if (!wake)
811
- throw new Error("Goal change source Wake does not exist");
812
- if (wake.status !== "consumed" || sourceTurnId && wake.turnId !== sourceTurnId)
813
- throw new Error("Goal change source Wake does not match its Turn");
814
- if (authority.kind === "parent_goal" && (wake.bindingKind !== "goal" || wake.agent !== actor || wake.goalId !== authority.goalId))
815
- throw new Error("Goal change source Wake is not bound to the authorizing parent Goal");
816
- } }
817
- #goalAuthority(parentId, actor) { if (parentId === null)
818
- return actor === "human" ? { kind: "human" } : { kind: "system", reason: `root mutation by ${actor}` }; const parent = this.#getGoal(parentId); if (!parent)
819
- throw new Error("parent goal does not exist"); return { kind: "parent_goal", goalId: parent.id, goalRevision: parent.revision }; }
820
- #createWorkRecord(goal, actor, turnId, wakeId, seed) {
821
- return this.#recordWorkRecord({
822
- goalId: goal.id,
823
- recordRevision: 0,
824
- goalRevision: goal.revision,
825
- content: seed?.content ?? initialWorkRecord(),
826
- updatedBy: actor,
827
- updatedInTurn: turnId,
828
- sourceWakeId: wakeId ?? null,
829
- updatedAt: this.#now(),
830
- reason: "Goal created",
831
- evidence: seed?.evidence ?? [],
832
- lastEventSeq: 0,
833
- }, "work_record.created");
834
- }
835
- #recordWorkRecord(snapshot, type) {
836
- const seq = this.#nextEventSeq();
837
- const committed = { ...snapshot, lastEventSeq: seq };
838
- this.#recordProjection("work_records", committed, committed.updatedBy, type, committed.sourceWakeId ?? undefined, committed.updatedAt, seq, workRecordStream(committed.goalId));
839
- return committed;
840
- }
841
- #assertWorkRecordAuthority(goal, actor) {
842
- if (goal.owner === actor || (goal.parentId === null && actor === "human"))
843
- return;
844
- const parent = goal.parentId ? this.#getGoal(goal.parentId) : null;
845
- if (parent?.owner !== actor)
846
- throw new Error("only the goal owner or parent owner may update its work record");
847
- }
848
- #assertGoalAuthority(parentId, actor) {
849
- if (parentId === null) {
850
- if (actor !== "human")
851
- throw new Error("only human may modify a root goal");
852
- return;
853
- }
854
- const parent = this.#getGoal(parentId);
855
- if (!parent)
856
- throw new Error("parent goal does not exist");
857
- if (parent.owner !== actor)
858
- throw new Error("only the parent goal owner may modify a child goal");
859
- }
860
- #assertOwnerSeparation(goalId, parentId, owner) { if (parentId && this.#getGoal(parentId)?.owner === owner)
861
- throw new Error("parent and child Goals require distinct owners"); if (this.goals().some((goal) => goal.parentId === goalId && goal.owner === owner))
862
- throw new Error("parent and child Goals require distinct owners"); }
863
- #hasNonCompleteDescendant(goalId) {
864
- return Boolean(this.db.prepare(`WITH RECURSIVE descendants(id) AS (
865
- SELECT id FROM goals WHERE parent_id=?
866
- UNION ALL SELECT g.id FROM goals g JOIN descendants d ON g.parent_id=d.id
867
- ) SELECT 1 FROM goals WHERE id IN (SELECT id FROM descendants) AND phase<>'complete' LIMIT 1`).get(goalId));
868
- }
869
- #assertEvidenceExists(evidence) {
870
- if (evidence.length === 0)
871
- throw new Error("evidence is required");
872
- const exists = this.db.prepare("SELECT 1 FROM events WHERE seq=?");
873
- for (const seq of evidence)
874
- if (!Number.isInteger(seq) || seq <= 0 || !exists.get(seq))
875
- throw new Error(`evidence event does not exist: ${seq}`);
876
- }
877
- #assertTurnLease(turn, leaseToken) { if (turn.leaseToken !== leaseToken)
878
- throw new Error("stale Turn lease token"); }
879
- #assertRawEvent(input) { if (input.type === "goal.changed")
880
- throw new Error("projection-driving events must use a typed Ledger domain API"); }
881
- #getGoal(id) { const row = this.db.prepare("SELECT * FROM goals WHERE id=?").get(id); return row ? mapGoal(row) : null; }
882
- #requiredTurn(id) { const value = this.turn(id); if (!value)
883
- throw new Error(`turn not found: ${id}`); return value; }
884
- #requiredWake(id) { const value = this.wake(id); if (!value)
885
- throw new Error(`wake not found: ${id}`); return value; }
886
- #admitWake(input, actor, allowExisting) {
887
- if (actor !== "supervisor")
888
- throw new Error("only supervisor may enqueue wakes");
889
- this.#assertExecutionBinding(input, true);
890
- if (!input.id.trim() || !input.agent.trim() || !input.triggerRef.trim())
891
- throw new Error("Wake id, agent, and trigger are required");
892
- if (input.status !== "queued" || input.attempt !== 0 || input.claimedAt || input.consumedAt || input.turnId)
893
- throw new Error("new wake must be pristine and queued");
894
- const sameId = this.wake(input.id);
895
- if (sameId) {
896
- const sameIdentity = sameId.bindingKind === input.bindingKind && sameId.agent === input.agent && sameId.specialistRole === input.specialistRole && sameId.triggerRef === input.triggerRef && sameId.goalId === input.goalId;
897
- if (!allowExisting || !sameIdentity)
898
- throw new Error("wake id was reused with a different identity");
899
- const row = this.db.prepare("SELECT * FROM events WHERE type='wake.enqueued' AND json_extract(data,'$.snapshot.id')=? ORDER BY seq LIMIT 1").get(sameId.id);
900
- if (!row)
901
- throw new Error("wake projection has no source event");
902
- return { event: mapEvent(row), created: false, wake: sameId };
903
- }
904
- const duplicate = this.wakeByTrigger(input.agent, input.triggerRef);
905
- if (duplicate) {
906
- const sameBinding = duplicate.bindingKind === input.bindingKind && duplicate.specialistRole === input.specialistRole && duplicate.goalId === input.goalId;
907
- if (!allowExisting || !sameBinding)
908
- throw new Error("Wake trigger was reused with a different execution binding");
909
- const row = this.db.prepare("SELECT * FROM events WHERE type='wake.enqueued' AND json_extract(data,'$.snapshot.id')=? ORDER BY seq LIMIT 1").get(duplicate.id);
910
- if (!row)
911
- throw new Error("wake projection has no source event");
912
- return { event: mapEvent(row), created: false, wake: duplicate };
913
- }
914
- if (input.bindingKind === "goal") {
915
- const goal = this.#getGoal(input.goalId);
916
- if (!goal || goal.owner !== input.agent || goal.phase !== "active")
917
- throw new Error("Wake Goal binding is inactive or owned by another Agent");
918
- }
919
- const enqueuedSeq = this.#nextEventSeq();
920
- const wake = { ...input, enqueuedSeq };
921
- const event = this.#recordProjection("wakes", wake, actor, "wake.enqueued", wake.id, undefined, enqueuedSeq);
922
- this.#admitWakeTrigger(wake.id, wake.triggerRef, actor, event.ts);
923
- return { event, created: true, wake };
924
- }
925
- #admitWakeTrigger(wakeId, triggerRef, actor, at) { if (actor !== "supervisor")
926
- throw new Error("only supervisor may add Wake triggers"); if (!triggerRef.trim())
927
- throw new Error("Wake trigger is required"); const wake = this.#requiredWake(wakeId); if (wake.status !== "queued" && wake.status !== "claimed")
928
- throw new Error("triggers may only be added before a Wake starts its Turn"); const row = this.db.prepare("SELECT * FROM wake_triggers WHERE agent=? AND trigger_ref=?").get(wake.agent, triggerRef); if (row) {
929
- const current = mapWakeTrigger(row);
930
- if (current.wakeId !== wake.id)
931
- throw new Error("Wake trigger is already owned by another Wake");
932
- return current;
933
- } const mailId = mailIdFromTrigger(triggerRef); const mail = mailId ? this.mailbox().find((candidate) => candidate.id === mailId) : null; if (mail) {
934
- const matches = mail.routeKind === "goal" ? wake.bindingKind === "goal" && wake.goalId === mail.goalId : mail.routeKind === "human_inbox" && mail.from === "human" ? wake.bindingKind === "human" : mail.routeKind === "specialist_inbox" ? wake.bindingKind === "specialist" && wake.specialistRole === mail.specialistRole : false;
935
- if (!matches)
936
- throw new Error("Mail trigger does not match the Wake execution binding");
937
- } const source = wake.bindingKind === "human" ? "human" : wake.bindingKind === "goal" ? "goal" : "system"; const trigger = { wakeId: wake.id, agent: wake.agent, triggerRef, source, status: "pending", addedAt: at, resolvedAt: null }; this.#recordProjection("wake_triggers", trigger, "supervisor", "wake_trigger.added", wake.id, at); return trigger; }
938
- #resolveWakeTriggers(wakeId, now) { return this.wakeTriggers(wakeId).filter((trigger) => trigger.status === "pending").map((trigger) => { const next = { ...trigger, status: "resolved", resolvedAt: now }; this.#recordProjection("wake_triggers", next, "supervisor", "wake_trigger.resolved", wakeId, now); return next; }); }
939
- #cancelWakeProjection(wake, now) { if (wake.status !== "queued" && wake.status !== "claimed")
940
- throw new Error("only a pending Wake may be cancelled"); this.#resolveWakeTriggers(wake.id, now); const next = { ...wake, status: "cancelled", consumedAt: now }; this.#recordProjection("wakes", next, "supervisor", "wake.cancelled", wake.id, now); return next; }
941
- #requiredSchedule(id) { const row = this.db.prepare("SELECT * FROM schedule WHERE id=?").get(id); if (!row)
942
- throw new Error(`schedule not found: ${id}`); return mapSchedule(row); }
943
- #admitTurnItem(item, actor, streamId = `turn:${item.turnId}`) { if (!item.id.trim() || !item.turnId.trim())
944
- throw new Error("turn item id and turn are required"); const turn = this.turn(item.turnId); if (!turn)
945
- throw new Error("turn item turn does not exist"); if (turn.status !== "in_progress")
946
- throw new Error("terminal turn cannot accept items"); if (item.status === "in_progress" && item.completedAt !== null || item.status !== "in_progress" && item.completedAt === null)
947
- throw new Error("turn item terminal time does not match status"); const current = this.db.prepare("SELECT * FROM turn_items WHERE id=?").get(item.id); if (current && (String(current.turn_id) !== item.turnId || String(current.type) !== item.type || String(current.status) !== "in_progress"))
948
- throw new Error("turn item identity or terminal state cannot change"); return this.#recordProjection("turn_items", item, actor, current ? `item.${item.type}.${item.status}` : `item.${item.type}.started`, undefined, item.completedAt ?? item.createdAt, undefined, streamId); }
949
- #assertMailRequest(mail, actor) { if (!mail.id.trim() || !mail.to.trim() || !mail.from.trim())
950
- throw new Error("mail id, sender, and recipient are required"); if (mail.from !== actor && actor !== "supervisor")
951
- throw new Error("mail sender does not match actor"); if (mail.readAt !== null)
952
- throw new Error("new mail must be unread"); if (mail.routeKind === "goal") {
953
- if (mail.specialistRole !== null)
954
- throw new Error("Goal Mail cannot carry a specialist role");
955
- const goal = this.#getGoal(mail.goalId);
956
- if (!goal || goal.owner !== mail.to)
957
- throw new Error("Mail Goal route is not owned by its recipient");
958
- }
959
- else if (mail.routeKind === "human_inbox") {
960
- if (mail.to !== "ceo" || mail.goalId !== null || mail.specialistRole !== null || !["human", "verifier", "audit", "supervisor"].includes(mail.from))
961
- throw new Error("Human inbox Mail has an invalid sender or recipient");
962
- }
963
- else if (mail.routeKind === "human_request") {
964
- if (mail.to !== "human" || mail.from !== "ceo" || mail.goalId !== null || mail.specialistRole !== null)
965
- throw new Error("Human request Mail has an invalid sender or recipient");
966
- }
967
- else if (mail.goalId !== null || mail.specialistRole === null)
968
- throw new Error("Specialist inbox Mail has an invalid route"); }
969
- #assertNewMail(mail, actor) { this.#assertMailRequest(mail, actor); if (this.db.prepare("SELECT 1 FROM mailbox WHERE id=?").get(mail.id))
970
- throw new Error("mail id is already in use"); }
971
- #recordMailReads(mails, now, streamId) { for (const mail of mails)
972
- this.#recordProjection("mailbox", { ...mail, readAt: now }, "supervisor", "mail.read", undefined, now, undefined, streamId); const recipients = new Set(mails.map((mail) => mail.to)); const ids = new Set(mails.map((mail) => mail.id)); for (const wake of this.wakes().filter((candidate) => recipients.has(candidate.agent) && (candidate.status === "queued" || candidate.status === "claimed"))) {
973
- for (const trigger of this.wakeTriggers(wake.id).filter((candidate) => candidate.status === "pending")) {
974
- const mailId = mailIdFromTrigger(trigger.triggerRef);
975
- if (mailId && ids.has(mailId)) {
976
- const next = { ...trigger, status: "resolved", resolvedAt: now };
977
- this.#recordProjection("wake_triggers", next, "supervisor", "wake_trigger.resolved", wake.id, now);
978
- }
979
- }
980
- if (this.wakeTriggers(wake.id).every((trigger) => trigger.status === "resolved"))
981
- this.#cancelWakeProjection(wake, now);
982
- } }
983
- #normalizeSchedule(value, actor, binding) { this.#assertExecutionBinding(value, false); if (actor !== "supervisor" && actor !== value.agent)
984
- throw new Error("schedule may only be set by its agent or supervisor"); if (value.setBy !== actor)
985
- throw new Error("schedule setBy does not match actor"); const parsed = Date.parse(value.nextWakeAt); if (!value.id.trim() || !value.agent.trim() || !value.reason.trim() || !Number.isFinite(parsed))
986
- throw new Error("schedule requires an id, agent, valid time, and reason"); const normalized = { ...value, nextWakeAt: new Date(parsed).toISOString() }; if (normalized.status !== "pending" || normalized.resolvedAt !== null)
987
- throw new Error("new schedule must be pending"); if (binding && normalized.goalId !== binding.goalId)
988
- throw new Error("handoff schedule does not match the Turn Goal binding"); if (normalized.bindingKind === "goal") {
989
- const goal = this.#getGoal(normalized.goalId);
990
- if (!goal || goal.owner !== normalized.agent || goal.phase !== "active")
991
- throw new Error("schedule Goal target is inactive or owned by another Agent");
992
- } return normalized; }
993
- #assertExecutionBinding(value, allowHuman) { if (value.bindingKind === "human") {
994
- if (!allowHuman || value.agent !== "ceo" || value.goalId !== null || value.specialistRole !== null)
995
- throw new Error("invalid Human execution binding");
996
- return;
997
- } if (value.bindingKind === "goal") {
998
- if (!value.goalId || value.specialistRole !== null)
999
- throw new Error("invalid Goal execution binding");
1000
- return;
1001
- } if (value.bindingKind !== "specialist" || value.goalId !== null || !value.specialistRole || !["verifier", "audit"].includes(value.specialistRole))
1002
- throw new Error("invalid Specialist execution binding"); }
1003
- #assertTurnBinding(value) { if (value.bindingKind === "human") {
1004
- if (value.source !== "human" || value.goalId !== null || value.goalRevision !== null || value.specialistRole !== null)
1005
- throw new Error("invalid Human Turn binding");
1006
- return;
1007
- } if (value.bindingKind === "goal") {
1008
- if (!["human", "goal"].includes(value.source) || !value.goalId || value.goalRevision === null || value.specialistRole !== null)
1009
- throw new Error("invalid Goal Turn binding");
1010
- return;
1011
- } if (value.bindingKind !== "specialist" || value.source !== "system" || value.goalId !== null || value.goalRevision !== null || !value.specialistRole || !["verifier", "audit"].includes(value.specialistRole))
1012
- throw new Error("invalid Specialist Turn binding"); }
1013
- #replayProjection(projection, snapshot, event) { if (projection === "turns")
1014
- this.#assertReplayTurn(snapshot, event);
1015
- else if (projection === "wakes")
1016
- this.#assertReplayWake(snapshot, event); this.#applyProjection(projection, snapshot, event.seq); }
1017
- #assertReplayTurn(turn, event) { this.#assertTurnBinding(turn); const thread = this.thread(turn.threadId); if (!thread)
1018
- throw new Error(`turn event ${event.seq} has no Thread`); const current = this.turn(turn.id); if (!current) {
1019
- if (event.type !== "turn.started" || turn.status !== "in_progress" || turn.attempt !== 1)
1020
- throw new Error(`turn event ${event.seq} has an invalid initial state`);
1021
- if (event.actor === "human") {
1022
- if (turn.bindingKind !== "human" || thread.agent !== "ceo")
1023
- throw new Error(`turn event ${event.seq} has invalid Human ownership`);
1024
- }
1025
- else {
1026
- if (event.actor !== "supervisor" || !this.wakes().some((wake) => wake.status === "claimed" && wake.agent === thread.agent && sameWakeTurnBinding(wake, turn)))
1027
- throw new Error(`turn event ${event.seq} bypasses Wake admission`);
1028
- this.#assertCurrentAutomaticTurn(turn, thread.agent, event.seq);
1029
- }
1030
- return;
1031
- } if (current.threadId !== turn.threadId || current.source !== turn.source || current.startedAt !== turn.startedAt || current.runnerProfileId !== turn.runnerProfileId)
1032
- throw new Error(`turn event ${event.seq} changes Turn identity`); if (current.status !== "in_progress")
1033
- throw new Error(`turn event ${event.seq} changes a terminal Turn`); const bindsGoal = event.actor === "supervisor" && current.bindingKind === "human" && turn.bindingKind === "goal" && current.source === "human"; if (current.bindingKind !== turn.bindingKind && !bindsGoal || current.bindingKind === turn.bindingKind && (current.goalId !== turn.goalId || current.goalRevision !== turn.goalRevision || current.specialistRole !== turn.specialistRole))
1034
- throw new Error(`turn event ${event.seq} changes execution binding`); if (bindsGoal) {
1035
- const goal = this.#getGoal(turn.goalId);
1036
- if (thread.agent !== "ceo" || !goal || goal.parentId !== null || goal.owner !== "ceo" || goal.phase !== "active" || goal.revision !== turn.goalRevision)
1037
- throw new Error(`turn event ${event.seq} has an invalid Human-to-Goal binding`);
1038
- } if (turn.status === "in_progress") {
1039
- if (event.type !== "turn.in_progress" || turn.attempt !== current.attempt && turn.attempt !== current.attempt + 1)
1040
- throw new Error(`turn event ${event.seq} has an invalid retry transition`);
1041
- }
1042
- else {
1043
- if (event.type !== `turn.${turn.status}` || turn.attempt !== current.attempt)
1044
- throw new Error(`turn event ${event.seq} has an invalid terminal transition`);
1045
- if (turn.status === "completed" && turn.bindingKind === "goal")
1046
- this.#assertReplayGoalCompletion(turn, event);
1047
- } }
1048
- #assertReplayGoalCompletion(turn, event) { const items = this.turnItems(turn.id); const responses = items.filter((item) => item.type === "assistant_message" && item.status === "completed" && typeof item.data.text === "string" && Boolean(item.data.text.trim())); const handoffItem = items.findLast((item) => item.type === "handoff" && item.status === "completed"); const responseRow = this.db.prepare("SELECT data FROM events WHERE stream_id=? AND type='response.committed' AND seq<? ORDER BY seq DESC LIMIT 1").get(`turn:${turn.id}`, event.seq); const handoffRow = this.db.prepare("SELECT data FROM events WHERE stream_id=? AND type='handoff.recorded' AND seq<? ORDER BY seq DESC LIMIT 1").get(`turn:${turn.id}`, event.seq); if (!responseRow || !handoffRow || !handoffItem)
1049
- throw new Error(`turn event ${event.seq} completes a Goal without response and Handoff`); const response = JSON.parse(responseRow.data); const handoff = JSON.parse(handoffRow.data); const responseItem = responses.find((item) => item.id === response.messageItemId); if (!responseItem || responseItem.data.text !== response.text || !isDeepStrictEqual(handoffItem.data, handoff))
1050
- throw new Error(`turn event ${event.seq} has mismatched response or Handoff facts`); assertHandoff(handoff); const record = this.workRecord(turn.goalId); if (handoff.goalId !== turn.goalId || handoff.goalRevision !== turn.goalRevision || record?.recordRevision !== handoff.recordRevision)
1051
- throw new Error(`turn event ${event.seq} has a Handoff for another Goal or Work Record`); for (const seq of handoff.evidence)
1052
- if (seq >= event.seq || !this.db.prepare("SELECT 1 FROM events WHERE seq=?").get(seq))
1053
- throw new Error(`turn event ${event.seq} has invalid Handoff evidence`); }
1054
- #assertReplayWake(wake, event) { this.#assertExecutionBinding(wake, true); const current = this.wake(wake.id); if (!current) {
1055
- if (event.type !== "wake.enqueued" || wake.status !== "queued" || wake.attempt !== 0 || wake.claimedAt || wake.consumedAt || wake.turnId)
1056
- throw new Error(`wake event ${event.seq} has an invalid initial state`);
1057
- if (wake.bindingKind === "goal") {
1058
- const goal = this.#getGoal(wake.goalId);
1059
- if (!goal || goal.phase !== "active" || goal.owner !== wake.agent)
1060
- throw new Error(`wake event ${event.seq} has an invalid Goal binding`);
1061
- }
1062
- return;
1063
- } if (current.bindingKind !== wake.bindingKind || current.agent !== wake.agent || current.goalId !== wake.goalId || current.specialistRole !== wake.specialistRole || current.triggerRef !== wake.triggerRef || current.enqueuedSeq !== wake.enqueuedSeq)
1064
- throw new Error(`wake event ${event.seq} changes Wake identity`); if (current.status === "consumed" || current.status === "cancelled")
1065
- throw new Error(`wake event ${event.seq} changes a terminal Wake`); if (wake.status === "claimed") {
1066
- if (event.type !== "wake.claimed" || current.status !== "queued" || wake.attempt !== current.attempt + 1 || !wake.claimedAt || wake.consumedAt !== null || wake.turnId !== null)
1067
- throw new Error(`wake event ${event.seq} has an invalid claim transition`);
1068
- }
1069
- else if (wake.status === "queued") {
1070
- if (event.type !== "wake.released" || current.status !== "claimed" || wake.attempt !== current.attempt || wake.claimedAt !== null || wake.consumedAt !== null || wake.turnId !== null)
1071
- throw new Error(`wake event ${event.seq} has an invalid release transition`);
1072
- }
1073
- else if (wake.status === "cancelled") {
1074
- if (event.type !== "wake.cancelled" || wake.attempt !== current.attempt || wake.claimedAt !== current.claimedAt || wake.consumedAt === null || wake.turnId !== null)
1075
- throw new Error(`wake event ${event.seq} has an invalid cancel transition`);
1076
- }
1077
- else {
1078
- if (event.type !== "wake.consumed" || current.status !== "claimed" || wake.attempt !== current.attempt || wake.claimedAt !== current.claimedAt || wake.consumedAt === null || !wake.turnId)
1079
- throw new Error(`wake event ${event.seq} has an invalid consume transition`);
1080
- const turn = this.turn(wake.turnId);
1081
- const thread = turn ? this.thread(turn.threadId) : null;
1082
- if (!turn || thread?.agent !== wake.agent || !sameWakeTurnBinding(wake, turn))
1083
- throw new Error(`wake event ${event.seq} does not match its Turn`);
1084
- } }
1085
- #assertCurrentAutomaticTurn(turn, agent, seq) { if (turn.bindingKind === "human") {
1086
- if (agent !== "ceo")
1087
- throw new Error(seq ? `turn event ${seq} has invalid Human ownership` : "Human Wake may start only the CEO Turn");
1088
- return;
1089
- } if (turn.bindingKind === "goal") {
1090
- const goal = this.#getGoal(turn.goalId);
1091
- if (!goal || goal.phase !== "active" || goal.owner !== agent || goal.revision !== turn.goalRevision)
1092
- throw new Error(seq ? `turn event ${seq} has a stale Goal binding` : "Wake Turn must bind the current active Goal revision owned by its Agent");
1093
- } }
1094
- #admitSchedule(value, actor, wakeId, ts = this.#now(), streamId, binding, allowExisting = true) { const normalized = this.#normalizeSchedule(value, actor, binding); const existing = this.db.prepare("SELECT * FROM schedule WHERE id=?").get(normalized.id); if (existing) {
1095
- const current = mapSchedule(existing);
1096
- if (!allowExisting || !isDeepStrictEqual(current, normalized))
1097
- throw new Error("schedule id was reused with different content");
1098
- const row = this.db.prepare("SELECT * FROM events WHERE type='schedule.put' AND json_extract(data,'$.snapshot.id')=? ORDER BY seq LIMIT 1").get(normalized.id);
1099
- if (!row)
1100
- throw new Error("schedule projection has no source event");
1101
- return mapEvent(row);
1102
- } this.#supersedeScheduleRoute(normalized.agent, normalized.goalId ?? null, normalized.id, ts); return this.#recordProjection("schedule", normalized, actor, "schedule.put", wakeId, ts, undefined, streamId); }
1103
- #supersedeScheduleRoute(agent, goalId, exceptId, now) { const rows = (goalId === null ? this.db.prepare("SELECT * FROM schedule WHERE agent=? AND goal_id IS NULL AND id<>? AND status='pending' ORDER BY id").all(agent, exceptId) : this.db.prepare("SELECT * FROM schedule WHERE agent=? AND goal_id=? AND id<>? AND status='pending' ORDER BY id").all(agent, goalId, exceptId)); return rows.map((row) => { const current = mapSchedule(row); const next = { ...current, status: "superseded", resolvedAt: now }; this.#recordProjection("schedule", next, "supervisor", "schedule.superseded", undefined, now); return next; }); }
1104
- #supersedeSchedulesForGoal(goalId, now) { const rows = this.db.prepare("SELECT * FROM schedule WHERE goal_id=? AND status='pending' ORDER BY id").all(goalId); return rows.map((row) => { const current = mapSchedule(row); const next = { ...current, status: "superseded", resolvedAt: now }; this.#recordProjection("schedule", next, "supervisor", "schedule.superseded", undefined, now); return next; }); }
1105
- #cancelWakesForGoal(goalId, now) { return this.wakes().filter((wake) => wake.goalId === goalId && (wake.status === "queued" || wake.status === "claimed")).map((wake) => this.#cancelWakeProjection(wake, now)); }
1106
- #repairOpenTurnItems(turnId, reason, now, actor) { const streamId = `turn:${turnId}`; const open = this.turnItems(turnId).filter((item) => item.status === "in_progress"); const repaired = []; let ordinal = this.turnItems(turnId).length + 1; for (const item of open) {
1107
- const failed = { ...item, status: "failed", completedAt: now };
1108
- this.#recordProjection("turn_items", failed, actor, `item.${item.type}.failed`, undefined, now, undefined, streamId);
1109
- repaired.push(failed);
1110
- if (item.type === "tool_call") {
1111
- const callId = String(item.data.callId ?? item.id);
1112
- const result = { id: `repair:${turnId}:${item.ordinal}`, turnId, ordinal: ordinal++, type: "tool_result", status: "completed", data: { callId, result: { outcome: "unknown", synthetic: true, reason } }, createdAt: now, completedAt: now };
1113
- this.#admitTurnItem(result, actor, streamId);
1114
- this.#insertEvent({ streamId, ts: now, actor, type: "tool.completed", data: { callId, messageId: `repair:${callId}`, result: { outcome: "unknown", synthetic: true, reason }, isError: true } });
1115
- repaired.push(result);
1116
- }
1117
- } return repaired; }
1118
- #project(projection, snapshot, actor, type, wakeId, ts, streamId) {
1119
- return this.#transaction(() => this.#recordProjection(projection, snapshot, actor, type, wakeId, ts, undefined, streamId));
1120
- }
1121
- #recordProjection(projection, snapshot, actor, type, wakeId, ts, expectedSeq, streamId) {
1122
- const event = this.#insertEvent({ streamId: streamId ?? (wakeId ? wakeStream(wakeId) : controlStream(projection)), ts: ts ?? this.#now(), actor, type, data: { snapshot }, ignorable: true }, expectedSeq, projection);
1123
- this.#faultInjector?.("after_event_before_projection");
1124
- this.#applyProjection(projection, snapshot, event.seq);
1125
- return event;
1126
- }
1127
- #insertEvent(input, expectedSeq, projection) {
1128
- if (!input.streamId.trim() || !input.actor.trim() || !input.type.trim())
1129
- throw new Error("event streamId, actor and type are required");
1130
- const streamSeq = Number(this.db.prepare("SELECT COALESCE(MAX(stream_seq),0)+1 AS next FROM events WHERE stream_id=?").get(input.streamId).next);
1131
- const result = expectedSeq === undefined
1132
- ? this.db.prepare("INSERT INTO events(stream_id,stream_seq,ts,actor,type,data,projection_name,ignorable) VALUES (?,?,?,?,?,json(?),?,?)").run(input.streamId, streamSeq, input.ts, input.actor, input.type, JSON.stringify(input.data), projection ?? null, input.ignorable === true ? 1 : null)
1133
- : this.db.prepare("INSERT INTO events(seq,stream_id,stream_seq,ts,actor,type,data,projection_name,ignorable) VALUES (?,?,?,?,?,?,json(?),?,?)").run(expectedSeq, input.streamId, streamSeq, input.ts, input.actor, input.type, JSON.stringify(input.data), projection ?? null, input.ignorable === true ? 1 : null);
1134
- return { ...input, seq: Number(result.lastInsertRowid), streamSeq };
1135
- }
1136
- #nextEventSeq() {
1137
- const row = this.db.prepare("SELECT seq FROM sqlite_sequence WHERE name='events'").get();
1138
- return Number(row?.seq ?? 0) + 1;
1139
- }
1140
- #applyProjection(projection, raw, sourceSeq) {
1141
- if (projection === "threads") {
1142
- const v = raw;
1143
- this.db.prepare(`INSERT INTO threads VALUES (?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET agent=excluded.agent,parent_thread_id=excluded.parent_thread_id,updated_at=excluded.updated_at`).run(v.id, v.agent, v.parentThreadId, v.createdAt, v.updatedAt);
1144
- }
1145
- else if (projection === "turns") {
1146
- const v = raw;
1147
- this.db.prepare(`INSERT INTO turns VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET binding_kind=excluded.binding_kind,specialist_role=excluded.specialist_role,goal_id=excluded.goal_id,goal_revision=excluded.goal_revision,status=excluded.status,attempt=excluded.attempt,error=excluded.error,ended_at=excluded.ended_at,lease_until=excluded.lease_until,lease_token=excluded.lease_token,runner_pid=excluded.runner_pid`).run(v.id, v.threadId, v.source, v.bindingKind, v.specialistRole, v.goalId, v.goalRevision, v.status, v.attempt, v.error === null ? null : JSON.stringify(v.error), v.startedAt, v.endedAt, v.leaseUntil, v.leaseToken, v.runnerPid, v.runnerProfileId ?? null);
1148
- this.db.prepare("UPDATE threads SET updated_at=CASE WHEN updated_at<? THEN ? ELSE updated_at END WHERE id=?").run(v.endedAt ?? v.startedAt, v.endedAt ?? v.startedAt, v.threadId);
1149
- }
1150
- else if (projection === "turn_items") {
1151
- const v = raw;
1152
- this.db.prepare(`INSERT INTO turn_items VALUES (?,?,?,?,?,json(?),?,?) ON CONFLICT(id) DO UPDATE SET status=excluded.status,data=excluded.data,completed_at=excluded.completed_at`).run(v.id, v.turnId, v.ordinal, v.type, v.status, JSON.stringify(v.data), v.createdAt, v.completedAt);
1153
- this.db.prepare("UPDATE threads SET updated_at=CASE WHEN updated_at<? THEN ? ELSE updated_at END WHERE id=(SELECT thread_id FROM turns WHERE id=?)").run(v.completedAt ?? v.createdAt, v.completedAt ?? v.createdAt, v.turnId);
1154
- }
1155
- else if (projection === "goals") {
1156
- const v = normalizeGoal(raw);
1157
- this.db.prepare(`INSERT INTO goals VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET parent_id=excluded.parent_id,objective=excluded.objective,observation_method=excluded.observation_method,verification_method=excluded.verification_method,owner=excluded.owner,phase=excluded.phase,revision=excluded.revision`).run(v.id, v.parentId, v.objective, v.observationMethod, v.verificationMethod ?? null, v.owner, v.phase, v.revision);
1158
- }
1159
- else if (projection === "work_records") {
1160
- const v = raw;
1161
- this.db.prepare(`INSERT INTO work_records VALUES (?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(goal_id) DO UPDATE SET record_revision=excluded.record_revision,goal_revision=excluded.goal_revision,content=excluded.content,updated_by=excluded.updated_by,updated_in_turn=excluded.updated_in_turn,source_wake_id=excluded.source_wake_id,updated_at=excluded.updated_at,reason=excluded.reason,evidence=excluded.evidence,last_event_seq=excluded.last_event_seq`).run(v.goalId, v.recordRevision, v.goalRevision, v.content, v.updatedBy, v.updatedInTurn, v.sourceWakeId, v.updatedAt, v.reason, JSON.stringify(v.evidence), v.lastEventSeq || sourceSeq);
1162
- }
1163
- else if (projection === "schedule") {
1164
- const v = raw;
1165
- this.db.prepare(`INSERT INTO schedule VALUES (?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET binding_kind=excluded.binding_kind,agent=excluded.agent,specialist_role=excluded.specialist_role,next_wake_at=excluded.next_wake_at,reason=excluded.reason,set_by=excluded.set_by,status=excluded.status,resolved_at=excluded.resolved_at,goal_id=excluded.goal_id`).run(v.id, v.bindingKind, v.agent, v.specialistRole, v.nextWakeAt, v.reason, v.setBy, v.status, v.resolvedAt, v.goalId);
1166
- }
1167
- else if (projection === "wakes") {
1168
- const v = raw;
1169
- this.db.prepare(`INSERT INTO wakes VALUES (?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET binding_kind=excluded.binding_kind,agent=excluded.agent,specialist_role=excluded.specialist_role,trigger_ref=excluded.trigger_ref,status=excluded.status,attempt=excluded.attempt,enqueued_seq=excluded.enqueued_seq,claimed_at=excluded.claimed_at,consumed_at=excluded.consumed_at,turn_id=excluded.turn_id,goal_id=excluded.goal_id`).run(v.id, v.bindingKind, v.agent, v.specialistRole, v.triggerRef, v.status, v.attempt, v.enqueuedSeq || sourceSeq, v.claimedAt, v.consumedAt, v.turnId, v.goalId);
1170
- }
1171
- else if (projection === "wake_triggers") {
1172
- const v = raw;
1173
- this.db.prepare(`INSERT INTO wake_triggers VALUES (?,?,?,?,?,?,?) ON CONFLICT(wake_id,trigger_ref) DO UPDATE SET status=excluded.status,resolved_at=excluded.resolved_at`).run(v.wakeId, v.agent, v.triggerRef, v.source, v.status, v.addedAt, v.resolvedAt);
1174
- }
1175
- else if (projection === "mailbox") {
1176
- const v = raw;
1177
- this.db.prepare(`INSERT INTO mailbox VALUES (?,?,?,?,?,?,?,json(?),?) ON CONFLICT(id) DO UPDATE SET route_kind=excluded.route_kind,to_agent=excluded.to_agent,from_agent=excluded.from_agent,specialist_role=excluded.specialist_role,level=excluded.level,goal_id=excluded.goal_id,body=excluded.body,read_at=excluded.read_at`).run(v.id, v.routeKind, v.to, v.from, v.specialistRole, v.level, v.goalId, JSON.stringify(v.body), v.readAt);
1178
- }
1179
- }
1180
- #transaction(fn) {
1181
- this.db.exec("BEGIN IMMEDIATE");
1182
- try {
1183
- const result = fn();
1184
- this.db.exec("COMMIT");
1185
- return result;
1186
- }
1187
- catch (error) {
1188
- this.db.exec("ROLLBACK");
1189
- throw error;
1190
- }
1191
- }
1192
- #now() { return this.#clock.now().toISOString(); }
1193
- }
1194
- function mapEvent(r) { return { seq: Number(r.seq), streamId: String(r.stream_id), streamSeq: Number(r.stream_seq), ts: String(r.ts), actor: String(r.actor), type: String(r.type), data: JSON.parse(String(r.data)), ...(Number(r.ignorable) === 1 ? { ignorable: true } : {}) }; }
1195
- function mapThread(r) { return { id: String(r.id), agent: String(r.agent), parentThreadId: r.parent_thread_id === null ? null : String(r.parent_thread_id), createdAt: String(r.created_at), updatedAt: String(r.updated_at) }; }
1196
- function mapTurn(r) { return { id: String(r.id), threadId: String(r.thread_id), source: String(r.source), bindingKind: String(r.binding_kind), specialistRole: r.specialist_role === null ? null : String(r.specialist_role), goalId: r.goal_id === null ? null : String(r.goal_id), goalRevision: r.goal_revision === null ? null : Number(r.goal_revision), status: String(r.status), attempt: Number(r.attempt), error: r.error === null ? null : JSON.parse(String(r.error)), startedAt: String(r.started_at), endedAt: r.ended_at === null ? null : String(r.ended_at), leaseUntil: r.lease_until === null ? null : String(r.lease_until), leaseToken: r.lease_token === null ? null : String(r.lease_token), runnerPid: r.runner_pid === null ? null : Number(r.runner_pid), ...(r.runner_profile_id === null || r.runner_profile_id === undefined ? {} : { runnerProfileId: String(r.runner_profile_id) }) }; }
1197
- function mapTurnItem(r) { return { id: String(r.id), turnId: String(r.turn_id), ordinal: Number(r.ordinal), type: String(r.type), status: String(r.status), data: JSON.parse(String(r.data)), createdAt: String(r.created_at), completedAt: r.completed_at === null ? null : String(r.completed_at) }; }
1198
- function normalizeGoal(goal) { return { ...goal, observationMethod: goal.observationMethod ?? null, verificationMethod: goal.verificationMethod === undefined ? goal.observationMethod ?? null : goal.verificationMethod }; }
1199
- function mapGoal(r) { return { id: String(r.id), parentId: r.parent_id === null ? null : String(r.parent_id), objective: String(r.objective), observationMethod: r.observation_method === null || r.observation_method === undefined ? null : String(r.observation_method), verificationMethod: r.verification_method === null || r.verification_method === undefined ? null : String(r.verification_method), owner: String(r.owner), phase: String(r.phase), revision: Number(r.revision) }; }
1200
- function mapWorkRecord(r) { return { goalId: String(r.goal_id), recordRevision: Number(r.record_revision), goalRevision: Number(r.goal_revision), content: String(r.content), updatedBy: String(r.updated_by), updatedInTurn: String(r.updated_in_turn), sourceWakeId: r.source_wake_id === null ? null : String(r.source_wake_id), updatedAt: String(r.updated_at), reason: String(r.reason), evidence: JSON.parse(String(r.evidence)), lastEventSeq: Number(r.last_event_seq) }; }
1201
- function mapWorkRecordEvent(event) { const data = event.data; if (!data.snapshot)
1202
- throw new Error(`work record event ${event.seq} has no snapshot`); return { ...data.snapshot, lastEventSeq: event.seq }; }
1203
- function initialWorkRecord() { return "# Current State\n\nGoal created. Work has not started.\n\n# Observations\n\n# Work Completed\n\n# Decisions\n\n# Blockers\n\n# Next Steps\n"; }
1204
- function goalOperation(previous, next) { if (!previous)
1205
- return "create"; if (previous.phase !== next.phase) {
1206
- if (next.phase === "paused")
1207
- return "pause";
1208
- if (next.phase === "active")
1209
- return "resume";
1210
- if (next.phase === "blocked")
1211
- return "block";
1212
- if (next.phase === "complete")
1213
- return "complete";
1214
- } return previous.owner !== next.owner ? "reassign" : "revise"; }
1215
- function defaultGoalReason(operation) { return `Goal ${operation}`; }
1216
- function withoutSourceTurn(value) { const { sourceTurnId: _, ...semantic } = value; return semantic; }
1217
- function projectionForEvent(type) { if (type === "thread.put")
1218
- return "threads"; if (type.startsWith("turn."))
1219
- return "turns"; if (type.startsWith("item."))
1220
- return "turn_items"; if (type === "goal.changed")
1221
- return "goals"; if (type.startsWith("schedule."))
1222
- return "schedule"; if (type.startsWith("wake_trigger."))
1223
- return "wake_triggers"; if (type.startsWith("wake."))
1224
- return "wakes"; if (type.startsWith("mail."))
1225
- return "mailbox"; if (type === "work_record.created" || type === "work_record.updated")
1226
- return "work_records"; return null; }
1227
- function lineDiff(from, to) {
1228
- const before = from.split("\n");
1229
- const after = to.split("\n");
1230
- const lines = [];
1231
- for (let index = 0; index < Math.max(before.length, after.length); index += 1) {
1232
- if (before[index] === after[index]) {
1233
- if (before[index] !== undefined)
1234
- lines.push(` ${before[index]}`);
1235
- continue;
1236
- }
1237
- if (before[index] !== undefined)
1238
- lines.push(`-${before[index]}`);
1239
- if (after[index] !== undefined)
1240
- lines.push(`+${after[index]}`);
1241
- }
1242
- return lines.join("\n");
1243
- }
1244
- function mapSchedule(r) { return { id: String(r.id), bindingKind: String(r.binding_kind), agent: String(r.agent), specialistRole: r.specialist_role === null ? null : String(r.specialist_role), goalId: r.goal_id === null ? null : String(r.goal_id), nextWakeAt: String(r.next_wake_at), reason: String(r.reason), setBy: String(r.set_by), status: String(r.status), resolvedAt: r.resolved_at === null ? null : String(r.resolved_at) }; }
1245
- function mapWake(r) { return { id: String(r.id), bindingKind: String(r.binding_kind), agent: String(r.agent), specialistRole: r.specialist_role === null ? null : String(r.specialist_role), goalId: r.goal_id === null ? null : String(r.goal_id), triggerRef: String(r.trigger_ref), status: String(r.status), attempt: Number(r.attempt), enqueuedSeq: Number(r.enqueued_seq), claimedAt: r.claimed_at === null ? null : String(r.claimed_at), consumedAt: r.consumed_at === null ? null : String(r.consumed_at), turnId: r.turn_id === null ? null : String(r.turn_id) }; }
1246
- function sameWakeTurnBinding(wake, turn) { if (wake.bindingKind !== turn.bindingKind)
1247
- return false; if (wake.bindingKind === "human")
1248
- return turn.bindingKind === "human" && turn.source === "human"; if (wake.bindingKind === "goal")
1249
- return turn.bindingKind === "goal" && wake.goalId === turn.goalId; return turn.bindingKind === "specialist" && wake.specialistRole === turn.specialistRole && turn.source === "system"; }
1250
- function mapWakeTrigger(r) { return { wakeId: String(r.wake_id), agent: String(r.agent), triggerRef: String(r.trigger_ref), source: String(r.source), status: String(r.status), addedAt: String(r.added_at), resolvedAt: r.resolved_at === null ? null : String(r.resolved_at) }; }
1251
- function mapMail(r) { return { id: String(r.id), routeKind: String(r.route_kind), to: String(r.to_agent), from: String(r.from_agent), specialistRole: r.specialist_role === null ? null : String(r.specialist_role), level: String(r.level), goalId: r.goal_id === null ? null : String(r.goal_id), body: JSON.parse(String(r.body)), readAt: r.read_at === null ? null : String(r.read_at) }; }
1252
- function mailIdFromTrigger(trigger) { if (!trigger.startsWith("mail:"))
1253
- return null; return trigger.slice("mail:".length).split("@redelivery:")[0] || null; }
1254
- //# sourceMappingURL=index.js.map