@dsh-ray/assistant-delivery 0.0.1-seed.0 → 0.2.1

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 (185) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +610 -1
  3. package/bin/dsh-restart-supervisor.js +102 -0
  4. package/cordis.patch.yml +29 -0
  5. package/lib/acceptance.d.ts +54 -0
  6. package/lib/acceptance.d.ts.map +1 -0
  7. package/lib/acceptance.js +2 -0
  8. package/lib/acceptance.js.map +1 -0
  9. package/lib/agent-runtime.d.ts +247 -0
  10. package/lib/agent-runtime.d.ts.map +1 -0
  11. package/lib/agent-runtime.js +4458 -0
  12. package/lib/agent-runtime.js.map +1 -0
  13. package/lib/approval-status-context.d.ts +8 -0
  14. package/lib/approval-status-context.d.ts.map +1 -0
  15. package/lib/approval-status-context.js +55 -0
  16. package/lib/approval-status-context.js.map +1 -0
  17. package/lib/attention-audit-store.d.ts +54 -0
  18. package/lib/attention-audit-store.d.ts.map +1 -0
  19. package/lib/attention-audit-store.js +213 -0
  20. package/lib/attention-audit-store.js.map +1 -0
  21. package/lib/attention-enforcement.d.ts +75 -0
  22. package/lib/attention-enforcement.d.ts.map +1 -0
  23. package/lib/attention-enforcement.js +84 -0
  24. package/lib/attention-enforcement.js.map +1 -0
  25. package/lib/attention.d.ts +208 -0
  26. package/lib/attention.d.ts.map +1 -0
  27. package/lib/attention.js +288 -0
  28. package/lib/attention.js.map +1 -0
  29. package/lib/canonical.d.ts +28 -0
  30. package/lib/canonical.d.ts.map +1 -0
  31. package/lib/canonical.js +190 -0
  32. package/lib/canonical.js.map +1 -0
  33. package/lib/coordinator.d.ts +134 -0
  34. package/lib/coordinator.d.ts.map +1 -0
  35. package/lib/coordinator.js +746 -0
  36. package/lib/coordinator.js.map +1 -0
  37. package/lib/feedback-command.d.ts +105 -0
  38. package/lib/feedback-command.d.ts.map +1 -0
  39. package/lib/feedback-command.js +547 -0
  40. package/lib/feedback-command.js.map +1 -0
  41. package/lib/foreground-observation.d.ts +66 -0
  42. package/lib/foreground-observation.d.ts.map +1 -0
  43. package/lib/foreground-observation.js +13 -0
  44. package/lib/foreground-observation.js.map +1 -0
  45. package/lib/foreground-termination.d.ts +31 -0
  46. package/lib/foreground-termination.d.ts.map +1 -0
  47. package/lib/foreground-termination.js +42 -0
  48. package/lib/foreground-termination.js.map +1 -0
  49. package/lib/goal-wake-types.d.ts +93 -0
  50. package/lib/goal-wake-types.d.ts.map +1 -0
  51. package/lib/goal-wake-types.js +70 -0
  52. package/lib/goal-wake-types.js.map +1 -0
  53. package/lib/in-process-reload-runtime.d.ts +120 -0
  54. package/lib/in-process-reload-runtime.d.ts.map +1 -0
  55. package/lib/in-process-reload-runtime.js +1280 -0
  56. package/lib/in-process-reload-runtime.js.map +1 -0
  57. package/lib/inbound-images.d.ts +38 -0
  58. package/lib/inbound-images.d.ts.map +1 -0
  59. package/lib/inbound-images.js +269 -0
  60. package/lib/inbound-images.js.map +1 -0
  61. package/lib/index.d.ts +41 -0
  62. package/lib/index.d.ts.map +1 -0
  63. package/lib/index.js +25 -0
  64. package/lib/index.js.map +1 -0
  65. package/lib/learning-command.d.ts +40 -0
  66. package/lib/learning-command.d.ts.map +1 -0
  67. package/lib/learning-command.js +57 -0
  68. package/lib/learning-command.js.map +1 -0
  69. package/lib/native-termination.d.ts +12 -0
  70. package/lib/native-termination.d.ts.map +1 -0
  71. package/lib/native-termination.js +57 -0
  72. package/lib/native-termination.js.map +1 -0
  73. package/lib/native-web-owner.d.ts +97 -0
  74. package/lib/native-web-owner.d.ts.map +1 -0
  75. package/lib/native-web-owner.js +338 -0
  76. package/lib/native-web-owner.js.map +1 -0
  77. package/lib/operator-snapshot.d.ts +107 -0
  78. package/lib/operator-snapshot.d.ts.map +1 -0
  79. package/lib/operator-snapshot.js +1013 -0
  80. package/lib/operator-snapshot.js.map +1 -0
  81. package/lib/operator.d.ts +25 -0
  82. package/lib/operator.d.ts.map +1 -0
  83. package/lib/operator.js +48 -0
  84. package/lib/operator.js.map +1 -0
  85. package/lib/progress-attention.d.ts +55 -0
  86. package/lib/progress-attention.d.ts.map +1 -0
  87. package/lib/progress-attention.js +128 -0
  88. package/lib/progress-attention.js.map +1 -0
  89. package/lib/reply-replay.d.ts +52 -0
  90. package/lib/reply-replay.d.ts.map +1 -0
  91. package/lib/reply-replay.js +122 -0
  92. package/lib/reply-replay.js.map +1 -0
  93. package/lib/restart-native.d.ts +47 -0
  94. package/lib/restart-native.d.ts.map +1 -0
  95. package/lib/restart-native.js +170 -0
  96. package/lib/restart-native.js.map +1 -0
  97. package/lib/restart-runtime.d.ts +38 -0
  98. package/lib/restart-runtime.d.ts.map +1 -0
  99. package/lib/restart-runtime.js +335 -0
  100. package/lib/restart-runtime.js.map +1 -0
  101. package/lib/restart-store.d.ts +132 -0
  102. package/lib/restart-store.d.ts.map +1 -0
  103. package/lib/restart-store.js +757 -0
  104. package/lib/restart-store.js.map +1 -0
  105. package/lib/restart-supervisor.d.ts +129 -0
  106. package/lib/restart-supervisor.d.ts.map +1 -0
  107. package/lib/restart-supervisor.js +615 -0
  108. package/lib/restart-supervisor.js.map +1 -0
  109. package/lib/service.d.ts +1279 -0
  110. package/lib/service.d.ts.map +1 -0
  111. package/lib/service.js +8694 -0
  112. package/lib/service.js.map +1 -0
  113. package/lib/session-commands.d.ts +52 -0
  114. package/lib/session-commands.d.ts.map +1 -0
  115. package/lib/session-commands.js +180 -0
  116. package/lib/session-commands.js.map +1 -0
  117. package/lib/session-lease-runtime.d.ts +70 -0
  118. package/lib/session-lease-runtime.d.ts.map +1 -0
  119. package/lib/session-lease-runtime.js +395 -0
  120. package/lib/session-lease-runtime.js.map +1 -0
  121. package/lib/session-lease-types.d.ts +27 -0
  122. package/lib/session-lease-types.d.ts.map +1 -0
  123. package/lib/session-lease-types.js +2 -0
  124. package/lib/session-lease-types.js.map +1 -0
  125. package/lib/sqlite.d.ts +8 -0
  126. package/lib/sqlite.d.ts.map +1 -0
  127. package/lib/sqlite.js +1665 -0
  128. package/lib/sqlite.js.map +1 -0
  129. package/lib/store.d.ts +1267 -0
  130. package/lib/store.d.ts.map +1 -0
  131. package/lib/store.js +8039 -0
  132. package/lib/store.js.map +1 -0
  133. package/lib/tools.d.ts +4 -0
  134. package/lib/tools.d.ts.map +1 -0
  135. package/lib/tools.js +73 -0
  136. package/lib/tools.js.map +1 -0
  137. package/lib/types.d.ts +1091 -0
  138. package/lib/types.d.ts.map +1 -0
  139. package/lib/types.js +10 -0
  140. package/lib/types.js.map +1 -0
  141. package/lib/version-query.d.ts +77 -0
  142. package/lib/version-query.d.ts.map +1 -0
  143. package/lib/version-query.js +2208 -0
  144. package/lib/version-query.js.map +1 -0
  145. package/lib/version.d.ts +2 -0
  146. package/lib/version.d.ts.map +1 -0
  147. package/lib/version.js +2 -0
  148. package/lib/version.js.map +1 -0
  149. package/lib/work-item-engineering-context.d.ts +127 -0
  150. package/lib/work-item-engineering-context.d.ts.map +1 -0
  151. package/lib/work-item-engineering-context.js +151 -0
  152. package/lib/work-item-engineering-context.js.map +1 -0
  153. package/lib/work-item-feedback-schema.d.ts +2 -0
  154. package/lib/work-item-feedback-schema.d.ts.map +1 -0
  155. package/lib/work-item-feedback-schema.js +29 -0
  156. package/lib/work-item-feedback-schema.js.map +1 -0
  157. package/lib/work-item-feedback-store.d.ts +29 -0
  158. package/lib/work-item-feedback-store.d.ts.map +1 -0
  159. package/lib/work-item-feedback-store.js +111 -0
  160. package/lib/work-item-feedback-store.js.map +1 -0
  161. package/lib/work-item-feedback.d.ts +157 -0
  162. package/lib/work-item-feedback.d.ts.map +1 -0
  163. package/lib/work-item-feedback.js +2 -0
  164. package/lib/work-item-feedback.js.map +1 -0
  165. package/lib/work-item-replies-schema.d.ts +3 -0
  166. package/lib/work-item-replies-schema.d.ts.map +1 -0
  167. package/lib/work-item-replies-schema.js +45 -0
  168. package/lib/work-item-replies-schema.js.map +1 -0
  169. package/lib/work-item-replies-store.d.ts +43 -0
  170. package/lib/work-item-replies-store.d.ts.map +1 -0
  171. package/lib/work-item-replies-store.js +203 -0
  172. package/lib/work-item-replies-store.js.map +1 -0
  173. package/lib/work-item-replies.d.ts +93 -0
  174. package/lib/work-item-replies.d.ts.map +1 -0
  175. package/lib/work-item-replies.js +15 -0
  176. package/lib/work-item-replies.js.map +1 -0
  177. package/lib/workflow-auto-producer.d.ts +37 -0
  178. package/lib/workflow-auto-producer.d.ts.map +1 -0
  179. package/lib/workflow-auto-producer.js +58 -0
  180. package/lib/workflow-auto-producer.js.map +1 -0
  181. package/lib/workflow-command.d.ts +16 -0
  182. package/lib/workflow-command.d.ts.map +1 -0
  183. package/lib/workflow-command.js +52 -0
  184. package/lib/workflow-command.js.map +1 -0
  185. package/package.json +174 -4
