@deksden-com/dd-flow-cli 0.9.0-beta.13 → 0.9.0-beta.133

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 (204) hide show
  1. package/CHANGELOG.md +666 -0
  2. package/README.md +101 -1
  3. package/dist/build-info.json +10 -10
  4. package/dist/cli/argument-values.js +38 -0
  5. package/dist/cli/command-inputs.js +306 -0
  6. package/dist/cli/help.js +88 -12
  7. package/dist/cli/hook-ingress.js +78 -0
  8. package/dist/cli/input-preparation.js +116 -0
  9. package/dist/cli/native-hook-ingress.js +80 -0
  10. package/dist/cli/run-cli.js +1465 -450
  11. package/dist/cli/runtime-maintenance-diagnostics.js +46 -0
  12. package/dist/cli/runtime-maintenance-ingress.js +52 -0
  13. package/dist/cli/runtime-process.js +153 -0
  14. package/dist/cli.js +17 -2
  15. package/dist/domain/stage-catalog.js +1 -1
  16. package/dist/harness-runtime/DD-ZCODE.md +99 -0
  17. package/dist/harness-runtime/bin/dd-agy.mjs +56 -0
  18. package/dist/harness-runtime/bin/dd-codex.mjs +27 -0
  19. package/dist/harness-runtime/bin/dd-droid.mjs +34 -0
  20. package/dist/harness-runtime/bin/dd-grok.mjs +40 -0
  21. package/dist/harness-runtime/bin/dd-opencode.mjs +22 -0
  22. package/dist/harness-runtime/bin/dd-zcode.mjs +87 -0
  23. package/dist/harness-runtime/lib/adapter-timeouts.d.mts +5 -0
  24. package/dist/harness-runtime/lib/adapter-timeouts.mjs +34 -0
  25. package/dist/harness-runtime/lib/agy-hooks.d.mts +1 -0
  26. package/dist/harness-runtime/lib/agy-hooks.mjs +9 -0
  27. package/dist/harness-runtime/lib/codex-capacity-policy.d.mts +10 -0
  28. package/dist/harness-runtime/lib/codex-capacity-policy.mjs +89 -0
  29. package/dist/harness-runtime/lib/daemon-observation.d.mts +2 -0
  30. package/dist/harness-runtime/lib/daemon-observation.mjs +163 -0
  31. package/dist/harness-runtime/lib/daemon-operations.mjs +370 -0
  32. package/dist/harness-runtime/lib/dd-agy-daemon.d.mts +6 -0
  33. package/dist/harness-runtime/lib/dd-agy-daemon.mjs +693 -0
  34. package/dist/harness-runtime/lib/dd-agy.mjs +59 -0
  35. package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
  36. package/dist/harness-runtime/lib/dd-codex-daemon.mjs +190 -0
  37. package/dist/harness-runtime/lib/dd-codex.d.mts +1 -0
  38. package/dist/harness-runtime/lib/dd-codex.mjs +805 -0
  39. package/dist/harness-runtime/lib/dd-droid-daemon.mjs +128 -0
  40. package/dist/harness-runtime/lib/dd-droid.mjs +561 -0
  41. package/dist/harness-runtime/lib/dd-grok-daemon.mjs +490 -0
  42. package/dist/harness-runtime/lib/dd-grok.mjs +177 -0
  43. package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +255 -0
  44. package/dist/harness-runtime/lib/dd-opencode.mjs +128 -0
  45. package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +703 -0
  46. package/dist/harness-runtime/lib/dd-zcode.mjs +1108 -0
  47. package/dist/harness-runtime/lib/delegation-instructions.d.mts +13 -0
  48. package/dist/harness-runtime/lib/delegation-instructions.mjs +144 -0
  49. package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
  50. package/dist/harness-runtime/lib/driver-recovery.mjs +139 -0
  51. package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
  52. package/dist/harness-runtime/lib/lease-renewal.d.mts +8 -0
  53. package/dist/harness-runtime/lib/lease-renewal.mjs +36 -0
  54. package/dist/harness-runtime/lib/lifecycle-command.d.mts +20 -0
  55. package/dist/harness-runtime/lib/lifecycle-command.mjs +272 -0
  56. package/dist/harness-runtime/lib/lifecycle-contract.d.mts +10 -0
  57. package/dist/harness-runtime/lib/lifecycle-contract.mjs +19 -0
  58. package/dist/harness-runtime/lib/managed-daemon.d.mts +12 -0
  59. package/dist/harness-runtime/lib/managed-daemon.mjs +619 -0
  60. package/dist/harness-runtime/lib/model-observations.mjs +101 -0
  61. package/dist/harness-runtime/lib/native-children.d.mts +13 -0
  62. package/dist/harness-runtime/lib/native-children.mjs +78 -0
  63. package/dist/harness-runtime/lib/native-hook-command.d.mts +7 -0
  64. package/dist/harness-runtime/lib/native-hook-command.mjs +251 -0
  65. package/dist/harness-runtime/lib/native-streams.mjs +45 -0
  66. package/dist/harness-runtime/lib/observation-clock.d.mts +18 -0
  67. package/dist/harness-runtime/lib/observation-clock.mjs +92 -0
  68. package/dist/harness-runtime/lib/operation-context.mjs +5 -0
  69. package/dist/harness-runtime/lib/operation-errors.d.mts +14 -0
  70. package/dist/harness-runtime/lib/operation-errors.mjs +116 -0
  71. package/dist/harness-runtime/lib/operation-progress.d.mts +7 -0
  72. package/dist/harness-runtime/lib/operation-progress.mjs +112 -0
  73. package/dist/harness-runtime/lib/process-json.d.mts +5 -0
  74. package/dist/harness-runtime/lib/process-json.mjs +201 -0
  75. package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
  76. package/dist/harness-runtime/lib/runner-events.mjs +200 -0
  77. package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
  78. package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
  79. package/dist/harness-runtime/lib/setup-progress.d.mts +9 -0
  80. package/dist/harness-runtime/lib/setup-progress.mjs +51 -0
  81. package/dist/harness-runtime/lib/tool-observations.d.mts +21 -0
  82. package/dist/harness-runtime/lib/tool-observations.mjs +228 -0
  83. package/dist/harness-runtime/lib/zcode-usage.mjs +55 -0
  84. package/dist/protocol/local-files.js +18 -9
  85. package/dist/runtime/context.js +8 -4
  86. package/dist/schemas/agent-profile.schema.json +1 -1
  87. package/dist/schemas/code-review-result.schema.json +1 -1
  88. package/dist/schemas/code-verification.schema.json +7 -5
  89. package/dist/schemas/code-work-batch.schema.json +2 -2
  90. package/dist/schemas/flow-run.schema.json +2 -0
  91. package/dist/schemas/plan-review-decision.schema.json +3 -3
  92. package/dist/schemas/plan-review-result.schema.json +2 -2
  93. package/dist/schemas/run-control-receipt.schema.json +118 -0
  94. package/dist/schemas/run-control-request.schema.json +36 -0
  95. package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
  96. package/dist/services/branch-context.js +3 -3
  97. package/dist/services/canon.js +11 -8
  98. package/dist/services/check-runner-evidence.js +121 -0
  99. package/dist/services/cleanup.js +133 -40
  100. package/dist/services/cli-operation-classifier.js +22 -24
  101. package/dist/services/code-checks.js +851 -109
  102. package/dist/services/codex-capacity.js +367 -0
  103. package/dist/services/codex-hook-delivery.js +32 -0
  104. package/dist/services/command-context.js +80 -0
  105. package/dist/services/compatibility-preflight.js +13 -3
  106. package/dist/services/config.js +11 -8
  107. package/dist/services/continuation-outcome.js +20 -0
  108. package/dist/services/controller-fanout.js +119 -0
  109. package/dist/services/dashboard.js +135 -56
  110. package/dist/services/engines.js +245 -119
  111. package/dist/services/eval-snapshots.js +1146 -105
  112. package/dist/services/execution-policy.js +181 -0
  113. package/dist/services/external-work-launch.js +230 -0
  114. package/dist/services/harness-adapter.js +329 -36
  115. package/dist/services/harness-config.js +2 -0
  116. package/dist/services/hooks.js +747 -325
  117. package/dist/services/lanes.js +78 -65
  118. package/dist/services/lifecycle-command.js +1 -288
  119. package/dist/services/lifecycle-contract.js +1 -0
  120. package/dist/services/lifecycle-invocations.js +1774 -0
  121. package/dist/services/managed-daemon-binding.js +38 -0
  122. package/dist/services/managed-lease-monitor.js +133 -0
  123. package/dist/services/managed-processes.js +409 -51
  124. package/dist/services/merge-queue.js +228 -149
  125. package/dist/services/merge-server.js +163 -35
  126. package/dist/services/migrations.js +37 -16
  127. package/dist/services/native-daemon-history.js +49 -0
  128. package/dist/services/native-session-control.js +39 -0
  129. package/dist/services/plan-runtime.js +26 -11
  130. package/dist/services/plans.js +28 -25
  131. package/dist/services/projects.js +20 -15
  132. package/dist/services/prompts.js +28 -17
  133. package/dist/services/protocols.js +163 -87
  134. package/dist/services/recovery-observation-budget.js +121 -0
  135. package/dist/services/recovery-snapshot-database.js +145 -0
  136. package/dist/services/repair-intents.js +42 -0
  137. package/dist/services/review-copy.js +157 -0
  138. package/dist/services/review-deferral.js +23 -0
  139. package/dist/services/run-control-receipt.js +56 -0
  140. package/dist/services/run-control-worker.js +411 -0
  141. package/dist/services/run-control.js +985 -0
  142. package/dist/services/run-controller-adapter.js +399 -0
  143. package/dist/services/run-controller-capture.js +179 -0
  144. package/dist/services/run-controller-process.js +187 -0
  145. package/dist/services/run-controller-recovery.js +289 -0
  146. package/dist/services/run-controller-state.js +97 -0
  147. package/dist/services/run-controller.js +1035 -0
  148. package/dist/services/run-engine-bindings.js +1 -1
  149. package/dist/services/run-fork.js +147 -0
  150. package/dist/services/run-observations.js +152 -0
  151. package/dist/services/run-projection.js +22 -64
  152. package/dist/services/run-recovery-guard.js +75 -0
  153. package/dist/services/run-recovery-runtime.js +112 -0
  154. package/dist/services/run-recovery.js +349 -0
  155. package/dist/services/runs.js +558 -217
  156. package/dist/services/runtime-budget.js +430 -0
  157. package/dist/services/runtime-command.js +43 -0
  158. package/dist/services/runtime-scope-capture.js +52 -0
  159. package/dist/services/runtime-scope-control.js +468 -0
  160. package/dist/services/runtime-scope-resume.js +599 -0
  161. package/dist/services/runtime-scope-stop.js +180 -0
  162. package/dist/services/runtime-scope-worker.js +287 -0
  163. package/dist/services/runtime-service.js +96 -0
  164. package/dist/services/schema-validation.js +10 -8
  165. package/dist/services/scope-writer-cleanup.js +27 -0
  166. package/dist/services/sessions.js +35 -69
  167. package/dist/services/stage-blocker.js +17 -7
  168. package/dist/services/stage-context.js +185 -19
  169. package/dist/services/stage-lifecycle.js +98 -107
  170. package/dist/services/stage-pause.js +89 -75
  171. package/dist/services/stage-report-renderer.js +158 -6
  172. package/dist/services/stage-work-graph.js +35 -0
  173. package/dist/services/tooling.js +32 -23
  174. package/dist/services/usage.js +49 -101
  175. package/dist/services/verification-matrix.js +374 -0
  176. package/dist/services/vnext-code-review.js +222 -87
  177. package/dist/services/vnext-code.js +324 -251
  178. package/dist/services/vnext-contracts.js +10 -1
  179. package/dist/services/vnext-execution-profile.js +79 -4
  180. package/dist/services/vnext-fanout.js +177 -17
  181. package/dist/services/vnext-merge.js +335 -113
  182. package/dist/services/vnext-plan-review.js +276 -126
  183. package/dist/services/vnext-plan.js +227 -102
  184. package/dist/services/vnext-protocolize.js +335 -82
  185. package/dist/services/vnext-specify.js +119 -81
  186. package/dist/services/work-registry.js +1038 -192
  187. package/dist/services/workspace-bootstrap.js +87 -0
  188. package/dist/services/workspace-files.js +85 -0
  189. package/dist/services/worktrees.js +98 -44
  190. package/dist/shared/entity-references.js +8 -0
  191. package/dist/shared/errors.js +17 -0
  192. package/dist/storage/agent-output.js +26 -0
  193. package/dist/storage/database.js +781 -37
  194. package/dist/storage/foreign-key-transaction.js +39 -0
  195. package/dist/storage/immutable-input.js +45 -0
  196. package/dist/storage/import-guard.js +102 -0
  197. package/dist/storage/native-cleanup.js +52 -0
  198. package/dist/storage/paths.js +17 -4
  199. package/dist/storage/projection-lock.js +73 -0
  200. package/dist/storage/work-references.js +23 -0
  201. package/dist/storage/writer-contract.js +77 -0
  202. package/dist/storage/writer-migration.js +85 -0
  203. package/package.json +30 -13
  204. package/tools/repair-paused-run-status.mjs +84 -0
