@indigoai-us/hq-cli 5.345.214 → 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 (200) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
  3. package/dist/command-catalog.generated.d.ts +180 -13
  4. package/dist/command-catalog.generated.js +221 -13
  5. package/dist/commands/agents.d.ts +51 -1
  6. package/dist/commands/agents.js +154 -2
  7. package/dist/commands/bot-jobs.d.ts +2 -15
  8. package/dist/commands/bot-jobs.js +2 -94
  9. package/dist/commands/bot-runtime.d.ts +46 -5
  10. package/dist/commands/bot-runtime.js +228 -18
  11. package/dist/commands/bot.d.ts +16 -9
  12. package/dist/commands/bot.js +231 -55
  13. package/dist/commands/capacity.d.ts +4 -1
  14. package/dist/commands/capacity.js +46 -10
  15. package/dist/commands/cloud.d.ts +66 -13
  16. package/dist/commands/cloud.js +121 -40
  17. package/dist/commands/company-restore.d.ts +23 -0
  18. package/dist/commands/company-restore.js +128 -0
  19. package/dist/commands/company.js +2 -0
  20. package/dist/commands/core-delegate-w1b.js +15 -1
  21. package/dist/commands/core-policy.js +67 -8
  22. package/dist/commands/daemon.js +5 -0
  23. package/dist/commands/files-browse.d.ts +11 -4
  24. package/dist/commands/files-browse.js +21 -4
  25. package/dist/commands/files.d.ts +1 -1
  26. package/dist/commands/files.js +25 -11
  27. package/dist/commands/integrations-auth-rules.d.ts +27 -0
  28. package/dist/commands/integrations-auth-rules.js +79 -0
  29. package/dist/commands/integrations-connect.d.ts +10 -3
  30. package/dist/commands/integrations-connect.js +87 -13
  31. package/dist/commands/integrations-import.js +124 -12
  32. package/dist/commands/lanes.js +28 -11
  33. package/dist/commands/mesh.d.ts +2 -0
  34. package/dist/commands/mesh.js +60 -35
  35. package/dist/commands/sources.js +6 -0
  36. package/dist/commands/storage-offload.d.ts +12 -0
  37. package/dist/commands/storage-offload.js +41 -3
  38. package/dist/commands/sync-held.js +5 -2
  39. package/dist/commands/sync-mode.js +5 -0
  40. package/dist/commands/whoami.js +4 -0
  41. package/dist/lazy-commands.js +3 -5
  42. package/dist/lib/bot/config.d.ts +1 -0
  43. package/dist/lib/bot/config.js +10 -0
  44. package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
  45. package/dist/lib/bot/eventbridge-cron.js +104 -0
  46. package/dist/lib/bot/fleet-cron.d.ts +8 -0
  47. package/dist/lib/bot/fleet-cron.js +35 -3
  48. package/dist/lib/bot/fleet-daemon.d.ts +46 -0
  49. package/dist/lib/bot/fleet-daemon.js +99 -1
  50. package/dist/lib/bot/fleet-local.d.ts +33 -1
  51. package/dist/lib/bot/fleet-local.js +215 -31
  52. package/dist/lib/bot/fleet-python.d.ts +3 -0
  53. package/dist/lib/bot/fleet-python.js +34 -4
  54. package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
  55. package/dist/lib/bot/fleet-runtime-sources.js +30 -0
  56. package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
  57. package/dist/lib/bot/legacy-provider-login.js +19 -2
  58. package/dist/lib/bot/probe.js +7 -1
  59. package/dist/lib/bot/prompt.js +1 -1
  60. package/dist/lib/bot/readiness.d.ts +8 -0
  61. package/dist/lib/bot/readiness.js +17 -3
  62. package/dist/lib/bot/run.js +20 -1
  63. package/dist/lib/bot/runtime/codex.js +1 -1
  64. package/dist/lib/bot/runtime/grok-acp.d.ts +5 -1
  65. package/dist/lib/bot/runtime/grok-acp.js +6 -3
  66. package/dist/lib/bot/runtime/index.js +19 -9
  67. package/dist/lib/bot/runtime/messages-stream.js +2 -2
  68. package/dist/lib/bot/runtime/types.d.ts +15 -0
  69. package/dist/lib/bot/runtime/types.js +9 -0
  70. package/dist/lib/bot/runtime-auth.d.ts +30 -0
  71. package/dist/lib/bot/runtime-auth.js +94 -3
  72. package/dist/lib/bot/runtime-failure.d.ts +23 -0
  73. package/dist/lib/bot/runtime-failure.js +43 -1
  74. package/dist/lib/bot/status.d.ts +2 -0
  75. package/dist/lib/capacity/accounts.d.ts +8 -0
  76. package/dist/lib/capacity/accounts.js +19 -0
  77. package/dist/lib/capacity/available.d.ts +154 -0
  78. package/dist/lib/capacity/available.js +905 -0
  79. package/dist/lib/capacity/codex-availability.d.ts +14 -1
  80. package/dist/lib/capacity/codex-availability.js +26 -1
  81. package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
  82. package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
  83. package/dist/lib/capacity/collectors/codex.js +10 -7
  84. package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
  85. package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
  86. package/dist/lib/capacity/collectors/grok.d.ts +5 -0
  87. package/dist/lib/capacity/collectors/grok.js +56 -5
  88. package/dist/lib/capacity/ledger.d.ts +37 -1
  89. package/dist/lib/capacity/ledger.js +207 -30
  90. package/dist/lib/capacity/project.d.ts +26 -0
  91. package/dist/lib/capacity/project.js +137 -8
  92. package/dist/lib/capacity/refusal-rows.d.ts +31 -0
  93. package/dist/lib/capacity/refusal-rows.js +61 -0
  94. package/dist/lib/capacity/refusal.d.ts +53 -2
  95. package/dist/lib/capacity/refusal.js +284 -65
  96. package/dist/lib/capacity/route.js +46 -11
  97. package/dist/lib/capacity/widget.d.ts +12 -1
  98. package/dist/lib/capacity/widget.js +91 -3
  99. package/dist/lib/daemon/catalog.js +11 -1
  100. package/dist/lib/daemon/resolver.d.ts +2 -0
  101. package/dist/lib/daemon/resolver.js +3 -0
  102. package/dist/lib/daemon/run.d.ts +9 -0
  103. package/dist/lib/daemon/run.js +54 -1
  104. package/dist/lib/daemon/server.d.ts +2 -0
  105. package/dist/lib/daemon/server.js +10 -1
  106. package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
  107. package/dist/lib/daemon/tcc-eperm.js +310 -0
  108. package/dist/lib/db/sqlite-binding.d.ts +1 -0
  109. package/dist/lib/db/sqlite-binding.js +1 -1
  110. package/dist/lib/delivery/admission.d.ts +86 -0
  111. package/dist/lib/delivery/admission.js +148 -0
  112. package/dist/lib/delivery/artifacts.d.ts +105 -0
  113. package/dist/lib/delivery/artifacts.js +567 -0
  114. package/dist/lib/delivery/attempt-id.d.ts +13 -0
  115. package/dist/lib/delivery/attempt-id.js +16 -0
  116. package/dist/lib/delivery/backup.d.ts +78 -0
  117. package/dist/lib/delivery/backup.js +343 -0
  118. package/dist/lib/delivery/cache.d.ts +29 -0
  119. package/dist/lib/delivery/cache.js +33 -0
  120. package/dist/lib/delivery/contracts.d.ts +142 -0
  121. package/dist/lib/delivery/contracts.js +289 -0
  122. package/dist/lib/delivery/credentials.d.ts +54 -0
  123. package/dist/lib/delivery/credentials.js +119 -0
  124. package/dist/lib/delivery/disposable-target.d.ts +42 -0
  125. package/dist/lib/delivery/disposable-target.js +111 -0
  126. package/dist/lib/delivery/effects.d.ts +136 -0
  127. package/dist/lib/delivery/effects.js +541 -0
  128. package/dist/lib/delivery/enrollment.d.ts +146 -0
  129. package/dist/lib/delivery/enrollment.js +460 -0
  130. package/dist/lib/delivery/escalations.d.ts +51 -0
  131. package/dist/lib/delivery/escalations.js +60 -0
  132. package/dist/lib/delivery/identity.d.ts +25 -0
  133. package/dist/lib/delivery/identity.js +82 -0
  134. package/dist/lib/delivery/inbox.d.ts +116 -0
  135. package/dist/lib/delivery/inbox.js +260 -0
  136. package/dist/lib/delivery/lease.d.ts +80 -0
  137. package/dist/lib/delivery/lease.js +134 -0
  138. package/dist/lib/delivery/migrations.d.ts +255 -0
  139. package/dist/lib/delivery/migrations.js +823 -0
  140. package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
  141. package/dist/lib/delivery/mqtt-adapter.js +242 -0
  142. package/dist/lib/delivery/mqtt.d.ts +63 -0
  143. package/dist/lib/delivery/mqtt.js +119 -0
  144. package/dist/lib/delivery/outbox.d.ts +95 -0
  145. package/dist/lib/delivery/outbox.js +187 -0
  146. package/dist/lib/delivery/provenance.d.ts +129 -0
  147. package/dist/lib/delivery/provenance.js +93 -0
  148. package/dist/lib/delivery/reconciler.d.ts +215 -0
  149. package/dist/lib/delivery/reconciler.js +703 -0
  150. package/dist/lib/delivery/restore.d.ts +35 -0
  151. package/dist/lib/delivery/restore.js +134 -0
  152. package/dist/lib/delivery/rpc/client.d.ts +22 -0
  153. package/dist/lib/delivery/rpc/client.js +159 -0
  154. package/dist/lib/delivery/rpc/port.d.ts +40 -0
  155. package/dist/lib/delivery/rpc/port.js +16 -0
  156. package/dist/lib/delivery/rpc/server.d.ts +30 -0
  157. package/dist/lib/delivery/rpc/server.js +205 -0
  158. package/dist/lib/delivery/rpc/wire.d.ts +85 -0
  159. package/dist/lib/delivery/rpc/wire.js +143 -0
  160. package/dist/lib/delivery/store.d.ts +163 -0
  161. package/dist/lib/delivery/store.js +944 -0
  162. package/dist/lib/delivery/windows-service-install.d.ts +262 -0
  163. package/dist/lib/delivery/windows-service-install.js +892 -0
  164. package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
  165. package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
  166. package/dist/lib/delivery/workers/macos.d.ts +191 -0
  167. package/dist/lib/delivery/workers/macos.js +943 -0
  168. package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
  169. package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
  170. package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
  171. package/dist/lib/delivery/workers/windows-service-live.js +711 -0
  172. package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
  173. package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
  174. package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
  175. package/dist/lib/delivery/workers/windows-service.js +584 -0
  176. package/dist/lib/delivery/workers/windows.d.ts +251 -0
  177. package/dist/lib/delivery/workers/windows.js +594 -0
  178. package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
  179. package/dist/lib/hot-channels/adapters/meetings.js +36 -3
  180. package/dist/lib/hot-channels/signals-pass.d.ts +10 -0
  181. package/dist/lib/hot-channels/signals-pass.js +71 -2
  182. package/dist/lib/hot-channels/signals-redo.js +10 -2
  183. package/dist/lib/install/provider-wrappers.d.ts +2 -0
  184. package/dist/lib/install/provider-wrappers.js +68 -3
  185. package/dist/lib/lanes/watcher.js +35 -0
  186. package/dist/lib/signals/steps/extract.js +40 -4
  187. package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
  188. package/dist/utils/catalog-runtime-paths.d.ts +34 -0
  189. package/dist/utils/catalog-runtime-paths.js +53 -0
  190. package/dist/utils/cognito-callback-port.d.ts +14 -0
  191. package/dist/utils/cognito-callback-port.js +24 -0
  192. package/dist/utils/cognito-session.js +3 -3
  193. package/dist/utils/deleted-company-notice.d.ts +59 -0
  194. package/dist/utils/deleted-company-notice.js +156 -0
  195. package/dist/utils/files-browse-acl.js +1 -1
  196. package/dist/utils/login-browser.d.ts +1 -1
  197. package/dist/utils/login-browser.js +7 -5
  198. package/dist/utils/resident-package-preload.js +30 -15
  199. package/dist/utils/vault-api.js +7 -0
  200. package/package.json +7 -7
