@indigoai-us/hq-cli 5.345.214 → 5.345.215-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/command-catalog.generated.d.ts +134 -7
  3. package/dist/command-catalog.generated.js +168 -7
  4. package/dist/commands/agents.d.ts +51 -1
  5. package/dist/commands/agents.js +154 -2
  6. package/dist/commands/bot-jobs.d.ts +2 -15
  7. package/dist/commands/bot-jobs.js +2 -94
  8. package/dist/commands/bot-runtime.d.ts +46 -5
  9. package/dist/commands/bot-runtime.js +228 -18
  10. package/dist/commands/bot.d.ts +16 -9
  11. package/dist/commands/bot.js +169 -51
  12. package/dist/commands/cloud.d.ts +66 -13
  13. package/dist/commands/cloud.js +120 -39
  14. package/dist/commands/company-restore.d.ts +23 -0
  15. package/dist/commands/company-restore.js +128 -0
  16. package/dist/commands/company.js +2 -0
  17. package/dist/commands/integrations-connect.d.ts +10 -3
  18. package/dist/commands/integrations-connect.js +87 -13
  19. package/dist/commands/lanes.js +26 -9
  20. package/dist/commands/sources.js +6 -0
  21. package/dist/commands/storage-offload.d.ts +12 -0
  22. package/dist/commands/storage-offload.js +41 -3
  23. package/dist/commands/sync-mode.js +5 -0
  24. package/dist/commands/whoami.js +4 -0
  25. package/dist/lib/bot/config.d.ts +1 -0
  26. package/dist/lib/bot/config.js +10 -0
  27. package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
  28. package/dist/lib/bot/eventbridge-cron.js +104 -0
  29. package/dist/lib/bot/fleet-local.d.ts +33 -1
  30. package/dist/lib/bot/fleet-local.js +215 -31
  31. package/dist/lib/bot/fleet-python.d.ts +3 -0
  32. package/dist/lib/bot/fleet-python.js +34 -4
  33. package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
  34. package/dist/lib/bot/fleet-runtime-sources.js +30 -0
  35. package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
  36. package/dist/lib/bot/legacy-provider-login.js +19 -2
  37. package/dist/lib/bot/prompt.js +1 -1
  38. package/dist/lib/bot/readiness.d.ts +8 -0
  39. package/dist/lib/bot/readiness.js +17 -3
  40. package/dist/lib/bot/runtime-auth.d.ts +30 -0
  41. package/dist/lib/bot/runtime-auth.js +94 -3
  42. package/dist/lib/bot/status.d.ts +2 -0
  43. package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
  44. package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
  45. package/dist/lib/capacity/collectors/grok.d.ts +5 -0
  46. package/dist/lib/capacity/collectors/grok.js +56 -5
  47. package/dist/lib/daemon/catalog.js +11 -1
  48. package/dist/lib/db/sqlite-binding.d.ts +1 -0
  49. package/dist/lib/db/sqlite-binding.js +1 -1
  50. package/dist/lib/delivery/artifacts.d.ts +99 -0
  51. package/dist/lib/delivery/artifacts.js +548 -0
  52. package/dist/lib/delivery/backup.d.ts +78 -0
  53. package/dist/lib/delivery/backup.js +343 -0
  54. package/dist/lib/delivery/cache.d.ts +29 -0
  55. package/dist/lib/delivery/cache.js +33 -0
  56. package/dist/lib/delivery/contracts.d.ts +142 -0
  57. package/dist/lib/delivery/contracts.js +289 -0
  58. package/dist/lib/delivery/credentials.d.ts +54 -0
  59. package/dist/lib/delivery/credentials.js +119 -0
  60. package/dist/lib/delivery/enrollment.d.ts +142 -0
  61. package/dist/lib/delivery/enrollment.js +382 -0
  62. package/dist/lib/delivery/identity.d.ts +25 -0
  63. package/dist/lib/delivery/identity.js +82 -0
  64. package/dist/lib/delivery/inbox.d.ts +116 -0
  65. package/dist/lib/delivery/inbox.js +260 -0
  66. package/dist/lib/delivery/migrations.d.ts +139 -0
  67. package/dist/lib/delivery/migrations.js +623 -0
  68. package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
  69. package/dist/lib/delivery/mqtt-adapter.js +242 -0
  70. package/dist/lib/delivery/mqtt.d.ts +61 -0
  71. package/dist/lib/delivery/mqtt.js +112 -0
  72. package/dist/lib/delivery/outbox.d.ts +95 -0
  73. package/dist/lib/delivery/outbox.js +187 -0
  74. package/dist/lib/delivery/provenance.d.ts +129 -0
  75. package/dist/lib/delivery/provenance.js +93 -0
  76. package/dist/lib/delivery/reconciler.d.ts +151 -0
  77. package/dist/lib/delivery/reconciler.js +492 -0
  78. package/dist/lib/delivery/restore.d.ts +35 -0
  79. package/dist/lib/delivery/restore.js +134 -0
  80. package/dist/lib/delivery/store.d.ts +161 -0
  81. package/dist/lib/delivery/store.js +940 -0
  82. package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
  83. package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
  84. package/dist/lib/delivery/workers/macos.d.ts +176 -0
  85. package/dist/lib/delivery/workers/macos.js +901 -0
  86. package/dist/lib/delivery/workers/windows-boundary.d.ts +453 -0
  87. package/dist/lib/delivery/workers/windows-boundary.js +693 -0
  88. package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
  89. package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
  90. package/dist/lib/delivery/workers/windows.d.ts +241 -0
  91. package/dist/lib/delivery/workers/windows.js +608 -0
  92. package/dist/lib/install/provider-wrappers.d.ts +2 -0
  93. package/dist/lib/install/provider-wrappers.js +68 -3
  94. package/dist/utils/cognito-callback-port.d.ts +14 -0
  95. package/dist/utils/cognito-callback-port.js +24 -0
  96. package/dist/utils/cognito-session.js +3 -3
  97. package/dist/utils/deleted-company-notice.d.ts +59 -0
  98. package/dist/utils/deleted-company-notice.js +156 -0
  99. package/dist/utils/login-browser.d.ts +1 -1
  100. package/dist/utils/login-browser.js +7 -5
  101. package/dist/utils/resident-package-preload.js +30 -15
  102. package/dist/utils/vault-api.js +7 -0
  103. package/package.json +7 -7