package/lib/sqlite.js ADDED
@@ -0,0 +1,1665 @@
1
+ import { workItemFeedbackSchema } from './work-item-feedback-schema.js';
2
+ import { attentionAuditSchema } from './attention-audit-store.js';
3
+ import { workItemRepliesSchema } from './work-item-replies-schema.js';
4
+ import { foregroundTerminationKinds } from './foreground-termination.js';
5
+ import { chmodSync, mkdirSync } from 'node:fs';
6
+ import { dirname, isAbsolute } from 'node:path';
7
+ import { DatabaseSync } from 'node:sqlite';
8
+ export const deliverySchemaVersion = 31;
9
+ /** Provider progress is a presentation journal, keyed to the authoritative Inbox. */
10
+ const progressSchema = `
11
+ CREATE TABLE IF NOT EXISTS delivery_progress (
12
+ inbox_id TEXT PRIMARY KEY REFERENCES inbox_messages(id),
13
+ binding_id TEXT NOT NULL REFERENCES conversation_bindings(id),
14
+ binding_version INTEGER NOT NULL CHECK(binding_version >= 1),
15
+ binding_generation INTEGER NOT NULL CHECK(binding_generation >= 1),
16
+ target_hash TEXT NOT NULL CHECK(length(target_hash) = 64),
17
+ credential_hash TEXT NOT NULL CHECK(length(credential_hash) = 64),
18
+ provider_handle TEXT CHECK(provider_handle IS NULL OR length(provider_handle) BETWEEN 2 AND 2048),
19
+ sequence INTEGER NOT NULL CHECK(sequence BETWEEN 1 AND 9007199254740991),
20
+ step INTEGER NOT NULL DEFAULT 0 CHECK(step BETWEEN 0 AND 9007199254740991),
21
+ show_details INTEGER NOT NULL CHECK(show_details IN (0, 1)),
22
+ state TEXT NOT NULL CHECK(state IN ('creating', 'active', 'pending', 'delivered')),
23
+ terminal_kind TEXT CHECK(terminal_kind IN ('completed', 'failed', 'paused')),
24
+ terminal_code TEXT,
25
+ retry_attempts INTEGER NOT NULL DEFAULT 0 CHECK(retry_attempts BETWEEN 0 AND 8),
26
+ next_retry_at INTEGER NOT NULL DEFAULT 0 CHECK(next_retry_at >= 0),
27
+ created_at INTEGER NOT NULL CHECK(created_at >= 0),
28
+ updated_at INTEGER NOT NULL CHECK(updated_at >= 0),
29
+ CHECK((state = 'creating' AND provider_handle IS NULL)
30
+ OR (state = 'active' AND provider_handle IS NOT NULL AND terminal_kind IS NULL)
31
+ OR (state IN ('pending', 'delivered') AND provider_handle IS NOT NULL AND terminal_kind IS NOT NULL))
32
+ ) STRICT;
33
+ CREATE INDEX IF NOT EXISTS delivery_progress_recovery
34
+ ON delivery_progress(state, next_retry_at, created_at);
35
+ `;
36
+ const restartFenceSchema = `
37
+ CREATE TABLE IF NOT EXISTS delivery_restart_fence (
38
+ singleton INTEGER PRIMARY KEY CHECK(singleton = 1),
39
+ request_id TEXT NOT NULL,
40
+ source_invocation_id TEXT NOT NULL
41
+ ) STRICT;
42
+ `;
43
+ const restartInboxFenceSchema = `
44
+ CREATE TRIGGER IF NOT EXISTS delivery_restart_inbox_claim_fence
45
+ BEFORE UPDATE OF status ON inbox_messages
46
+ WHEN NEW.status = 'claimed' AND OLD.status != 'claimed'
47
+ AND EXISTS(SELECT 1 FROM delivery_restart_fence WHERE singleton = 1)
48
+ BEGIN SELECT RAISE(ABORT, 'planned restart blocks new inbox claims'); END;
49
+ `;
50
+ const restartOutboxFenceSchema = `
51
+ CREATE TRIGGER IF NOT EXISTS delivery_restart_outbox_claim_fence
52
+ BEFORE UPDATE OF status ON outbox_messages
53
+ WHEN NEW.status = 'attempting' AND OLD.status != 'attempting'
54
+ AND NOT (NEW.idempotency_key GLOB 'inbound:*:maintenance'
55
+ AND COALESCE(json_extract(NEW.intent_json, '$.format') = 'plain', 0)
56
+ AND json_type(NEW.intent_json, '$.metadata') IS NULL
57
+ AND json_type(NEW.intent_json, '$.approval') IS NULL
58
+ AND json_type(NEW.intent_json, '$.modelPicker') IS NULL
59
+ AND json_type(NEW.intent_json, '$.permissionPicker') IS NULL)
60
+ AND EXISTS(SELECT 1 FROM delivery_restart_fence WHERE singleton = 1)
61
+ BEGIN SELECT RAISE(ABORT, 'planned restart blocks new outbound sends'); END;
62
+ `;
63
+ const goalOutcomeTargetSchema = `
64
+ CREATE TABLE IF NOT EXISTS delivery_goal_outcome_targets (
65
+ outbox_id TEXT PRIMARY KEY,
66
+ locator_json TEXT NOT NULL CHECK (json_valid(locator_json) AND json_type(locator_json) = 'object'),
67
+ proof_json TEXT NOT NULL CHECK (json_valid(proof_json) AND json_type(proof_json) = 'object'),
68
+ proof_digest TEXT NOT NULL CHECK (
69
+ length(proof_digest) = 64 AND proof_digest NOT GLOB '*[^0-9a-f]*'
70
+ ),
71
+ owner_route_id TEXT NOT NULL,
72
+ principal_id TEXT NOT NULL,
73
+ principal_record_id TEXT NOT NULL,
74
+ principal_version INTEGER NOT NULL CHECK (principal_version >= 1),
75
+ workspace TEXT NOT NULL,
76
+ preset TEXT NOT NULL,
77
+ binding_id TEXT NOT NULL,
78
+ binding_version INTEGER NOT NULL CHECK (binding_version >= 1),
79
+ binding_generation INTEGER NOT NULL CHECK (binding_generation >= 1),
80
+ session_id TEXT NOT NULL,
81
+ goal_id TEXT NOT NULL,
82
+ assessment_id TEXT NOT NULL,
83
+ FOREIGN KEY (outbox_id) REFERENCES outbox_messages(id) ON DELETE CASCADE,
84
+ FOREIGN KEY (binding_id) REFERENCES conversation_bindings(id),
85
+ FOREIGN KEY (principal_record_id) REFERENCES delivery_principals(id)
86
+ ) STRICT;
87
+ CREATE INDEX IF NOT EXISTS delivery_goal_outcome_target_binding
88
+ ON delivery_goal_outcome_targets(binding_id, binding_version, binding_generation);
89
+ CREATE INDEX IF NOT EXISTS delivery_goal_outcome_target_owner
90
+ ON delivery_goal_outcome_targets(principal_record_id, principal_version, workspace, preset);
91
+ `;
92
+ const sessionLeaseSchema = `
93
+ CREATE TABLE IF NOT EXISTS delivery_session_leases (
94
+ session_id TEXT PRIMARY KEY,
95
+ holder_id TEXT NOT NULL,
96
+ fencing_token INTEGER NOT NULL CHECK (fencing_token >= 1),
97
+ lease_until INTEGER NOT NULL CHECK (lease_until >= 0),
98
+ state TEXT NOT NULL CHECK (state IN ('prepared', 'dispatched', 'unknown', 'released')),
99
+ target_json TEXT NOT NULL,
100
+ principal_record_id TEXT NOT NULL,
101
+ principal_version INTEGER NOT NULL CHECK (principal_version >= 1)
102
+ ) STRICT;
103
+ `;
104
+ const taskAcceptanceExecutionSchemaV21 = `
105
+ CREATE TABLE IF NOT EXISTS delivery_task_acceptance_executions (
106
+ inbox_id TEXT PRIMARY KEY REFERENCES inbox_messages(id),
107
+ contract_id TEXT NOT NULL UNIQUE,
108
+ contract_digest TEXT NOT NULL CHECK(length(contract_digest) = 64),
109
+ workspace TEXT NOT NULL,
110
+ preset TEXT NOT NULL,
111
+ principal_record_id TEXT NOT NULL,
112
+ principal_version INTEGER NOT NULL CHECK(principal_version >= 1),
113
+ binding_id TEXT NOT NULL REFERENCES conversation_bindings(id),
114
+ binding_version INTEGER NOT NULL CHECK(binding_version >= 1),
115
+ binding_generation INTEGER NOT NULL CHECK(binding_generation >= 1),
116
+ dispatched_at INTEGER NOT NULL CHECK(dispatched_at >= 0),
117
+ status TEXT NOT NULL CHECK(status IN ('pending', 'succeeded', 'failed', 'timed-out', 'cancelled', 'unknown')),
118
+ quiescent INTEGER NOT NULL CHECK(quiescent IN (0, 1)),
119
+ completed_at INTEGER,
120
+ execution_ref TEXT,
121
+ CHECK((status = 'pending') = (completed_at IS NULL AND execution_ref IS NULL))
122
+ ) STRICT;
123
+ `;
124
+ const taskAcceptanceExecutionSchema = `
125
+ CREATE TABLE IF NOT EXISTS delivery_task_acceptance_executions (
126
+ inbox_id TEXT PRIMARY KEY REFERENCES inbox_messages(id),
127
+ contract_id TEXT NOT NULL UNIQUE,
128
+ contract_digest TEXT NOT NULL CHECK(length(contract_digest) = 64),
129
+ workspace TEXT NOT NULL,
130
+ preset TEXT NOT NULL,
131
+ principal_record_id TEXT NOT NULL,
132
+ principal_version INTEGER NOT NULL CHECK(principal_version >= 1),
133
+ binding_id TEXT NOT NULL REFERENCES conversation_bindings(id),
134
+ binding_version INTEGER NOT NULL CHECK(binding_version >= 1),
135
+ binding_generation INTEGER NOT NULL CHECK(binding_generation >= 1),
136
+ dispatched_at INTEGER NOT NULL CHECK(dispatched_at >= 0),
137
+ status TEXT NOT NULL CHECK(status IN ('pending', 'succeeded', 'failed', 'timed-out', 'cancelled', 'unknown')),
138
+ quiescent INTEGER NOT NULL CHECK(quiescent IN (0, 1)),
139
+ completed_at INTEGER,
140
+ execution_ref TEXT,
141
+ model_selection_state TEXT NOT NULL DEFAULT 'missing' CHECK(model_selection_state IN ('missing', 'frozen', 'inconsistent')),
142
+ model_provider TEXT,
143
+ model_id TEXT,
144
+ model_reasoning_effort TEXT,
145
+ CHECK((status = 'pending') = (completed_at IS NULL AND execution_ref IS NULL))
146
+ ) STRICT;
147
+ `;
148
+ /** A non-contract execution receipt for every authenticated owner foreground turn. */
149
+ const foregroundExecutionSchema = `
150
+ CREATE TABLE IF NOT EXISTS delivery_foreground_executions (
151
+ inbox_id TEXT PRIMARY KEY REFERENCES inbox_messages(id),
152
+ workspace TEXT NOT NULL,
153
+ preset TEXT NOT NULL,
154
+ principal_record_id TEXT NOT NULL REFERENCES delivery_principals(id),
155
+ principal_version INTEGER NOT NULL CHECK(principal_version >= 1),
156
+ binding_id TEXT NOT NULL REFERENCES conversation_bindings(id),
157
+ binding_version INTEGER NOT NULL CHECK(binding_version >= 1),
158
+ binding_generation INTEGER NOT NULL CHECK(binding_generation >= 1),
159
+ dispatched_at INTEGER NOT NULL CHECK(dispatched_at >= 0),
160
+ status TEXT NOT NULL CHECK(status IN ('pending', 'succeeded', 'failed', 'timed-out', 'cancelled', 'unknown')),
161
+ quiescent INTEGER NOT NULL CHECK(quiescent IN (0, 1)),
162
+ completed_at INTEGER,
163
+ execution_ref TEXT,
164
+ model_selection_state TEXT NOT NULL DEFAULT 'missing' CHECK(model_selection_state IN ('missing', 'frozen', 'inconsistent')),
165
+ model_provider TEXT,
166
+ model_id TEXT,
167
+ model_reasoning_effort TEXT,
168
+ completion_sequence INTEGER CHECK(completion_sequence BETWEEN 1 AND 9007199254740991),
169
+ termination_json TEXT CHECK(termination_json IS NULL OR (json_valid(termination_json) AND length(CAST(termination_json AS BLOB)) <= 1024)),
170
+ CHECK((status = 'pending' AND completed_at IS NULL AND execution_ref IS NULL)
171
+ OR (status != 'pending' AND completed_at IS NOT NULL AND completed_at >= dispatched_at AND execution_ref IS NOT NULL AND execution_ref = inbox_id)),
172
+ CHECK(quiescent = 0 OR status = 'succeeded'),
173
+ CHECK((model_selection_state = 'missing' AND model_provider IS NULL AND model_id IS NULL AND model_reasoning_effort IS NULL)
174
+ OR (model_selection_state = 'frozen' AND model_provider IS NOT NULL AND model_id IS NOT NULL)
175
+ OR (model_selection_state = 'inconsistent' AND model_provider IS NULL AND model_id IS NULL AND model_reasoning_effort IS NULL))
176
+ ) STRICT;
177
+ CREATE INDEX IF NOT EXISTS delivery_foreground_execution_owner
178
+ ON delivery_foreground_executions(principal_record_id, principal_version, workspace, preset, binding_id);
179
+ `;
180
+ const terminationValid = `NEW.termination_json IS NULL OR (
181
+ NEW.status != 'pending' AND json_valid(NEW.termination_json)
182
+ AND length(CAST(NEW.termination_json AS BLOB)) <= 1024
183
+ AND instr(CAST(NEW.termination_json AS BLOB), X'00') = 0
184
+ AND (SELECT COUNT(*) FROM json_each(NEW.termination_json)) = 7
185
+ AND NOT EXISTS (SELECT 1 FROM json_each(NEW.termination_json) WHERE key NOT IN ('protocol','producer','kind','causeCode','handleDisposed','effects','replay'))
186
+ AND json_extract(NEW.termination_json,'$.protocol') = 'assistant-delivery/foreground-termination/v1'
187
+ AND json_extract(NEW.termination_json,'$.producer') IN ('delivery-agent','native-web')
188
+ AND json_type(NEW.termination_json,'$.handleDisposed') IN ('true','false')
189
+ AND json_extract(NEW.termination_json,'$.effects') = 'unknown'
190
+ AND json_extract(NEW.termination_json,'$.replay') = 'forbidden'
191
+ AND (${Object.entries(foregroundTerminationKinds).map(([cause, kind]) => `(json_extract(NEW.termination_json,'$.causeCode') = '${cause}' AND json_extract(NEW.termination_json,'$.kind') = '${kind}')`).join(' OR ')})
192
+ AND ((json_extract(NEW.termination_json,'$.kind') = 'completed' AND NEW.status = 'succeeded' AND NEW.quiescent = 1 AND json_type(NEW.termination_json,'$.handleDisposed') = 'true')
193
+ OR (json_extract(NEW.termination_json,'$.kind') != 'completed' AND NEW.status != 'succeeded'))
194
+ )`;
195
+ const foregroundTerminationTriggers = [
196
+ `CREATE TRIGGER delivery_foreground_termination_insert BEFORE INSERT ON delivery_foreground_executions
197
+ WHEN COALESCE((${terminationValid}), 0) = 0 BEGIN SELECT RAISE(ABORT, 'foreground termination is invalid'); END`,
198
+ `CREATE TRIGGER delivery_foreground_termination_update BEFORE UPDATE OF termination_json,status,quiescent ON delivery_foreground_executions
199
+ WHEN COALESCE((${terminationValid}), 0) = 0 BEGIN SELECT RAISE(ABORT, 'foreground termination is invalid'); END`,
200
+ `CREATE TRIGGER delivery_foreground_termination_immutable BEFORE UPDATE ON delivery_foreground_executions
201
+ WHEN OLD.status != 'pending' AND NEW.termination_json IS NOT OLD.termination_json
202
+ BEGIN SELECT RAISE(ABORT, 'foreground termination is immutable'); END`,
203
+ ];
204
+ function assertForegroundTerminationSchema(database) {
205
+ if (!hasTable(database, 'delivery_foreground_executions'))
206
+ return;
207
+ if (!hasColumn(database, 'delivery_foreground_executions', 'termination_json')
208
+ || foregroundTerminationTriggers.some(sql => !database.prepare("SELECT 1 FROM sqlite_schema WHERE type='trigger' AND sql=?").get(sql))) {
209
+ throw new DeliveryDatabaseError('schema-too-new', 'delivery foreground termination schema differs');
210
+ }
211
+ }
212
+ /** Database-owned order, independent of admission order and wall-clock time. */
213
+ const foregroundCompletionSchema = `
214
+ CREATE TABLE IF NOT EXISTS delivery_foreground_completion_clock (
215
+ singleton INTEGER PRIMARY KEY CHECK(singleton = 1),
216
+ current_sequence INTEGER NOT NULL CHECK(current_sequence BETWEEN 0 AND 9007199254740991)
217
+ ) STRICT;
218
+ INSERT OR IGNORE INTO delivery_foreground_completion_clock VALUES (1, 0);
219
+ UPDATE delivery_foreground_completion_clock SET current_sequence = MAX(current_sequence,
220
+ (SELECT COALESCE(MAX(completion_sequence), 0) FROM delivery_foreground_executions));
221
+ WITH numbered AS MATERIALIZED (
222
+ SELECT inbox_id, ROW_NUMBER() OVER (ORDER BY completed_at, dispatched_at, inbox_id) AS ordinal
223
+ FROM delivery_foreground_executions WHERE status != 'pending' AND completion_sequence IS NULL
224
+ )
225
+ UPDATE delivery_foreground_executions SET completion_sequence =
226
+ (SELECT current_sequence FROM delivery_foreground_completion_clock WHERE singleton = 1)
227
+ + (SELECT ordinal FROM numbered WHERE numbered.inbox_id = delivery_foreground_executions.inbox_id)
228
+ WHERE status != 'pending' AND completion_sequence IS NULL;
229
+ UPDATE delivery_foreground_completion_clock SET current_sequence = MAX(current_sequence,
230
+ (SELECT COALESCE(MAX(completion_sequence), 0) FROM delivery_foreground_executions));
231
+ CREATE UNIQUE INDEX IF NOT EXISTS delivery_foreground_completion_order
232
+ ON delivery_foreground_executions(completion_sequence) WHERE completion_sequence IS NOT NULL;
233
+ CREATE INDEX IF NOT EXISTS delivery_foreground_owner_completion_order
234
+ ON delivery_foreground_executions(principal_record_id, principal_version, workspace, preset, completion_sequence)
235
+ WHERE status != 'pending';
236
+
237
+ CREATE TRIGGER IF NOT EXISTS delivery_foreground_identity_immutable
238
+ BEFORE UPDATE ON delivery_foreground_executions
239
+ WHEN NEW.inbox_id IS NOT OLD.inbox_id OR NEW.workspace IS NOT OLD.workspace
240
+ OR NEW.preset IS NOT OLD.preset OR NEW.principal_record_id IS NOT OLD.principal_record_id
241
+ OR NEW.principal_version IS NOT OLD.principal_version OR NEW.binding_id IS NOT OLD.binding_id
242
+ OR NEW.binding_version IS NOT OLD.binding_version OR NEW.binding_generation IS NOT OLD.binding_generation
243
+ OR NEW.dispatched_at IS NOT OLD.dispatched_at
244
+ BEGIN SELECT RAISE(ABORT, 'foreground execution identity is immutable'); END;
245
+
246
+ CREATE TRIGGER IF NOT EXISTS delivery_foreground_terminal_immutable
247
+ BEFORE UPDATE ON delivery_foreground_executions
248
+ WHEN (OLD.status != 'pending' AND (
249
+ NEW.status IS NOT OLD.status OR NEW.quiescent IS NOT OLD.quiescent
250
+ OR NEW.completed_at IS NOT OLD.completed_at OR NEW.execution_ref IS NOT OLD.execution_ref
251
+ OR NEW.model_selection_state IS NOT OLD.model_selection_state OR NEW.model_provider IS NOT OLD.model_provider
252
+ OR NEW.model_id IS NOT OLD.model_id OR NEW.model_reasoning_effort IS NOT OLD.model_reasoning_effort))
253
+ OR (OLD.completion_sequence IS NOT NULL AND NEW.completion_sequence IS NOT OLD.completion_sequence)
254
+ OR (OLD.completion_sequence IS NULL AND NEW.completion_sequence IS NOT NULL AND
255
+ (OLD.status = 'pending' OR NEW.completion_sequence IS NOT
256
+ (SELECT current_sequence FROM delivery_foreground_completion_clock WHERE singleton = 1)))
257
+ BEGIN SELECT RAISE(ABORT, 'foreground execution completion is immutable'); END;
258
+ CREATE TRIGGER IF NOT EXISTS delivery_foreground_terminal_delete_immutable
259
+ BEFORE DELETE ON delivery_foreground_executions WHEN OLD.status != 'pending'
260
+ BEGIN SELECT RAISE(ABORT, 'foreground execution completion is immutable'); END;
261
+
262
+ CREATE TRIGGER IF NOT EXISTS delivery_foreground_completion_after_update
263
+ AFTER UPDATE OF status ON delivery_foreground_executions
264
+ WHEN OLD.status = 'pending' AND NEW.status != 'pending'
265
+ BEGIN
266
+ UPDATE delivery_foreground_completion_clock SET current_sequence = current_sequence + 1 WHERE singleton = 1;
267
+ UPDATE delivery_foreground_executions SET completion_sequence =
268
+ (SELECT current_sequence FROM delivery_foreground_completion_clock WHERE singleton = 1)
269
+ WHERE inbox_id = NEW.inbox_id;
270
+ END;
271
+ CREATE TRIGGER IF NOT EXISTS delivery_foreground_completion_after_insert
272
+ AFTER INSERT ON delivery_foreground_executions WHEN NEW.status != 'pending'
273
+ BEGIN
274
+ UPDATE delivery_foreground_completion_clock SET current_sequence = current_sequence + 1 WHERE singleton = 1;
275
+ UPDATE delivery_foreground_executions SET completion_sequence =
276
+ (SELECT current_sequence FROM delivery_foreground_completion_clock WHERE singleton = 1)
277
+ WHERE inbox_id = NEW.inbox_id;
278
+ END;
279
+ `;
280
+ const ownerObjectiveRevisionSchema = `
281
+ CREATE TABLE delivery_owner_objective_commands (
282
+ inbox_id TEXT PRIMARY KEY,
283
+ source_outbox_id TEXT NOT NULL,
284
+ principal_record_id TEXT NOT NULL,
285
+ principal_version INTEGER NOT NULL,
286
+ version INTEGER NOT NULL,
287
+ objective_status TEXT NOT NULL,
288
+ command_json TEXT NOT NULL,
289
+ result_json TEXT NOT NULL
290
+ ) STRICT;
291
+ CREATE INDEX delivery_owner_objective_current ON delivery_owner_objective_commands(source_outbox_id, version);
292
+ `;
293
+ /** Frozen owner wording/target and CAS state, independent of Agent dispatch replay. */
294
+ const naturalObjectiveIntentSchema = `
295
+ CREATE TABLE IF NOT EXISTS delivery_natural_objective_intents (
296
+ inbox_id TEXT PRIMARY KEY REFERENCES inbox_messages(id),
297
+ envelope_hash TEXT NOT NULL,
298
+ source_inbox_id TEXT NOT NULL REFERENCES inbox_messages(id),
299
+ source_outbox_id TEXT NOT NULL REFERENCES outbox_messages(id),
300
+ binding_id TEXT NOT NULL REFERENCES conversation_bindings(id),
301
+ binding_version INTEGER NOT NULL CHECK(binding_version >= 1),
302
+ binding_generation INTEGER NOT NULL CHECK(binding_generation >= 1),
303
+ principal_record_id TEXT NOT NULL REFERENCES delivery_principals(id),
304
+ principal_version INTEGER NOT NULL CHECK(principal_version >= 1),
305
+ admission_epoch TEXT NOT NULL,
306
+ admission_sequence INTEGER NOT NULL CHECK(admission_sequence >= 1),
307
+ occurred_at INTEGER NOT NULL CHECK(occurred_at >= 0),
308
+ parser_version INTEGER NOT NULL CHECK(parser_version = 1),
309
+ intent_status TEXT NOT NULL CHECK(intent_status IN ('awaiting-evaluation', 'frozen', 'projected', 'conflict')),
310
+ selection TEXT NOT NULL CHECK(selection IN ('achieved', 'not-achieved', 'withdraw')),
311
+ command_json TEXT CHECK(command_json IS NULL OR json_valid(command_json)),
312
+ canonical_json TEXT CHECK(canonical_json IS NULL OR json_valid(canonical_json)),
313
+ created_at INTEGER NOT NULL,
314
+ updated_at INTEGER NOT NULL
315
+ ) STRICT;
316
+ CREATE INDEX IF NOT EXISTS delivery_natural_objective_target_order
317
+ ON delivery_natural_objective_intents(source_outbox_id, admission_sequence);
318
+ CREATE INDEX IF NOT EXISTS delivery_natural_objective_pending
319
+ ON delivery_natural_objective_intents(intent_status, admission_sequence);
320
+ `;
321
+ /**
322
+ * A database-local, durable total order for every admitted Inbox. The trigger
323
+ * deliberately lives in SQLite so an already-open v12 process also receives
324
+ * a cursor after a v13 process migrates the shared database.
325
+ */
326
+ const inboxAdmissionSchema = `
327
+ CREATE TABLE IF NOT EXISTS delivery_inbox_admission_clock (
328
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
329
+ current_sequence INTEGER NOT NULL CHECK (
330
+ current_sequence BETWEEN 0 AND 9007199254740991
331
+ )
332
+ ) STRICT;
333
+ INSERT INTO delivery_inbox_admission_clock(singleton, current_sequence)
334
+ VALUES (1, 0) ON CONFLICT(singleton) DO NOTHING;
335
+
336
+ CREATE TABLE IF NOT EXISTS delivery_inbox_admissions (
337
+ inbox_id TEXT PRIMARY KEY,
338
+ epoch TEXT NOT NULL CHECK (
339
+ length(epoch) = 32 AND epoch NOT GLOB '*[^0-9a-f]*'
340
+ ),
341
+ admission_sequence INTEGER NOT NULL UNIQUE CHECK (
342
+ admission_sequence BETWEEN 1 AND 9007199254740991
343
+ ),
344
+ FOREIGN KEY (inbox_id) REFERENCES inbox_messages(id) ON DELETE CASCADE
345
+ ) STRICT;
346
+
347
+ INSERT OR IGNORE INTO delivery_inbox_admissions(inbox_id, epoch, admission_sequence)
348
+ SELECT message.id, instance.instance_id,
349
+ ROW_NUMBER() OVER (ORDER BY message.rowid)
350
+ FROM inbox_messages AS message
351
+ CROSS JOIN delivery_instance AS instance
352
+ WHERE instance.singleton = 1;
353
+
354
+ UPDATE delivery_inbox_admission_clock
355
+ SET current_sequence = MAX(current_sequence,
356
+ (SELECT COALESCE(MAX(admission_sequence), 0) FROM delivery_inbox_admissions))
357
+ WHERE singleton = 1;
358
+
359
+ CREATE TRIGGER IF NOT EXISTS delivery_inbox_admission_after_insert
360
+ AFTER INSERT ON inbox_messages
361
+ BEGIN
362
+ UPDATE delivery_inbox_admission_clock
363
+ SET current_sequence = current_sequence + 1
364
+ WHERE singleton = 1;
365
+ INSERT INTO delivery_inbox_admissions(inbox_id, epoch, admission_sequence)
366
+ SELECT NEW.id, instance.instance_id, clock.current_sequence
367
+ FROM delivery_instance AS instance
368
+ CROSS JOIN delivery_inbox_admission_clock AS clock
369
+ WHERE instance.singleton = 1 AND clock.singleton = 1;
370
+ END;
371
+ `;
372
+ const preferenceProjectionSchema = `
373
+ CREATE TABLE delivery_preference_projection_outbox (
374
+ batch_key TEXT PRIMARY KEY,
375
+ payload_digest TEXT NOT NULL CHECK (
376
+ length(payload_digest) = 64 AND payload_digest NOT GLOB '*[^0-9a-f]*'
377
+ ),
378
+ events_json TEXT NOT NULL CHECK (
379
+ json_valid(events_json) AND json_type(events_json) = 'array'
380
+ AND json_array_length(events_json) BETWEEN 1 AND 16
381
+ ),
382
+ status TEXT NOT NULL CHECK (status IN ('pending', 'retry_wait')),
383
+ attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0),
384
+ next_attempt_at INTEGER NOT NULL,
385
+ failure_code TEXT,
386
+ lane_kind TEXT NOT NULL DEFAULT 'unclassified' CHECK (
387
+ lane_kind IN ('exact', 'legacy', 'unclassified')
388
+ ),
389
+ lane_epoch TEXT CHECK (
390
+ lane_epoch IS NULL OR (
391
+ length(lane_epoch) = 32 AND lane_epoch NOT GLOB '*[^0-9a-f]*'
392
+ )
393
+ ),
394
+ lane_workspace TEXT,
395
+ lane_preset TEXT,
396
+ lane_principal_record_id TEXT,
397
+ lane_principal_version INTEGER CHECK (
398
+ lane_principal_version IS NULL OR lane_principal_version >= 1
399
+ ),
400
+ admission_sequence INTEGER CHECK (
401
+ admission_sequence IS NULL OR admission_sequence BETWEEN 1 AND 9007199254740991
402
+ ),
403
+ terminal_at INTEGER CHECK (terminal_at IS NULL OR terminal_at >= 0),
404
+ created_at INTEGER NOT NULL,
405
+ updated_at INTEGER NOT NULL
406
+ ) STRICT;
407
+ CREATE INDEX delivery_preference_projection_due
408
+ ON delivery_preference_projection_outbox(
409
+ terminal_at, lane_kind, status, next_attempt_at, updated_at, batch_key
410
+ );
411
+ CREATE INDEX delivery_preference_projection_lane
412
+ ON delivery_preference_projection_outbox(
413
+ terminal_at, lane_epoch, lane_workspace, lane_preset,
414
+ lane_principal_record_id, lane_principal_version, admission_sequence,
415
+ created_at, batch_key
416
+ );
417
+ `;
418
+ const workflowTraceSchema = `
419
+ CREATE TABLE workflow_trace_source (
420
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
421
+ contract_version INTEGER NOT NULL CHECK (contract_version = 1),
422
+ generation INTEGER NOT NULL CHECK (generation >= 1),
423
+ authority_digest TEXT NOT NULL CHECK (
424
+ length(authority_digest) = 64 AND authority_digest NOT GLOB '*[^0-9a-f]*'
425
+ ),
426
+ created_at INTEGER NOT NULL,
427
+ updated_at INTEGER NOT NULL
428
+ ) STRICT;
429
+
430
+ CREATE TABLE workflow_template_registry (
431
+ template_ref TEXT PRIMARY KEY,
432
+ template_digest TEXT NOT NULL CHECK (
433
+ length(template_digest) = 64 AND template_digest NOT GLOB '*[^0-9a-f]*'
434
+ ),
435
+ scope_key TEXT NOT NULL,
436
+ workspace TEXT NOT NULL,
437
+ preset TEXT NOT NULL,
438
+ owner_binding_id TEXT NOT NULL,
439
+ content_json TEXT NOT NULL,
440
+ privacy_kind TEXT NOT NULL CHECK (
441
+ privacy_kind IN ('deterministic-deidentification', 'owner-explicit')
442
+ ),
443
+ privacy_attestation_id TEXT NOT NULL UNIQUE,
444
+ privacy_attestation_digest TEXT NOT NULL CHECK (
445
+ length(privacy_attestation_digest) = 64
446
+ AND privacy_attestation_digest NOT GLOB '*[^0-9a-f]*'
447
+ ),
448
+ review_receipt_json TEXT NOT NULL,
449
+ status TEXT NOT NULL CHECK (status IN ('active', 'revoked')),
450
+ review_inbox_id TEXT NOT NULL,
451
+ source_inbox_id TEXT NOT NULL,
452
+ source_outbox_id TEXT NOT NULL,
453
+ created_at INTEGER NOT NULL,
454
+ updated_at INTEGER NOT NULL,
455
+ version INTEGER NOT NULL CHECK (version >= 1),
456
+ FOREIGN KEY (owner_binding_id) REFERENCES conversation_bindings(id),
457
+ FOREIGN KEY (review_inbox_id) REFERENCES inbox_messages(id),
458
+ FOREIGN KEY (source_inbox_id) REFERENCES inbox_messages(id),
459
+ FOREIGN KEY (source_outbox_id) REFERENCES outbox_messages(id)
460
+ ) STRICT;
461
+ CREATE INDEX workflow_template_scope
462
+ ON workflow_template_registry(scope_key, status, updated_at, template_ref);
463
+
464
+ CREATE TABLE workflow_trace_revisions (
465
+ subject_ref TEXT NOT NULL,
466
+ version INTEGER NOT NULL CHECK (version >= 1),
467
+ source_generation INTEGER NOT NULL CHECK (source_generation >= 1),
468
+ source_authority_digest TEXT NOT NULL CHECK (
469
+ length(source_authority_digest) = 64
470
+ AND source_authority_digest NOT GLOB '*[^0-9a-f]*'
471
+ ),
472
+ scope_key TEXT NOT NULL,
473
+ workspace TEXT NOT NULL,
474
+ preset TEXT NOT NULL,
475
+ disposition TEXT NOT NULL CHECK (disposition IN ('upsert', 'retract')),
476
+ digest TEXT NOT NULL CHECK (length(digest) = 64 AND digest NOT GLOB '*[^0-9a-f]*'),
477
+ payload_json TEXT NOT NULL,
478
+ created_at INTEGER NOT NULL,
479
+ PRIMARY KEY (subject_ref, version)
480
+ ) STRICT;
481
+
482
+ CREATE TABLE workflow_trace_current (
483
+ subject_ref TEXT PRIMARY KEY,
484
+ version INTEGER NOT NULL CHECK (version >= 1),
485
+ digest TEXT NOT NULL,
486
+ disposition TEXT NOT NULL CHECK (disposition IN ('upsert', 'retract')),
487
+ payload_json TEXT NOT NULL,
488
+ updated_at INTEGER NOT NULL,
489
+ FOREIGN KEY (subject_ref, version) REFERENCES workflow_trace_revisions(subject_ref, version)
490
+ ) STRICT;
491
+
492
+ CREATE TABLE workflow_trace_outbox (
493
+ subject_ref TEXT NOT NULL,
494
+ version INTEGER NOT NULL CHECK (version >= 1),
495
+ status TEXT NOT NULL CHECK (status IN ('pending', 'delivered', 'retry_wait')),
496
+ attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0),
497
+ next_attempt_at INTEGER NOT NULL,
498
+ failure_code TEXT,
499
+ created_at INTEGER NOT NULL,
500
+ updated_at INTEGER NOT NULL,
501
+ PRIMARY KEY (subject_ref, version),
502
+ FOREIGN KEY (subject_ref, version) REFERENCES workflow_trace_revisions(subject_ref, version)
503
+ ) STRICT;
504
+ CREATE INDEX workflow_trace_outbox_due
505
+ ON workflow_trace_outbox(status, next_attempt_at, updated_at, subject_ref, version);
506
+
507
+ CREATE TABLE workflow_trace_commands (
508
+ operation_id TEXT PRIMARY KEY,
509
+ payload_digest TEXT NOT NULL CHECK (
510
+ length(payload_digest) = 64 AND payload_digest NOT GLOB '*[^0-9a-f]*'
511
+ ),
512
+ result_json TEXT NOT NULL,
513
+ created_at INTEGER NOT NULL
514
+ ) STRICT;
515
+
516
+ CREATE TABLE trusted_delivery_evaluation_outbox (
517
+ idempotency_key TEXT PRIMARY KEY,
518
+ payload_digest TEXT NOT NULL CHECK (
519
+ length(payload_digest) = 64 AND payload_digest NOT GLOB '*[^0-9a-f]*'
520
+ ),
521
+ claims_json TEXT NOT NULL,
522
+ status TEXT NOT NULL CHECK (status IN ('pending', 'retry_wait', 'delivered')),
523
+ attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0),
524
+ next_attempt_at INTEGER NOT NULL,
525
+ failure_code TEXT,
526
+ created_at INTEGER NOT NULL,
527
+ updated_at INTEGER NOT NULL
528
+ ) STRICT;
529
+ CREATE INDEX trusted_delivery_evaluation_due
530
+ ON trusted_delivery_evaluation_outbox(status, next_attempt_at, updated_at, idempotency_key);
531
+ `;
532
+ /**
533
+ * Privately-learned workflow templates anchored to a Delivery-reverified
534
+ * owner-root successful goal (Growth signal `owner-anchored`). Unlike
535
+ * `workflow_template_registry` there is deliberately NO live Inbox/Outbox
536
+ * fence: the proof is the goals owner-run trace + accepted contract, so the
537
+ * anchor columns replace the three NOT NULL inbox/outbox foreign keys. The raw
538
+ * goal objective stays only here in `content_json` and never crosses Growth.
539
+ */
540
+ const workflowOwnerAnchoredSchema = `
541
+ CREATE TABLE IF NOT EXISTS workflow_owner_anchored_templates (
542
+ template_ref TEXT PRIMARY KEY,
543
+ template_digest TEXT NOT NULL CHECK (
544
+ length(template_digest) = 64 AND template_digest NOT GLOB '*[^0-9a-f]*'
545
+ ),
546
+ scope_key TEXT NOT NULL,
547
+ workspace TEXT NOT NULL,
548
+ preset TEXT NOT NULL,
549
+ owner_binding_id TEXT NOT NULL,
550
+ binding_version INTEGER NOT NULL CHECK (binding_version >= 1),
551
+ binding_generation INTEGER NOT NULL CHECK (binding_generation >= 1),
552
+ principal_id TEXT NOT NULL,
553
+ content_json TEXT NOT NULL,
554
+ privacy_kind TEXT NOT NULL CHECK (privacy_kind = 'owner-anchored'),
555
+ privacy_attestation_id TEXT NOT NULL UNIQUE,
556
+ privacy_attestation_digest TEXT NOT NULL CHECK (
557
+ length(privacy_attestation_digest) = 64
558
+ AND privacy_attestation_digest NOT GLOB '*[^0-9a-f]*'
559
+ ),
560
+ review_receipt_json TEXT NOT NULL,
561
+ status TEXT NOT NULL CHECK (status IN ('active', 'revoked')),
562
+ version INTEGER NOT NULL CHECK (version >= 1),
563
+ task_ref TEXT NOT NULL UNIQUE CHECK (
564
+ length(task_ref) = 64 AND task_ref NOT GLOB '*[^0-9a-f]*'
565
+ ),
566
+ owner_route_id TEXT NOT NULL,
567
+ goal_id TEXT NOT NULL,
568
+ native_goal_id TEXT NOT NULL,
569
+ session_id TEXT NOT NULL,
570
+ run_id TEXT NOT NULL,
571
+ turn INTEGER NOT NULL CHECK (turn >= 0),
572
+ acceptance_contract_id TEXT NOT NULL,
573
+ acceptance_receipt_digest TEXT NOT NULL,
574
+ owner_run_trace_digest TEXT NOT NULL,
575
+ created_at INTEGER NOT NULL,
576
+ updated_at INTEGER NOT NULL,
577
+ FOREIGN KEY (owner_binding_id) REFERENCES conversation_bindings(id)
578
+ ) STRICT;
579
+ CREATE INDEX IF NOT EXISTS workflow_owner_anchored_scope
580
+ ON workflow_owner_anchored_templates(scope_key, status, updated_at, template_ref);
581
+ `;
582
+ /**
583
+ * One authenticated owner objective judgement for one ordinary Delivery turn.
584
+ * This is intentionally separate from Evaluation's cross-plugin ledger: the
585
+ * local receipt is the atomic proof coupled to a WorkflowTrace, so a restart
586
+ * cannot leave a supposedly verified trace without its exact owner fence.
587
+ */
588
+ const workflowVerifiedTaskFeedbackSchema = `
589
+ CREATE TABLE IF NOT EXISTS workflow_verified_task_feedback (
590
+ source_outbox_id TEXT PRIMARY KEY,
591
+ source_inbox_id TEXT NOT NULL UNIQUE,
592
+ feedback_inbox_id TEXT NOT NULL UNIQUE,
593
+ binding_id TEXT NOT NULL,
594
+ binding_version INTEGER NOT NULL CHECK (binding_version >= 1),
595
+ binding_generation INTEGER NOT NULL CHECK (binding_generation >= 1),
596
+ principal_record_id TEXT NOT NULL,
597
+ objective_status TEXT NOT NULL CHECK (
598
+ objective_status IN ('achieved', 'partial', 'not-achieved')
599
+ ),
600
+ task_ref TEXT NOT NULL CHECK (
601
+ length(task_ref) = 64 AND task_ref NOT GLOB '*[^0-9a-f]*'
602
+ ),
603
+ task_evidence_digest TEXT NOT NULL CHECK (
604
+ length(task_evidence_digest) = 64
605
+ AND task_evidence_digest NOT GLOB '*[^0-9a-f]*'
606
+ ),
607
+ trace_subject_ref TEXT CHECK (
608
+ trace_subject_ref IS NULL
609
+ OR (length(trace_subject_ref) = 64 AND trace_subject_ref NOT GLOB '*[^0-9a-f]*')
610
+ ),
611
+ trace_version INTEGER CHECK (trace_version IS NULL OR trace_version >= 1),
612
+ trace_digest TEXT CHECK (
613
+ trace_digest IS NULL
614
+ OR (length(trace_digest) = 64 AND trace_digest NOT GLOB '*[^0-9a-f]*')
615
+ ),
616
+ template_ref TEXT,
617
+ created_at INTEGER NOT NULL,
618
+ CHECK (
619
+ (trace_subject_ref IS NOT NULL AND trace_version IS NOT NULL
620
+ AND trace_digest IS NOT NULL AND template_ref IS NOT NULL)
621
+ OR
622
+ (trace_subject_ref IS NULL AND trace_version IS NULL
623
+ AND trace_digest IS NULL AND template_ref IS NULL)
624
+ ),
625
+ FOREIGN KEY (source_outbox_id) REFERENCES outbox_messages(id),
626
+ FOREIGN KEY (source_inbox_id) REFERENCES inbox_messages(id),
627
+ FOREIGN KEY (feedback_inbox_id) REFERENCES inbox_messages(id),
628
+ FOREIGN KEY (binding_id) REFERENCES conversation_bindings(id),
629
+ FOREIGN KEY (principal_record_id) REFERENCES delivery_principals(id),
630
+ FOREIGN KEY (template_ref) REFERENCES workflow_template_registry(template_ref),
631
+ FOREIGN KEY (trace_subject_ref, trace_version)
632
+ REFERENCES workflow_trace_revisions(subject_ref, version)
633
+ ) STRICT;
634
+ CREATE INDEX IF NOT EXISTS workflow_verified_task_feedback_binding
635
+ ON workflow_verified_task_feedback(binding_id, created_at, source_outbox_id);
636
+ `;
637
+ const deliveryPresentationSchema = `
638
+ CREATE TABLE IF NOT EXISTS delivery_presentations (
639
+ presentation_key TEXT PRIMARY KEY,
640
+ original_outbox_idempotency_key TEXT NOT NULL,
641
+ revision INTEGER NOT NULL CHECK (revision >= 1),
642
+ payload_hash TEXT NOT NULL,
643
+ payload_json TEXT NOT NULL,
644
+ status TEXT NOT NULL CHECK (
645
+ status IN ('pending', 'attempting', 'presented', 'retry_wait', 'dead')
646
+ ),
647
+ attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0),
648
+ presented_revision INTEGER NOT NULL DEFAULT 0 CHECK (presented_revision >= 0),
649
+ next_attempt_at INTEGER,
650
+ claimed_by TEXT,
651
+ fencing_token INTEGER,
652
+ lease_until INTEGER,
653
+ provider_message_id TEXT,
654
+ failure_code TEXT,
655
+ created_at INTEGER NOT NULL,
656
+ updated_at INTEGER NOT NULL
657
+ ) STRICT;
658
+ CREATE INDEX IF NOT EXISTS delivery_presentation_claim
659
+ ON delivery_presentations(status, next_attempt_at, lease_until, created_at, presentation_key);
660
+ `;
661
+ const deadLetterResolutionSchema = `
662
+ CREATE TABLE dead_letter_resolutions (
663
+ kind TEXT NOT NULL CHECK (kind IN ('inbox', 'outbox')),
664
+ message_id TEXT NOT NULL,
665
+ attempt_count INTEGER NOT NULL CHECK (attempt_count >= 0),
666
+ receipt_version INTEGER NOT NULL CHECK (receipt_version = 1),
667
+ resolution TEXT NOT NULL CHECK (resolution IN ('cancel', 'retry')),
668
+ original_status TEXT NOT NULL CHECK (
669
+ (kind = 'inbox' AND original_status = 'dead_letter')
670
+ OR (kind = 'outbox' AND original_status IN ('dead', 'unknown_after_send'))
671
+ ),
672
+ original_failure_code TEXT,
673
+ operator_id TEXT NOT NULL,
674
+ created_at INTEGER NOT NULL,
675
+ PRIMARY KEY (kind, message_id, attempt_count)
676
+ ) STRICT;
677
+ CREATE INDEX dead_letter_resolution_projection
678
+ ON dead_letter_resolutions(kind, resolution, message_id, attempt_count);
679
+ `;
680
+ // These triggers are a rolling-upgrade fence for a v8 process that opened the
681
+ // database before v9 changed PRAGMA user_version. SQLite does not evict that
682
+ // already-open writer. A v9 writer first persists the exact operator receipt
683
+ // in the same transaction, so any receipt-less v8 resolution is rejected.
684
+ const deadLetterResolutionCompatibilitySchema = `
685
+ CREATE TRIGGER dead_letter_inbox_resolution_fence
686
+ BEFORE UPDATE ON inbox_messages
687
+ WHEN OLD.status = 'dead_letter' AND NEW.attempt_count = OLD.attempt_count AND (
688
+ NEW.status = 'queued'
689
+ OR (NEW.status = 'dead_letter' AND NEW.failure_code = 'operator-cancelled')
690
+ ) AND NOT EXISTS (
691
+ SELECT 1 FROM dead_letter_resolutions AS resolution
692
+ WHERE resolution.kind = 'inbox' AND resolution.message_id = OLD.id
693
+ AND resolution.attempt_count = OLD.attempt_count
694
+ AND resolution.resolution = CASE WHEN NEW.status = 'queued' THEN 'retry' ELSE 'cancel' END
695
+ AND resolution.original_status = OLD.status
696
+ AND resolution.original_failure_code IS OLD.failure_code
697
+ )
698
+ BEGIN
699
+ SELECT RAISE(ABORT, 'inbox resolution requires an exact v9 receipt');
700
+ END;
701
+
702
+ CREATE TRIGGER dead_letter_outbox_resolution_fence
703
+ BEFORE UPDATE ON outbox_messages
704
+ WHEN OLD.status IN ('dead', 'unknown_after_send')
705
+ AND NEW.attempt_count = OLD.attempt_count AND (
706
+ NEW.status = 'pending'
707
+ OR (NEW.status = 'dead' AND NEW.failure_code = 'operator-cancelled')
708
+ OR (NEW.status = 'unknown_after_send' AND NEW.failure_code = 'operator-cancelled-unknown')
709
+ ) AND NOT EXISTS (
710
+ SELECT 1 FROM dead_letter_resolutions AS resolution
711
+ WHERE resolution.kind = 'outbox' AND resolution.message_id = OLD.id
712
+ AND resolution.attempt_count = OLD.attempt_count
713
+ AND resolution.resolution = CASE WHEN NEW.status = 'pending' THEN 'retry' ELSE 'cancel' END
714
+ AND resolution.original_status = OLD.status
715
+ AND resolution.original_failure_code IS OLD.failure_code
716
+ )
717
+ BEGIN
718
+ SELECT RAISE(ABORT, 'outbox resolution requires an exact v9 receipt');
719
+ END;
720
+
721
+ CREATE TRIGGER dead_letter_outbox_cancelled_unknown_fence
722
+ BEFORE UPDATE ON outbox_messages
723
+ WHEN OLD.status = 'unknown_after_send' AND EXISTS (
724
+ SELECT 1 FROM dead_letter_resolutions AS resolution
725
+ WHERE resolution.kind = 'outbox' AND resolution.message_id = OLD.id
726
+ AND resolution.attempt_count = OLD.attempt_count AND resolution.resolution = 'cancel'
727
+ AND resolution.original_status = 'unknown_after_send'
728
+ ) AND NOT (
729
+ NEW.attempt_count = OLD.attempt_count AND (
730
+ (NEW.status = 'unknown_after_send' AND NEW.failure_code = 'operator-cancelled-unknown')
731
+ OR (
732
+ NEW.status IN ('accepted', 'delivered', 'read') AND EXISTS (
733
+ SELECT 1 FROM delivery_receipts AS receipt
734
+ WHERE receipt.channel = OLD.channel AND receipt.account = OLD.account
735
+ AND receipt.provider_message_id = OLD.provider_message_id
736
+ AND receipt.status = NEW.status
737
+ )
738
+ )
739
+ )
740
+ )
741
+ BEGIN
742
+ SELECT RAISE(ABORT, 'cancelled unknown outbox attempt cannot be reclaimed');
743
+ END;
744
+ `;
745
+ const deliveryInstanceSchema = `
746
+ CREATE TABLE delivery_instance (
747
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
748
+ instance_id TEXT NOT NULL UNIQUE CHECK (
749
+ length(instance_id) = 32 AND instance_id NOT GLOB '*[^0-9a-f]*'
750
+ )
751
+ ) STRICT;
752
+ INSERT INTO delivery_instance (singleton, instance_id)
753
+ VALUES (1, lower(hex(randomblob(16))));
754
+ `;
755
+ const approvalDispatchCursorSchema = `
756
+ CREATE TABLE approval_dispatch_cursor (
757
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
758
+ after_created_at INTEGER CHECK (after_created_at IS NULL OR after_created_at >= 0),
759
+ after_proposal_id TEXT,
760
+ version INTEGER NOT NULL CHECK (version >= 1),
761
+ updated_at INTEGER NOT NULL,
762
+ CHECK ((after_created_at IS NULL) = (after_proposal_id IS NULL))
763
+ ) STRICT;
764
+ `;
765
+ /** Immutable v2 route receipt coupled to the approval Outbox insertion. */
766
+ const approvalOutboxRouteSchema = `
767
+ CREATE TABLE IF NOT EXISTS approval_outbox_routes (
768
+ outbox_id TEXT PRIMARY KEY,
769
+ route_version INTEGER NOT NULL CHECK (route_version = 2),
770
+ source_id TEXT NOT NULL,
771
+ binding_id TEXT NOT NULL,
772
+ binding_version INTEGER NOT NULL CHECK (binding_version >= 1),
773
+ binding_generation INTEGER NOT NULL CHECK (binding_generation >= 1),
774
+ workspace TEXT NOT NULL,
775
+ principal TEXT NOT NULL,
776
+ principal_record_id TEXT NOT NULL,
777
+ principal_version INTEGER NOT NULL CHECK (principal_version >= 1),
778
+ FOREIGN KEY (outbox_id) REFERENCES outbox_messages(id) ON DELETE CASCADE,
779
+ FOREIGN KEY (binding_id) REFERENCES conversation_bindings(id),
780
+ FOREIGN KEY (principal_record_id) REFERENCES delivery_principals(id)
781
+ ) STRICT;
782
+ CREATE INDEX IF NOT EXISTS approval_outbox_route_binding
783
+ ON approval_outbox_routes(binding_id, binding_version, binding_generation);
784
+ `;
785
+ function assertSessionLeaseSchema(database) {
786
+ const columns = database.prepare('PRAGMA table_info(delivery_session_leases)').all();
787
+ const expected = [
788
+ ['session_id', 'TEXT', 1, 1], ['holder_id', 'TEXT', 1, 0], ['fencing_token', 'INTEGER', 1, 0],
789
+ ['lease_until', 'INTEGER', 1, 0], ['state', 'TEXT', 1, 0], ['target_json', 'TEXT', 1, 0],
790
+ ['principal_record_id', 'TEXT', 1, 0], ['principal_version', 'INTEGER', 1, 0],
791
+ ];
792
+ const sql = database.prepare("SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = 'delivery_session_leases'").get()?.sql;
793
+ if (!sql || columns.length !== expected.length || expected.some((entry, index) => {
794
+ const column = columns[index];
795
+ return column === undefined || column.name !== entry[0] || column.type !== entry[1] || column.notnull !== entry[2] || column.pk !== entry[3];
796
+ }) || !/\bSTRICT\b/u.test(sql) || !/fencing_token\s*>=\s*1/u.test(sql)
797
+ || !/state\s+IN\s*\(\s*'prepared'\s*,\s*'dispatched'\s*,\s*'unknown'\s*,\s*'released'\s*\)/iu.test(sql)) {
798
+ throw new Error('delivery session lease schema is invalid');
799
+ }
800
+ }
801
+ function assertApprovalOutboxRouteSchema(database) {
802
+ const columns = database.prepare('PRAGMA table_info(approval_outbox_routes)').all();
803
+ const expected = [
804
+ ['outbox_id', 'TEXT', 1, 1],
805
+ ['route_version', 'INTEGER', 1, 0],
806
+ ['source_id', 'TEXT', 1, 0],
807
+ ['binding_id', 'TEXT', 1, 0],
808
+ ['binding_version', 'INTEGER', 1, 0],
809
+ ['binding_generation', 'INTEGER', 1, 0],
810
+ ['workspace', 'TEXT', 1, 0],
811
+ ['principal', 'TEXT', 1, 0],
812
+ ['principal_record_id', 'TEXT', 1, 0],
813
+ ['principal_version', 'INTEGER', 1, 0],
814
+ ];
815
+ if (columns.length !== expected.length || expected.some((entry, index) => {
816
+ const column = columns[index];
817
+ return column === undefined || column.name !== entry[0] || column.type !== entry[1]
818
+ || column.notnull !== entry[2] || column.pk !== entry[3];
819
+ })) {
820
+ throw new Error('delivery approval route receipt schema is invalid');
821
+ }
822
+ const foreignKeys = database.prepare('PRAGMA foreign_key_list(approval_outbox_routes)').all();
823
+ const expectedForeignKeys = [
824
+ ['binding_id', 'conversation_bindings', 'id'],
825
+ ['outbox_id', 'outbox_messages', 'id'],
826
+ ['principal_record_id', 'delivery_principals', 'id'],
827
+ ];
828
+ const actualForeignKeys = foreignKeys.map(row => [row.from, row.table, row.to]).sort();
829
+ if (JSON.stringify(actualForeignKeys) !== JSON.stringify(expectedForeignKeys)) {
830
+ throw new Error('delivery approval route receipt foreign keys are invalid');
831
+ }
832
+ }
833
+ function assertGoalOutcomeTargetSchema(database) {
834
+ const columns = database.prepare('PRAGMA table_info(delivery_goal_outcome_targets)').all();
835
+ const expected = [
836
+ ['outbox_id', 'TEXT', 1, 1], ['locator_json', 'TEXT', 1, 0], ['proof_json', 'TEXT', 1, 0],
837
+ ['proof_digest', 'TEXT', 1, 0], ['owner_route_id', 'TEXT', 1, 0], ['principal_id', 'TEXT', 1, 0],
838
+ ['principal_record_id', 'TEXT', 1, 0], ['principal_version', 'INTEGER', 1, 0],
839
+ ['workspace', 'TEXT', 1, 0], ['preset', 'TEXT', 1, 0], ['binding_id', 'TEXT', 1, 0],
840
+ ['binding_version', 'INTEGER', 1, 0], ['binding_generation', 'INTEGER', 1, 0],
841
+ ['session_id', 'TEXT', 1, 0], ['goal_id', 'TEXT', 1, 0], ['assessment_id', 'TEXT', 1, 0],
842
+ ];
843
+ const sql = database.prepare("SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = 'delivery_goal_outcome_targets'")
844
+ .get()?.sql;
845
+ const requiredChecks = [
846
+ /locator_json\s+TEXT\s+NOT\s+NULL\s+CHECK\s*\(\s*json_valid\s*\(\s*locator_json\s*\)\s+AND\s+json_type\s*\(\s*locator_json\s*\)\s*=\s*'object'\s*\)/iu,
847
+ /proof_json\s+TEXT\s+NOT\s+NULL\s+CHECK\s*\(\s*json_valid\s*\(\s*proof_json\s*\)\s+AND\s+json_type\s*\(\s*proof_json\s*\)\s*=\s*'object'\s*\)/iu,
848
+ /proof_digest\s+TEXT\s+NOT\s+NULL\s+CHECK\s*\(\s*length\s*\(\s*proof_digest\s*\)\s*=\s*64\s+AND\s+proof_digest\s+NOT\s+GLOB\s+'\*\[\^0-9a-f\]\*'\s*\)/iu,
849
+ /principal_version\s+INTEGER\s+NOT\s+NULL\s+CHECK\s*\(\s*principal_version\s*>=\s*1\s*\)/iu,
850
+ /binding_version\s+INTEGER\s+NOT\s+NULL\s+CHECK\s*\(\s*binding_version\s*>=\s*1\s*\)/iu,
851
+ /binding_generation\s+INTEGER\s+NOT\s+NULL\s+CHECK\s*\(\s*binding_generation\s*>=\s*1\s*\)/iu,
852
+ ];
853
+ if (!sql || !/\bSTRICT\b/u.test(sql) || requiredChecks.some(check => !check.test(sql))
854
+ || columns.length !== expected.length || expected.some((entry, index) => {
855
+ const column = columns[index];
856
+ return column === undefined || column.name !== entry[0] || column.type !== entry[1]
857
+ || column.notnull !== entry[2] || column.pk !== entry[3];
858
+ }))
859
+ throw new Error('delivery goal outcome target schema is invalid');
860
+ const foreignKeys = database.prepare('PRAGMA foreign_key_list(delivery_goal_outcome_targets)').all();
861
+ const expectedForeignKeys = [
862
+ ['binding_id', 'conversation_bindings', 'id', 'NO ACTION', 'NO ACTION', 'NONE'],
863
+ ['outbox_id', 'outbox_messages', 'id', 'NO ACTION', 'CASCADE', 'NONE'],
864
+ ['principal_record_id', 'delivery_principals', 'id', 'NO ACTION', 'NO ACTION', 'NONE'],
865
+ ];
866
+ const actualForeignKeys = foreignKeys.map(row => [
867
+ row.from, row.table, row.to, row.on_update, row.on_delete, row.match,
868
+ ]).sort();
869
+ if (JSON.stringify(actualForeignKeys) !== JSON.stringify(expectedForeignKeys)) {
870
+ throw new Error('delivery goal outcome target foreign keys are invalid');
871
+ }
872
+ const indexes = database.prepare('PRAGMA index_list(delivery_goal_outcome_targets)').all();
873
+ const expectedIndexes = new Map([
874
+ ['delivery_goal_outcome_target_binding', ['binding_id', 'binding_version', 'binding_generation']],
875
+ ['delivery_goal_outcome_target_owner', ['principal_record_id', 'principal_version', 'workspace', 'preset']],
876
+ ]);
877
+ const declaredIndexes = indexes.filter(index => index.origin === 'c');
878
+ if (declaredIndexes.length !== expectedIndexes.size || declaredIndexes.some(index => {
879
+ const expectedColumns = expectedIndexes.get(index.name);
880
+ if (expectedColumns === undefined || index.unique !== 0 || index.partial !== 0)
881
+ return true;
882
+ const actualColumns = database.prepare(`PRAGMA index_xinfo(${index.name})`).all();
883
+ const keyColumns = actualColumns.filter(column => column.key === 1);
884
+ return keyColumns.length !== expectedColumns.length || keyColumns.some((column, position) => (column.name !== expectedColumns[position] || column.desc !== 0 || column.coll !== 'BINARY'));
885
+ }))
886
+ throw new Error('delivery goal outcome target indexes are invalid');
887
+ }
888
+ const modelPickerStateSchema = `
889
+ CREATE TABLE conversation_model_epochs (
890
+ conversation_hash TEXT PRIMARY KEY,
891
+ conversation_json TEXT NOT NULL,
892
+ epoch INTEGER NOT NULL CHECK (epoch >= 1),
893
+ updated_at INTEGER NOT NULL
894
+ ) STRICT;
895
+
896
+ CREATE TABLE model_picker_states (
897
+ operation_id TEXT PRIMARY KEY,
898
+ binding_id TEXT NOT NULL,
899
+ revision INTEGER NOT NULL CHECK (revision >= 1),
900
+ provider TEXT NOT NULL,
901
+ model TEXT NOT NULL,
902
+ reasoning_effort TEXT,
903
+ created_at INTEGER NOT NULL,
904
+ updated_at INTEGER NOT NULL,
905
+ FOREIGN KEY (binding_id) REFERENCES conversation_bindings(id)
906
+ ) STRICT;
907
+
908
+ CREATE TABLE model_selection_settlements (
909
+ operation_id TEXT PRIMARY KEY,
910
+ binding_id TEXT NOT NULL,
911
+ conversation_hash TEXT NOT NULL,
912
+ command_epoch INTEGER NOT NULL CHECK (command_epoch >= 1),
913
+ payload_hash TEXT NOT NULL,
914
+ payload_json TEXT NOT NULL,
915
+ status TEXT NOT NULL CHECK (status IN ('pending', 'processing', 'completed')),
916
+ result_json TEXT,
917
+ outbox_id TEXT,
918
+ attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0),
919
+ claimed_by TEXT,
920
+ lease_until INTEGER,
921
+ created_at INTEGER NOT NULL,
922
+ updated_at INTEGER NOT NULL,
923
+ FOREIGN KEY (binding_id) REFERENCES conversation_bindings(id),
924
+ FOREIGN KEY (conversation_hash) REFERENCES conversation_model_epochs(conversation_hash),
925
+ FOREIGN KEY (outbox_id) REFERENCES outbox_messages(id)
926
+ ) STRICT;
927
+ CREATE INDEX model_selection_claim
928
+ ON model_selection_settlements(status, lease_until, created_at, operation_id);
929
+ `;
930
+ export class DeliveryDatabaseError extends Error {
931
+ code;
932
+ constructor(code, message) {
933
+ super(message);
934
+ this.code = code;
935
+ this.name = 'DeliveryDatabaseError';
936
+ }
937
+ }
938
+ function hasTable(database, name) {
939
+ return database.prepare(`
940
+ SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ?
941
+ `).get(name) !== undefined;
942
+ }
943
+ function hasColumn(database, table, column) {
944
+ return database.prepare(`PRAGMA table_info(${table})`).all()
945
+ .some(entry => entry.name === column);
946
+ }
947
+ function migratePreferenceProjectionLane(database) {
948
+ const lockedVersion = database.prepare('PRAGMA user_version').get()
949
+ .user_version;
950
+ if (lockedVersion >= 14)
951
+ return;
952
+ if (lockedVersion !== 13) {
953
+ throw new Error(`delivery preference lane migration expected schema 13, received ${lockedVersion}`);
954
+ }
955
+ if (!hasTable(database, 'delivery_preference_projection_outbox')) {
956
+ database.exec('PRAGMA user_version = 14');
957
+ return;
958
+ }
959
+ const additions = [
960
+ ['lane_kind', `TEXT NOT NULL DEFAULT 'unclassified' CHECK (
961
+ lane_kind IN ('exact', 'legacy', 'unclassified')
962
+ )`],
963
+ ['lane_epoch', `TEXT CHECK (
964
+ lane_epoch IS NULL OR (
965
+ length(lane_epoch) = 32 AND lane_epoch NOT GLOB '*[^0-9a-f]*'
966
+ )
967
+ )`],
968
+ ['lane_workspace', 'TEXT'],
969
+ ['lane_preset', 'TEXT'],
970
+ ['lane_principal_record_id', 'TEXT'],
971
+ ['lane_principal_version', `INTEGER CHECK (
972
+ lane_principal_version IS NULL OR lane_principal_version >= 1
973
+ )`],
974
+ ['admission_sequence', `INTEGER CHECK (
975
+ admission_sequence IS NULL OR admission_sequence BETWEEN 1 AND 9007199254740991
976
+ )`],
977
+ ['terminal_at', 'INTEGER CHECK (terminal_at IS NULL OR terminal_at >= 0)'],
978
+ ];
979
+ const alter = additions
980
+ .filter(([column]) => !hasColumn(database, 'delivery_preference_projection_outbox', column))
981
+ .map(([column, definition]) => `
982
+ ALTER TABLE delivery_preference_projection_outbox
983
+ ADD COLUMN ${column} ${definition};
984
+ `)
985
+ .join('');
986
+ database.exec(`
987
+ ${alter}
988
+ DROP INDEX IF EXISTS delivery_preference_projection_due;
989
+ CREATE INDEX delivery_preference_projection_due
990
+ ON delivery_preference_projection_outbox(
991
+ terminal_at, lane_kind, status, next_attempt_at, updated_at, batch_key
992
+ );
993
+ CREATE INDEX IF NOT EXISTS delivery_preference_projection_lane
994
+ ON delivery_preference_projection_outbox(
995
+ terminal_at, lane_epoch, lane_workspace, lane_preset,
996
+ lane_principal_record_id, lane_principal_version, admission_sequence,
997
+ created_at, batch_key
998
+ );
999
+ PRAGMA user_version = 14;
1000
+ `);
1001
+ }
1002
+ function migrateTaskAcceptanceModelSelection(database) {
1003
+ const additions = [
1004
+ ['model_selection_state', "TEXT NOT NULL DEFAULT 'missing' CHECK(model_selection_state IN ('missing', 'frozen', 'inconsistent'))"],
1005
+ ['model_provider', 'TEXT'],
1006
+ ['model_id', 'TEXT'],
1007
+ ['model_reasoning_effort', 'TEXT'],
1008
+ ];
1009
+ for (const [column, definition] of additions) {
1010
+ if (!hasColumn(database, 'delivery_task_acceptance_executions', column)) {
1011
+ database.exec(`ALTER TABLE delivery_task_acceptance_executions ADD COLUMN ${column} ${definition};`);
1012
+ }
1013
+ }
1014
+ const malformed = database.prepare(`SELECT 1 FROM delivery_task_acceptance_executions
1015
+ WHERE model_selection_state NOT IN ('missing', 'frozen', 'inconsistent')
1016
+ OR (model_selection_state = 'missing' AND (model_provider IS NOT NULL OR model_id IS NOT NULL OR model_reasoning_effort IS NOT NULL))
1017
+ OR (model_selection_state = 'frozen' AND (model_provider IS NULL OR model_id IS NULL))
1018
+ OR (model_selection_state = 'inconsistent' AND (model_provider IS NOT NULL OR model_id IS NOT NULL OR model_reasoning_effort IS NOT NULL))
1019
+ LIMIT 1`).get();
1020
+ if (malformed !== undefined)
1021
+ throw new DeliveryDatabaseError('schema-too-new', 'delivery foreground model-selection migration found malformed state');
1022
+ }
1023
+ function migrateObserved(database) {
1024
+ const row = database.prepare('PRAGMA user_version').get();
1025
+ let version = row.user_version;
1026
+ if (version > deliverySchemaVersion) {
1027
+ throw new DeliveryDatabaseError('schema-too-new', `delivery schema ${version} is newer than supported schema ${deliverySchemaVersion}`);
1028
+ }
1029
+ if (version === deliverySchemaVersion)
1030
+ return;
1031
+ if (version === 1) {
1032
+ database.exec(`
1033
+ ALTER TABLE delivery_attachments ADD COLUMN resource_kind TEXT;
1034
+ ALTER TABLE delivery_attachments ADD COLUMN provider_ref TEXT;
1035
+ ALTER TABLE delivery_attachments ADD COLUMN file_name TEXT;
1036
+ PRAGMA user_version = 2;
1037
+ `);
1038
+ version = 2;
1039
+ }
1040
+ if (version === 2) {
1041
+ database.exec(`
1042
+ CREATE TABLE conversation_model_selections (
1043
+ conversation_hash TEXT PRIMARY KEY,
1044
+ conversation_json TEXT NOT NULL,
1045
+ provider TEXT NOT NULL,
1046
+ model TEXT NOT NULL,
1047
+ reasoning_effort TEXT,
1048
+ updated_at INTEGER NOT NULL,
1049
+ version INTEGER NOT NULL CHECK (version >= 1)
1050
+ ) STRICT;
1051
+ PRAGMA user_version = 4;
1052
+ `);
1053
+ version = 4;
1054
+ }
1055
+ if (version === 3) {
1056
+ database.exec(`
1057
+ ALTER TABLE conversation_model_selections ADD COLUMN reasoning_effort TEXT;
1058
+ PRAGMA user_version = 4;
1059
+ `);
1060
+ version = 4;
1061
+ }
1062
+ if (version === 4) {
1063
+ database.exec(`
1064
+ ${modelPickerStateSchema}
1065
+ PRAGMA user_version = 5;
1066
+ `);
1067
+ version = 5;
1068
+ }
1069
+ if (version === 5) {
1070
+ database.exec(`
1071
+ ${approvalDispatchCursorSchema}
1072
+ PRAGMA user_version = 6;
1073
+ `);
1074
+ version = 6;
1075
+ }
1076
+ if (version === 6) {
1077
+ database.exec(`
1078
+ CREATE TABLE delivery_attachments_v7 (
1079
+ id TEXT PRIMARY KEY,
1080
+ owner_kind TEXT NOT NULL CHECK (owner_kind IN ('inbox', 'outbox')),
1081
+ owner_id TEXT NOT NULL,
1082
+ ordinal INTEGER NOT NULL CHECK (ordinal >= 0),
1083
+ media_type TEXT NOT NULL,
1084
+ size_bytes INTEGER NOT NULL CHECK (size_bytes >= 0),
1085
+ sha256 TEXT NOT NULL,
1086
+ spool_ref TEXT,
1087
+ resource_kind TEXT,
1088
+ provider_ref TEXT,
1089
+ file_name TEXT,
1090
+ status TEXT NOT NULL CHECK (status IN ('metadata', 'quarantined', 'ready', 'expired')),
1091
+ expires_at INTEGER,
1092
+ created_at INTEGER NOT NULL
1093
+ ) STRICT;
1094
+ INSERT INTO delivery_attachments_v7 (
1095
+ id, owner_kind, owner_id, ordinal, media_type, size_bytes, sha256, spool_ref,
1096
+ resource_kind, provider_ref, file_name, status, expires_at, created_at
1097
+ )
1098
+ SELECT attachment.id, attachment.owner_kind, attachment.owner_id,
1099
+ ROW_NUMBER() OVER (
1100
+ PARTITION BY attachment.owner_kind, attachment.owner_id
1101
+ ORDER BY attachment.rowid
1102
+ ) - 1,
1103
+ attachment.media_type, attachment.size_bytes, attachment.sha256, attachment.spool_ref,
1104
+ attachment.resource_kind, attachment.provider_ref, attachment.file_name, attachment.status,
1105
+ attachment.expires_at, attachment.created_at
1106
+ FROM delivery_attachments AS attachment;
1107
+ DROP TABLE delivery_attachments;
1108
+ ALTER TABLE delivery_attachments_v7 RENAME TO delivery_attachments;
1109
+ CREATE UNIQUE INDEX delivery_attachment_owner_ordinal
1110
+ ON delivery_attachments(owner_kind, owner_id, ordinal);
1111
+ PRAGMA user_version = 7;
1112
+ `);
1113
+ version = 7;
1114
+ }
1115
+ if (version === 7) {
1116
+ database.exec(`
1117
+ ${deliveryInstanceSchema}
1118
+ PRAGMA user_version = 8;
1119
+ `);
1120
+ version = 8;
1121
+ }
1122
+ if (version === 8) {
1123
+ // v8 represented an operator cancel only by overwriting failure_code. A
1124
+ // plain table creation would revive those terminal attempts as actionable
1125
+ // and allow an old ambiguous send to be retried after upgrade. Preserve
1126
+ // the lost decision as an immutable legacy receipt before publishing v9.
1127
+ const hasInbox = hasTable(database, 'inbox_messages');
1128
+ const hasOutbox = hasTable(database, 'outbox_messages');
1129
+ const hasInboxAttempts = hasTable(database, 'inbox_attempts');
1130
+ const hasOutboxAttempts = hasTable(database, 'outbox_attempts');
1131
+ const inboxOriginalFailure = hasInboxAttempts ? `COALESCE((
1132
+ SELECT attempt.failure_code FROM inbox_attempts AS attempt
1133
+ WHERE attempt.inbox_id = message.id
1134
+ AND attempt.attempt_number = message.attempt_count
1135
+ AND attempt.failure_code IS NOT NULL
1136
+ ORDER BY attempt.rowid DESC LIMIT 1
1137
+ ), 'legacy-unknown')` : `'legacy-unknown'`;
1138
+ const outboxOriginalFailure = hasOutboxAttempts ? `COALESCE((
1139
+ SELECT attempt.failure_code FROM outbox_attempts AS attempt
1140
+ WHERE attempt.outbox_id = message.id
1141
+ AND attempt.attempt_number = message.attempt_count
1142
+ AND attempt.failure_code IS NOT NULL
1143
+ ORDER BY attempt.rowid DESC LIMIT 1
1144
+ ), 'legacy-unknown')` : `'legacy-unknown'`;
1145
+ const inboxBackfill = hasInbox ? `
1146
+ INSERT INTO dead_letter_resolutions (
1147
+ kind, message_id, attempt_count, receipt_version, resolution, original_status,
1148
+ original_failure_code, operator_id, created_at
1149
+ )
1150
+ SELECT 'inbox', message.id, message.attempt_count, 1, 'cancel', 'dead_letter',
1151
+ ${inboxOriginalFailure}, 'legacy-v8-migration', message.updated_at
1152
+ FROM inbox_messages AS message
1153
+ WHERE message.status = 'dead_letter' AND message.failure_code = 'operator-cancelled';
1154
+ ` : '';
1155
+ const outboxBackfill = hasOutbox ? `
1156
+ INSERT INTO dead_letter_resolutions (
1157
+ kind, message_id, attempt_count, receipt_version, resolution, original_status,
1158
+ original_failure_code, operator_id, created_at
1159
+ )
1160
+ SELECT 'outbox', message.id, message.attempt_count, 1, 'cancel',
1161
+ CASE WHEN ${hasOutboxAttempts ? `EXISTS (
1162
+ SELECT 1 FROM outbox_attempts AS attempt
1163
+ WHERE attempt.outbox_id = message.id
1164
+ AND attempt.attempt_number = message.attempt_count
1165
+ AND attempt.status = 'unknown_after_send'
1166
+ )` : '0'} THEN 'unknown_after_send' ELSE 'dead' END,
1167
+ ${outboxOriginalFailure}, 'legacy-v8-migration', message.updated_at
1168
+ FROM outbox_messages AS message
1169
+ WHERE message.status = 'dead' AND message.failure_code = 'operator-cancelled';
1170
+
1171
+ UPDATE outbox_messages AS message
1172
+ SET status = 'unknown_after_send', failure_code = 'operator-cancelled-unknown'
1173
+ WHERE message.status = 'dead' AND message.failure_code = 'operator-cancelled'
1174
+ AND EXISTS (
1175
+ SELECT 1 FROM dead_letter_resolutions AS resolution
1176
+ WHERE resolution.kind = 'outbox' AND resolution.message_id = message.id
1177
+ AND resolution.attempt_count = message.attempt_count
1178
+ AND resolution.original_status = 'unknown_after_send'
1179
+ );
1180
+ ` : '';
1181
+ database.exec(`
1182
+ ${deadLetterResolutionSchema}
1183
+ ${inboxBackfill}
1184
+ ${outboxBackfill}
1185
+ ${hasInbox && hasOutbox ? deadLetterResolutionCompatibilitySchema : ''}
1186
+ PRAGMA user_version = 9;
1187
+ `);
1188
+ version = 9;
1189
+ }
1190
+ if (version === 9) {
1191
+ database.exec(`
1192
+ ${deliveryPresentationSchema}
1193
+ PRAGMA user_version = 10;
1194
+ `);
1195
+ version = 10;
1196
+ }
1197
+ if (version === 10) {
1198
+ database.exec(`
1199
+ ${workflowTraceSchema}
1200
+ PRAGMA user_version = 11;
1201
+ `);
1202
+ version = 11;
1203
+ }
1204
+ if (version === 11) {
1205
+ database.exec(`
1206
+ ${preferenceProjectionSchema}
1207
+ PRAGMA user_version = 12;
1208
+ `);
1209
+ version = 12;
1210
+ }
1211
+ if (version === 12) {
1212
+ database.exec(hasTable(database, 'inbox_messages')
1213
+ && hasTable(database, 'delivery_instance')
1214
+ ? `
1215
+ ${inboxAdmissionSchema}
1216
+ PRAGMA user_version = 13;
1217
+ `
1218
+ : `
1219
+ PRAGMA user_version = 13;
1220
+ `);
1221
+ version = 13;
1222
+ }
1223
+ if (version === 13) {
1224
+ migratePreferenceProjectionLane(database);
1225
+ version = 14;
1226
+ }
1227
+ if (version === 14) {
1228
+ database.exec(`
1229
+ ${workflowVerifiedTaskFeedbackSchema}
1230
+ PRAGMA user_version = 15;
1231
+ `);
1232
+ version = 15;
1233
+ }
1234
+ if (version === 15) {
1235
+ database.exec(`
1236
+ ${approvalOutboxRouteSchema}
1237
+ PRAGMA user_version = 16;
1238
+ `);
1239
+ assertApprovalOutboxRouteSchema(database);
1240
+ version = 16;
1241
+ }
1242
+ if (version === 16) {
1243
+ database.exec(`${ownerObjectiveRevisionSchema} PRAGMA user_version = 17;`);
1244
+ version = 17;
1245
+ }
1246
+ if (version === 17) {
1247
+ database.exec(`${taskAcceptanceExecutionSchemaV21} PRAGMA user_version = 18;`);
1248
+ version = 18;
1249
+ }
1250
+ if (version === 18) {
1251
+ database.exec(`${sessionLeaseSchema} PRAGMA user_version = 19;`);
1252
+ version = 19;
1253
+ }
1254
+ if (version === 19) {
1255
+ database.exec(`${goalOutcomeTargetSchema} PRAGMA user_version = 20;`);
1256
+ version = 20;
1257
+ }
1258
+ if (version === 20) {
1259
+ database.exec(`${workflowOwnerAnchoredSchema} PRAGMA user_version = 21;`);
1260
+ version = 21;
1261
+ }
1262
+ if (version === 21) {
1263
+ migrateTaskAcceptanceModelSelection(database);
1264
+ database.exec('PRAGMA user_version = 22;');
1265
+ version = 22;
1266
+ }
1267
+ if (version === 22) {
1268
+ // Do not synthesize ordinary-use receipts from acceptance contracts: an
1269
+ // old accepted task was not necessarily captured as a general execution.
1270
+ database.exec(`${foregroundExecutionSchema} PRAGMA user_version = 23;`);
1271
+ version = 23;
1272
+ }
1273
+ if (version === 23) {
1274
+ database.exec(`${naturalObjectiveIntentSchema} PRAGMA user_version = 24;`);
1275
+ version = 24;
1276
+ }
1277
+ if (version === 24) {
1278
+ const columns = database.prepare('PRAGMA table_info(delivery_foreground_executions)').all();
1279
+ if (!columns.some(column => column.name === 'completion_sequence')) {
1280
+ database.exec('ALTER TABLE delivery_foreground_executions ADD COLUMN completion_sequence INTEGER CHECK(completion_sequence BETWEEN 1 AND 9007199254740991);');
1281
+ }
1282
+ database.exec(`${foregroundCompletionSchema} PRAGMA user_version = 25;`);
1283
+ version = 25;
1284
+ }
1285
+ if (version === 25) {
1286
+ database.exec(restartFenceSchema);
1287
+ // Historical partial ledgers may omit a message lane entirely. There is
1288
+ // no claim to fence for an absent table; every existing lane gets its
1289
+ // trigger in this same migration transaction (including old open writers).
1290
+ if (hasTable(database, 'inbox_messages'))
1291
+ database.exec(restartInboxFenceSchema);
1292
+ if (hasTable(database, 'outbox_messages'))
1293
+ database.exec(restartOutboxFenceSchema);
1294
+ database.exec('PRAGMA user_version = 26;');
1295
+ version = 26;
1296
+ }
1297
+ if (version === 26) {
1298
+ database.exec(`${progressSchema} PRAGMA user_version = 27;`);
1299
+ version = 27;
1300
+ }
1301
+ if (version === 27) {
1302
+ if (hasTable(database, 'delivery_foreground_executions')) {
1303
+ if (!hasColumn(database, 'delivery_foreground_executions', 'termination_json'))
1304
+ database.exec('ALTER TABLE delivery_foreground_executions ADD COLUMN termination_json TEXT CHECK(termination_json IS NULL OR (json_valid(termination_json) AND length(CAST(termination_json AS BLOB)) <= 1024))');
1305
+ for (const statement of foregroundTerminationTriggers) {
1306
+ const name = /^CREATE TRIGGER (\w+)/u.exec(statement.trim())?.[1];
1307
+ const existing = database.prepare('SELECT sql FROM sqlite_schema WHERE type = ? AND name = ?').get('trigger', name ?? '');
1308
+ if (existing && existing.sql !== statement.trim())
1309
+ throw new Error('invalid foreground termination schema');
1310
+ if (!existing)
1311
+ database.exec(statement);
1312
+ }
1313
+ }
1314
+ database.exec('PRAGMA user_version = 28;');
1315
+ version = 28;
1316
+ }
1317
+ if (version === 28) {
1318
+ database.exec(`${workItemRepliesSchema} PRAGMA user_version = 29;`);
1319
+ version = 29;
1320
+ }
1321
+ if (version === 29) {
1322
+ database.exec(`${workItemFeedbackSchema} PRAGMA user_version = 30;`);
1323
+ version = 30;
1324
+ }
1325
+ if (version === 30) {
1326
+ database.exec(`${attentionAuditSchema} PRAGMA user_version = 31;`);
1327
+ version = 31;
1328
+ }
1329
+ if (version === deliverySchemaVersion)
1330
+ return;
1331
+ database.exec(`
1332
+ ${deliveryInstanceSchema}
1333
+ CREATE TABLE delivery_principals (
1334
+ id TEXT PRIMARY KEY,
1335
+ key_hash TEXT NOT NULL UNIQUE,
1336
+ principal_json TEXT NOT NULL,
1337
+ role TEXT NOT NULL CHECK (role IN ('owner', 'linked')),
1338
+ status TEXT NOT NULL CHECK (status IN ('active', 'revoked')),
1339
+ linked_to_id TEXT,
1340
+ created_at INTEGER NOT NULL,
1341
+ updated_at INTEGER NOT NULL,
1342
+ version INTEGER NOT NULL CHECK (version >= 1),
1343
+ FOREIGN KEY (linked_to_id) REFERENCES delivery_principals(id)
1344
+ ) STRICT;
1345
+
1346
+ CREATE TABLE pairing_challenges (
1347
+ id TEXT PRIMARY KEY,
1348
+ principal_hash TEXT NOT NULL,
1349
+ principal_json TEXT NOT NULL,
1350
+ code_salt TEXT NOT NULL,
1351
+ code_hash TEXT NOT NULL,
1352
+ status TEXT NOT NULL CHECK (status IN ('active', 'consumed', 'expired', 'locked')),
1353
+ attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
1354
+ max_attempts INTEGER NOT NULL CHECK (max_attempts >= 1),
1355
+ expires_at INTEGER NOT NULL,
1356
+ created_at INTEGER NOT NULL,
1357
+ updated_at INTEGER NOT NULL
1358
+ ) STRICT;
1359
+ CREATE INDEX pairing_active ON pairing_challenges(principal_hash, status, expires_at);
1360
+
1361
+ CREATE TABLE conversation_bindings (
1362
+ id TEXT PRIMARY KEY,
1363
+ conversation_hash TEXT NOT NULL,
1364
+ conversation_json TEXT NOT NULL,
1365
+ principal_id TEXT NOT NULL,
1366
+ principal_json TEXT NOT NULL,
1367
+ workspace TEXT NOT NULL,
1368
+ agent_preset TEXT NOT NULL,
1369
+ session_id TEXT NOT NULL UNIQUE,
1370
+ generation INTEGER NOT NULL CHECK (generation >= 1),
1371
+ policy_ref TEXT NOT NULL,
1372
+ status TEXT NOT NULL CHECK (status IN ('active', 'revoked')),
1373
+ created_at INTEGER NOT NULL,
1374
+ updated_at INTEGER NOT NULL,
1375
+ version INTEGER NOT NULL CHECK (version >= 1),
1376
+ UNIQUE (conversation_hash, generation),
1377
+ FOREIGN KEY (principal_id) REFERENCES delivery_principals(id)
1378
+ ) STRICT;
1379
+ CREATE UNIQUE INDEX binding_one_active ON conversation_bindings(conversation_hash) WHERE status = 'active';
1380
+
1381
+ CREATE TABLE conversation_model_selections (
1382
+ conversation_hash TEXT PRIMARY KEY,
1383
+ conversation_json TEXT NOT NULL,
1384
+ provider TEXT NOT NULL,
1385
+ model TEXT NOT NULL,
1386
+ reasoning_effort TEXT,
1387
+ updated_at INTEGER NOT NULL,
1388
+ version INTEGER NOT NULL CHECK (version >= 1)
1389
+ ) STRICT;
1390
+
1391
+ CREATE TABLE inbox_messages (
1392
+ id TEXT PRIMARY KEY,
1393
+ channel TEXT NOT NULL,
1394
+ account TEXT NOT NULL,
1395
+ event_id TEXT NOT NULL,
1396
+ envelope_hash TEXT NOT NULL,
1397
+ envelope_json TEXT NOT NULL,
1398
+ status TEXT NOT NULL CHECK (status IN ('received', 'authorized', 'queued', 'claimed', 'processed', 'retry_wait', 'dead_letter')),
1399
+ binding_id TEXT,
1400
+ attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0),
1401
+ next_attempt_at INTEGER,
1402
+ claimed_by TEXT,
1403
+ fencing_token INTEGER,
1404
+ lease_until INTEGER,
1405
+ failure_code TEXT,
1406
+ received_at INTEGER NOT NULL,
1407
+ updated_at INTEGER NOT NULL,
1408
+ UNIQUE (channel, account, event_id),
1409
+ FOREIGN KEY (binding_id) REFERENCES conversation_bindings(id)
1410
+ ) STRICT;
1411
+ CREATE INDEX inbox_claim ON inbox_messages(status, next_attempt_at, received_at, id);
1412
+
1413
+ CREATE TABLE inbox_attempts (
1414
+ id TEXT PRIMARY KEY,
1415
+ inbox_id TEXT NOT NULL,
1416
+ attempt_number INTEGER NOT NULL,
1417
+ owner_id TEXT NOT NULL,
1418
+ fencing_token INTEGER NOT NULL,
1419
+ status TEXT NOT NULL CHECK (status IN ('claimed', 'processed', 'retry_wait', 'dead_letter', 'lost')),
1420
+ failure_code TEXT,
1421
+ created_at INTEGER NOT NULL,
1422
+ finished_at INTEGER,
1423
+ UNIQUE (inbox_id, attempt_number),
1424
+ FOREIGN KEY (inbox_id) REFERENCES inbox_messages(id)
1425
+ ) STRICT;
1426
+
1427
+ CREATE TABLE outbox_messages (
1428
+ id TEXT PRIMARY KEY,
1429
+ idempotency_key TEXT NOT NULL UNIQUE,
1430
+ binding_id TEXT NOT NULL,
1431
+ intent_hash TEXT NOT NULL,
1432
+ intent_json TEXT NOT NULL,
1433
+ channel TEXT NOT NULL,
1434
+ account TEXT NOT NULL,
1435
+ lane_hash TEXT NOT NULL,
1436
+ status TEXT NOT NULL CHECK (status IN ('pending', 'attempting', 'accepted', 'delivered', 'read', 'retry_wait', 'dead', 'unknown_after_send')),
1437
+ provider_message_id TEXT,
1438
+ attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0),
1439
+ next_attempt_at INTEGER,
1440
+ claimed_by TEXT,
1441
+ fencing_token INTEGER,
1442
+ lease_until INTEGER,
1443
+ failure_code TEXT,
1444
+ created_at INTEGER NOT NULL,
1445
+ updated_at INTEGER NOT NULL,
1446
+ FOREIGN KEY (binding_id) REFERENCES conversation_bindings(id)
1447
+ ) STRICT;
1448
+ CREATE INDEX outbox_claim ON outbox_messages(status, next_attempt_at, created_at, id);
1449
+ CREATE INDEX outbox_lane ON outbox_messages(lane_hash, created_at, id);
1450
+ CREATE UNIQUE INDEX outbox_provider_message ON outbox_messages(channel, account, provider_message_id)
1451
+ WHERE provider_message_id IS NOT NULL;
1452
+
1453
+ CREATE TABLE outbox_attempts (
1454
+ id TEXT PRIMARY KEY,
1455
+ outbox_id TEXT NOT NULL,
1456
+ attempt_number INTEGER NOT NULL,
1457
+ owner_id TEXT NOT NULL,
1458
+ fencing_token INTEGER NOT NULL,
1459
+ operation TEXT NOT NULL CHECK (operation IN ('send', 'reconcile')),
1460
+ status TEXT NOT NULL CHECK (status IN ('attempting', 'accepted', 'retry_wait', 'dead', 'unknown_after_send', 'reconciled')),
1461
+ provider_message_id TEXT,
1462
+ failure_code TEXT,
1463
+ created_at INTEGER NOT NULL,
1464
+ finished_at INTEGER,
1465
+ UNIQUE (outbox_id, attempt_number),
1466
+ FOREIGN KEY (outbox_id) REFERENCES outbox_messages(id)
1467
+ ) STRICT;
1468
+
1469
+ CREATE TABLE delivery_receipts (
1470
+ id TEXT PRIMARY KEY,
1471
+ channel TEXT NOT NULL,
1472
+ account TEXT NOT NULL,
1473
+ provider_message_id TEXT NOT NULL,
1474
+ status TEXT NOT NULL CHECK (status IN ('accepted', 'delivered', 'read')),
1475
+ receipt_hash TEXT NOT NULL UNIQUE,
1476
+ receipt_json TEXT NOT NULL,
1477
+ occurred_at INTEGER NOT NULL,
1478
+ created_at INTEGER NOT NULL,
1479
+ UNIQUE (channel, account, provider_message_id, status)
1480
+ ) STRICT;
1481
+
1482
+ CREATE TABLE delivery_attachments (
1483
+ id TEXT PRIMARY KEY,
1484
+ owner_kind TEXT NOT NULL CHECK (owner_kind IN ('inbox', 'outbox')),
1485
+ owner_id TEXT NOT NULL,
1486
+ ordinal INTEGER NOT NULL CHECK (ordinal >= 0),
1487
+ media_type TEXT NOT NULL,
1488
+ size_bytes INTEGER NOT NULL CHECK (size_bytes >= 0),
1489
+ sha256 TEXT NOT NULL,
1490
+ spool_ref TEXT,
1491
+ resource_kind TEXT,
1492
+ provider_ref TEXT,
1493
+ file_name TEXT,
1494
+ status TEXT NOT NULL CHECK (status IN ('metadata', 'quarantined', 'ready', 'expired')),
1495
+ expires_at INTEGER,
1496
+ created_at INTEGER NOT NULL
1497
+ ) STRICT;
1498
+ CREATE UNIQUE INDEX delivery_attachment_owner_ordinal
1499
+ ON delivery_attachments(owner_kind, owner_id, ordinal);
1500
+
1501
+ CREATE TABLE approval_settlements (
1502
+ operation_id TEXT PRIMARY KEY,
1503
+ payload_hash TEXT NOT NULL,
1504
+ payload_json TEXT NOT NULL,
1505
+ status TEXT NOT NULL CHECK (status IN ('pending', 'completed')),
1506
+ result_json TEXT,
1507
+ created_at INTEGER NOT NULL,
1508
+ updated_at INTEGER NOT NULL
1509
+ ) STRICT;
1510
+
1511
+ ${modelPickerStateSchema}
1512
+
1513
+ CREATE TABLE delivery_duty_lease (
1514
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
1515
+ owner_id TEXT NOT NULL,
1516
+ fencing_token INTEGER NOT NULL CHECK (fencing_token >= 1),
1517
+ lease_until INTEGER NOT NULL,
1518
+ updated_at INTEGER NOT NULL
1519
+ ) STRICT;
1520
+
1521
+ ${approvalDispatchCursorSchema}
1522
+
1523
+ ${approvalOutboxRouteSchema}
1524
+
1525
+ ${deadLetterResolutionSchema}
1526
+
1527
+ ${deadLetterResolutionCompatibilitySchema}
1528
+
1529
+ ${deliveryPresentationSchema}
1530
+
1531
+ ${workflowTraceSchema}
1532
+
1533
+ ${workflowVerifiedTaskFeedbackSchema}
1534
+
1535
+ ${preferenceProjectionSchema}
1536
+
1537
+ ${inboxAdmissionSchema}
1538
+
1539
+ ${ownerObjectiveRevisionSchema}
1540
+ ${naturalObjectiveIntentSchema}
1541
+ ${taskAcceptanceExecutionSchema}
1542
+ ${foregroundExecutionSchema}
1543
+ ${foregroundCompletionSchema}
1544
+ ${foregroundTerminationTriggers.join(';')};
1545
+ ${sessionLeaseSchema}
1546
+ ${goalOutcomeTargetSchema}
1547
+
1548
+ ${workflowOwnerAnchoredSchema}
1549
+ ${restartFenceSchema}
1550
+ ${restartInboxFenceSchema}
1551
+ ${restartOutboxFenceSchema}
1552
+ ${progressSchema}
1553
+ ${workItemRepliesSchema}
1554
+ ${workItemFeedbackSchema}
1555
+ ${attentionAuditSchema}
1556
+ PRAGMA user_version = 31;
1557
+ `);
1558
+ }
1559
+ /** Verify exact authority tables/triggers on reopening; version labels alone confer no authority. */
1560
+ function assertWorkItemRepliesSchema(database) {
1561
+ const expected = new DatabaseSync(':memory:');
1562
+ try {
1563
+ expected.exec(workItemRepliesSchema + workItemFeedbackSchema);
1564
+ const query = `SELECT type,name,tbl_name,sql FROM sqlite_schema
1565
+ WHERE tbl_name IN ('delivery_work_item_reports','delivery_work_item_reply_streams','delivery_work_item_replies','delivery_work_item_feedback') ORDER BY type,name`;
1566
+ if (JSON.stringify(database.prepare(query).all()) !== JSON.stringify(expected.prepare(query).all())) {
1567
+ throw new Error('invalid work item reply authority schema');
1568
+ }
1569
+ }
1570
+ finally {
1571
+ expected.close();
1572
+ }
1573
+ }
1574
+ function assertAttentionAuditSchema(database) {
1575
+ const expected = new DatabaseSync(':memory:');
1576
+ try {
1577
+ expected.exec('CREATE TABLE outbox_messages (id TEXT PRIMARY KEY);' + attentionAuditSchema);
1578
+ const query = `SELECT type,name,tbl_name,sql FROM sqlite_schema WHERE tbl_name='delivery_attention_audit' ORDER BY type,name`;
1579
+ if (JSON.stringify(database.prepare(query).all()) !== JSON.stringify(expected.prepare(query).all())) {
1580
+ throw new Error('invalid attention audit schema');
1581
+ }
1582
+ }
1583
+ finally {
1584
+ expected.close();
1585
+ }
1586
+ }
1587
+ /** Serialize the complete forward migration chain across every Host process. */
1588
+ function migrate(database) {
1589
+ database.exec('BEGIN IMMEDIATE');
1590
+ try {
1591
+ migrateObserved(database);
1592
+ assertApprovalOutboxRouteSchema(database);
1593
+ assertSessionLeaseSchema(database);
1594
+ assertGoalOutcomeTargetSchema(database);
1595
+ assertForegroundTerminationSchema(database);
1596
+ assertWorkItemRepliesSchema(database);
1597
+ assertAttentionAuditSchema(database);
1598
+ database.exec('COMMIT');
1599
+ }
1600
+ catch (error) {
1601
+ try {
1602
+ database.exec('ROLLBACK');
1603
+ }
1604
+ catch { }
1605
+ throw error;
1606
+ }
1607
+ }
1608
+ // SQLite's journal-mode transition is outside the migration transaction. A
1609
+ // simultaneous opener can therefore finish migration while another connection
1610
+ // is still changing mode, which returns SQLITE_BUSY even after busy_timeout.
1611
+ // Keep the migration mutex intact and retry only that transient transition.
1612
+ const walRetryWait = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
1613
+ function enableWal(database) {
1614
+ const deadline = performance.now() + 5_000;
1615
+ // busy_timeout applies to each statement. Disable it only for this bounded
1616
+ // retry loop so one SQLite wait cannot extend the five-second overall cap.
1617
+ database.exec('PRAGMA busy_timeout = 0');
1618
+ try {
1619
+ while (true) {
1620
+ try {
1621
+ const row = database.prepare('PRAGMA journal_mode = WAL').get();
1622
+ if (row.journal_mode.toLowerCase() !== 'wal') {
1623
+ throw new Error(`delivery database refused WAL mode: ${row.journal_mode}`);
1624
+ }
1625
+ return;
1626
+ }
1627
+ catch (error) {
1628
+ const retryable = error instanceof Error && /database is (?:busy|locked)/i.test(error.message);
1629
+ if (!retryable || performance.now() >= deadline)
1630
+ throw error;
1631
+ Atomics.wait(walRetryWait, 0, 0, 10);
1632
+ }
1633
+ }
1634
+ }
1635
+ finally {
1636
+ database.exec('PRAGMA busy_timeout = 5000');
1637
+ }
1638
+ }
1639
+ export function openDeliveryDatabase(path) {
1640
+ if (path !== ':memory:' && !isAbsolute(path)) {
1641
+ throw new DeliveryDatabaseError('invalid-path', 'delivery database path must be absolute');
1642
+ }
1643
+ if (path !== ':memory:') {
1644
+ const directory = dirname(path);
1645
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
1646
+ chmodSync(directory, 0o700);
1647
+ }
1648
+ const database = new DatabaseSync(path);
1649
+ try {
1650
+ database.exec('PRAGMA foreign_keys = ON');
1651
+ database.exec('PRAGMA busy_timeout = 5000');
1652
+ database.exec('PRAGMA synchronous = FULL');
1653
+ migrate(database);
1654
+ if (path !== ':memory:') {
1655
+ enableWal(database);
1656
+ chmodSync(path, 0o600);
1657
+ }
1658
+ return database;
1659
+ }
1660
+ catch (error) {
1661
+ database.close();
1662
+ throw error;
1663
+ }
1664
+ }
1665
+ //# sourceMappingURL=sqlite.js.map