@@ -1,12 +1,211 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import crypto from "node:crypto";
4
+ import { channel } from "node:diagnostics_channel";
4
5
  import { createRequire } from "node:module";
5
6
  import { ensureDir } from "./paths.js";
6
7
  import { AppError } from "../shared/errors.js";
8
+ import { executeStoreSchema, readStoreWriterContract, registerStoreWriter, STORE_WRITER_VERSION } from "./writer-contract.js";
9
+ import { assertImportAdmission } from "./import-guard.js";
10
+ import { withStoreCleanup, rollbackStoreTransaction } from "./native-cleanup.js";
11
+ const workContinuationStorageSql = `
12
+ CREATE TABLE IF NOT EXISTS stage_work_memberships (
13
+ project_id TEXT NOT NULL, run_id TEXT NOT NULL, work_id TEXT NOT NULL REFERENCES works(work_id),
14
+ stage TEXT NOT NULL, attempt TEXT NOT NULL, cycle TEXT NOT NULL DEFAULT '',
15
+ PRIMARY KEY(project_id, run_id, work_id, stage, attempt, cycle)
16
+ );
17
+ CREATE TABLE IF NOT EXISTS repair_intents (
18
+ identity TEXT PRIMARY KEY, project_id TEXT NOT NULL, run_id TEXT NOT NULL,
19
+ stage TEXT NOT NULL, attempt TEXT NOT NULL, payload_hash TEXT NOT NULL,
20
+ payload_json TEXT NOT NULL, work_id TEXT NOT NULL REFERENCES works(work_id), created_at TEXT NOT NULL
21
+ );
22
+ `;
23
+ function closeAfterOpenFailure(db, error) {
24
+ return withStoreCleanup(() => { throw error; }, () => { if (db.isOpen)
25
+ db.close(); });
26
+ }
7
27
  const require = createRequire(import.meta.url);
8
28
  const { DatabaseSync } = require("node:sqlite");
9
29
  const resourceDatabases = new Map();
