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

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 (124) hide show
  1. package/CHANGELOG.md +65 -1
  2. package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
  3. package/dist/command-catalog.generated.d.ts +46 -6
  4. package/dist/command-catalog.generated.js +53 -6
  5. package/dist/commands/bot.js +64 -6
  6. package/dist/commands/capacity.d.ts +4 -1
  7. package/dist/commands/capacity.js +46 -10
  8. package/dist/commands/cloud.js +1 -1
  9. package/dist/commands/core-delegate-w1b.js +15 -1
  10. package/dist/commands/core-policy.js +67 -8
  11. package/dist/commands/daemon.js +5 -0
  12. package/dist/commands/files-browse.d.ts +11 -4
  13. package/dist/commands/files-browse.js +21 -4
  14. package/dist/commands/files.d.ts +1 -1
  15. package/dist/commands/files.js +25 -11
  16. package/dist/commands/integrations-auth-rules.d.ts +27 -0
  17. package/dist/commands/integrations-auth-rules.js +79 -0
  18. package/dist/commands/integrations-import.js +124 -12
  19. package/dist/commands/lanes.js +2 -2
  20. package/dist/commands/mesh.d.ts +2 -0
  21. package/dist/commands/mesh.js +60 -35
  22. package/dist/commands/sync-held.js +5 -2
  23. package/dist/lazy-commands.js +3 -5
  24. package/dist/lib/bot/fleet-cron.d.ts +8 -0
  25. package/dist/lib/bot/fleet-cron.js +35 -3
  26. package/dist/lib/bot/fleet-daemon.d.ts +46 -0
  27. package/dist/lib/bot/fleet-daemon.js +99 -1
  28. package/dist/lib/bot/probe.js +7 -1
  29. package/dist/lib/bot/run.js +20 -1
  30. package/dist/lib/bot/runtime/codex.js +1 -1
  31. package/dist/lib/bot/runtime/grok-acp.d.ts +5 -1
  32. package/dist/lib/bot/runtime/grok-acp.js +6 -3
  33. package/dist/lib/bot/runtime/index.js +19 -9
  34. package/dist/lib/bot/runtime/messages-stream.js +2 -2
  35. package/dist/lib/bot/runtime/types.d.ts +15 -0
  36. package/dist/lib/bot/runtime/types.js +9 -0
  37. package/dist/lib/bot/runtime-failure.d.ts +23 -0
  38. package/dist/lib/bot/runtime-failure.js +43 -1
  39. package/dist/lib/capacity/accounts.d.ts +8 -0
  40. package/dist/lib/capacity/accounts.js +19 -0
  41. package/dist/lib/capacity/available.d.ts +154 -0
  42. package/dist/lib/capacity/available.js +905 -0
  43. package/dist/lib/capacity/codex-availability.d.ts +14 -1
  44. package/dist/lib/capacity/codex-availability.js +26 -1
  45. package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
  46. package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
  47. package/dist/lib/capacity/collectors/codex.js +10 -7
  48. package/dist/lib/capacity/ledger.d.ts +37 -1
  49. package/dist/lib/capacity/ledger.js +207 -30
  50. package/dist/lib/capacity/project.d.ts +26 -0
  51. package/dist/lib/capacity/project.js +137 -8
  52. package/dist/lib/capacity/refusal-rows.d.ts +31 -0
  53. package/dist/lib/capacity/refusal-rows.js +61 -0
  54. package/dist/lib/capacity/refusal.d.ts +53 -2
  55. package/dist/lib/capacity/refusal.js +284 -65
  56. package/dist/lib/capacity/route.js +46 -11
  57. package/dist/lib/capacity/widget.d.ts +12 -1
  58. package/dist/lib/capacity/widget.js +91 -3
  59. package/dist/lib/daemon/resolver.d.ts +2 -0
  60. package/dist/lib/daemon/resolver.js +3 -0
  61. package/dist/lib/daemon/run.d.ts +9 -0
  62. package/dist/lib/daemon/run.js +54 -1
  63. package/dist/lib/daemon/server.d.ts +2 -0
  64. package/dist/lib/daemon/server.js +10 -1
  65. package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
  66. package/dist/lib/daemon/tcc-eperm.js +310 -0
  67. package/dist/lib/delivery/admission.d.ts +86 -0
  68. package/dist/lib/delivery/admission.js +148 -0
  69. package/dist/lib/delivery/artifacts.d.ts +7 -1
  70. package/dist/lib/delivery/artifacts.js +29 -10
  71. package/dist/lib/delivery/attempt-id.d.ts +13 -0
  72. package/dist/lib/delivery/attempt-id.js +16 -0
  73. package/dist/lib/delivery/disposable-target.d.ts +42 -0
  74. package/dist/lib/delivery/disposable-target.js +111 -0
  75. package/dist/lib/delivery/effects.d.ts +136 -0
  76. package/dist/lib/delivery/effects.js +541 -0
  77. package/dist/lib/delivery/enrollment.d.ts +21 -17
  78. package/dist/lib/delivery/enrollment.js +83 -5
  79. package/dist/lib/delivery/escalations.d.ts +51 -0
  80. package/dist/lib/delivery/escalations.js +60 -0
  81. package/dist/lib/delivery/lease.d.ts +80 -0
  82. package/dist/lib/delivery/lease.js +134 -0
  83. package/dist/lib/delivery/migrations.d.ts +120 -4
  84. package/dist/lib/delivery/migrations.js +215 -15
  85. package/dist/lib/delivery/mqtt.d.ts +2 -0
  86. package/dist/lib/delivery/mqtt.js +7 -0
  87. package/dist/lib/delivery/reconciler.d.ts +65 -1
  88. package/dist/lib/delivery/reconciler.js +224 -13
  89. package/dist/lib/delivery/rpc/client.d.ts +22 -0
  90. package/dist/lib/delivery/rpc/client.js +159 -0
  91. package/dist/lib/delivery/rpc/port.d.ts +40 -0
  92. package/dist/lib/delivery/rpc/port.js +16 -0
  93. package/dist/lib/delivery/rpc/server.d.ts +30 -0
  94. package/dist/lib/delivery/rpc/server.js +205 -0
  95. package/dist/lib/delivery/rpc/wire.d.ts +85 -0
  96. package/dist/lib/delivery/rpc/wire.js +143 -0
  97. package/dist/lib/delivery/store.d.ts +2 -0
  98. package/dist/lib/delivery/store.js +4 -0
  99. package/dist/lib/delivery/windows-service-install.d.ts +262 -0
  100. package/dist/lib/delivery/windows-service-install.js +892 -0
  101. package/dist/lib/delivery/workers/macos.d.ts +16 -1
  102. package/dist/lib/delivery/workers/macos.js +54 -12
  103. package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
  104. package/dist/lib/delivery/workers/windows-service-live.js +711 -0
  105. package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
  106. package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
  107. package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
  108. package/dist/lib/delivery/workers/windows-service.js +584 -0
  109. package/dist/lib/delivery/workers/windows.d.ts +32 -22
  110. package/dist/lib/delivery/workers/windows.js +50 -64
  111. package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
  112. package/dist/lib/hot-channels/adapters/meetings.js +36 -3
  113. package/dist/lib/hot-channels/signals-pass.d.ts +10 -0
  114. package/dist/lib/hot-channels/signals-pass.js +71 -2
  115. package/dist/lib/hot-channels/signals-redo.js +10 -2
  116. package/dist/lib/lanes/watcher.js +35 -0
  117. package/dist/lib/signals/steps/extract.js +40 -4
  118. package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
  119. package/dist/utils/catalog-runtime-paths.d.ts +34 -0
  120. package/dist/utils/catalog-runtime-paths.js +53 -0
  121. package/dist/utils/files-browse-acl.js +1 -1
  122. package/package.json +7 -7
  123. package/dist/lib/delivery/workers/windows-boundary.d.ts +0 -453
  124. package/dist/lib/delivery/workers/windows-boundary.js +0 -693