@@ -0,0 +1,492 @@
1
+ /**
2
+ * Delivery controller: work admission, claims and restart recovery (US-003).
3
+ *
4
+ * The controller wraps one DeliveryStore handle. Every accept, claim and
5
+ * outcome is a single atomic store commit, so a crash leaves either all of
6
+ * it or none of it on disk.
7
+ *
8
+ * Recovery rule: when a controller opens the store, every attempt still
9
+ * "open" from an earlier epoch is marked abandoned (outcome "failed") in one
10
+ * commit, before any new work is admitted. Its job then allows exactly one
11
+ * new attempt, numbered after the abandoned one. A late report for an
12
+ * abandoned attempt is refused with ATTEMPT_ABANDONED and does not change it.
13
+ *
14
+ * Claimability: a job is claimable ("ready") when it has no passed attempt,
15
+ * no open attempt, its last attempt did not fail, and every dependency has a
16
+ * passed attempt. A failed job stays failed and blocks its dependents.
17
+ * Dependencies must name jobs in the same run; cycles and unknown
18
+ * dependencies are rejected at accept time.
19
+ *
20
+ * Attempts are idempotent by attemptId: claiming with a known attemptId for
21
+ * the same job returns the stored attempt, including after a restart, where
22
+ * it is reported as abandoned.
23
+ *
24
+ * US-004: claim and recordOutcome take an optional guard that runs inside the
25
+ * commit against the draft state, so an access check and the write it allows
26
+ * are one atomic step on the fenced store.
27
+ */
28
+ import { randomUUID } from "node:crypto";
29
+ import { DELIVERY_SCHEMA_VERSIONS, validateRecord, } from "./contracts.js";
30
+ import { DeliveryStoreError, findCycle, } from "./migrations.js";
31
+ import { ledgerEvents } from "./outbox.js";
32
+ import { DeliveryStore } from "./store.js";
33
+ export { DeliveryStoreError } from "./migrations.js";
34
+ /** JSON text with object keys sorted, so records that differ only in key order compare equal. */
35
+ function canonical(v) {
36
+ return JSON.stringify(v, (_key, value) => value !== null && typeof value === "object" && !Array.isArray(value)
37
+ ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
38
+ : value);
39
+ }
40
+ function same(a, b) {
41
+ return canonical(a) === canonical(b);
42
+ }
43
+ function invalid(found, expected) {
44
+ return new DeliveryStoreError("INVALID_RECORD", { found, expected, action: "Fix the input and retry. Nothing was written." });
45
+ }
46
+ function deriveJobState(state, entry) {
47
+ const attempts = state.attempts.filter((a) => a.record.jobId === entry.record.jobId);
48
+ if (attempts.some((a) => a.record.outcome === "passed"))
49
+ return "passed";
50
+ const last = attempts.reduce((m, a) => (!m || a.record.number > m.record.number ? a : m), undefined);
51
+ if (last?.resolution === "open")
52
+ return "running";
53
+ if (last?.resolution === "reported" && last.record.outcome === "failed")
54
+ return "failed";
55
+ const passed = (jobId) => state.attempts.some((a) => a.record.jobId === jobId && a.record.outcome === "passed");
56
+ return entry.dependsOn.every(passed) ? "ready" : "waiting";
57
+ }
58
+ function jobView(state, j) {
59
+ return {
60
+ job: { ...j.record },
61
+ dependsOn: [...j.dependsOn],
62
+ state: deriveJobState(state, j),
63
+ attempts: state.attempts.filter((a) => a.record.jobId === j.record.jobId).length,
64
+ };
65
+ }
66
+ function attemptView(a) {
67
+ return { attempt: { ...a.record }, resolution: a.resolution, claimedEpoch: a.claimedEpoch, claimedBy: a.claimedBy };
68
+ }
69
+ /** Open a store directory as its single controller and apply the recovery rule. */
70
+ export function openDeliveryController(opts) {
71
+ return DeliveryController.open(opts);
72
+ }
73
+ export class DeliveryController {
74
+ recovery;
75
+ store;
76
+ ids;
77
+ constructor(store, ids, recovery) {
78
+ this.store = store;
79
+ this.ids = ids;
80
+ this.recovery = recovery;
81
+ }
82
+ static open(opts) {
83
+ const store = DeliveryStore.open(opts);
84
+ try {
85
+ const epoch = store.epoch;
86
+ const stale = store.state.attempts.filter((a) => a.resolution === "open" && a.claimedEpoch < epoch).map((a) => a.record.attemptId);
87
+ if (stale.length > 0) {
88
+ const now = store.now();
89
+ store.commit(epoch, (draft) => {
90
+ for (const a of draft.attempts) {
91
+ if (!stale.includes(a.record.attemptId))
92
+ continue;
93
+ a.record.outcome = "failed";
94
+ a.resolution = "abandoned";
95
+ a.resolvedAt = now;
96
+ a.resolvedEpoch = epoch;
97
+ }
98
+ });
99
+ }
100
+ return new DeliveryController(store, opts.ids ?? (() => `attempt-${randomUUID()}`), { ...store.report, abandonedAttemptIds: stale });
101
+ }
102
+ catch (err) {
103
+ store.close();
104
+ throw err;
105
+ }
106
+ }
107
+ /** The fencing epoch this controller writes with. */
108
+ get epoch() {
109
+ return this.store.epoch;
110
+ }
111
+ runs() {
112
+ return this.store.state.runs.map((r) => ({ ...r.record }));
113
+ }
114
+ jobs(runId) {
115
+ const state = this.store.state;
116
+ return state.jobs.filter((j) => runId === undefined || j.record.runId === runId).map((j) => jobView(state, j));
117
+ }
118
+ /** One job's view, or undefined when no such job was accepted. Scans the attempts once, not once per job. */
119
+ job(jobId) {
120
+ const state = this.store.state;
121
+ const entry = state.jobs.find((j) => j.record.jobId === jobId);
122
+ return entry ? jobView(state, entry) : undefined;
123
+ }
124
+ /** Jobs whose state is "ready", in accept order. */
125
+ claimable(runId) {
126
+ return this.jobs(runId).filter((j) => j.state === "ready");
127
+ }
128
+ attempts(jobId) {
129
+ return this.store.state.attempts.filter((a) => jobId === undefined || a.record.jobId === jobId).map(attemptView);
130
+ }
131
+ jobState(jobId) {
132
+ const entry = this.store.state.jobs.find((j) => j.record.jobId === jobId);
133
+ if (!entry)
134
+ throw this.unknownJob(jobId);
135
+ return deriveJobState(this.store.state, entry);
136
+ }
137
+ /**
138
+ * Accept a run and its jobs in one commit. Replaying an identical accept is
139
+ * a no-op; a different run or job under an existing id is DUPLICATE_CONFLICT.
140
+ */
141
+ acceptRun(input) {
142
+ const res = validateRecord("run", input.run);
143
+ if (!res.ok)
144
+ throw invalid(`run: ${res.errors.join("; ")}`, "a run valid under the US-001 contract");
145
+ const run = res.value;
146
+ const existing = this.store.state.runs.find((r) => r.record.runId === run.runId);
147
+ // Another tenant's runId is refused without saying that it exists or whose it is.
148
+ if (existing && existing.record.tenantId !== run.tenantId)
149
+ throw unavailableId("run", run.runId);
150
+ if (existing && !same(existing.record, run)) {
151
+ throw new DeliveryStoreError("DUPLICATE_CONFLICT", {
152
+ found: `run ${run.runId} already accepted with different content`,
153
+ expected: "the same run content, or a new runId",
154
+ action: "Use a new runId for a different run. Nothing was written.",
155
+ });
156
+ }
157
+ return this.admit(run, input.jobs, existing === undefined);
158
+ }
159
+ /** Add jobs to an accepted run in one commit. Dependencies may name existing jobs in the run. */
160
+ acceptJobs(input) {
161
+ const existing = this.store.state.runs.find((r) => r.record.runId === input.runId);
162
+ // Another tenant's run is answered exactly like a missing one.
163
+ if (!existing || existing.record.tenantId !== input.tenantId) {
164
+ throw new DeliveryStoreError("UNKNOWN_RUN", {
165
+ found: `no accepted run ${input.runId}`,
166
+ expected: `an accepted run ${input.runId} for tenant ${input.tenantId}`,
167
+ action: "Accept the run with acceptRun first. Nothing was written.",
168
+ });
169
+ }
170
+ return this.admit(existing.record, input.jobs, false);
171
+ }
172
+ admit(run, inputs, newRun) {
173
+ const state = this.store.state;
174
+ const stored = new Map(state.jobs.filter((j) => j.record.runId === run.runId).map((j) => [j.record.jobId, j]));
175
+ const batch = new Map();
176
+ for (const [i, input] of inputs.entries()) {
177
+ const res = validateRecord("job", input?.job);
178
+ if (!res.ok)
179
+ throw invalid(`jobs[${i}]: ${res.errors.join("; ")}`, "a job valid under the US-001 contract");
180
+ const job = res.value;
181
+ if (job.runId !== run.runId || job.tenantId !== run.tenantId) {
182
+ throw invalid(`job ${job.jobId} names run ${job.runId} for tenant ${job.tenantId}`, `run ${run.runId} for tenant ${run.tenantId}`);
183
+ }
184
+ const deps = input.dependsOn ?? [];
185
+ if (!Array.isArray(deps) || !deps.every((d) => typeof d === "string" && d !== "") || new Set(deps).size !== deps.length) {
186
+ throw invalid(`job ${job.jobId} dependsOn ${JSON.stringify(deps)}`, "a list of distinct jobIds");
187
+ }
188
+ if (batch.has(job.jobId)) {
189
+ throw new DeliveryStoreError("DUPLICATE_CONFLICT", {
190
+ found: `job ${job.jobId} twice in one accept`,
191
+ expected: "each jobId once",
192
+ action: "Remove the duplicate job. Nothing was written.",
193
+ });
194
+ }
195
+ const other = state.jobs.find((j) => j.record.jobId === job.jobId);
196
+ if (other && other.record.tenantId !== run.tenantId)
197
+ throw unavailableId("job", job.jobId);
198
+ if (other && (!same(other.record, job) || !same(other.dependsOn, deps))) {
199
+ throw new DeliveryStoreError("DUPLICATE_CONFLICT", {
200
+ found: `job ${job.jobId} already accepted with different content or dependencies`,
201
+ expected: "the same job and dependencies, or a new jobId",
202
+ action: "Use a new jobId for a different job. Nothing was written.",
203
+ });
204
+ }
205
+ batch.set(job.jobId, { job, dependsOn: [...deps] });
206
+ }
207
+ for (const [jobId, { dependsOn }] of batch) {
208
+ for (const dep of dependsOn) {
209
+ if (dep === jobId) {
210
+ throw new DeliveryStoreError("DEPENDENCY_CYCLE", {
211
+ found: `job ${jobId} depends on itself`,
212
+ expected: "an acyclic dependency graph",
213
+ action: "Remove the self-dependency. Nothing was written.",
214
+ });
215
+ }
216
+ if (batch.has(dep) || stored.has(dep))
217
+ continue;
218
+ // Only the caller's own jobs are visible: another tenant's job reads as unknown.
219
+ const elsewhere = state.jobs.find((j) => j.record.jobId === dep && j.record.tenantId === run.tenantId);
220
+ throw new DeliveryStoreError("UNKNOWN_DEPENDENCY", {
221
+ found: elsewhere
222
+ ? `job ${jobId} depends on ${dep}, which belongs to run ${elsewhere.record.runId}`
223
+ : `job ${jobId} depends on unknown job ${dep}`,
224
+ expected: `dependencies on jobs in run ${run.runId}`,
225
+ action: elsewhere
226
+ ? "Cross-run dependencies are not supported; put both jobs in one run. Nothing was written."
227
+ : `Accept ${dep} in the same call or earlier. Nothing was written.`,
228
+ });
229
+ }
230
+ }
231
+ const graph = new Map([...stored].map(([id, j]) => [id, j.dependsOn]));
232
+ for (const [id, j] of batch)
233
+ graph.set(id, j.dependsOn);
234
+ const cycle = findCycle(graph);
235
+ if (cycle) {
236
+ throw new DeliveryStoreError("DEPENDENCY_CYCLE", {
237
+ found: `dependency cycle ${cycle.join(" -> ")}`,
238
+ expected: "an acyclic dependency graph",
239
+ action: "Break the cycle. Nothing was written.",
240
+ });
241
+ }
242
+ const fresh = [...batch.values()].filter((j) => !stored.has(j.job.jobId));
243
+ if (!newRun && fresh.length === 0)
244
+ return { runId: run.runId, acceptedJobIds: [], replayed: true };
245
+ const now = this.store.now();
246
+ const epoch = this.epoch;
247
+ // Store copies: the caller keeps its objects, and later changes to them must not reach the store.
248
+ this.store.commit(epoch, (draft) => {
249
+ if (newRun)
250
+ draft.runs.push({ record: structuredClone(run), acceptedAt: now, acceptedEpoch: epoch });
251
+ for (const j of fresh) {
252
+ draft.jobs.push({ record: structuredClone(j.job), dependsOn: [...j.dependsOn], acceptedAt: now, acceptedEpoch: epoch });
253
+ }
254
+ });
255
+ return { runId: run.runId, acceptedJobIds: fresh.map((j) => j.job.jobId), replayed: false };
256
+ }
257
+ /**
258
+ * Claim a ready job by committing a new open attempt. With a known
259
+ * attemptId for the same job, returns the stored attempt (replayed: true).
260
+ */
261
+ claim(jobId, opts = {}) {
262
+ const state = this.store.state;
263
+ if (opts.attemptId !== undefined) {
264
+ const known = state.attempts.find((a) => a.record.attemptId === opts.attemptId);
265
+ if (known) {
266
+ if (known.record.jobId !== jobId) {
267
+ throw new DeliveryStoreError("ATTEMPT_CONFLICT", {
268
+ found: `attempt ${opts.attemptId} belongs to job ${known.record.jobId}`,
269
+ expected: `a new attemptId, or one stored for job ${jobId}`,
270
+ action: "Use a new attemptId. Nothing was written.",
271
+ });
272
+ }
273
+ // A replay is answered only while this handle still owns the store (CX-4).
274
+ this.store.assertOwner();
275
+ if (known.claimedBy !== (opts.workerId ?? null))
276
+ throw notClaimant(opts.workerId, opts.attemptId);
277
+ opts.guard?.(state);
278
+ return { ...attemptView(known), replayed: true };
279
+ }
280
+ }
281
+ const entry = state.jobs.find((j) => j.record.jobId === jobId);
282
+ if (!entry)
283
+ throw this.unknownJob(jobId);
284
+ const jobState = deriveJobState(state, entry);
285
+ if (jobState !== "ready") {
286
+ const actions = {
287
+ waiting: `Wait until ${entry.dependsOn.join(", ")} have passed.`,
288
+ running: "An attempt is already open; record its outcome first.",
289
+ passed: "The job has already passed; nothing to do.",
290
+ failed: "The job failed; it stays failed and blocks its dependents.",
291
+ };
292
+ throw new DeliveryStoreError("NOT_CLAIMABLE", {
293
+ found: `job ${jobId} is ${jobState}`,
294
+ expected: "a ready job",
295
+ action: actions[jobState],
296
+ });
297
+ }
298
+ const attemptId = opts.attemptId ?? this.ids();
299
+ if (state.attempts.some((a) => a.record.attemptId === attemptId)) {
300
+ throw new DeliveryStoreError("ATTEMPT_CONFLICT", {
301
+ found: `generated attemptId ${attemptId} already exists`,
302
+ expected: "a unique attemptId",
303
+ action: "Fix the id generator. Nothing was written.",
304
+ });
305
+ }
306
+ const job = entry.record;
307
+ // max+1, not count+1: a gap in stored numbers must not produce a duplicate (CX-5).
308
+ const number = Math.max(0, ...state.attempts.filter((a) => a.record.jobId === jobId).map((a) => a.record.number)) + 1;
309
+ const record = {
310
+ schemaVersion: DELIVERY_SCHEMA_VERSIONS.attempt,
311
+ tenantId: job.tenantId,
312
+ attemptId,
313
+ jobId,
314
+ runId: job.runId,
315
+ number,
316
+ outcome: "pending",
317
+ };
318
+ const res = validateRecord("attempt", record);
319
+ if (!res.ok)
320
+ throw invalid(`attempt: ${res.errors.join("; ")}`, "an attempt valid under the US-001 contract");
321
+ const epoch = this.epoch;
322
+ const now = this.store.now();
323
+ const stored = { record, claimedAt: now, claimedEpoch: epoch, claimedBy: opts.workerId ?? null, resolution: "open", resolvedAt: null, resolvedEpoch: null };
324
+ this.store.commit(epoch, (draft) => {
325
+ opts.guard?.(draft);
326
+ draft.attempts.push(structuredClone(stored));
327
+ });
328
+ return { ...attemptView(stored), replayed: false };
329
+ }
330
+ /** Report the outcome of an open attempt. Repeating the same report is a no-op. */
331
+ recordOutcome(attemptId, outcome, opts = {}) {
332
+ if (outcome !== "passed" && outcome !== "failed")
333
+ throw invalid(`outcome ${JSON.stringify(outcome)}`, '"passed" or "failed"');
334
+ const known = this.store.state.attempts.find((a) => a.record.attemptId === attemptId);
335
+ if (!known) {
336
+ throw new DeliveryStoreError("UNKNOWN_ATTEMPT", {
337
+ found: `no attempt ${attemptId}`,
338
+ expected: "an attemptId returned by claim",
339
+ action: "Check the attemptId. Nothing was written.",
340
+ });
341
+ }
342
+ if (known.resolution === "abandoned") {
343
+ throw new DeliveryStoreError("ATTEMPT_ABANDONED", {
344
+ found: `attempt ${attemptId} was abandoned at epoch ${known.resolvedEpoch} after its controller stopped`,
345
+ expected: "an open attempt",
346
+ action: "Discard this result. Claim the job again to run a new attempt. Nothing was written.",
347
+ });
348
+ }
349
+ if (known.resolution === "reported") {
350
+ if (known.record.outcome === outcome) {
351
+ opts.guard?.(this.store.state);
352
+ return attemptView(known);
353
+ }
354
+ throw new DeliveryStoreError("ATTEMPT_CONFLICT", {
355
+ found: `attempt ${attemptId} already reported ${known.record.outcome}`,
356
+ expected: `no report, or the same outcome ${known.record.outcome}`,
357
+ action: "Outcomes are final. Nothing was written.",
358
+ });
359
+ }
360
+ const epoch = this.epoch;
361
+ const now = this.store.now();
362
+ this.store.commit(epoch, (draft) => {
363
+ opts.guard?.(draft);
364
+ const a = draft.attempts.find((x) => x.record.attemptId === attemptId);
365
+ if (!a)
366
+ return;
367
+ a.record.outcome = outcome;
368
+ a.resolution = "reported";
369
+ a.resolvedAt = now;
370
+ a.resolvedEpoch = epoch;
371
+ });
372
+ const updated = this.store.state.attempts.find((a) => a.record.attemptId === attemptId);
373
+ return attemptView(updated ?? known);
374
+ }
375
+ /**
376
+ * US-007: return an open attempt unfinished, so its job can run again. The
377
+ * attempt is marked abandoned (outcome "failed") in one fenced commit, the
378
+ * same state the recovery rule leaves a stale attempt in: the job allows
379
+ * exactly one new attempt and a late report is refused with
380
+ * ATTEMPT_ABANDONED. Returning an abandoned attempt again is a no-op; a
381
+ * reported attempt cannot be returned.
382
+ */
383
+ returnAttempt(attemptId, opts = {}) {
384
+ const known = this.store.state.attempts.find((a) => a.record.attemptId === attemptId);
385
+ if (!known) {
386
+ throw new DeliveryStoreError("UNKNOWN_ATTEMPT", {
387
+ found: `no attempt ${attemptId}`,
388
+ expected: "an attemptId returned by claim",
389
+ action: "Check the attemptId. Nothing was written.",
390
+ });
391
+ }
392
+ if (known.resolution === "abandoned") {
393
+ this.store.assertOwner();
394
+ opts.guard?.(this.store.state);
395
+ return attemptView(known);
396
+ }
397
+ if (known.resolution === "reported") {
398
+ throw new DeliveryStoreError("ATTEMPT_CONFLICT", {
399
+ found: `attempt ${attemptId} already reported ${known.record.outcome}`,
400
+ expected: "an open attempt",
401
+ action: "A reported attempt is final and cannot be returned. Nothing was written.",
402
+ });
403
+ }
404
+ const epoch = this.epoch;
405
+ const now = this.store.now();
406
+ this.store.commit(epoch, (draft) => {
407
+ opts.guard?.(draft);
408
+ const a = draft.attempts.find((x) => x.record.attemptId === attemptId);
409
+ if (!a)
410
+ return;
411
+ a.record.outcome = "failed";
412
+ a.resolution = "abandoned";
413
+ a.resolvedAt = now;
414
+ a.resolvedEpoch = epoch;
415
+ });
416
+ const updated = this.store.state.attempts.find((a) => a.record.attemptId === attemptId);
417
+ return attemptView(updated ?? known);
418
+ }
419
+ /**
420
+ * Throw unless this handle still owns the store: STORE_CLOSED for a closed
421
+ * or failed handle, FENCED when another controller has taken over. Read only.
422
+ */
423
+ assertOwner() {
424
+ this.store.assertOwner();
425
+ }
426
+ /**
427
+ * The notification events the committed ledger implies (US-005), in ledger
428
+ * order. Derived from committed records only, so an event exists exactly
429
+ * when its transition was committed. Only an owning handle may serve them.
430
+ */
431
+ ledgerEvents() {
432
+ this.store.assertOwner();
433
+ return ledgerEvents(this.store.state);
434
+ }
435
+ /** Copies of the stored worker records, including secret digests. For the US-004 access layer. */
436
+ workerRecords() {
437
+ return structuredClone(this.store.state.workers);
438
+ }
439
+ /**
440
+ * Change worker records in one fenced store commit. `mutate` may throw to
441
+ * refuse; nothing is written then.
442
+ * @internal Used by enrollment.ts; callers outside the access layer must not write workers.
443
+ */
444
+ commitWorkers(mutate) {
445
+ const epoch = this.epoch;
446
+ const now = this.store.now();
447
+ this.store.commit(epoch, (draft) => mutate(draft.workers, { epoch, now }));
448
+ }
449
+ /** US-008: copies of the artifact provenance records and cache entries. */
450
+ artifactRecords() {
451
+ return structuredClone({ artifacts: this.store.state.artifacts, cache: this.store.state.cache });
452
+ }
453
+ /**
454
+ * Change artifact and cache records in one fenced store commit. `mutate`
455
+ * gets the whole draft so it can re-check workers and attempts against the
456
+ * state being written; it may throw to refuse, and nothing is written then.
457
+ * @internal Used by artifacts.ts; other callers must not write artifacts.
458
+ */
459
+ commitArtifacts(mutate) {
460
+ const epoch = this.epoch;
461
+ const now = this.store.now();
462
+ this.store.commit(epoch, (draft) => mutate(draft, { epoch, now }));
463
+ }
464
+ /** Release ownership of the store. Idempotent. */
465
+ close() {
466
+ this.store.close();
467
+ }
468
+ unknownJob(jobId) {
469
+ return new DeliveryStoreError("UNKNOWN_JOB", {
470
+ found: `no accepted job ${jobId}`,
471
+ expected: "an accepted jobId",
472
+ action: "Accept the job first. Nothing was written.",
473
+ });
474
+ }
475
+ }
476
+ /** An id another tenant holds. The answer does not say that it exists or whose it is. */
477
+ function unavailableId(kind, id) {
478
+ return new DeliveryStoreError("DUPLICATE_CONFLICT", {
479
+ found: `${kind}Id ${id} cannot be used`,
480
+ expected: `a new ${kind}Id`,
481
+ action: `Use a different ${kind}Id. Nothing was written.`,
482
+ });
483
+ }
484
+ /** An attempt claimed by a different worker. Names only the caller and the attemptId it presented. */
485
+ export function notClaimant(workerId, attemptId) {
486
+ return new DeliveryStoreError("ACCESS_DENIED", {
487
+ found: `${workerId === undefined ? "a caller without a worker" : `worker ${workerId}`} asked for attempt ${attemptId}, which it did not claim`,
488
+ expected: "an attempt claimed by the same worker",
489
+ action: "Report or return an attempt only from the worker that claimed it. Nothing was written.",
490
+ });
491
+ }
492
+ //# sourceMappingURL=reconciler.js.map
@@ -0,0 +1,35 @@
1
+ import { type BackupManifest, type BackupSigning } from "./backup.js";
2
+ export declare const RESTORE_RECORD_FILE = "restore.activated.json";
3
+ export interface RestoreReport {
4
+ targetDir: string;
5
+ manifest: BackupManifest;
6
+ }
7
+ /** Restore `backupPath` into the clean directory `targetDir`, pending activation. */
8
+ export declare function restoreBackup(opts: {
9
+ backupPath: string;
10
+ targetDir: string;
11
+ signing: BackupSigning;
12
+ clock?: () => number;
13
+ }): RestoreReport;
14
+ export type RetireTarget = {
15
+ dir: string;
16
+ } | {
17
+ unreachable: {
18
+ reason: string;
19
+ };
20
+ };
21
+ export interface ActivationReport {
22
+ /** The epoch the restored controller's next open takes. */
23
+ authorityEpoch: number;
24
+ /** The retired old store, or null when it was declared unreachable. */
25
+ retiredDir: string | null;
26
+ backupId: string;
27
+ }
28
+ /** Move authority to a restored store. See the header for the steps. */
29
+ export declare function activateRestore(opts: {
30
+ targetDir: string;
31
+ retire: RetireTarget;
32
+ clock?: () => number;
33
+ gateWaitMs?: number;
34
+ }): ActivationReport;
35
+ //# sourceMappingURL=restore.d.ts.map
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Restore a verified backup into a clean controller directory and move
3
+ * authority to it (US-010). See docs/delivery-recovery.md.
4
+ *
5
+ * restoreBackup verifies the backup (manifest signature, state digest and
6
+ * load, every blob digest and provenance signature), writes it into a
7
+ * sibling temp directory with restore.pending.json first, re-checks every
8
+ * written blob, and renames it to the target. The target must not exist or
9
+ * be empty. A pending store refuses to open (RESTORE_PENDING).
10
+ *
11
+ * activateRestore is the explicit authority transfer:
12
+ * 1. Retire the old store when it is reachable (retireStore): under its
13
+ * store lock it records the highest epoch it reached and removes its
14
+ * owner lock, so the old controller's next commit is FENCED and every
15
+ * later open of it is refused with STORE_RETIRED, including a
16
+ * stale-pid takeover after a restart. When it is not reachable, an
17
+ * operator reason is required and recorded instead.
18
+ * 2. Raise the restored state's epoch to at least that epoch, so the
19
+ * restored controller's first open takes a strictly higher authority
20
+ * epoch than any the old controller held.
21
+ * 3. Record the activation and remove restore.pending.json.
22
+ * Attempts open in the backup are from earlier epochs; the restored
23
+ * controller abandons them on open (reconciler recovery rule), so their
24
+ * late reports are refused with ATTEMPT_ABANDONED and each job allows one
25
+ * new attempt. Every step is safe to re-run after a crash.
26
+ */
27
+ import { randomBytes } from "node:crypto";
28
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, rmdirSync, unlinkSync } from "node:fs";
29
+ import { dirname, join } from "node:path";
30
+ import { blobRelativePath } from "./artifacts.js";
31
+ import { backupInvalid, fsyncDirectory, resolveKey, verifyBackup, writeFileDurable, } from "./backup.js";
32
+ import { DeliveryStoreError, parseStoreText, serializeState } from "./migrations.js";
33
+ import { sha256Hex, signatureMatches } from "./provenance.js";
34
+ import { RESTORE_PENDING_FILE, retireStore, STATE_FILE } from "./store.js";
35
+ export const RESTORE_RECORD_FILE = "restore.activated.json";
36
+ /** Restore `backupPath` into the clean directory `targetDir`, pending activation. */
37
+ export function restoreBackup(opts) {
38
+ const manifest = verifyBackup(opts.backupPath, opts.signing);
39
+ if (existsSync(opts.targetDir) && readdirSync(opts.targetDir).length > 0) {
40
+ throw backupInvalid(`restore target ${opts.targetDir} is not empty`, "a missing or empty directory", "Restore into a clean directory. Nothing was written.");
41
+ }
42
+ const stateText = readFileSync(join(opts.backupPath, STATE_FILE), "utf8");
43
+ const state = parseStoreText(stateText, join(opts.backupPath, STATE_FILE)).state;
44
+ const key = resolveKey(opts.signing);
45
+ for (const a of state.artifacts) {
46
+ if (!signatureMatches(a, key)) {
47
+ throw backupInvalid(`artifact ${a.record.artifactId}: provenance signature does not verify`, "provenance signed with the configured key");
48
+ }
49
+ }
50
+ const parent = dirname(opts.targetDir);
51
+ mkdirSync(parent, { recursive: true });
52
+ const temp = join(parent, `.restoring-${randomBytes(6).toString("hex")}`);
53
+ try {
54
+ mkdirSync(temp, { mode: 0o700 });
55
+ const pending = {
56
+ backupId: manifest.backupId,
57
+ restoredAt: new Date((opts.clock ?? Date.now)()).toISOString(),
58
+ backupEpoch: manifest.epoch,
59
+ };
60
+ writeFileDurable(join(temp, RESTORE_PENDING_FILE), Buffer.from(`${JSON.stringify(pending)}\n`), 0o600);
61
+ fsyncDirectory(temp);
62
+ for (const e of manifest.artifacts) {
63
+ const bytes = readFileSync(join(opts.backupPath, e.file));
64
+ const rel = blobRelativePath(e.tenantId, e.partition, e.digest);
65
+ const dest = join(temp, rel);
66
+ if (existsSync(dest))
67
+ continue;
68
+ mkdirSync(dirname(dest), { recursive: true, mode: 0o700 });
69
+ writeFileDurable(dest, bytes);
70
+ if (sha256Hex(readFileSync(dest)) !== e.digest)
71
+ throw backupInvalid(`restored blob ${rel} does not match ${e.digest}`, "an exact copy");
72
+ fsyncDirectory(dirname(dest));
73
+ }
74
+ writeFileDurable(join(temp, STATE_FILE), Buffer.from(stateText), 0o600);
75
+ fsyncDirectory(temp);
76
+ if (existsSync(opts.targetDir))
77
+ rmdirSync(opts.targetDir); // empty; checked above
78
+ renameSync(temp, opts.targetDir);
79
+ fsyncDirectory(parent);
80
+ }
81
+ catch (err) {
82
+ rmSync(temp, { recursive: true, force: true });
83
+ throw err;
84
+ }
85
+ return { targetDir: opts.targetDir, manifest };
86
+ }
87
+ /** Move authority to a restored store. See the header for the steps. */
88
+ export function activateRestore(opts) {
89
+ const now = new Date((opts.clock ?? Date.now)()).toISOString();
90
+ const pendingPath = join(opts.targetDir, RESTORE_PENDING_FILE);
91
+ if (!existsSync(pendingPath)) {
92
+ throw new DeliveryStoreError("INVALID_RECORD", {
93
+ found: `no ${RESTORE_PENDING_FILE} in ${opts.targetDir}`,
94
+ expected: "a directory written by restoreBackup and not yet activated",
95
+ action: "Restore a backup into the directory first. Nothing was changed.",
96
+ });
97
+ }
98
+ const pending = JSON.parse(readFileSync(pendingPath, "utf8"));
99
+ let observedEpoch = 0;
100
+ let retiredDir = null;
101
+ let note;
102
+ if ("dir" in opts.retire) {
103
+ const rec = retireStore(opts.retire.dir, { successorDir: opts.targetDir, backupId: pending.backupId, now, waitMs: opts.gateWaitMs });
104
+ observedEpoch = rec.observedEpoch;
105
+ retiredDir = opts.retire.dir;
106
+ note = `retired ${opts.retire.dir} at epoch ${rec.observedEpoch}`;
107
+ }
108
+ else {
109
+ const reason = opts.retire.unreachable?.reason;
110
+ if (typeof reason !== "string" || reason.trim() === "") {
111
+ throw new DeliveryStoreError("INVALID_RECORD", {
112
+ found: "an unreachable old store with no operator reason",
113
+ expected: "a reason saying why the old controller cannot publish (host destroyed, disk lost)",
114
+ action: "Retire the old store directory, or give the reason. Nothing was changed.",
115
+ });
116
+ }
117
+ note = `old store unreachable: ${reason}`;
118
+ }
119
+ const statePath = join(opts.targetDir, STATE_FILE);
120
+ const state = parseStoreText(readFileSync(statePath, "utf8"), statePath).state;
121
+ state.epoch = Math.max(state.epoch, observedEpoch, pending.backupEpoch);
122
+ const temp = `${statePath}.tmp-restore-${randomBytes(4).toString("hex")}`;
123
+ writeFileDurable(temp, Buffer.from(serializeState(state)), 0o600);
124
+ renameSync(temp, statePath);
125
+ const authorityEpoch = state.epoch + 1;
126
+ const recordPath = join(opts.targetDir, RESTORE_RECORD_FILE);
127
+ if (existsSync(recordPath))
128
+ unlinkSync(recordPath);
129
+ writeFileDurable(recordPath, Buffer.from(`${JSON.stringify({ backupId: pending.backupId, activatedAt: now, authorityEpoch, retiredDir, note })}\n`), 0o600);
130
+ unlinkSync(pendingPath);
131
+ fsyncDirectory(opts.targetDir);
132
+ return { authorityEpoch, retiredDir, backupId: pending.backupId };
133
+ }
134
+ //# sourceMappingURL=restore.js.map