30
+ const publicationScopes = [];
31
+ /** Defer committed cross-store projections until the surrounding writer exits. */
32
+ export function withDeferredPublications(operation) {
33
+ const pending = [];
34
+ publicationScopes.push(pending);
35
+ let value;
36
+ let primary;
37
+ let failed = false;
38
+ try {
39
+ value = operation();
40
+ if (value && typeof value.then === "function")
41
+ throw new AppError("write_transaction_async", "Deferred publication scope must be synchronous", 1);
42
+ }
43
+ catch (error) {
44
+ primary = error;
45
+ failed = true;
46
+ }
47
+ publicationScopes.pop();
48
+ const parent = publicationScopes.at(-1);
49
+ if (parent)
50
+ parent.push(...pending);
51
+ else {
52
+ try {
53
+ executePublications(pending);
54
+ }
55
+ catch (publicationError) {
56
+ if (failed && primary instanceof AppError)
57
+ throw new AppError(primary.code, primary.message, primary.exitCode, { ...primary.details, effect: "partial", committed_publications: pending.length, publication_pending: true, publication_error: errorDetails(publicationError) });
58
+ if (failed)
59
+ throw new AppError("cross_store_failed", "Cross-store mutation failed and committed projections need reconciliation", 1, { effect: "partial", cause: errorDetails(primary), committed_publications: pending.length, publication_pending: true, publication_error: errorDetails(publicationError) });
60
+ throw publicationError;
61
+ }
62
+ }
63
+ if (failed && pending.length && primary instanceof AppError)
64
+ throw new AppError(primary.code, primary.message, primary.exitCode, { ...primary.details, effect: "partial", committed_publications: pending.length });
65
+ if (failed && pending.length)
66
+ throw new AppError("cross_store_failed", "Cross-store mutation failed after a committed inner write", 1, { effect: "partial", cause: errorDetails(primary), committed_publications: pending.length });
67
+ if (failed)
68
+ throw primary;
69
+ return value;
70
+ }
71
+ function executePublications(pending) {
72
+ let firstError;
73
+ let failed = false;
74
+ for (const operation of pending) {
75
+ try {
76
+ operation();
77
+ }
78
+ catch (error) {
79
+ if (!failed)
80
+ firstError = error;
81
+ failed = true;
82
+ }
83
+ }
84
+ if (failed) {
85
+ if (firstError instanceof AppError && firstError.details.effect === "committed")
86
+ throw firstError;
87
+ throw new AppError("publication_pending", "SQL committed but a required projection needs reconciliation", 1, { effect: "committed", publication_pending: true, cause: errorDetails(firstError) });
88
+ }
89
+ }
90
+ /** Invocation authority is prepared once with the runtime schema. Native
91
+ * hooks must only verify this table; they never create it on the hot path. */
92
+ export function ensureLifecycleInvocationStorage(db) {
93
+ db.exec(`
94
+ CREATE TABLE IF NOT EXISTS lifecycle_invocations (
95
+ id TEXT PRIMARY KEY, scope_json TEXT NOT NULL, command TEXT NOT NULL,
96
+ fingerprint TEXT NOT NULL, status TEXT NOT NULL,
97
+ event_key TEXT UNIQUE, identity_json TEXT, deadline INTEGER, outcome_json TEXT,
98
+ created_at TEXT NOT NULL, updated_at TEXT NOT NULL
99
+ );
100
+ CREATE INDEX IF NOT EXISTS idx_lifecycle_invocations_scope
101
+ ON lifecycle_invocations(scope_json, fingerprint, created_at);
102
+ CREATE TABLE IF NOT EXISTS lifecycle_packet_assignments (
103
+ packet_sha256 TEXT NOT NULL,
104
+ invocation_id TEXT NOT NULL REFERENCES lifecycle_invocations(id),
105
+ PRIMARY KEY(packet_sha256, invocation_id)
106
+ );
107
+ `);
108
+ }
109
+ /** RUN authority stays in its existing store; process leases stay in runtime.sqlite. */
110
+ export function ensureRunControlStorage(db) {
111
+ db.execSchema(`
112
+ CREATE TABLE IF NOT EXISTS run_controls (
113
+ control_id TEXT PRIMARY KEY,
114
+ project_id TEXT NOT NULL, run_id TEXT NOT NULL,
115
+ request_id TEXT NOT NULL, request_hash TEXT NOT NULL, request_json TEXT NOT NULL,
116
+ recovery_id TEXT NOT NULL REFERENCES run_recovery_guards(recovery_id),
117
+ action TEXT NOT NULL, status TEXT NOT NULL,
118
+ created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
119
+ UNIQUE(project_id, run_id, request_id),
120
+ FOREIGN KEY(project_id, run_id) REFERENCES runs(project_id, id)
121
+ );
122
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_run_control_active
123
+ ON run_controls(project_id, run_id) WHERE status IN ('requested','settled','resuming');
124
+ CREATE TABLE IF NOT EXISTS run_control_admissions (
125
+ control_id TEXT NOT NULL REFERENCES run_controls(control_id),
126
+ work_session_id TEXT NOT NULL REFERENCES work_sessions(id),
127
+ work_id TEXT NOT NULL REFERENCES works(work_id),
128
+ session_id TEXT NOT NULL, admitted_at TEXT NOT NULL,
129
+ PRIMARY KEY(control_id, work_session_id)
130
+ );
131
+ CREATE TABLE IF NOT EXISTS run_control_stage_admissions (
132
+ control_id TEXT NOT NULL REFERENCES run_controls(control_id),
133
+ stage TEXT NOT NULL, attempt TEXT NOT NULL,
134
+ work_session_id TEXT NOT NULL REFERENCES work_sessions(id),
135
+ PRIMARY KEY(control_id, stage)
136
+ );
137
+ CREATE TABLE IF NOT EXISTS run_control_operations (
138
+ operation_id TEXT PRIMARY KEY, control_id TEXT NOT NULL REFERENCES run_controls(control_id),
139
+ target_json TEXT NOT NULL, status TEXT NOT NULL, receipt_json TEXT, error_json TEXT,
140
+ created_at TEXT NOT NULL, updated_at TEXT NOT NULL
141
+ );
142
+ CREATE TABLE IF NOT EXISTS run_control_workers (
143
+ control_id TEXT PRIMARY KEY REFERENCES run_controls(control_id),
144
+ owner_token TEXT NOT NULL, owner_pid INTEGER,
145
+ status TEXT NOT NULL, process_id TEXT, process_lease_token TEXT,
146
+ resource_home TEXT NOT NULL, state_dir TEXT NOT NULL,
147
+ snapshot_json TEXT, error_json TEXT,
148
+ created_at TEXT NOT NULL, updated_at TEXT NOT NULL
149
+ );
150
+ `);
151
+ }
152
+ export function ensureRunControllerStorage(db) {
153
+ db.execSchema(`
154
+ CREATE TABLE IF NOT EXISTS run_controllers (
155
+ controller_id TEXT PRIMARY KEY,
156
+ project_id TEXT NOT NULL, run_id TEXT NOT NULL,
157
+ request_id TEXT NOT NULL, request_hash TEXT NOT NULL,
158
+ generation INTEGER NOT NULL, status TEXT NOT NULL,
159
+ owner_token TEXT NOT NULL, process_id TEXT, process_lease_token TEXT,
160
+ owner_pid INTEGER, manifest_json TEXT NOT NULL, state_json TEXT NOT NULL,
161
+ state_dir TEXT NOT NULL, last_error_json TEXT,
162
+ created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
163
+ FOREIGN KEY(project_id, run_id) REFERENCES runs(project_id, id),
164
+ UNIQUE(project_id, run_id, request_id)
165
+ );
166
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_run_controller_owner
167
+ ON run_controllers(project_id, run_id)
168
+ WHERE status NOT IN ('completed', 'cancelled', 'superseded');
169
+ CREATE TABLE IF NOT EXISTS run_controller_events (
170
+ sequence INTEGER PRIMARY KEY AUTOINCREMENT,
171
+ controller_id TEXT NOT NULL REFERENCES run_controllers(controller_id),
172
+ event_type TEXT NOT NULL, data_json TEXT NOT NULL, created_at TEXT NOT NULL
173
+ );
174
+ CREATE INDEX IF NOT EXISTS idx_run_controller_events
175
+ ON run_controller_events(controller_id, sequence);
176
+ CREATE TABLE IF NOT EXISTS run_controller_operations (
177
+ operation_id TEXT PRIMARY KEY,
178
+ controller_id TEXT NOT NULL REFERENCES run_controllers(controller_id),
179
+ generation INTEGER NOT NULL, input_hash TEXT NOT NULL,
180
+ input_json TEXT NOT NULL, status TEXT NOT NULL,
181
+ receipt_json TEXT, error_json TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL
182
+ );
183
+ `);
184
+ }
185
+ /** Recovery guards apply to every RUN kind, including custom eval fixtures. */
186
+ export function ensureRecoveryStorage(db) {
187
+ db.exec(`
188
+ CREATE TABLE IF NOT EXISTS run_recovery_guards (
189
+ recovery_id TEXT PRIMARY KEY, project_id TEXT NOT NULL, run_id TEXT NOT NULL, generation INTEGER NOT NULL, status TEXT NOT NULL, interruption_json TEXT NOT NULL, settlement_json TEXT, capture_path TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, sealed_at TEXT, resumed_at TEXT, UNIQUE(project_id, run_id, generation), FOREIGN KEY(project_id, run_id) REFERENCES runs(project_id, id)
190
+ );
191
+ CREATE INDEX IF NOT EXISTS idx_run_recovery_guards_run ON run_recovery_guards(project_id, run_id, generation DESC);
192
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_run_recovery_guards_active ON run_recovery_guards(project_id, run_id) WHERE status IN ('draining', 'sealed', 'resuming');
193
+ CREATE TABLE IF NOT EXISTS work_recovery_segments (
194
+ recovery_id TEXT NOT NULL, work_id TEXT NOT NULL, generation INTEGER NOT NULL, prior_started_at TEXT, evidence_path TEXT NOT NULL, status TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, PRIMARY KEY(recovery_id, work_id), FOREIGN KEY(recovery_id) REFERENCES run_recovery_guards(recovery_id), FOREIGN KEY(work_id) REFERENCES works(work_id)
195
+ );
196
+ CREATE INDEX IF NOT EXISTS idx_work_recovery_segments_work ON work_recovery_segments(work_id, generation DESC);
197
+ CREATE TABLE IF NOT EXISTS run_recovery_bindings (
198
+ recovery_id TEXT PRIMARY KEY REFERENCES run_recovery_guards(recovery_id),
199
+ work_id TEXT NOT NULL REFERENCES works(work_id), prior_work_session_id TEXT NOT NULL,
200
+ session_id TEXT NOT NULL, harness TEXT NOT NULL, provider_session_id TEXT NOT NULL,
201
+ daemon_id TEXT NOT NULL, status TEXT NOT NULL, hook_event_key TEXT,
202
+ created_at TEXT NOT NULL, accepted_at TEXT
203
+ );
204
+ `);
205
+ ensureColumn(db, "run_recovery_bindings", "packet_json", "ALTER TABLE run_recovery_bindings ADD COLUMN packet_json TEXT");
206
+ ensureColumn(db, "run_recovery_bindings", "packet_sha256", "ALTER TABLE run_recovery_bindings ADD COLUMN packet_sha256 TEXT");
207
+ ensureColumn(db, "run_recovery_bindings", "runtime_dispatch_json", "ALTER TABLE run_recovery_bindings ADD COLUMN runtime_dispatch_json TEXT");
208
+ }
10
209
  /** Creates the single Work/Session authority used by a fresh vNext beta runtime. */