@@ -24,6 +24,16 @@
24
24
  * US-004: claim and recordOutcome take an optional guard that runs inside the
25
25
  * commit against the draft state, so an access check and the write it allows
26
26
  * are one atomic step on the fenced store.
27
+ *
28
+ * Claim leases (US-011 slice 4): a claim made by a worker carries a lease of
29
+ * claimLeaseMs, which the worker extends with renewLease. Expiry is decided by
30
+ * the store's injected clock, never by Date.now, in claim(), recordOutcome(),
31
+ * returnAttempt(), renewLease() and the expireLeases() sweep: an open attempt
32
+ * whose lease time has been reached (now >= leaseExpiresAt) is abandoned in one
33
+ * commit, the same state the recovery rule leaves. Its job allows one new
34
+ * attempt with a new attemptId, and a late report is refused with
35
+ * ATTEMPT_ABANDONED. A claim made without a worker has no lease and never
36
+ * expires; neither do attempts migrated from store v6 or older.
27
37
  */
28
38
  import { randomUUID } from "node:crypto";
29
39
  import { DELIVERY_SCHEMA_VERSIONS, validateRecord, } from "./contracts.js";
@@ -31,6 +41,15 @@ import { DeliveryStoreError, findCycle, } from "./migrations.js";
31
41
  import { ledgerEvents } from "./outbox.js";
32
42
  import { DeliveryStore } from "./store.js";
33
43
  export { DeliveryStoreError } from "./migrations.js";
44
+ /** Default claim lease: 120 s. A worker renews it every third of that (startLeaseHeartbeat). */
45
+ export const DEFAULT_CLAIM_LEASE_MS = 120_000;
46
+ /** True when `a` is open, has a lease, and the lease time has been reached at `nowMs`. */
47
+ export function leaseExpired(a, nowMs) {
48
+ return a.resolution === "open" && a.leaseExpiresAt !== null && nowMs >= Date.parse(a.leaseExpiresAt);
49
+ }
50
+ function iso(ms) {
51
+ return new Date(ms).toISOString();
52
+ }
34
53
  /** JSON text with object keys sorted, so records that differ only in key order compare equal. */