@@ -0,0 +1,60 @@
1
+ import { escalationTopic } from "./mqtt.js";
2
+ import { openTransportDb } from "./outbox.js";
3
+ export const ESCALATION_SCHEMA = "hq-delivery.escalation.v1";
4
+ /** Every escalation the committed ledger implies, in ledger order. */
5
+ export function escalationEvents(deployments) {
6
+ return deployments
7
+ .filter((d) => d.status === "blocked" && d.decision !== null)
8
+ .map((d) => ({
9
+ schemaVersion: ESCALATION_SCHEMA,
10
+ eventId: `deployment.escalated:${d.deploymentId}`,
11
+ type: "deployment.escalated",
12
+ tenantId: d.decision.scope.tenantId,
13
+ environment: d.decision.scope.environment,
14
+ deploymentId: d.deploymentId,
15
+ code: d.decision.code,
16
+ found: d.decision.found,
17
+ escalateTo: d.decision.escalateTo,
18
+ epoch: d.requestedEpoch,
19
+ }));
20
+ }
21
+ export class EscalationPublisher {
22
+ access;
23
+ broker;
24
+ db;
25
+ constructor(access, broker, db) {
26
+ this.access = access;
27
+ this.broker = broker;
28
+ this.db = db;
29
+ }
30
+ static open(opts) {
31
+ const db = openTransportDb(opts.path);
32
+ db.exec("CREATE TABLE IF NOT EXISTS published (event_id TEXT PRIMARY KEY, at INTEGER NOT NULL)");
33
+ return new EscalationPublisher(opts.access, opts.broker, db);
34
+ }
35
+ pending() {
36
+ const done = new Set(this.db.prepare("SELECT event_id FROM published").all().map((r) => r.event_id));
37
+ return escalationEvents(this.access.controller.deploymentRecords()).filter((e) => !done.has(e.eventId));
38
+ }
39
+ /** Publish every pending escalation, oldest first. Stops at the first broker error. */
40
+ async publishPending() {
41
+ const pending = this.pending();
42
+ const insert = this.db.prepare("INSERT OR IGNORE INTO published (event_id, at) VALUES (?, ?)");
43
+ let published = 0;
44
+ for (const event of pending) {
45
+ try {
46
+ await this.broker.publish(escalationTopic(event.tenantId), JSON.stringify(event));
47
+ }
48
+ catch (err) {
49
+ return { published, remaining: pending.length - published, error: err instanceof Error ? err.message : "broker error" };
50
+ }
51
+ insert.run(event.eventId, Date.now());
52
+ published += 1;
53
+ }
54
+ return { published, remaining: 0, error: null };
55
+ }
56
+ close() {
57
+ this.db.close();
58
+ }
59
+ }
60
+ //# sourceMappingURL=escalations.js.map
@@ -0,0 +1,25 @@
1
+ import { type StoredWorker, type WorkerCapability, type WorkerTrust } from "./migrations.js";
2
+ export interface WorkerIdentity {
3
+ workerId: string;
4
+ token: string;
5
+ }
6
+ /** Check the shape of a presented identity. Exactly two non-empty strings, nothing else. */
7
+ export declare function parseIdentity(input: unknown): WorkerIdentity;
8
+ /** SHA-256 hex digest of a secret. The only form a secret is stored in. */
9
+ export declare function secretDigest(secret: string): string;
10
+ /** A new random secret: hqw_ for a worker token, hqe_ for an enrollment ticket. */
11
+ export declare function newSecret(kind: "worker" | "enrollment"): string;
12
+ /** Constant-time comparison of a presented secret with a stored digest. */
13
+ export declare function secretMatches(secret: string, storedSha256: string): boolean;
14
+ /** True when a worker with trust `have` may do what needs trust `want`. */
15
+ export declare function trustAllows(have: WorkerTrust, want: WorkerTrust): boolean;
16
+ /**
17
+ * Return the active worker for `input` when it may use `capability`, and,
18
+ * when tenantId is given, belongs to that tenant. Throws ACCESS_DENIED, or
19
+ * WORKER_REVOKED for a revoked worker with a valid token.
20
+ */
21
+ export declare function authenticate(workers: readonly StoredWorker[], input: unknown, need: {
22
+ capability: WorkerCapability;
23
+ tenantId?: string;
24
+ }): StoredWorker;
25
+ //# sourceMappingURL=identity.d.ts.map
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Worker identity (US-004).
3
+ *
4
+ * A worker presents { workerId, token } on every operation. The store keeps
5
+ * only a SHA-256 digest of the token, so a store file or backup never holds a
6
+ * usable secret. authenticate checks the presented identity against the
7
+ * stored workers and the operation's capability and tenant, and fails closed:
8
+ * anything missing, malformed or ambiguous is ACCESS_DENIED. An unknown worker
9
+ * and a wrong token get the same denial, so a caller cannot probe which
10
+ * workerIds exist. Errors never carry the token.
11
+ */
12
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
13
+ import { DeliveryStoreError } from "./migrations.js";
14
+ const TRUST_RANK = { standard: 0, release: 1 };
15
+ function deny(found, expected, action) {
16
+ return new DeliveryStoreError("ACCESS_DENIED", { found, expected, action: `${action} Nothing was written.` });
17
+ }
18
+ /** Check the shape of a presented identity. Exactly two non-empty strings, nothing else. */
19
+ export function parseIdentity(input) {
20
+ const ok = typeof input === "object" &&
21
+ input !== null &&
22
+ !Array.isArray(input) &&
23
+ Object.keys(input).sort().join(",") === "token,workerId" &&
24
+ typeof input.workerId === "string" &&
25
+ typeof input.token === "string" &&
26
+ input.workerId !== "" &&
27
+ input.token !== "";
28
+ if (!ok) {
29
+ throw deny("a missing or malformed worker identity", "an object with exactly a non-empty workerId and token", "Pass the identity returned by enroll.");
30
+ }
31
+ const { workerId, token } = input;
32
+ return { workerId, token };
33
+ }
34
+ /** SHA-256 hex digest of a secret. The only form a secret is stored in. */
35
+ export function secretDigest(secret) {
36
+ return createHash("sha256").update(secret, "utf8").digest("hex");
37
+ }
38
+ /** A new random secret: hqw_ for a worker token, hqe_ for an enrollment ticket. */
39
+ export function newSecret(kind) {
40
+ return `${kind === "worker" ? "hqw" : "hqe"}_${randomBytes(32).toString("base64url")}`;
41
+ }
42
+ /** Constant-time comparison of a presented secret with a stored digest. */
43
+ export function secretMatches(secret, storedSha256) {
44
+ const a = Buffer.from(secretDigest(secret), "hex");
45
+ const b = Buffer.from(storedSha256, "hex");
46
+ return a.length === b.length && timingSafeEqual(a, b);
47
+ }
48
+ /** True when a worker with trust `have` may do what needs trust `want`. */
49
+ export function trustAllows(have, want) {
50
+ return TRUST_RANK[have] >= TRUST_RANK[want];
51
+ }
52
+ /**
53
+ * Return the active worker for `input` when it may use `capability`, and,
54
+ * when tenantId is given, belongs to that tenant. Throws ACCESS_DENIED, or
55
+ * WORKER_REVOKED for a revoked worker with a valid token.
56
+ */
57
+ export function authenticate(workers, input, need) {
58
+ const identity = parseIdentity(input);
59
+ const matches = workers.filter((w) => w.workerId === identity.workerId);
60
+ if (matches.length > 1) {
61
+ throw deny(`${matches.length} stored workers named ${identity.workerId}`, "one worker per workerId", "The store is ambiguous about this worker; ask an admin to revoke and re-enroll it.");
62
+ }
63
+ const worker = matches[0];
64
+ if (!worker || !secretMatches(identity.token, worker.secretSha256) || worker.status === "pending") {
65
+ throw deny(`no enrolled worker ${identity.workerId} with the presented token`, "the workerId and token returned by enroll", "Check the identity, or ask an admin for a new enrollment ticket.");
66
+ }
67
+ if (worker.status === "revoked") {
68
+ throw new DeliveryStoreError("WORKER_REVOKED", {
69
+ found: `worker ${worker.workerId} was revoked at epoch ${worker.revokedEpoch}`,
70
+ expected: "an active worker",
71
+ action: "This worker can no longer claim, read or report. Ask an admin to enroll a new worker. Nothing was written.",
72
+ });
73
+ }
74
+ if (need.tenantId !== undefined && worker.tenantId !== need.tenantId) {
75
+ throw deny(`worker ${worker.workerId} of ${worker.tenantId} asked for work of another company`, `work of the worker's own company ${worker.tenantId}`, "Use a worker enrolled in the company that owns the work.");
76
+ }
77
+ if (!worker.capabilities.includes(need.capability)) {
78
+ throw deny(`worker ${worker.workerId} has capabilities [${worker.capabilities.join(", ")}]`, `the ${need.capability} capability`, `Enroll a worker with ${need.capability}, or use one that has it.`);
79
+ }
80
+ return worker;
81
+ }
82
+ //# sourceMappingURL=identity.js.map
@@ -0,0 +1,116 @@
1
+ import type { DeliveryAccess } from "./enrollment.js";
2
+ import type { WorkerIdentity } from "./identity.js";
3
+ import { type NotificationBroker } from "./mqtt.js";
4
+ import { type BackoffPolicy } from "./outbox.js";
5
+ export type HandleOutcome = "claimed" | "ignored" | "duplicate" | "rejected" | "deferred";
6
+ export interface HandleResult {
7
+ /** The presented event id, or null when the payload did not parse. */
8
+ eventId: string | null;
9
+ outcome: HandleOutcome;
10
+ /** An error code when rejected or deferred, else null. Never repeats presented ids. */
11
+ reason: string | null;
12
+ /** Jobs this call claimed. */
13
+ claims: string[];
14
+ }
15
+ export interface InboxRecord {
16
+ key: string;
17
+ outcome: HandleOutcome;
18
+ reason: string | null;
19
+ at: number;
20
+ }
21
+ export interface ConsumerClaim {
22
+ attemptId: string;
23
+ jobId: string;
24
+ at: number;
25
+ }
26
+ export interface ReconcileReport {
27
+ claimed: string[];
28
+ /** Jobs this worker could not claim (for example a release job); backed off. */
29
+ deferred: string[];
30
+ /** Jobs still inside their backoff window. */
31
+ skipped: string[];
32
+ cursor: string | null;
33
+ }
34
+ export interface ReconcileOptions {
35
+ /** Most jobs to scan in this call, an integer from 1 to MAX_BATCH. */
36
+ batchSize: number;
37
+ /**
38
+ * Optional time budget in milliseconds, read from the consumer's clock. Once
39
+ * it is spent the call stops after the job in hand, saves the cursor at that
40
+ * job and returns; the next call resumes after it. Absent means no budget.
41
+ */
42
+ maxMs?: number;
43
+ }
44
+ export interface ConsumerOptions {
45
+ access: DeliveryAccess;
46
+ identity: WorkerIdentity;
47
+ /** Path of the consumer's inbox sqlite file. Not the ledger. */
48
+ path: string;
49
+ /** Credential refs requested on each dispatch. Default none. */
50
+ credentials?: string[];
51
+ clock?: () => number;
52
+ backoff?: BackoffPolicy;
53
+ /**
54
+ * Test-only crash barrier, inert unless passed. Called after a dispatch
55
+ * commits its claim to the ledger and before the inbox claim row is saved,
56
+ * which is also before the handler returns and the broker ack is sent.
57
+ * process-crash.test.ts uses it to SIGKILL a child at that point.
58
+ */
59
+ testBarrier?: (stage: "claimed", jobId: string, attemptId: string) => void;
60
+ }
61
+ export declare class NotificationConsumer {
62
+ private readonly access;
63
+ private readonly identity;
64
+ private readonly db;
65
+ private readonly credentials;
66
+ private readonly clock;
67
+ private readonly backoff;
68
+ private readonly testBarrier;
69
+ private results;
70
+ private detach;
71
+ private readonly statements;
72
+ private constructor();
73
+ static open(opts: ConsumerOptions): NotificationConsumer;
74
+ /**
75
+ * Handle one notification payload. Never throws: every outcome is returned.
76
+ * Only "deferred" leaves nothing recorded.
77
+ */
78
+ handle(payload: string): HandleResult;
79
+ private handleOnce;
80
+ /**
81
+ * Claim one job through the access layer. False when the ledger says it is
82
+ * not claimable now or this worker may not run it (left for reconciliation
83
+ * and its backoff). Throws on anything that means the handle cannot act.
84
+ */
85
+ private tryClaim;
86
+ /**
87
+ * Claim up to `batchSize` ready jobs of this worker's company from the
88
+ * ledger, continuing after the saved cursor and wrapping to the start.
89
+ * With `maxMs`, the clock is read after each scanned job; once that much
90
+ * time has passed the call stops, saving that job as the cursor. FENCED and STORE_CLOSED are thrown; nothing is
91
+ * claimed then.
92
+ */
93
+ reconcile(opts: ReconcileOptions): ReconcileReport;
94
+ /** Scan one ready job: skip it while its retry delay runs, else claim it or defer it. */
95
+ private reconcileOne;
96
+ /**
97
+ * Subscribe to this worker's company topic. A deferred result throws so the
98
+ * broker keeps the message; every other outcome acks it.
99
+ */
100
+ attach(broker: NotificationBroker): void;
101
+ /** Attempts this consumer claimed, in claim order. */
102
+ claims(): ConsumerClaim[];
103
+ /** True when a verified event with this id has been handled. */
104
+ seen(eventId: string): boolean;
105
+ records(): InboxRecord[];
106
+ /** Results of handle() since the last call, oldest first. */
107
+ lastResults(): HandleResult[];
108
+ close(): void;
109
+ private cursor;
110
+ private recorded;
111
+ private record;
112
+ /** A prepared statement, prepared once per consumer. */
113
+ private stmt;
114
+ private saveClaim;
115
+ }
116
+ //# sourceMappingURL=inbox.d.ts.map
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Idempotent notification inbox and bounded reconciliation (US-005).
3
+ *
4
+ * A consumer belongs to one enrolled worker. It treats every notification as
5
+ * a hint: the payload is parsed strictly, then checked against the committed
6
+ * ledger through the US-004 access layer (tenant, capability, owner epoch)
7
+ * before any claim, and claims go through `dispatch`, which applies the same
8
+ * checks inside the store commit. A notification therefore cannot authorize,
9
+ * create or claim a job the ledger does not already hold as ready.
10
+ *
11
+ * The inbox is a sqlite file of handled keys. A verified event is recorded
12
+ * under its stable event id, so a redelivery or a republish is a duplicate and
13
+ * each durable transition is applied once. A payload that fails parsing or
14
+ * verification is recorded under its sha256 only, so a forgery cannot occupy
15
+ * a genuine event's id. A handle that is fenced or closed records nothing and
16
+ * reports "deferred", which leaves the message unacked.
17
+ *
18
+ * Reconciliation finds ready work from the ledger without the broker. Each
19
+ * call reads at most one batch after a durable cursor and wraps to the start
20
+ * when the scan reaches the end, so every ready job is reached within a
21
+ * bounded number of calls. A job this worker may not run is backed off
22
+ * exponentially and skipped until its retry time; it is never deleted.
23
+ */
24
+ import { createHash } from "node:crypto";
25
+ import { DeliveryStoreError } from "./migrations.js";
26
+ import { notificationTopic } from "./mqtt.js";
27
+ import { DEFAULT_BACKOFF, backoffDelay, checkBatch, openTransportDb, parseNotification, } from "./outbox.js";
28
+ /** The handle can no longer act for the store; the caller must stop or reopen. */
29
+ const OWNERSHIP_LOST = new Set(["FENCED", "STORE_CLOSED"]);
30
+ /** Verification failures: the payload is recorded and acked, never retried. */
31
+ const NOT_GENUINE = new Set(["ACCESS_DENIED", "NOTIFICATION_UNVERIFIED", "WORKER_REVOKED"]);
32
+ /** A reconcile time budget: absent, or a finite number of milliseconds above zero. */
33
+ function checkBudget(maxMs) {
34
+ if (maxMs === undefined)
35
+ return undefined;
36
+ if (typeof maxMs !== "number" || !Number.isFinite(maxMs) || maxMs <= 0) {
37
+ throw new RangeError("maxMs must be a finite number of milliseconds above zero");
38
+ }
39
+ return maxMs;
40
+ }
41
+ function codeOf(err) {
42
+ return err instanceof DeliveryStoreError ? err.code : "INTERNAL";
43
+ }
44
+ export class NotificationConsumer {
45
+ access;
46
+ identity;
47
+ db;
48
+ credentials;
49
+ clock;
50
+ backoff;
51
+ testBarrier;
52
+ results = [];
53
+ detach = null;
54
+ statements = new Map();
55
+ constructor(access, identity, db, credentials, clock, backoff, testBarrier) {
56
+ this.access = access;
57
+ this.identity = identity;
58
+ this.db = db;
59
+ this.credentials = credentials;
60
+ this.clock = clock;
61
+ this.backoff = backoff;
62
+ this.testBarrier = testBarrier;
63
+ }
64
+ static open(opts) {
65
+ const db = openTransportDb(opts.path);
66
+ db.exec(`
67
+ CREATE TABLE IF NOT EXISTS inbox (key TEXT PRIMARY KEY, outcome TEXT NOT NULL, reason TEXT, at INTEGER NOT NULL);
68
+ CREATE TABLE IF NOT EXISTS claims (attempt_id TEXT PRIMARY KEY, job_id TEXT NOT NULL, at INTEGER NOT NULL);
69
+ CREATE TABLE IF NOT EXISTS cursor (id INTEGER PRIMARY KEY CHECK (id = 1), after TEXT);
70
+ CREATE TABLE IF NOT EXISTS retry (job_id TEXT PRIMARY KEY, failures INTEGER NOT NULL, next_at INTEGER NOT NULL);
71
+ `);
72
+ return new NotificationConsumer(opts.access, opts.identity, db, [...(opts.credentials ?? [])], opts.clock ?? Date.now, opts.backoff ?? DEFAULT_BACKOFF, opts.testBarrier);
73
+ }
74
+ /**
75
+ * Handle one notification payload. Never throws: every outcome is returned.
76
+ * Only "deferred" leaves nothing recorded.
77
+ */
78
+ handle(payload) {
79
+ const result = this.handleOnce(payload);
80
+ this.results.push(result);
81
+ return result;
82
+ }
83
+ handleOnce(payload) {
84
+ const hashKey = `payload:${createHash("sha256").update(String(payload)).digest("hex")}`;
85
+ if (this.recorded(hashKey))
86
+ return { eventId: null, outcome: "duplicate", reason: null, claims: [] };
87
+ const event = parseNotification(payload);
88
+ if (!event) {
89
+ this.record(hashKey, "rejected", "NOTIFICATION_MALFORMED");
90
+ return { eventId: null, outcome: "rejected", reason: "NOTIFICATION_MALFORMED", claims: [] };
91
+ }
92
+ const eventKey = `event:${event.eventId}`;
93
+ if (this.recorded(eventKey))
94
+ return { eventId: event.eventId, outcome: "duplicate", reason: null, claims: [] };
95
+ let candidates;
96
+ try {
97
+ candidates = this.access.verifyNotification(this.identity, event);
98
+ }
99
+ catch (err) {
100
+ const code = codeOf(err);
101
+ if (NOT_GENUINE.has(code)) {
102
+ this.record(hashKey, "rejected", code);
103
+ return { eventId: event.eventId, outcome: "rejected", reason: code, claims: [] };
104
+ }
105
+ return { eventId: event.eventId, outcome: "deferred", reason: code, claims: [] };
106
+ }
107
+ const claims = [];
108
+ for (const jobId of candidates) {
109
+ try {
110
+ if (this.tryClaim(jobId))
111
+ claims.push(jobId);
112
+ }
113
+ catch (err) {
114
+ return { eventId: event.eventId, outcome: "deferred", reason: codeOf(err), claims };
115
+ }
116
+ }
117
+ const outcome = claims.length > 0 ? "claimed" : "ignored";
118
+ this.record(eventKey, outcome, null);
119
+ return { eventId: event.eventId, outcome, reason: null, claims };
120
+ }
121
+ /**
122
+ * Claim one job through the access layer. False when the ledger says it is
123
+ * not claimable now or this worker may not run it (left for reconciliation
124
+ * and its backoff). Throws on anything that means the handle cannot act.
125
+ */
126
+ tryClaim(jobId) {
127
+ try {
128
+ const d = this.access.dispatch(this.identity, jobId, { credentials: this.credentials });
129
+ this.testBarrier?.("claimed", jobId, d.claim.attempt.attemptId);
130
+ this.saveClaim(d.claim.attempt.attemptId, jobId);
131
+ return true;
132
+ }
133
+ catch (err) {
134
+ const code = codeOf(err);
135
+ if (code === "NOT_CLAIMABLE" || code === "PRIVILEGE_REJECTED" || code === "CREDENTIAL_UNAVAILABLE")
136
+ return false;
137
+ throw err;
138
+ }
139
+ }
140
+ /**
141
+ * Claim up to `batchSize` ready jobs of this worker's company from the
142
+ * ledger, continuing after the saved cursor and wrapping to the start.
143
+ * With `maxMs`, the clock is read after each scanned job; once that much
144
+ * time has passed the call stops, saving that job as the cursor. FENCED and STORE_CLOSED are thrown; nothing is
145
+ * claimed then.
146
+ */
147
+ reconcile(opts) {
148
+ const batchSize = checkBatch(opts?.batchSize);
149
+ const maxMs = checkBudget(opts?.maxMs);
150
+ const after = this.cursor();
151
+ const first = this.access.readyWork(this.identity, { after, limit: batchSize });
152
+ const scan = [...first.jobs];
153
+ let cursor = first.cursor;
154
+ if (after !== null && first.cursor === null && scan.length < batchSize) {
155
+ const wrapped = this.access.readyWork(this.identity, { after: null, limit: batchSize });
156
+ for (const id of wrapped.jobs) {
157
+ if (scan.length === batchSize)
158
+ break;
159
+ if (!scan.includes(id))
160
+ scan.push(id);
161
+ }
162
+ cursor = scan.length === batchSize ? scan[scan.length - 1] : null;
163
+ }
164
+ const report = { claimed: [], deferred: [], skipped: [], cursor };
165
+ const now = this.clock();
166
+ for (const jobId of scan) {
167
+ this.reconcileOne(jobId, now, report);
168
+ if (maxMs !== undefined && this.clock() - now >= maxMs) {
169
+ // Budget spent: stop after this job and resume after it next call.
170
+ report.cursor = jobId;
171
+ break;
172
+ }
173
+ }
174
+ this.stmt("INSERT INTO cursor (id, after) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET after = excluded.after").run(report.cursor);
175
+ return report;
176
+ }
177
+ /** Scan one ready job: skip it while its retry delay runs, else claim it or defer it. */
178
+ reconcileOne(jobId, now, report) {
179
+ const retry = this.stmt("SELECT failures, next_at FROM retry WHERE job_id = ?").get(jobId);
180
+ if (retry && retry.next_at > now) {
181
+ report.skipped.push(jobId);
182
+ return;
183
+ }
184
+ try {
185
+ const d = this.access.dispatch(this.identity, jobId, { credentials: this.credentials });
186
+ this.saveClaim(d.claim.attempt.attemptId, jobId);
187
+ }
188
+ catch (err) {
189
+ const code = codeOf(err);
190
+ if (OWNERSHIP_LOST.has(code))
191
+ throw err;
192
+ if (code === "NOT_CLAIMABLE")
193
+ return;
194
+ const failures = (retry?.failures ?? 0) + 1;
195
+ this
196
+ .stmt("INSERT INTO retry (job_id, failures, next_at) VALUES (?, ?, ?) ON CONFLICT(job_id) DO UPDATE SET failures = excluded.failures, next_at = excluded.next_at")
197
+ .run(jobId, failures, now + backoffDelay(this.backoff, failures));
198
+ report.deferred.push(jobId);
199
+ return;
200
+ }
201
+ this.stmt("DELETE FROM retry WHERE job_id = ?").run(jobId);
202
+ report.claimed.push(jobId);
203
+ }
204
+ /**
205
+ * Subscribe to this worker's company topic. A deferred result throws so the
206
+ * broker keeps the message; every other outcome acks it.
207
+ */
208
+ attach(broker) {
209
+ this.detach?.();
210
+ const topic = notificationTopic(this.access.workerTenant(this.identity));
211
+ this.detach = broker.subscribe(topic, (message) => {
212
+ const result = this.handle(message.payload);
213
+ if (result.outcome === "deferred")
214
+ throw new Error("notification deferred");
215
+ });
216
+ }
217
+ /** Attempts this consumer claimed, in claim order. */
218
+ claims() {
219
+ return this.db.prepare("SELECT attempt_id, job_id, at FROM claims ORDER BY rowid").all().map((r) => ({ attemptId: r.attempt_id, jobId: r.job_id, at: r.at }));
220
+ }
221
+ /** True when a verified event with this id has been handled. */
222
+ seen(eventId) {
223
+ return this.recorded(`event:${eventId}`);
224
+ }
225
+ records() {
226
+ return this.db.prepare("SELECT key, outcome, reason, at FROM inbox ORDER BY rowid").all();
227
+ }
228
+ /** Results of handle() since the last call, oldest first. */
229
+ lastResults() {
230
+ return this.results.splice(0);
231
+ }
232
+ close() {
233
+ this.detach?.();
234
+ this.detach = null;
235
+ this.db.close();
236
+ }
237
+ cursor() {
238
+ const row = this.db.prepare("SELECT after FROM cursor WHERE id = 1").get();
239
+ return row?.after ?? null;
240
+ }
241
+ recorded(key) {
242
+ return this.db.prepare("SELECT 1 FROM inbox WHERE key = ?").get(key) !== undefined;
243
+ }
244
+ record(key, outcome, reason) {
245
+ this.db.prepare("INSERT OR IGNORE INTO inbox (key, outcome, reason, at) VALUES (?, ?, ?, ?)").run(key, outcome, reason, this.clock());
246
+ }
247
+ /** A prepared statement, prepared once per consumer. */
248
+ stmt(sql) {
249
+ let st = this.statements.get(sql);
250
+ if (!st) {
251
+ st = this.db.prepare(sql);
252
+ this.statements.set(sql, st);
253
+ }
254
+ return st;
255
+ }
256
+ saveClaim(attemptId, jobId) {
257
+ this.stmt("INSERT OR IGNORE INTO claims (attempt_id, job_id, at) VALUES (?, ?, ?)").run(attemptId, jobId, this.clock());
258
+ }
259
+ }
260
+ //# sourceMappingURL=inbox.js.map
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Worker heartbeat for a claim lease (US-011 slice 4).
3
+ *
4
+ * A worker's claim carries a lease of claimLeaseMs on the controller's clock
5
+ * (reconciler.ts). While the worker runs the attempt, startLeaseHeartbeat
6
+ * renews it every leaseMs / 3, so two missed beats still leave the lease
7
+ * alive. The lease length comes from the controller (`controller.claimLeaseMs`)
8
+ * unless the caller passes it, so the period cannot drift from the lease. A
9
+ * worker on the RPC port has no controller object and passes leaseMs.
10
+ *
11
+ * A store refusal means the lease is gone or the controller can no longer hold
12
+ * it: the attempt was abandoned, reported or is not the worker's, the worker
13
+ * was revoked, or the controller was fenced, closed, retired or is restoring.
14
+ * The heartbeat then stops and calls onLost once: the worker must stop work on
15
+ * the attempt and discard its result.
16
+ *
17
+ * A transient failure (store I/O, an RPC timeout, a closed or unreachable
18
+ * controller, or an error that is not a store refusal) goes to onError and the
19
+ * heartbeat keeps beating, but only until the renewal deadline (slice 4 B):
20
+ * the lease the controller confirmed last runs from no earlier than the moment
21
+ * that renewal was sent, so the worker gives the claim up at
22
+ * send time of the last confirmed renewal + leaseMs - callDeadlineMs - marginMs
23
+ * on a one-shot timer (not on the next tick), stopping with LEASE_UNCONFIRMED.
24
+ * callDeadlineMs is how long a call may take to fail (pass the RPC client's
25
+ * total deadline); marginMs defaults to one beat. A partitioned worker thus
26
+ * gives the claim up strictly before the controller's lease can run out and
27
+ * hand the job to someone else. A renewal that never answers counts the same.
28
+ *
29
+ * renewLease may answer synchronously (the in-process access layer) or with a
30
+ * promise (the RPC client). A beat is skipped while the previous one is still
31
+ * waiting for its answer.
32
+ */
33
+ import type { LeaseView } from "./reconciler.js";
34
+ import type { WorkerIdentity } from "./identity.js";
35
+ import { DeliveryStoreError } from "./migrations.js";
36
+ export interface HeartbeatTimers {
37
+ setInterval(fn: () => void, ms: number): unknown;
38
+ clearInterval(handle: unknown): void;
39
+ /** The give-up timer. Injected timers without it are checked on each tick and each failed renewal only. */
40
+ setTimeout?(fn: () => void, ms: number): unknown;
41
+ clearTimeout?(handle: unknown): void;
42
+ }
43
+ export interface LeaseHeartbeatOptions {
44
+ /** Renews the lease. When it also exposes `controller.claimLeaseMs`, the period derives from it. */
45
+ access: {
46
+ renewLease(identity: WorkerIdentity, attemptId: string): LeaseView | Promise<LeaseView>;
47
+ readonly controller?: {
48
+ readonly claimLeaseMs: number;
49
+ };
50
+ };
51
+ identity: WorkerIdentity;
52
+ attemptId: string;
53
+ /** The controller's claimLeaseMs. Default: `access.controller.claimLeaseMs`. One of the two is required. */
54
+ leaseMs?: number;
55
+ /** How long a renewal call may take before it fails (for the RPC client: retries + 1 times its timeout). Default 0. */
56
+ callDeadlineMs?: number;
57
+ /** Safety margin before the controller's expiry. Default floor(leaseMs / 3), one beat. */
58
+ marginMs?: number;
59
+ /**
60
+ * The worker's clock in ms, used only for intervals (the renewal deadline).
61
+ * Default performance.now, a monotonic clock, so a wall-clock step cannot
62
+ * move the deadline. An injected clock should be monotonic too.
63
+ */
64
+ now?: () => number;
65
+ /** Called once when the lease is refused or unconfirmed past the deadline; the heartbeat has stopped. */
66
+ onLost?: (err: DeliveryStoreError) => void;
67
+ /** Called for a transient failure; the heartbeat keeps going until the deadline. */
68
+ onError?: (err: unknown) => void;
69
+ /** Injected timers, for tests. Default the global setInterval and clearInterval. */
70
+ timers?: HeartbeatTimers;
71
+ }
72
+ export interface LeaseHeartbeat {
73
+ stop(): void;
74
+ /** Renewals the controller accepted so far. */
75
+ renewals(): number;
76
+ /** Resolves when no renewal is waiting for its answer. */
77
+ settled(): Promise<void>;
78
+ }
79
+ export declare function startLeaseHeartbeat(opts: LeaseHeartbeatOptions): LeaseHeartbeat;
80
+ //# sourceMappingURL=lease.d.ts.map