11
210
  export function ensureVnextWorkStorage(db) {
12
211
  const legacy = db.get("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('vnext_works', 'vnext_agent_turns', 'flow_agent_turns') LIMIT 1");
@@ -16,7 +215,7 @@ export function ensureVnextWorkStorage(db) {
16
215
  if (existing && (!/task TEXT NOT NULL/.test(existing.sql) || /launch_token|adapter_session_id/.test(existing.sql))) {
17
216
  throw new AppError("beta_storage_recreate_required", "This beta requires a fresh DD_FLOW_HOME; the existing works schema is not compatible", 1);
18
217
  }
19
- db.exec(`
218
+ db.execSchema(`
20
219
  CREATE TABLE IF NOT EXISTS works (
21
220
  work_id TEXT PRIMARY KEY,
22
221
  project_id TEXT NOT NULL,
@@ -46,6 +245,9 @@ export function ensureVnextWorkStorage(db) {
46
245
  status TEXT NOT NULL,
47
246
  prompt_path TEXT NOT NULL,
48
247
  result_path TEXT,
248
+ start_receipt_json TEXT,
249
+ start_publication_status TEXT,
250
+ result_receipt_json TEXT,
49
251
  created_at TEXT NOT NULL,
50
252
  updated_at TEXT NOT NULL,
51
253
  completed_at TEXT,
@@ -53,6 +255,16 @@ export function ensureVnextWorkStorage(db) {
53
255
  );
54
256
  CREATE INDEX IF NOT EXISTS idx_work_sessions_work ON work_sessions(work_id, created_at DESC);
55
257
  CREATE UNIQUE INDEX IF NOT EXISTS idx_work_sessions_open ON work_sessions(work_id) WHERE status = 'running';
258
+
259
+ CREATE TABLE IF NOT EXISTS run_recovery_guards (
260
+ recovery_id TEXT PRIMARY KEY, project_id TEXT NOT NULL, run_id TEXT NOT NULL, generation INTEGER NOT NULL, status TEXT NOT NULL, interruption_json TEXT NOT NULL, settlement_json TEXT, capture_path TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, sealed_at TEXT, resumed_at TEXT, UNIQUE(project_id, run_id, generation), FOREIGN KEY(project_id, run_id) REFERENCES runs(project_id, id)
261
+ );
262
+ CREATE INDEX IF NOT EXISTS idx_run_recovery_guards_run ON run_recovery_guards(project_id, run_id, generation DESC);
263
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_run_recovery_guards_active ON run_recovery_guards(project_id, run_id) WHERE status IN ('draining', 'sealed', 'resuming');
264
+ CREATE TABLE IF NOT EXISTS work_recovery_segments (
265
+ recovery_id TEXT NOT NULL, work_id TEXT NOT NULL, generation INTEGER NOT NULL, prior_started_at TEXT, evidence_path TEXT NOT NULL, status TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, PRIMARY KEY(recovery_id, work_id), FOREIGN KEY(recovery_id) REFERENCES run_recovery_guards(recovery_id), FOREIGN KEY(work_id) REFERENCES works(work_id)
266
+ );
267
+ CREATE INDEX IF NOT EXISTS idx_work_recovery_segments_work ON work_recovery_segments(work_id, generation DESC);
56
268
  CREATE TABLE IF NOT EXISTS check_receipts (
57
269
  id TEXT PRIMARY KEY,
58
270
  project_id TEXT NOT NULL,
@@ -65,6 +277,9 @@ export function ensureVnextWorkStorage(db) {
65
277
  command TEXT NOT NULL,
66
278
  input_hash TEXT NOT NULL DEFAULT '',
67
279
  verification_epoch TEXT NOT NULL DEFAULT '',
280
+ reservation_sequence INTEGER NOT NULL DEFAULT 0,
281
+ retry_of_receipt_id TEXT,
282
+ retry_reason TEXT,
68
283
  status TEXT NOT NULL,
69
284
  exit_code INTEGER,
70
285
  stdout_path TEXT NOT NULL,
@@ -81,50 +296,232 @@ export function ensureVnextWorkStorage(db) {
81
296
  FOREIGN KEY(work_id) REFERENCES works(work_id)
82
297
  );
83
298
  CREATE INDEX IF NOT EXISTS idx_check_receipts_run ON check_receipts(project_id, run_id, started_at);
299
+ ${workContinuationStorageSql}
300
+ `);
301
+ // A committed Work start is authoritative even if publishing its prompt
302
+ // files is interrupted after commit. Keep the exact bytes for repair.
303
+ db.writeTransaction(() => {
304
+ const columns = db.all("PRAGMA table_info(work_sessions)");
305
+ if (!columns.some((column) => column.name === "start_receipt_json"))
306
+ db.execSchema("ALTER TABLE work_sessions ADD COLUMN start_receipt_json TEXT");
307
+ if (!columns.some((column) => column.name === "start_publication_status"))
308
+ db.execSchema("ALTER TABLE work_sessions ADD COLUMN start_publication_status TEXT");
309
+ if (!columns.some((column) => column.name === "result_receipt_json"))
310
+ db.execSchema("ALTER TABLE work_sessions ADD COLUMN result_receipt_json TEXT");
311
+ });
312
+ }
313
+ /** Durable intent for a provider-root external Work. It is deliberately
314
+ * separate from `work_sessions`: only a trusted hook may bind that Session. */
315
+ export function ensureWorkLaunchStorage(db) {
316
+ db.execSchema(`
317
+ CREATE TABLE IF NOT EXISTS work_launches (
318
+ operation_id TEXT PRIMARY KEY,
319
+ work_id TEXT NOT NULL UNIQUE,
320
+ profile_json TEXT NOT NULL,
321
+ profile_hash TEXT NOT NULL,
322
+ status TEXT NOT NULL,
323
+ state_dir TEXT NOT NULL,
324
+ journal_path TEXT NOT NULL,
325
+ provider_session_id TEXT,
326
+ adapter_receipt_json TEXT,
327
+ created_at TEXT NOT NULL,
328
+ updated_at TEXT NOT NULL,
329
+ FOREIGN KEY(work_id) REFERENCES works(work_id)
330
+ );
331
+ CREATE INDEX IF NOT EXISTS idx_work_launches_status ON work_launches(status, updated_at DESC);
84
332
  `);
85
333
  }
86
- export function getDatabase(ddFlowHome, mode = "initialize") {
334
+ export function getDatabase(ddFlowHome, mode = "initialize", importPermitId, hookDeadlineAt) {
335
+ channel("dd-flow.sqlite.ingress").publish({ phase: "store_open", store_kind: "run" });
336
+ if (hookDeadlineAt !== undefined && !Number.isSafeInteger(hookDeadlineAt))
337
+ throw new AppError("hook_deadline_invalid", "Deadline must be a finite absolute millisecond deadline", 1, { effect: "unknown" });
338
+ const deadline = hookDeadlineAt === undefined ? undefined : (phase) => {
339
+ const remaining = hookDeadlineAt - Date.now();
340
+ if (remaining <= 0)
341
+ throw new AppError("native_hook_timeout", "Native hook deadline expired before durable admission", 1, { phase, deadline_at: hookDeadlineAt, effect: "unknown" });
342
+ return Math.max(1, Math.min(4000, remaining));
343
+ };
344
+ deadline?.("store_open");
345
+ if (mode !== "read_existing")
346
+ assertImportAdmission(ddFlowHome, importPermitId);
87
347
  const dbPath = path.join(ddFlowHome, "db.sqlite");
88
348
  const exists = fs.existsSync(dbPath);
89
349
  if (mode === "read_existing" && !exists) {
90
350
  return emptyReadOnlyDatabase(dbPath);
91
351
  }
352
+ if (mode === "hook" && !exists)
353
+ throw new AppError("hook_storage_unprepared", "Prepare the runtime store before starting native hooks", 1);
92
354
  if (!exists || mode === "migrate")
93
355
  ensureDir(ddFlowHome);
94
356
  const db = mode === "read_existing" ? new DatabaseSync(dbPath, { readOnly: true }) : new DatabaseSync(dbPath);
95
- configureDatabase(db, mode);
357
+ try {
358
+ db.exec(`PRAGMA busy_timeout = ${deadline?.("store_open") ?? 4000}`);
359
+ }
360
+ catch (error) {
361
+ return closeAfterOpenFailure(db, error);
362
+ }
363
+ if (mode !== "read_existing") {
364
+ try {
365
+ registerStoreWriter(db);
366
+ }
367
+ catch (error) {
368
+ return closeAfterOpenFailure(db, error);
369
+ }
370
+ }
371
+ try {
372
+ configureDatabase(db, mode, deadline);
373
+ }
374
+ catch (error) {
375
+ return closeAfterOpenFailure(db, error);
376
+ }
96
377
  // Internal additive schema changes must be available to every write command.
97
378
  // Higher-level Memory Bank migrations remain explicit in services/migrations.
98
- if (mode !== "read_existing")
99
- migrate(db, dbPath);
379
+ if (mode !== "read_existing") {
380
+ try {
381
+ const initialize = () => { migrate(db); ensureRecoveryStorage(db); ensureLifecycleInvocationStorage(db); };
382
+ if (mode !== "hook") {
383
+ const fresh = !db.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' LIMIT 1").get();
384
+ if (fresh || readStoreWriterContract(db) !== null)
385
+ executeStoreSchema(db, initialize, fresh);
386
+ else
387
+ initialize();
388
+ // This migration owns a VACUUM backup and a separate data transaction.
389
+ migrateSessionStorageKeys(db, dbPath);
390
+ }
391
+ else {
392
+ deadline?.("store_validation");
393
+ assertHookStoreReady(db);
394
+ }
395
+ }
396
+ catch (error) {
397
+ return closeAfterOpenFailure(db, error);
398
+ }
399
+ }
100
400
  if (mode === "read_existing")
101
401
  db.exec("PRAGMA query_only = ON");
102
402
  db.exec("PRAGMA foreign_keys = ON");
103
- return {
104
- path: dbPath,
105
- writable: mode !== "read_existing",
106
- close: () => db.close?.(),
107
- exec: (sql) => db.exec(sql),
108
- run: (sql, params = []) => db.prepare(sql).run(...params),
109
- get: (sql, params = []) => db.prepare(sql).get(...params),
110
- all: (sql, params = []) => db.prepare(sql).all(...params)
403
+ return databaseFacade(dbPath, mode !== "read_existing", db, undefined, deadline);
404
+ }
405
+ /**
406
+ * Hook ingress is a hot, synchronous path. It may write receipts, but it
407
+ * must never perform schema migration or VACUUM while the native host waits.
408
+ * Startup/migration owns this contract; a missing table is an explicit
409
+ * preparation error instead of an implicit migration race.
410
+ */
411
+ function assertHookStoreReady(db) {
412
+ const required = ["projects", "hook_events", "codex_session_bindings", "sessions", "flow_session_segments", "lifecycle_invocations", "lifecycle_packet_assignments"];
413
+ const missing = required.filter((table) => !db.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?").get(table));
414
+ if (missing.length)
415
+ throw new AppError("hook_storage_unprepared", "Managed store is not prepared for synchronous hook admission", 1, { missing_tables: missing, next_action: "Open the runtime with a normal dd-flow command and complete migration before starting the native Session." });
416
+ // Table presence alone does not establish compatibility with an older home.
417
+ const receiptColumns = {
418
+ hook_events: "id, project_id, harness, provider_session_id, parent_session_id, daemon_id, session_id, agent_id, turn_id, event_name, tool_name, event_key, cwd, match_key, transcript_path, status, sanitized_summary, outcome_json, created_at",
419
+ lifecycle_invocations: "id, scope_json, command, fingerprint, status, event_key, identity_json, deadline, outcome_json, created_at, updated_at",
420
+ codex_session_bindings: "session_id, project_id, protocol_id, handshake_id, cwd, transcript_path, status, created_at, updated_at"
111
421
  };
422
+ for (const [table, columns] of Object.entries(receiptColumns)) {
423
+ try {
424
+ db.prepare(`SELECT ${columns} FROM ${table} LIMIT 0`);
425
+ }
426
+ catch {
427
+ throw new AppError("hook_storage_unprepared", "Managed receipt schema needs preparation before native hooks start", 1, { table });
428
+ }
429
+ }
112
430
  }
113
431
  /**
114
432
  * Opens the small host-wide resource registry. It is intentionally separate
115
433
  * from a RUN database: a process or a port can outlive the CLI client that
116
434
  * created it, while a RUN database belongs to one flow home.
117
435
  */
118
- export function getResourceDatabase(resourceHome) {
119
- ensureDir(resourceHome);
436
+ export function withResourceReadSnapshot(resourceHome, read) {
120
437
  const dbPath = path.join(resourceHome, "runtime.sqlite");
121
438
  const cached = resourceDatabases.get(dbPath);
439
+ if (!cached && !fs.existsSync(dbPath))
440
+ return read(emptyReadOnlyDatabase(dbPath));
441
+ const db = cached ?? new DatabaseSync(dbPath, { readOnly: true });
442
+ const operation = () => {
443
+ if (!cached)
444
+ db.exec("PRAGMA busy_timeout = 4000; PRAGMA query_only = ON");
445
+ // A second process can observe SQLite's file before the initializing
446
+ // transaction publishes its schema. Treat that pre-commit view exactly
447
+ // like an absent registry; the writer path remains the serialization
448
+ // boundary and will reopen the committed schema.
449
+ if (!cached && !db.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' LIMIT 1").get()) {
450
+ return read(emptyReadOnlyDatabase(dbPath));
451
+ }
452
+ const reader = cached
453
+ ? { ...emptyReadOnlyDatabase(dbPath), get: cached.get, all: cached.all }
454
+ : databaseFacade(dbPath, false, db);
455
+ // The facade owns savepoint cleanup and poisons a connection when rollback
456
+ // fails; the callback only receives the read-only view.
457
+ return (cached ?? reader).readSnapshot(() => read(reader));
458
+ };
122
459
  if (cached)
123
- return cached;
460
+ return operation();
461
+ const native = db;
462
+ return withStoreCleanup(operation, () => { if (native.isOpen)
463
+ native.close(); });
464
+ }
465
+ export function getResourceDatabase(resourceHome, mode = "initialize", deadlineAt) {
466
+ channel("dd-flow.sqlite.ingress").publish({ phase: "store_open", store_kind: "resource" });
467
+ const deadline = requestDeadline(deadlineAt);
468
+ deadline?.("resource_open");
469
+ const dbPath = path.join(resourceHome, "runtime.sqlite");
470
+ const cached = resourceDatabases.get(dbPath);
471
+ if (mode === "read_existing" || mode === "read_isolated") {
472
+ // Reuse a current transaction's view without exposing its write capability.
473
+ if (cached && mode === "read_existing") {
474
+ const bounded = deadlineAt === undefined ? cached : cached.withDeadline(deadlineAt);
475
+ return { ...emptyReadOnlyDatabase(dbPath), get: bounded.get, all: bounded.all };
476
+ }
477
+ if (!fs.existsSync(dbPath))
478
+ return emptyReadOnlyDatabase(dbPath);
479
+ const db = new DatabaseSync(dbPath, { readOnly: true });
480
+ try {
481
+ db.exec(`PRAGMA busy_timeout = ${deadline?.("resource_open") ?? 4000}; PRAGMA query_only = ON`);
482
+ if (!db.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' LIMIT 1").get()) {
483
+ db.close();
484
+ return emptyReadOnlyDatabase(dbPath);
485
+ }
486
+ }
487
+ catch (error) {
488
+ return closeAfterOpenFailure(db, error);
489
+ }
490
+ return databaseFacade(dbPath, false, db, undefined, deadline);
491
+ }
492
+ if (mode === "prepared_existing" && !fs.existsSync(dbPath))
493
+ throw new AppError("resource_storage_unprepared", "Prepare the resource registry before maintenance", 1);
494
+ if (cached) {
495
+ const bounded = deadlineAt === undefined ? cached : cached.withDeadline(deadlineAt);
496
+ if (mode === "prepared_existing")
497
+ assertResourceStoreReady({ prepare: sql => ({ get: (...params) => bounded.get(sql, params), all: (...params) => bounded.all(sql, params), run: (...params) => bounded.run(sql, params) }) });
498
+ return bounded;
499
+ }
500
+ if (mode !== "prepared_existing")
501
+ ensureDir(resourceHome);
124
502
  const db = new DatabaseSync(dbPath);
125
- configureDatabase(db, "initialize");
503
+ db.exec(`PRAGMA busy_timeout = ${deadline?.("resource_open") ?? 4000}`);
504
+ try {
505
+ registerStoreWriter(db);
506
+ }
507
+ catch (error) {
508
+ return closeAfterOpenFailure(db, error);
509
+ }
510
+ channel("dd-flow.sqlite.ingress").publish({ phase: "store_validation", store_kind: "resource" });
511
+ try {
512
+ if (mode === "prepared_existing")
513
+ assertResourceStoreReady(db);
514
+ else
515
+ configureDatabase(db, "initialize", deadline);
516
+ }
517
+ catch (error) {
518
+ return closeAfterOpenFailure(db, error);
519
+ }
126
520
  db.exec("PRAGMA foreign_keys = ON");
127
- db.exec(`
521
+ const fresh = !db.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' LIMIT 1").get();
522
+ try {
523
+ if (mode !== "prepared_existing")
524
+ executeStoreSchema(db, `
128
525
  CREATE TABLE IF NOT EXISTS managed_processes (
129
526
  id TEXT PRIMARY KEY,
130
527
  kind TEXT NOT NULL,
@@ -163,37 +560,356 @@ export function getResourceDatabase(resourceHome) {
163
560
  );
164
561
  CREATE INDEX IF NOT EXISTS idx_managed_resources_lease
165
562
  ON managed_resources(lease_expires_at, updated_at);
166
- `);
167
- const database = {
168
- path: dbPath,
169
- writable: true,
170
- close: () => { resourceDatabases.delete(dbPath); db.close?.(); },
171
- exec: (sql) => db.exec(sql),
172
- run: (sql, params = []) => db.prepare(sql).run(...params),
173
- get: (sql, params = []) => db.prepare(sql).get(...params),
174
- all: (sql, params = []) => db.prepare(sql).all(...params)
175
- };
563
+ `, fresh);
564
+ }
565
+ catch (error) {
566
+ return closeAfterOpenFailure(db, error);
567
+ }
568
+ const database = databaseFacade(dbPath, true, db, () => {
569
+ resourceDatabases.delete(dbPath);
570
+ db.close?.();
571
+ });
176
572
  resourceDatabases.set(dbPath, database);
177
- return database;
573
+ return deadlineAt === undefined ? database : database.withDeadline(deadlineAt);
574
+ }
575
+ function requestDeadline(at) {
576
+ if (at === undefined)
577
+ return undefined;
578
+ if (!Number.isSafeInteger(at))
579
+ throw new AppError("maintenance_deadline_invalid", "Maintenance deadline must be an absolute millisecond timestamp", 1);
580
+ return phase => { const remaining = at - Date.now(); if (remaining <= 0)
581
+ throw new AppError("process_heartbeat_timeout", "Maintenance storage deadline expired", 1, { phase, deadline_at: at, effect: "unknown" }); return Math.max(1, Math.min(4000, remaining)); };
582
+ }
583
+ function assertResourceStoreReady(db) {
584
+ const version = readStoreWriterContract(db);
585
+ if (version === null)
586
+ throw new AppError("resource_storage_unprepared", "Prepare the resource registry writer contract before maintenance", 1);
587
+ if (version !== STORE_WRITER_VERSION)
588
+ throw new AppError("store_writer_incompatible", "This CLI cannot maintain the resource registry's required contract", 1, { required: version, supported: STORE_WRITER_VERSION });
589
+ for (const [table, columns] of Object.entries({ managed_processes: "id,kind,pid,pid_started_at,owner_id,lease_token,lease_expires_at,project_id,run_id,work_id,check_id,operation_id,stdout_path,stderr_path,state,started_at,updated_at,finished_at,termination_reason,metadata_json", managed_resources: "resource_kind,resource_key,owner_id,lease_token,lease_expires_at,process_id,metadata_json,created_at,updated_at" })) {
590
+ try {
591
+ db.prepare(`SELECT ${columns} FROM ${table} LIMIT 0`);
592
+ }
593
+ catch {
594
+ throw new AppError("resource_storage_unprepared", "Prepare the resource registry schema before maintenance", 1, { table });
595
+ }
596
+ }
597
+ for (const name of ["idx_managed_processes_lease", "idx_managed_resources_lease"])
598
+ if (!db.prepare("SELECT 1 FROM sqlite_schema WHERE type='index' AND name=?").get(name))
599
+ throw new AppError("resource_storage_unprepared", "Prepare resource registry indexes before maintenance", 1, { index: name });
178
600
  }
179
601
  function emptyReadOnlyDatabase(dbPath) {
180
602
  return {
181
603
  path: dbPath,
182
604
  writable: false,
183
605
  exec: () => { throw new AppError("read_only_storage", "Read-only access cannot write absent dd-flow storage", 1, { path: dbPath }); },
606
+ execSchema: () => { throw new AppError("read_only_storage", "Read-only access cannot write absent dd-flow storage", 1, { path: dbPath }); },
607
+ beginWriteTransaction: () => { throw new AppError("read_only_storage", "Read-only access cannot start a write transaction", 1, { path: dbPath }); },
608
+ writeTransaction: () => { throw new AppError("read_only_storage", "Read-only access cannot start a write transaction", 1, { path: dbPath }); },
609
+ readSnapshot: (operation) => operation(),
610
+ afterCommit: () => { throw new AppError("read_only_storage", "Read-only access cannot publish absent dd-flow storage", 1, { path: dbPath }); },
184
611
  run: () => { throw new AppError("read_only_storage", "Read-only access cannot write absent dd-flow storage", 1, { path: dbPath }); },
185
612
  get: () => undefined,
186
613
  all: () => []
187
614
  };
188
615
  }
189
- function configureDatabase(db, mode) {
190
- db.exec("PRAGMA busy_timeout = 4000");
616
+ function databaseFacade(dbPath, writable, db, close = () => db.close?.(), deadline) {
617
+ let scopedDeadline = deadline;
618
+ let reserved = false;
619
+ let poisoned = false;
620
+ let closed = false;
621
+ const closeOnce = () => { if (closed || !db.isOpen) {
622
+ closed = true;
623
+ return;
624
+ } closed = true; close(); };
625
+ let savepoint = 0;
626
+ let afterCommit = [];
627
+ let manualFrames = [];
628
+ let readDepth = 0;
629
+ const writerTiming = channel("dd-flow.sqlite.writer");
630
+ const ingressPhase = channel("dd-flow.sqlite.ingress");
631
+ const storeKind = path.basename(dbPath) === "runtime.sqlite" ? "resource" : "run";
632
+ const bound = (phase) => {
633
+ const remaining = scopedDeadline?.(phase);
634
+ if (remaining !== undefined)
635
+ db.exec(`PRAGMA busy_timeout = ${remaining}`);
636
+ if (ingressPhase.hasSubscribers)
637
+ ingressPhase.publish({ phase, store_kind: storeKind, ...(remaining !== undefined ? { remaining_ms: remaining } : {}) });
638
+ };
639
+ const publishCommitted = () => {
640
+ const pending = afterCommit;
641
+ afterCommit = [];
642
+ const scope = publicationScopes.at(-1);
643
+ if (scope)
644
+ scope.push(...pending);
645
+ else
646
+ executePublications(pending);
647
+ };
648
+ const assertUsable = () => { if (poisoned || closed || !db.isOpen)
649
+ throw new AppError("write_transaction_unresolved", "Transaction cleanup failed or the connection is closed; reopen the connection before continuing", 1); };
650
+ const beginWriteTransaction = () => {
651
+ assertUsable();
652
+ if (readDepth)
653
+ throw new AppError("read_snapshot_write", "Cannot reserve a writer inside a read snapshot", 1);
654
+ if (!writable)
655
+ throw new AppError("read_only_storage", "Read-only access cannot start a write transaction", 1, { path: dbPath });
656
+ bound("writer_reservation");
657
+ db.exec("BEGIN IMMEDIATE");
658
+ reserved = true;
659
+ if (ingressPhase.hasSubscribers)
660
+ ingressPhase.publish({ phase: "writer_reserved", store_kind: storeKind });
661
+ };
662
+ const rollback = (sql, original) => {
663
+ try {
664
+ db.exec(sql);
665
+ }
666
+ catch (cleanup) {
667
+ poisoned = true;
668
+ let closeError;
669
+ try {
670
+ closeOnce();
671
+ }
672
+ catch (error) {
673
+ closeError = errorDetails(error);
674
+ }
675
+ const secondary = { transaction_cleanup_error: errorDetails(cleanup), ...(closeError ? { transaction_close_error: closeError } : {}) };
676
+ if (original instanceof AppError)
677
+ throw new AppError(original.code, original.message, original.exitCode, { ...original.details, ...secondary });
678
+ throw new AppError("write_transaction_failed", "Write transaction failed and SQLite cleanup also failed", 1, { cause: errorDetails(original), ...secondary });
679
+ }
680
+ throw original;
681
+ };
682
+ const writeTransaction = (operation, operationName = "writeTransaction") => {
683
+ assertUsable();
684
+ if (readDepth)
685
+ throw new AppError("read_snapshot_write", "Cannot reserve a writer inside a read snapshot", 1);
686
+ if (!writable)
687
+ throw new AppError("read_only_storage", "Read-only access cannot start a write transaction", 1, { path: dbPath });
688
+ if (db.isTransaction && !reserved)
689
+ throw new AppError("write_transaction_unowned", "Cannot write inside an unowned transaction or read snapshot", 1);
690
+ const nested = db.isTransaction;
691
+ const callbackLength = afterCommit.length;
692
+ const marker = `dd_flow_write_${++savepoint}`;
693
+ const startedAt = performance.now();
694
+ try {
695
+ if (nested)
696
+ db.exec(`SAVEPOINT ${marker}`);
697
+ else
698
+ beginWriteTransaction();
699
+ }
700
+ catch (error) {
701
+ if (error instanceof AppError)
702
+ throw error;
703
+ throw new AppError("storage_write_failed", "Cannot reserve SQLite writer", 1, { cause: errorDetails(error), transaction_phase: "begin", transaction_rolled_back: true });
704
+ }
705
+ let phase = "body";
706
+ try {
707
+ const value = operation();
708
+ if (value && typeof value.then === "function") {
709
+ void Promise.resolve(value).catch(() => { });
710
+ throw new AppError("write_transaction_async", "Write transaction callback must be synchronous", 1);
711
+ }
712
+ phase = "commit";
713
+ bound("commit");
714
+ if (nested)
715
+ db.exec(`RELEASE ${marker}`);
716
+ else
717
+ db.exec("COMMIT");
718
+ phase = "committed";
719
+ if (!nested && ingressPhase.hasSubscribers)
720
+ ingressPhase.publish({ phase: "committed", store_kind: storeKind });
721
+ if (!nested && writerTiming.hasSubscribers)
722
+ writerTiming.publish({ operation: operationName, wall_time_ms: performance.now() - startedAt, path: dbPath });
723
+ if (!nested)
724
+ publishCommitted();
725
+ return value;
726
+ }
727
+ catch (error) {
728
+ if (phase === "committed")
729
+ throw error;
730
+ afterCommit.length = callbackLength;
731
+ try {
732
+ return rollback(nested ? `ROLLBACK TO ${marker}; RELEASE ${marker}` : "ROLLBACK", error);
733
+ }
734
+ catch (failure) {
735
+ if (failure === error && !(error instanceof AppError) && typeof error === "object" && error !== null && "code" in error && String(error.code).startsWith("ERR_SQLITE"))
736
+ throw new AppError("storage_write_failed", "SQLite write failed", 1, { cause: errorDetails(error), transaction_phase: phase, transaction_rolled_back: true });
737
+ throw failure;
738
+ }
739
+ }
740
+ finally {
741
+ if (closed || !db.isOpen || !db.isTransaction) {
742
+ reserved = false;
743
+ if (phase !== "committed") {
744
+ afterCommit = [];
745
+ manualFrames = [];
746
+ }
747
+ }
748
+ }
749
+ };
750
+ const readSnapshot = (operation) => {
751
+ assertUsable();
752
+ const nested = db.isTransaction;
753
+ const marker = `dd_flow_read_${++savepoint}`;
754
+ const callbackLength = afterCommit.length;
755
+ try {
756
+ db.exec(nested ? `SAVEPOINT ${marker}` : "BEGIN");
757
+ }
758
+ catch (error) {
759
+ throw new AppError("read_snapshot_failed", "Cannot start SQLite read snapshot", 1, { cause: errorDetails(error) });
760
+ }
761
+ readDepth += 1;
762
+ let phase = "body";
763
+ try {
764
+ const value = operation();
765
+ if (value && typeof value.then === "function") {
766
+ void Promise.resolve(value).catch(() => { });
767
+ throw new AppError("read_snapshot_async", "Read snapshot callback must be synchronous", 1);
768
+ }
769
+ phase = "commit";
770
+ db.exec(nested ? `RELEASE ${marker}` : "COMMIT");
771
+ phase = "committed";
772
+ return value;
773
+ }
774
+ catch (error) {
775
+ if (phase === "committed")
776
+ throw error;
777
+ afterCommit.length = callbackLength;
778
+ return rollback(nested ? `ROLLBACK TO ${marker}; RELEASE ${marker}` : "ROLLBACK", error);
779
+ }
780
+ finally {
781
+ readDepth -= 1;
782
+ }
783
+ };
784
+ const applyManualBoundary = (sql) => {
785
+ for (const statement of sql.split(";")) {
786
+ const save = /^\s*SAVEPOINT\s+([\w-]+)/i.exec(statement);
787
+ if (save) {
788
+ manualFrames.push({ name: save[1], length: afterCommit.length });
789
+ continue;
790
+ }
791
+ const rollbackTo = /^\s*ROLLBACK\s+TO(?:\s+SAVEPOINT)?\s+([\w-]+)/i.exec(statement);
792
+ if (rollbackTo) {
793
+ const frame = manualFrames.findLastIndex((item) => item.name === rollbackTo[1]);
794
+ if (frame >= 0) {
795
+ afterCommit.length = manualFrames[frame].length;
796
+ manualFrames.length = frame + 1;
797
+ }
798
+ continue;
799
+ }
800
+ const release = /^\s*RELEASE(?:\s+SAVEPOINT)?\s+([\w-]+)/i.exec(statement);
801
+ if (release) {
802
+ const frame = manualFrames.findLastIndex((item) => item.name === release[1]);
803
+ if (frame >= 0)
804
+ manualFrames.length = frame;
805
+ continue;
806
+ }
807
+ if (/^\s*ROLLBACK\b/i.test(statement)) {
808
+ afterCommit = [];
809
+ manualFrames = [];
810
+ continue;
811
+ }
812
+ if (/^\s*COMMIT\b/i.test(statement)) {
813
+ manualFrames = [];
814
+ publishCommitted();
815
+ }
816
+ }
817
+ };
818
+ const facade = {
819
+ path: dbPath,
820
+ writable,
821
+ close: closeOnce,
822
+ exec: (sql) => {
823
+ assertUsable();
824
+ if (readDepth)
825
+ throw new AppError("read_snapshot_write", "Cannot execute SQL inside a read snapshot", 1);
826
+ try {
827
+ db.exec(sql);
828
+ applyManualBoundary(sql);
829
+ }
830
+ catch (error) {
831
+ if (/^\s*ROLLBACK\b/i.test(sql)) {
832
+ poisoned = true;
833
+ try {
834
+ closeOnce();
835
+ }
836
+ catch { /* Keep the primary SQLite failure. */ }
837
+ }
838
+ throw error;
839
+ }
840
+ finally {
841
+ if (closed || !db.isOpen || !db.isTransaction) {
842
+ reserved = false;
843
+ if (!/^\s*COMMIT\b/i.test(sql)) {
844
+ afterCommit = [];
845
+ manualFrames = [];
846
+ }
847
+ }
848
+ }
849
+ },
850
+ execSchema: (sql) => { assertUsable(); if (db.isTransaction && !reserved)
851
+ throw new AppError("write_transaction_unowned", "Cannot change schema inside an unowned transaction", 1); executeStoreSchema(db, sql); },
852
+ beginWriteTransaction,
853
+ writeTransaction,
854
+ readSnapshot,
855
+ afterCommit: (operation) => { assertUsable(); if (readDepth)
856
+ throw new AppError("read_snapshot_write", "Cannot queue publication inside a read snapshot", 1); if (db.isTransaction)
857
+ afterCommit.push(operation);
858
+ else {
859
+ const scope = publicationScopes.at(-1);
860
+ if (scope)
861
+ scope.push(operation);
862
+ else
863
+ executePublications([operation]);
864
+ } },
865
+ run: (sql, params = []) => { assertUsable(); if (readDepth)
866
+ throw new AppError("read_snapshot_write", "Cannot write inside a read snapshot", 1); bound("write"); return db.prepare(sql).run(...params); },
867
+ get: (sql, params = []) => { assertUsable(); bound("lookup"); return db.prepare(sql).get(...params); },
868
+ all: (sql, params = []) => { assertUsable(); bound("lookup"); return db.prepare(sql).all(...params); }
869
+ };
870
+ facade.withDeadline = (at) => {
871
+ const bounded = requestDeadline(at);
872
+ const scoped = (operation) => { const previous = scopedDeadline; scopedDeadline = phase => Math.min(bounded(phase), previous?.(phase) ?? 4000); try {
873
+ return operation();
874
+ }
875
+ finally {
876
+ scopedDeadline = previous;
877
+ if (db.isOpen)
878
+ db.exec("PRAGMA busy_timeout = 4000");
879
+ } };
880
+ return { ...facade, exec: sql => scoped(() => facade.exec(sql)), execSchema: sql => scoped(() => facade.execSchema(sql)), beginWriteTransaction: () => scoped(() => facade.beginWriteTransaction()), writeTransaction: (operation, name) => scoped(() => facade.writeTransaction(operation, name)), readSnapshot: operation => scoped(() => facade.readSnapshot(operation)), get: (sql, params) => scoped(() => facade.get(sql, params)), all: (sql, params) => scoped(() => facade.all(sql, params)), run: (sql, params) => scoped(() => facade.run(sql, params)) };
881
+ };
882
+ return facade;
883
+ }
884
+ function errorDetails(error) {
885
+ const value = error;
886
+ return { message: String(value?.message ?? error), ...(typeof value?.code === "string" ? { code: value.code } : {}), ...(typeof value?.errcode === "number" ? { sqlite_extended_code: value.errcode } : {}) };
887
+ }
888
+ function configureDatabase(db, mode, ingressDeadline) {
191
889
  if (mode !== "read_existing") {
192
- db.exec("PRAGMA journal_mode = WAL");
890
+ // Concurrent first openers can collide while changing journal mode, even
891
+ // with busy_timeout set. Retrying this configuration does not replay writes.
892
+ const deadline = performance.now() + 4000, pause = new Int32Array(new SharedArrayBuffer(4));
893
+ for (;;) {
894
+ try {
895
+ const remaining = ingressDeadline?.("store_configuration");
896
+ if (remaining !== undefined)
897
+ db.exec(`PRAGMA busy_timeout = ${remaining}`);
898
+ const current = db.prepare("PRAGMA journal_mode").get();
899
+ if (current.journal_mode !== "wal")
900
+ db.exec("PRAGMA journal_mode = WAL");
901
+ break;
902
+ }
903
+ catch (error) {
904
+ if ((error.errcode ?? 0) % 256 !== 5 || performance.now() >= deadline)
905
+ throw error;
906
+ Atomics.wait(pause, 0, 0, Math.min(25, Math.max(1, deadline - performance.now())));
907
+ }
908
+ }
193
909
  db.exec("PRAGMA synchronous = NORMAL");
194
910
  }
195
911
  }
196
- function migrate(db, dbPath) {
912
+ function migrate(db) {
197
913
  db.exec(`
198
914
  CREATE TABLE IF NOT EXISTS projects (
199
915
  id TEXT PRIMARY KEY,
@@ -229,6 +945,7 @@ function migrate(db, dbPath) {
229
945
  CREATE TABLE IF NOT EXISTS plan_bindings (
230
946
  project_id TEXT NOT NULL,
231
947
  protocol_id TEXT NOT NULL,
948
+ plan_id TEXT,
232
949
  plan_revision INTEGER NOT NULL,
233
950
  plan_sha256 TEXT NOT NULL,
234
951
  plan_path TEXT NOT NULL,
@@ -551,6 +1268,8 @@ function migrate(db, dbPath) {
551
1268
  CREATE INDEX IF NOT EXISTS idx_check_receipts_run
552
1269
  ON check_receipts(project_id, run_id, started_at);
553
1270
 
1271
+ ${workContinuationStorageSql}
1272
+
554
1273
  CREATE TABLE IF NOT EXISTS merge_requests (
555
1274
  merge_request_id TEXT PRIMARY KEY,
556
1275
  project_id TEXT NOT NULL,
@@ -799,7 +1518,6 @@ function migrate(db, dbPath) {
799
1518
  ensureColumn(db, "sessions", "plan_item_id", "ALTER TABLE sessions ADD COLUMN plan_item_id TEXT");
800
1519
  ensureColumn(db, "sessions", "session_kind", "ALTER TABLE sessions ADD COLUMN session_kind TEXT");
801
1520
  ensureColumn(db, "sessions", "coverage_units_json", "ALTER TABLE sessions ADD COLUMN coverage_units_json TEXT NOT NULL DEFAULT '[]'");
802
- migrateSessionStorageKeys(db, dbPath);
803
1521
  ensureColumn(db, "usage", "cache_read_input_tokens", "ALTER TABLE usage ADD COLUMN cache_read_input_tokens INTEGER");
804
1522
  ensureColumn(db, "usage", "cache_write_input_tokens", "ALTER TABLE usage ADD COLUMN cache_write_input_tokens INTEGER");
805
1523
  ensureColumn(db, "usage", "uncached_input_tokens", "ALTER TABLE usage ADD COLUMN uncached_input_tokens INTEGER");
@@ -809,17 +1527,40 @@ function migrate(db, dbPath) {
809
1527
  ensureColumn(db, "usage", "source_mtime_ms", "ALTER TABLE usage ADD COLUMN source_mtime_ms INTEGER");
810
1528
  db.prepare("UPDATE usage SET cache_read_input_tokens = cached_input_tokens WHERE cache_read_input_tokens IS NULL AND cached_input_tokens IS NOT NULL").run();
811
1529
  ensureColumn(db, "runs", "run_home_path", "ALTER TABLE runs ADD COLUMN run_home_path TEXT");
1530
+ ensureColumn(db, "plan_bindings", "plan_id", "ALTER TABLE plan_bindings ADD COLUMN plan_id TEXT");
1531
+ // Historical RUN projections already retain the canonical identifier. Use
1532
+ // those SQL bytes to backfill without opening plan files under the writer.
1533
+ for (const row of db.prepare("SELECT project_id, protocol_id FROM plan_bindings WHERE plan_id IS NULL").all()) {
1534
+ const runs = db.prepare("SELECT index_json FROM runs WHERE project_id = ? AND subject_type = 'protocol' AND subject_id = ? ORDER BY updated_at DESC").all(row.project_id, row.protocol_id);
1535
+ for (const run of runs) {
1536
+ try {
1537
+ const planId = JSON.parse(run.index_json).plan_ref?.plan_id;
1538
+ if (typeof planId !== "string" || !planId || planId === "unknown-plan")
1539
+ continue;
1540
+ db.prepare("UPDATE plan_bindings SET plan_id = ? WHERE project_id = ? AND protocol_id = ? AND plan_id IS NULL").run(planId, row.project_id, row.protocol_id);
1541
+ break;
1542
+ }
1543
+ catch { /* A malformed historical RUN cannot establish plan identity. */ }
1544
+ }
1545
+ }
812
1546
  ensureColumn(db, "runs", "run_root", "ALTER TABLE runs ADD COLUMN run_root TEXT");
813
1547
  db.prepare("UPDATE runs SET run_root = COALESCE(run_root, run_home_path, run_dir) WHERE run_root IS NULL OR run_root = ''").run();
814
1548
  ensureColumn(db, "merge_requests", "accepted_tree", "ALTER TABLE merge_requests ADD COLUMN accepted_tree TEXT");
815
1549
  ensureColumn(db, "merge_requests", "replacement_of_merge_request_id", "ALTER TABLE merge_requests ADD COLUMN replacement_of_merge_request_id TEXT");
816
1550
  // A failed integration gate may create a new immutable source candidate in
817
1551
  // the same RUN. The historical unique index made that repair path impossible.
818
- db.exec("DROP INDEX IF EXISTS idx_merge_requests_run");
1552
+ // Rebuilding an already-current index changes schema/data_version on every
1553
+ // CLI observation and prevents a controller's writer barrier from settling.
1554
+ const mergeRunIndex = db.prepare("PRAGMA index_list(merge_requests)").all().find(index => index.name === "idx_merge_requests_run");
1555
+ if (mergeRunIndex?.unique)
1556
+ db.exec("DROP INDEX idx_merge_requests_run");
819
1557
  db.exec("CREATE INDEX IF NOT EXISTS idx_merge_requests_run ON merge_requests(project_id, run_id, created_at)");
820
1558
  ensureColumn(db, "runs", "layout_version", "ALTER TABLE runs ADD COLUMN layout_version TEXT");
821
1559
  ensureColumn(db, "runs", "artifact_root_kind", "ALTER TABLE runs ADD COLUMN artifact_root_kind TEXT");
822
1560
  ensureColumn(db, "works", "payload_json", "ALTER TABLE works ADD COLUMN payload_json TEXT");
1561
+ ensureColumn(db, "work_sessions", "start_receipt_json", "ALTER TABLE work_sessions ADD COLUMN start_receipt_json TEXT");
1562
+ ensureColumn(db, "work_sessions", "start_publication_status", "ALTER TABLE work_sessions ADD COLUMN start_publication_status TEXT");
1563
+ ensureColumn(db, "work_sessions", "result_receipt_json", "ALTER TABLE work_sessions ADD COLUMN result_receipt_json TEXT");
823
1564
  ensureColumn(db, "check_receipts", "declaration_id", "ALTER TABLE check_receipts ADD COLUMN declaration_id TEXT NOT NULL DEFAULT 'CHK-LEGACY'");
824
1565
  ensureColumn(db, "check_receipts", "workspace_fingerprint", "ALTER TABLE check_receipts ADD COLUMN workspace_fingerprint TEXT NOT NULL DEFAULT ''");
825
1566
  ensureColumn(db, "check_receipts", "artifacts_json", "ALTER TABLE check_receipts ADD COLUMN artifacts_json TEXT NOT NULL DEFAULT '[]'");
@@ -827,6 +1568,9 @@ function migrate(db, dbPath) {
827
1568
  ensureColumn(db, "check_receipts", "gate", "ALTER TABLE check_receipts ADD COLUMN gate TEXT NOT NULL DEFAULT 'work'");
828
1569
  ensureColumn(db, "check_receipts", "input_hash", "ALTER TABLE check_receipts ADD COLUMN input_hash TEXT NOT NULL DEFAULT ''");
829
1570
  ensureColumn(db, "check_receipts", "verification_epoch", "ALTER TABLE check_receipts ADD COLUMN verification_epoch TEXT NOT NULL DEFAULT ''");
1571
+ ensureColumn(db, "check_receipts", "reservation_sequence", "ALTER TABLE check_receipts ADD COLUMN reservation_sequence INTEGER NOT NULL DEFAULT 0");
1572
+ ensureColumn(db, "check_receipts", "retry_of_receipt_id", "ALTER TABLE check_receipts ADD COLUMN retry_of_receipt_id TEXT");
1573
+ ensureColumn(db, "check_receipts", "retry_reason", "ALTER TABLE check_receipts ADD COLUMN retry_reason TEXT");
830
1574
  ensureColumn(db, "check_receipts", "before_fingerprint", "ALTER TABLE check_receipts ADD COLUMN before_fingerprint TEXT NOT NULL DEFAULT ''");
831
1575
  ensureColumn(db, "check_receipts", "after_fingerprint", "ALTER TABLE check_receipts ADD COLUMN after_fingerprint TEXT NOT NULL DEFAULT ''");
832
1576
  ensureColumn(db, "check_receipts", "profile_hash", "ALTER TABLE check_receipts ADD COLUMN profile_hash TEXT");
@@ -846,6 +1590,7 @@ function migrate(db, dbPath) {
846
1590
  ensureColumn(db, "hook_events", "parent_session_id", "ALTER TABLE hook_events ADD COLUMN parent_session_id TEXT");
847
1591
  ensureColumn(db, "hook_events", "daemon_id", "ALTER TABLE hook_events ADD COLUMN daemon_id TEXT");
848
1592
  ensureColumn(db, "hook_events", "cwd", "ALTER TABLE hook_events ADD COLUMN cwd TEXT");
1593
+ ensureColumn(db, "hook_events", "outcome_json", "ALTER TABLE hook_events ADD COLUMN outcome_json TEXT");
849
1594
  ensureColumn(db, "harness_usage_snapshots", "tool_calls", "ALTER TABLE harness_usage_snapshots ADD COLUMN tool_calls INTEGER");
850
1595
  ensureColumn(db, "harness_usage_snapshots", "tool_failures", "ALTER TABLE harness_usage_snapshots ADD COLUMN tool_failures INTEGER");
851
1596
  ensureColumn(db, "harness_usage_snapshots", "tool_by_name_json", "ALTER TABLE harness_usage_snapshots ADD COLUMN tool_by_name_json TEXT");
@@ -908,8 +1653,7 @@ function migrateSessionStorageKeys(db, dbPath) {
908
1653
  db.exec("COMMIT");
909
1654
  }
910
1655
  catch (error) {
911
- db.exec("ROLLBACK");
912
- throw error;
1656
+ return rollbackStoreTransaction(db, "ROLLBACK", error);
913
1657
  }
914
1658
  }
915
1659
  function storageSessionKey(harness, native) {