35
54
  function canonical(v) {
36
55
  return JSON.stringify(v, (_key, value) => value !== null && typeof value === "object" && !Array.isArray(value)
@@ -74,12 +93,17 @@ export class DeliveryController {
74
93
  recovery;
75
94
  store;
76
95
  ids;
77
- constructor(store, ids, recovery) {
96
+ leaseMs;
97
+ constructor(store, ids, recovery, leaseMs) {
78
98
  this.store = store;
79
99
  this.ids = ids;
80
100
  this.recovery = recovery;
101
+ this.leaseMs = leaseMs;
81
102
  }
82
103
  static open(opts) {
104
+ const leaseMs = opts.claimLeaseMs ?? DEFAULT_CLAIM_LEASE_MS;
105
+ if (!Number.isSafeInteger(leaseMs) || leaseMs < 1)
106
+ throw invalid(`claimLeaseMs ${String(opts.claimLeaseMs)}`, "a positive integer number of milliseconds");
83
107
  const store = DeliveryStore.open(opts);
84
108
  try {
85
109
  const epoch = store.epoch;
@@ -97,7 +121,7 @@ export class DeliveryController {
97
121
  }
98
122
  });
99
123
  }
100
- return new DeliveryController(store, opts.ids ?? (() => `attempt-${randomUUID()}`), { ...store.report, abandonedAttemptIds: stale });
124
+ return new DeliveryController(store, opts.ids ?? (() => `attempt-${randomUUID()}`), { ...store.report, abandonedAttemptIds: stale }, leaseMs);
101
125
  }
102
126
  catch (err) {
103
127
  store.close();
@@ -108,6 +132,10 @@ export class DeliveryController {
108
132
  get epoch() {
109
133
  return this.store.epoch;
110
134
  }
135
+ /** ISO timestamp from the store clock, the one commits are stamped with. */
136
+ now() {
137
+ return this.store.now();
138
+ }
111
139
  runs() {
112
140
  return this.store.state.runs.map((r) => ({ ...r.record }));
113
141
  }
@@ -259,9 +287,31 @@ export class DeliveryController {
259
287
  * attemptId for the same job, returns the stored attempt (replayed: true).
260
288
  */
261
289
  claim(jobId, opts = {}) {
290
+ const nowMs = this.store.nowMs();
291
+ this.expireDue(nowMs);
262
292
  const state = this.store.state;
263
293
  if (opts.attemptId !== undefined) {
264
294
  const known = state.attempts.find((a) => a.record.attemptId === opts.attemptId);
295
+ if (known && opts.workerId !== undefined) {
296
+ // A worker's replay (US-011 slice 4 B review C1) is answered only for its own live
297
+ // claim of this job: open, in lease, claimed by it. Anything else gets one generic
298
+ // refusal that names no job, worker or company, so a stale or foreign id reveals
299
+ // nothing and a replay can never hand out a dead claim (or its credentials) again.
300
+ // The leaseExpired condition is a second guard: expireDue(nowMs) above has already
301
+ // committed every lapsed open attempt as abandoned at this same nowMs, so a lapsed
302
+ // attempt fails the "open" condition first. It keeps the replay safe if the sweep
303
+ // is ever moved, skipped or given a different clock.
304
+ if (known.record.jobId !== jobId || known.claimedBy !== opts.workerId || known.resolution !== "open" || leaseExpired(known, nowMs)) {
305
+ throw new DeliveryStoreError("ATTEMPT_CONFLICT", {
306
+ found: `attemptId ${opts.attemptId} has no live claim of yours on this job to replay`,
307
+ expected: "a new attemptId, or the attemptId of your own open, unexpired claim of this job",
308
+ action: "Use a new attemptId. Nothing was written.",
309
+ });
310
+ }
311
+ this.store.assertOwner();
312
+ opts.guard?.(state);
313
+ return { ...attemptView(known), replayed: true };
314
+ }
265
315
  if (known) {
266
316
  if (known.record.jobId !== jobId) {
267
317
  throw new DeliveryStoreError("ATTEMPT_CONFLICT", {
@@ -319,8 +369,10 @@ export class DeliveryController {
319
369
  if (!res.ok)
320
370
  throw invalid(`attempt: ${res.errors.join("; ")}`, "an attempt valid under the US-001 contract");
321
371
  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 };
372
+ const now = iso(nowMs);
373
+ // Only a worker's claim has a lease: it is the worker that renews it. A direct claim never expires.
374
+ const leaseExpiresAt = opts.workerId !== undefined ? iso(nowMs + this.leaseMs) : null;
375
+ const stored = { record, claimedAt: now, claimedEpoch: epoch, claimedBy: opts.workerId ?? null, leaseExpiresAt, resolution: "open", resolvedAt: null, resolvedEpoch: null };
324
376
  this.store.commit(epoch, (draft) => {
325
377
  opts.guard?.(draft);
326
378
  draft.attempts.push(structuredClone(stored));
@@ -331,6 +383,8 @@ export class DeliveryController {
331
383
  recordOutcome(attemptId, outcome, opts = {}) {
332
384
  if (outcome !== "passed" && outcome !== "failed")
333
385
  throw invalid(`outcome ${JSON.stringify(outcome)}`, '"passed" or "failed"');
386
+ const nowMs = this.store.nowMs();
387
+ this.expireDue(nowMs);
334
388
  const known = this.store.state.attempts.find((a) => a.record.attemptId === attemptId);
335
389
  if (!known) {
336
390
  throw new DeliveryStoreError("UNKNOWN_ATTEMPT", {
@@ -339,13 +393,8 @@ export class DeliveryController {
339
393
  action: "Check the attemptId. Nothing was written.",
340
394
  });
341
395
  }
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
- }
396
+ if (known.resolution === "abandoned")
397
+ throw abandonedError(known);
349
398
  if (known.resolution === "reported") {
350
399
  if (known.record.outcome === outcome) {
351
400
  opts.guard?.(this.store.state);
@@ -358,12 +407,14 @@ export class DeliveryController {
358
407
  });
359
408
  }
360
409
  const epoch = this.epoch;
361
- const now = this.store.now();
410
+ const now = iso(nowMs);
362
411
  this.store.commit(epoch, (draft) => {
363
412
  opts.guard?.(draft);
364
413
  const a = draft.attempts.find((x) => x.record.attemptId === attemptId);
365
414
  if (!a)
366
415
  return;
416
+ if (a.resolution !== "open" || leaseExpired(a, nowMs))
417
+ throw abandonedError(a);
367
418
  a.record.outcome = outcome;
368
419
  a.resolution = "reported";
369
420
  a.resolvedAt = now;
@@ -381,6 +432,8 @@ export class DeliveryController {
381
432
  * reported attempt cannot be returned.
382
433
  */
383
434
  returnAttempt(attemptId, opts = {}) {
435
+ const nowMs = this.store.nowMs();
436
+ this.expireDue(nowMs);
384
437
  const known = this.store.state.attempts.find((a) => a.record.attemptId === attemptId);
385
438
  if (!known) {
386
439
  throw new DeliveryStoreError("UNKNOWN_ATTEMPT", {
@@ -402,7 +455,7 @@ export class DeliveryController {
402
455
  });
403
456
  }
404
457
  const epoch = this.epoch;
405
- const now = this.store.now();
458
+ const now = iso(nowMs);
406
459
  this.store.commit(epoch, (draft) => {
407
460
  opts.guard?.(draft);
408
461
  const a = draft.attempts.find((x) => x.record.attemptId === attemptId);
@@ -416,6 +469,126 @@ export class DeliveryController {
416
469
  const updated = this.store.state.attempts.find((a) => a.record.attemptId === attemptId);
417
470
  return attemptView(updated ?? known);
418
471
  }
472
+ /**
473
+ * Extend the lease of an open attempt to now + claimLeaseMs on the store clock.
474
+ * Refused with ATTEMPT_ABANDONED when the lease has already expired (at
475
+ * exactly leaseExpiresAt it has), with ATTEMPT_CONFLICT for a reported attempt
476
+ * or one without a lease, and ACCESS_DENIED for another claimant. The guard and
477
+ * every check run again inside the commit, so the renewal and the expiry it
478
+ * races are decided once, at one clock reading.
479
+ */
480
+ renewLease(attemptId, opts = {}) {
481
+ const nowMs = this.store.nowMs();
482
+ this.expireDue(nowMs);
483
+ const known = this.store.state.attempts.find((a) => a.record.attemptId === attemptId);
484
+ if (!known) {
485
+ throw new DeliveryStoreError("UNKNOWN_ATTEMPT", {
486
+ found: `no attempt ${attemptId}`,
487
+ expected: "an attemptId returned by claim",
488
+ action: "Check the attemptId. Nothing was written.",
489
+ });
490
+ }
491
+ if (known.claimedBy !== (opts.workerId ?? null))
492
+ throw notClaimant(opts.workerId, attemptId);
493
+ const check = (a) => {
494
+ if (!a)
495
+ throw notClaimant(opts.workerId, attemptId);
496
+ if (a.resolution === "abandoned" || leaseExpired(a, nowMs))
497
+ throw abandonedError(a);
498
+ if (a.resolution === "reported") {
499
+ throw new DeliveryStoreError("ATTEMPT_CONFLICT", {
500
+ found: `attempt ${attemptId} already reported ${a.record.outcome}`,
501
+ expected: "an open attempt",
502
+ action: "The outcome is final; there is no lease to renew. Nothing was written.",
503
+ });
504
+ }
505
+ if (a.leaseExpiresAt === null) {
506
+ throw new DeliveryStoreError("ATTEMPT_CONFLICT", {
507
+ found: `attempt ${attemptId} has no lease`,
508
+ expected: "an attempt claimed by a worker under a lease",
509
+ action: "Only a worker's claim has a lease to renew. Nothing was written.",
510
+ });
511
+ }
512
+ return a;
513
+ };
514
+ check(known);
515
+ const leaseExpiresAt = iso(nowMs + this.leaseMs);
516
+ this.store.commit(this.epoch, (draft) => {
517
+ opts.guard?.(draft);
518
+ const a = check(draft.attempts.find((x) => x.record.attemptId === attemptId));
519
+ if (a.claimedBy !== (opts.workerId ?? null))
520
+ throw notClaimant(opts.workerId, attemptId);
521
+ a.leaseExpiresAt = leaseExpiresAt;
522
+ });
523
+ return { attemptId, leaseExpiresAt };
524
+ }
525
+ /** The lease time of an attempt, or null when it has none. */
526
+ leaseExpiresAt(attemptId) {
527
+ const a = this.store.state.attempts.find((x) => x.record.attemptId === attemptId);
528
+ if (!a) {
529
+ throw new DeliveryStoreError("UNKNOWN_ATTEMPT", {
530
+ found: `no attempt ${attemptId}`,
531
+ expected: "an attemptId returned by claim",
532
+ action: "Check the attemptId.",
533
+ });
534
+ }
535
+ return a.leaseExpiresAt;
536
+ }
537
+ /** The claim lease length in ms that this controller gives a worker's claim. A heartbeat derives its period from it. */
538
+ get claimLeaseMs() {
539
+ return this.leaseMs;
540
+ }
541
+ /** True when the attempt is open under a lease that has run out on the store clock, but has not been swept yet. */
542
+ leaseLapsed(attemptId) {
543
+ const a = this.store.state.attempts.find((x) => x.record.attemptId === attemptId);
544
+ return a !== undefined && leaseExpired(a, this.store.nowMs());
545
+ }
546
+ /**
547
+ * Abandon every open attempt whose lease has run out at the store clock's
548
+ * current time, in one commit. Returns the abandoned attemptIds (none: no commit).
549
+ */
550
+ expireLeases() {
551
+ this.store.assertOwner();
552
+ return this.expireDue(this.store.nowMs());
553
+ }
554
+ /** Abandon the attempts whose lease has run out at `nowMs`. One commit, or none when nothing has expired. */
555
+ expireDue(nowMs) {
556
+ if (!this.store.state.attempts.some((a) => leaseExpired(a, nowMs)))
557
+ return [];
558
+ const epoch = this.epoch;
559
+ const expired = [];
560
+ this.store.commit(epoch, (draft) => {
561
+ for (const a of draft.attempts) {
562
+ if (!leaseExpired(a, nowMs))
563
+ continue;
564
+ abandon(a, iso(nowMs), epoch);
565
+ expired.push(a.record.attemptId);
566
+ }
567
+ });
568
+ return expired;
569
+ }
570
+ /**
571
+ * Revoke a worker and abandon its open attempts in the same fenced commit, so
572
+ * a revoked worker's claims are freed at once. `mutate` changes the worker
573
+ * records and may throw to refuse; nothing is written then. Returns the
574
+ * abandoned attemptIds.
575
+ * @internal Used by enrollment.ts revoke().
576
+ */
577
+ commitRevocation(workerId, mutate) {
578
+ const epoch = this.epoch;
579
+ const now = this.store.now();
580
+ const freed = [];
581
+ this.store.commit(epoch, (draft) => {
582
+ mutate(draft.workers, { epoch, now });
583
+ for (const a of draft.attempts) {
584
+ if (a.resolution !== "open" || a.claimedBy !== workerId)
585
+ continue;
586
+ abandon(a, now, epoch);
587
+ freed.push(a.record.attemptId);
588
+ }
589
+ });
590
+ return freed;
591
+ }
419
592
  /**
420
593
  * Throw unless this handle still owns the store: STORE_CLOSED for a closed
421
594
  * or failed handle, FENCED when another controller has taken over. Read only.
@@ -461,6 +634,27 @@ export class DeliveryController {
461
634
  const now = this.store.now();
462
635
  this.store.commit(epoch, (draft) => mutate(draft, { epoch, now }));
463
636
  }
637
+ /** US-009: copies of the deployment ledger. */
638
+ deploymentRecords() {
639
+ this.store.assertOwner();
640
+ return structuredClone(this.store.state.deployments);
641
+ }
642
+ /** US-009: copies of the stored company deploy policies. */
643
+ deployPolicyRecords() {
644
+ this.store.assertOwner();
645
+ return structuredClone(this.store.state.deployPolicies);
646
+ }
647
+ /**
648
+ * Change the deployment ledger in one fenced store commit. `mutate` gets the
649
+ * whole draft so it can re-check attempts against the state being written;
650
+ * it may throw to refuse, and nothing is written then.
651
+ * @internal Used by effects.ts; other callers must not write deployments.
652
+ */
653
+ commitDeployments(mutate) {
654
+ const epoch = this.epoch;
655
+ const now = this.store.now();
656
+ this.store.commit(epoch, (draft) => mutate(draft, { epoch, now }));
657
+ }
464
658
  /** Release ownership of the store. Idempotent. */
465
659
  close() {
466
660
  this.store.close();
@@ -473,6 +667,23 @@ export class DeliveryController {
473
667
  });
474
668
  }
475
669
  }
670
+ /** Mark an open attempt abandoned: outcome failed, resolved now in `epoch`. */
671
+ function abandon(a, now, epoch) {
672
+ a.record.outcome = "failed";
673
+ a.resolution = "abandoned";
674
+ a.resolvedAt = now;
675
+ a.resolvedEpoch = epoch;
676
+ }
677
+ /** The refusal of a late call for an abandoned (or lease-expired) attempt. */
678
+ function abandonedError(a) {
679
+ return new DeliveryStoreError("ATTEMPT_ABANDONED", {
680
+ found: a.resolution === "abandoned"
681
+ ? `attempt ${a.record.attemptId} was abandoned at epoch ${a.resolvedEpoch} (its controller stopped, its lease expired, its worker was revoked or it was returned)`
682
+ : `attempt ${a.record.attemptId} lease expired at ${a.leaseExpiresAt}`,
683
+ expected: "an open attempt",
684
+ action: "Discard this result. Claim the job again to run a new attempt. Nothing was written.",
685
+ });
686
+ }
476
687
  /** An id another tenant holds. The answer does not say that it exists or whose it is. */
477
688
  function unavailableId(kind, id) {
478
689
  return new DeliveryStoreError("DUPLICATE_CONFLICT", {
@@ -0,0 +1,22 @@
1
+ import type { WorkerIdentity } from "../identity.js";
2
+ import type { WorkerAccessPort } from "./port.js";
3
+ import { type RpcMethod } from "./wire.js";
4
+ export interface WorkerRpcClientOptions {
5
+ port: number;
6
+ /** Default "127.0.0.1". */
7
+ host?: string;
8
+ /** Required to dial anything but 127.0.0.1, ::1 or localhost. */
9
+ allowNonLoopback?: boolean;
10
+ /** Deadline of one call, connect to answer. Default DEFAULT_RPC_TIMEOUT_MS. */
11
+ timeoutMs?: number;
12
+ /** Retries after RPC_TIMEOUT, RPC_CLOSED or RPC_UNREACHABLE. Default 2. */
13
+ retries?: number;
14
+ /** The attemptId for a claim or dispatch that does not pass one. Default attempt-<uuid>. */
15
+ attemptIds?: () => string;
16
+ }
17
+ export type WorkerRpcClient = WorkerAccessPort & {
18
+ /** One allowlisted call with retries; resolves with the raw wire value. */
19
+ call(method: RpcMethod, identity: WorkerIdentity, args: unknown[]): Promise<unknown>;
20
+ };
21
+ export declare function workerRpcClient(opts: WorkerRpcClientOptions): WorkerRpcClient;
22
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1,159 @@
1
+ /**
2
+ * The worker side of the worker RPC (US-011 slice 4 B): a WorkerAccessPort
3
+ * over loopback TCP. See wire.ts for the format.
4
+ *
5
+ * - Dials 127.0.0.1 by default; any host but 127.0.0.1, ::1 or localhost is
6
+ * refused with RPC_NOT_LOOPBACK unless allowNonLoopback is true.
7
+ * - Each call has its own deadline (timeoutMs, default 10 s). No answer by
8
+ * then is RPC_TIMEOUT and the connection is destroyed, so a silent drop
9
+ * cannot hang the worker. A refused connection is RPC_UNREACHABLE; a
10
+ * connection that closes before the answer is RPC_CLOSED.
11
+ * - Those three are retried `retries` times (default 2) with the same request.
12
+ * That is safe for every allowlisted method: a claim or dispatch carries an
13
+ * attemptId fixed for the logical call, so a retry after a lost answer
14
+ * replays the stored claim instead of opening a second attempt; a repeated
15
+ * report with the same outcome and a repeated return are replays; a repeated
16
+ * renewal extends the lease again; reads are reads.
17
+ * - A refusal is rebuilt as the DeliveryStoreError the controller raised.
18
+ * - A request over MAX_REQUEST_BYTES is refused before it is sent.
19
+ */
20
+ import { randomUUID } from "node:crypto";
21
+ import { connect } from "node:net";
22
+ import { isSafeAttemptId } from "../attempt-id.js";
23
+ import { DeliveryStoreError } from "../migrations.js";
24
+ import { DEFAULT_RPC_TIMEOUT_MS, MAX_ANSWER_BYTES, MAX_REQUEST_BYTES, RPC_WIRE_VERSION, encodeLine, errorFromBody, isLoopbackDialHost, notLoopback, rpcError, } from "./wire.js";
25
+ const RETRYABLE = new Set(["RPC_TIMEOUT", "RPC_CLOSED", "RPC_UNREACHABLE", "RPC_BUSY"]);
26
+ /** A claim answer is used as a path by the worker: its attempt id must be a safe name (review I5). */
27
+ function checkedClaim(value, method) {
28
+ if (!isSafeAttemptId(value?.attempt?.attemptId)) {
29
+ throw rpcError("RPC_BAD_ANSWER", `a ${method} answer whose attempt id is not a safe name`, "an attempt id of letters, digits, dot, underscore or dash", "Do not use the answer. Check what is listening on the controller's port.");
30
+ }
31
+ return value;
32
+ }
33
+ /** Rebuild Dispatch's credentials from the wire's refs and values, with the same redacting JSON as in process. */
34
+ function dispatchFromWire(raw) {
35
+ const d = raw;
36
+ const refs = Object.freeze([...d.credentials.refs]);
37
+ const values = new Map(Object.entries(d.credentials.values));
38
+ const describe = () => `[credentials ${refs.join(", ")}]`;
39
+ const credentials = Object.freeze({
40
+ refs,
41
+ has: (ref) => values.has(ref),
42
+ get: (ref) => {
43
+ const v = values.get(ref);
44
+ if (v === undefined) {
45
+ throw new DeliveryStoreError("PRIVILEGE_REJECTED", { found: `credential ${ref} was not injected`, expected: `one of ${refs.join(", ") || "no credentials"}`, action: "Request it in dispatch. Nothing was read." });
46
+ }
47
+ return v;
48
+ },
49
+ toJSON: () => ({ refs: [...refs], values: "[credentials redacted]" }),
50
+ toString: describe,
51
+ });
52
+ return { claim: d.claim, jobClass: d.jobClass, credentials };
53
+ }
54
+ export function workerRpcClient(opts) {
55
+ const host = opts.host ?? "127.0.0.1";
56
+ if (!isLoopbackDialHost(host) && opts.allowNonLoopback !== true)
57
+ throw notLoopback(host, "dial");
58
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_RPC_TIMEOUT_MS;
59
+ const retries = opts.retries ?? 2;
60
+ if (!Number.isSafeInteger(retries) || retries < 0)
61
+ throw rpcError("RPC_BAD_REQUEST", `retries ${String(opts.retries)}`, "a non-negative integer", "Nothing was sent.");
62
+ const attemptIds = opts.attemptIds ?? (() => `attempt-${randomUUID()}`);
63
+ function once(line, method) {
64
+ return new Promise((resolve, reject) => {
65
+ let settled = false;
66
+ let connected = false;
67
+ const chunks = [];
68
+ let size = 0;
69
+ const sock = connect({ port: opts.port, host });
70
+ const timer = setTimeout(() => finish(rpcError("RPC_TIMEOUT", `no answer to ${method} within ${timeoutMs} ms`, "an answer from the controller", "The call may have been applied; it is safe to retry with the same arguments.")), timeoutMs);
71
+ function finish(err, value) {
72
+ if (settled)
73
+ return;
74
+ settled = true;
75
+ clearTimeout(timer);
76
+ sock.destroy();
77
+ if (err)
78
+ reject(err);
79
+ else
80
+ resolve(value);
81
+ }
82
+ sock.setNoDelay(true);
83
+ sock.on("error", (err) => {
84
+ if (!connected && (err.code === "ECONNREFUSED" || err.code === "EHOSTUNREACH" || err.code === "ENETUNREACH" || err.code === "EADDRNOTAVAIL")) {
85
+ finish(rpcError("RPC_UNREACHABLE", `no controller listening at ${host}:${opts.port} (${err.code})`, "a running controller RPC server", "Start the controller, or check the host and port. Nothing was sent."));
86
+ }
87
+ else {
88
+ finish(rpcError("RPC_CLOSED", `${method}: the connection failed (${err.code ?? err.message})`, "an answer from the controller", "The call may have been applied; it is safe to retry with the same arguments."));
89
+ }
90
+ });
91
+ sock.on("close", () => finish(rpcError("RPC_CLOSED", `${method}: the connection closed before an answer`, "an answer from the controller", "The call may have been applied; it is safe to retry with the same arguments.")));
92
+ sock.once("connect", () => {
93
+ connected = true;
94
+ sock.write(line);
95
+ });
96
+ sock.on("data", (b) => {
97
+ if (settled)
98
+ return;
99
+ const nl = b.indexOf(10);
100
+ if (size + (nl < 0 ? b.length : nl) > MAX_ANSWER_BYTES) {
101
+ finish(rpcError("RPC_BAD_ANSWER", `an answer to ${method} over ${MAX_ANSWER_BYTES} bytes`, `at most ${MAX_ANSWER_BYTES} bytes`, "Check the controller. The call may have been applied."));
102
+ return;
103
+ }
104
+ if (nl < 0) {
105
+ chunks.push(b);
106
+ size += b.length;
107
+ return;
108
+ }
109
+ chunks.push(b.subarray(0, nl));
110
+ let res;
111
+ try {
112
+ res = JSON.parse(Buffer.concat(chunks).toString("utf8"));
113
+ }
114
+ catch {
115
+ finish(rpcError("RPC_BAD_ANSWER", `an answer to ${method} that is not JSON`, "one JSON answer line", "Check that the controller runs a matching HQ version."));
116
+ return;
117
+ }
118
+ if (res?.v !== RPC_WIRE_VERSION)
119
+ finish(rpcError("RPC_BAD_ANSWER", `an answer to ${method} with wire version ${JSON.stringify(res?.v)}`, `version ${RPC_WIRE_VERSION}`, "Use a worker and controller of the same HQ version."));
120
+ else if (res.ok === true)
121
+ finish(null, res.value);
122
+ else
123
+ finish(errorFromBody(res.error, method));
124
+ });
125
+ });
126
+ }
127
+ async function call(method, identity, args) {
128
+ const line = encodeLine({ v: RPC_WIRE_VERSION, id: randomUUID(), method, identity, args });
129
+ if (Buffer.byteLength(line, "utf8") > MAX_REQUEST_BYTES) {
130
+ throw rpcError("RPC_TOO_LARGE", `a ${method} request over ${MAX_REQUEST_BYTES} bytes`, `at most ${MAX_REQUEST_BYTES} bytes per request`, "Send smaller arguments. Nothing was sent.");
131
+ }
132
+ for (let attempt = 0;; attempt += 1) {
133
+ try {
134
+ return await once(line, method);
135
+ }
136
+ catch (err) {
137
+ if (attempt < retries && err instanceof DeliveryStoreError && RETRYABLE.has(err.code))
138
+ continue;
139
+ throw err;
140
+ }
141
+ }
142
+ }
143
+ return {
144
+ call,
145
+ readRun: async (identity, runId) => (await call("readRun", identity, [runId])),
146
+ readyWork: async (identity, page) => (await call("readyWork", identity, [page])),
147
+ verifyNotification: async (identity, event) => (await call("verifyNotification", identity, [event])),
148
+ claim: async (identity, jobId, claimOpts) => checkedClaim((await call("claim", identity, [jobId, { attemptId: claimOpts?.attemptId ?? attemptIds() }])), "claim"),
149
+ dispatch: async (identity, jobId, request) => {
150
+ const d = dispatchFromWire(await call("dispatch", identity, [jobId, { credentials: request?.credentials, attemptId: request?.attemptId ?? attemptIds() }]));
151
+ checkedClaim(d.claim, "dispatch");
152
+ return d;
153
+ },
154
+ recordOutcome: async (identity, attemptId, outcome) => (await call("recordOutcome", identity, [attemptId, outcome])),
155
+ returnAttempt: async (identity, attemptId) => (await call("returnAttempt", identity, [attemptId])),
156
+ renewLease: async (identity, attemptId) => (await call("renewLease", identity, [attemptId])),
157
+ };
158
+ }
159
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The worker's view of the controller (US-011 slice 4 B): the allowlisted
3
+ * worker methods of DeliveryAccess, awaited. A worker runs against either the
4
+ * in-process access layer (inProcessPort) or the loopback RPC client
5
+ * (workerRpcClient); both answer and refuse identically.
6
+ *
7
+ * Methods may answer synchronously or with a promise, so a DeliveryAccess is
8
+ * itself a port; callers always await.
9
+ */
10
+ import type { LedgerEvent } from "../outbox.js";
11
+ import type { DeliveryAccess, Dispatch, ReadyPage } from "../enrollment.js";
12
+ import type { WorkerIdentity } from "../identity.js";
13
+ import type { AttemptView, ClaimResult, JobView, LeaseView } from "../reconciler.js";
14
+ import type { Run } from "../contracts.js";
15
+ export type Awaitable<T> = T | Promise<T>;
16
+ export interface WorkerAccessPort {
17
+ readRun(identity: WorkerIdentity, runId: string): Awaitable<{
18
+ run: Run;
19
+ jobs: JobView[];
20
+ }>;
21
+ readyWork(identity: WorkerIdentity, page: {
22
+ after: string | null;
23
+ limit: number;
24
+ }): Awaitable<ReadyPage>;
25
+ verifyNotification(identity: WorkerIdentity, event: LedgerEvent): Awaitable<string[]>;
26
+ /** opts.attemptId: claim again with the same id to replay a claim whose answer was lost. */
27
+ claim(identity: WorkerIdentity, jobId: string, opts?: {
28
+ attemptId?: string;
29
+ }): Awaitable<ClaimResult>;
30
+ dispatch(identity: WorkerIdentity, jobId: string, request: {
31
+ credentials: string[];
32
+ attemptId?: string;
33
+ }): Awaitable<Dispatch>;
34
+ recordOutcome(identity: WorkerIdentity, attemptId: string, outcome: "passed" | "failed"): Awaitable<AttemptView>;
35
+ returnAttempt(identity: WorkerIdentity, attemptId: string): Awaitable<AttemptView>;
36
+ renewLease(identity: WorkerIdentity, attemptId: string): Awaitable<LeaseView>;
37
+ }
38
+ /** The in-process port: each call goes straight to `access`, answered as a promise like the RPC client. */
39
+ export declare function inProcessPort(access: DeliveryAccess): WorkerAccessPort;
40
+ //# sourceMappingURL=port.d.ts.map
@@ -0,0 +1,16 @@
1
+ const _portMatchesAllowlist = true;
2
+ void _portMatchesAllowlist;
3
+ /** The in-process port: each call goes straight to `access`, answered as a promise like the RPC client. */
4
+ export function inProcessPort(access) {
5
+ return {
6
+ readRun: async (identity, runId) => access.readRun(identity, runId),
7
+ readyWork: async (identity, page) => access.readyWork(identity, page),
8
+ verifyNotification: async (identity, event) => access.verifyNotification(identity, event),
9
+ claim: async (identity, jobId, opts) => access.claim(identity, jobId, opts),
10
+ dispatch: async (identity, jobId, request) => access.dispatch(identity, jobId, request),
11
+ recordOutcome: async (identity, attemptId, outcome) => access.recordOutcome(identity, attemptId, outcome),
12
+ returnAttempt: async (identity, attemptId) => access.returnAttempt(identity, attemptId),
13
+ renewLease: async (identity, attemptId) => access.renewLease(identity, attemptId),
14
+ };
15
+ }
16
+ //# sourceMappingURL=port.js.map
@@ -0,0 +1,30 @@
1
+ import type { DeliveryAccess } from "../enrollment.js";
2
+ export interface WorkerRpcServerOptions {
3
+ access: DeliveryAccess;
4
+ /** Default "localhost": 127.0.0.1 and ::1. */
5
+ host?: string;
6
+ /** Default 0: any free port. */
7
+ port?: number;
8
+ /** Required to bind anything but 127.0.0.1, ::1 or localhost. */
9
+ allowNonLoopback?: boolean;
10
+ /** Close a connection that has not sent a complete request within this many ms. Default DEFAULT_SERVER_DEADLINE_MS. */
11
+ deadlineMs?: number;
12
+ /** Open connections held at once; past this a connection is answered RPC_BUSY and closed. Default DEFAULT_MAX_CONNECTIONS. */
13
+ maxConnections?: number;
14
+ /** Receives the full error whenever the wire carries less (an unexpected error, or a store-internal refusal). */
15
+ onError?: (err: unknown) => void;
16
+ }
17
+ export interface WorkerRpcServer {
18
+ readonly host: string;
19
+ readonly port: number;
20
+ /** The addresses actually bound, for example ["127.0.0.1", "::1"]. */
21
+ readonly addresses: string[];
22
+ /** Calls received for `method` (all methods when omitted), counted when a valid request line arrives. */
23
+ calls(method?: string): number;
24
+ /** Let the process exit while the server is listening. */
25
+ unref(): void;
26
+ /** Stop listening and close every open connection. Idempotent. */
27
+ close(): Promise<void>;
28
+ }
29
+ export declare function startWorkerRpcServer(opts: WorkerRpcServerOptions): Promise<WorkerRpcServer>;
30
+ //# sourceMappingURL=server.d.ts.map