@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,146 @@
1
+ import type { Run } from "./contracts.js";
2
+ import { type CredentialPolicy, type CredentialSource, type InjectedCredentials, type JobClass } from "./credentials.js";
3
+ import { type WorkerIdentity } from "./identity.js";
4
+ import { type WorkerCapability, type WorkerStatus, type WorkerTrust } from "./migrations.js";
5
+ import { type LedgerEvent } from "./outbox.js";
6
+ import { type AttemptView, type ClaimResult, type ControllerOptions, type DeliveryController, type JobView, type LeaseView } from "./reconciler.js";
7
+ export type AccessOptions = ControllerOptions & {
8
+ credentialPolicy?: CredentialPolicy;
9
+ credentialSource?: CredentialSource;
10
+ };
11
+ /** What an admin may manage: these tenants, up to this trust. */
12
+ export interface AdminScope {
13
+ tenantIds: string[];
14
+ maxTrust: WorkerTrust;
15
+ }
16
+ export interface EnrollmentRequest {
17
+ tenantId: string;
18
+ workerId: string;
19
+ capabilities: WorkerCapability[];
20
+ trust: WorkerTrust;
21
+ }
22
+ export interface IssuedEnrollment extends EnrollmentRequest {
23
+ /** One-time secret the worker presents to enroll. Only its digest is stored. */
24
+ ticket: string;
25
+ }
26
+ export interface WorkerView {
27
+ workerId: string;
28
+ tenantId: string;
29
+ capabilities: WorkerCapability[];
30
+ trust: WorkerTrust;
31
+ status: WorkerStatus;
32
+ issuedAt: string;
33
+ enrolledAt: string | null;
34
+ revokedAt: string | null;
35
+ }
36
+ /** One page of a tenant's ready work, for bounded reconciliation (US-005). */
37
+ export interface ReadyPage {
38
+ /** Ready jobIds after the cursor, in ledger order. */
39
+ jobs: string[];
40
+ /** The last jobId returned when the page is full, else null (the scan reached the end). */
41
+ cursor: string | null;
42
+ }
43
+ export declare const MAX_READY_PAGE = 1000;
44
+ export interface Dispatch {
45
+ claim: ClaimResult;
46
+ jobClass: JobClass;
47
+ credentials: InjectedCredentials;
48
+ }
49
+ /** Open a store directory as its controller, with the worker access layer on top. */
50
+ export declare function openDeliveryAccess(opts: AccessOptions): DeliveryAccess;
51
+ export declare class DeliveryAccess {
52
+ /** The underlying controller, for accepting runs and admin reads. Worker operations go through this class. */
53
+ readonly controller: DeliveryController;
54
+ private readonly policy;
55
+ private readonly source;
56
+ constructor(controller: DeliveryController, policy?: CredentialPolicy, source?: CredentialSource);
57
+ /** Issue a one-time enrollment ticket. The worker is pending until it enrolls. */
58
+ issueEnrollment(scope: AdminScope, request: EnrollmentRequest): IssuedEnrollment;
59
+ /**
60
+ * Redeem a ticket for a worker token. The request must name the ticket's
61
+ * company and stay within its capabilities and trust.
62
+ */
63
+ enroll(input: EnrollmentRequest & {
64
+ ticket: string;
65
+ }): WorkerIdentity;
66
+ /** Revoke a worker. It can no longer claim, read or report. Revoking twice is a no-op. */
67
+ revoke(scope: AdminScope, workerId: string): WorkerView;
68
+ /**
69
+ * US-011 slice 4: extend the lease of the worker's own open attempt. Needs
70
+ * "report". The claimant, the open attempt, the lease and that the worker is
71
+ * not revoked are checked again inside the commit. Refused with
72
+ * ATTEMPT_ABANDONED once the lease has expired.
73
+ */
74
+ renewLease(identity: WorkerIdentity, attemptId: string): LeaseView;
75
+ /** Workers in the admin's scope, without secret digests. */
76
+ workers(scope: AdminScope): WorkerView[];
77
+ /** Read a run of the worker's own company and its jobs. Needs "read". */
78
+ readRun(identity: WorkerIdentity, runId: string): {
79
+ run: Run;
80
+ jobs: JobView[];
81
+ };
82
+ /**
83
+ * Claim a ready job of the worker's own company. Needs "claim". A worker may
84
+ * choose the attemptId (US-011 slice 4 B): claiming again with the same id
85
+ * replays the stored claim instead of opening a second attempt, so a retry
86
+ * after a lost answer is safe. The id must be a safe name (it becomes a
87
+ * directory name on the worker).
88
+ */
89
+ claim(identity: WorkerIdentity, jobId: string, opts?: {
90
+ attemptId?: string;
91
+ }): ClaimResult;
92
+ /** Report the outcome of an attempt of the worker's own company. Needs "report". */
93
+ recordOutcome(identity: WorkerIdentity, attemptId: string, outcome: "passed" | "failed"): AttemptView;
94
+ /** US-007: return an open attempt of the worker's own company unfinished, so its job can be claimed again. Needs "report". */
95
+ returnAttempt(identity: WorkerIdentity, attemptId: string): AttemptView;
96
+ /**
97
+ * Claim a job and inject the credentials it may have. The request is planned
98
+ * first, so a rejected request looks nothing up; credentials are injected
99
+ * before the claim, so a lookup failure claims nothing.
100
+ */
101
+ dispatch(identity: WorkerIdentity, jobId: string, request: {
102
+ credentials: string[];
103
+ attemptId?: string;
104
+ }): Dispatch;
105
+ /** The trust an authenticated worker was enrolled with. Needs "claim". */
106
+ workerTrust(identity: WorkerIdentity): WorkerTrust;
107
+ /** The company of an authenticated worker. Needs "claim". */
108
+ workerTenant(identity: WorkerIdentity): string;
109
+ /**
110
+ * Ready jobs of the worker's own company after `after`, in ledger order, at
111
+ * most `limit`. An unknown cursor starts from the beginning. Needs "claim".
112
+ * Read only: it claims nothing and never removes a job.
113
+ */
114
+ readyWork(identity: WorkerIdentity, page: {
115
+ after: string | null;
116
+ limit: number;
117
+ }): ReadyPage;
118
+ /**
119
+ * Check a notification against the committed ledger and return the jobs it
120
+ * may have made ready. A notification is a hint: it is accepted only when
121
+ * the ledger derives an event with the same id and the same values in every
122
+ * field, for the worker's own company. Needs "claim". Claims nothing.
123
+ *
124
+ * Another company's event is ACCESS_DENIED naming only the worker's company.
125
+ * Anything else that does not match is NOTIFICATION_UNVERIFIED, and the
126
+ * message does not repeat the presented ids.
127
+ */
128
+ verifyNotification(identity: WorkerIdentity, event: LedgerEvent): string[];
129
+ /** Release ownership of the store. Idempotent. */
130
+ close(): void;
131
+ private prepareClaim;
132
+ /**
133
+ * Worker records, only while this handle owns the store. A superseded or
134
+ * closed handle still holds its last state in memory, which may list a
135
+ * worker the current owner has revoked; it must not authenticate or serve
136
+ * anything from that state (FENCED or STORE_CLOSED, read only).
137
+ */
138
+ private ownedRecords;
139
+ /** Re-authenticates against the state being committed, so a revocation in flight wins. */
140
+ private guard;
141
+ /** Re-authenticates for "report" and re-checks, inside the commit, that the caller claimed the attempt. */
142
+ private attemptGuard;
143
+ /** Deny work of another company. The message names the worker and its own company only. */
144
+ private sameTenant;
145
+ }
146
+ //# sourceMappingURL=enrollment.d.ts.map
@@ -0,0 +1,460 @@
1
+ /**
2
+ * Worker enrollment and the authenticated access layer (US-004).
3
+ *
4
+ * An admin with a company scope issues a one-time enrollment ticket for a
5
+ * worker of one tenant, with fixed capabilities and trust. The worker redeems
6
+ * the ticket for a token. Every worker operation then authenticates against
7
+ * the stored worker records: company scope, capability and status.
8
+ *
9
+ * Revocation is a fenced store commit. Each worker write re-authenticates
10
+ * inside the same commit, against the state about to be written, so a
11
+ * revocation that lands while an operation is in flight refuses that
12
+ * operation instead of racing it. Requests beyond the ticket, the admin's
13
+ * scope or the worker's trust are rejected, never downgraded.
14
+ */
15
+ import { createHash } from "node:crypto";
16
+ import { MAX_CHOSEN_ATTEMPT_ID, isSafeAttemptId } from "./attempt-id.js";
17
+ import { assertJobTrust, injectCredentials, planCredentials, } from "./credentials.js";
18
+ import { authenticate, newSecret, secretDigest, secretMatches, trustAllows } from "./identity.js";
19
+ import { DeliveryStoreError, WORKER_CAPABILITIES, WORKER_TRUSTS, } from "./migrations.js";
20
+ import { sameEvent } from "./outbox.js";
21
+ import { notClaimant, openDeliveryController, } from "./reconciler.js";
22
+ export const MAX_READY_PAGE = 1000;
23
+ const NO_CREDENTIALS = {
24
+ resolve: () => {
25
+ throw new Error("no credential source");
26
+ },
27
+ };
28
+ function denied(found, expected, action) {
29
+ return new DeliveryStoreError("ACCESS_DENIED", { found, expected, action: `${action} Nothing was written.` });
30
+ }
31
+ function rejected(found, expected, action) {
32
+ return new DeliveryStoreError("PRIVILEGE_REJECTED", { found, expected, action: `${action} Nothing was written.` });
33
+ }
34
+ function invalid(found, expected) {
35
+ return new DeliveryStoreError("INVALID_RECORD", { found, expected, action: "Fix the input and retry. Nothing was written." });
36
+ }
37
+ /** A worker-chosen attemptId: a safe name (attempt-id.ts) of at most MAX_CHOSEN_ATTEMPT_ID characters. */
38
+ function checkAttemptId(id) {
39
+ if (id === undefined)
40
+ return undefined;
41
+ if (!isSafeAttemptId(id) || id.length > MAX_CHOSEN_ATTEMPT_ID) {
42
+ throw invalid(`attemptId ${JSON.stringify(id)?.slice(0, 80)}`, `1 to ${MAX_CHOSEN_ATTEMPT_ID} letters, digits, dot, underscore or dash, starting with a letter or digit, and no '..'`);
43
+ }
44
+ return id;
45
+ }
46
+ /**
47
+ * The stored id of a worker-chosen attemptId (review I1): the chosen id behind
48
+ * a prefix derived from the worker's company and id. Ids of different workers
49
+ * can never collide, so no worker can squat another's ids or learn anything by
50
+ * reusing them, and a replay can only ever find the worker's own attempts.
51
+ */
52
+ function scopedAttemptId(worker, chosen) {
53
+ return `w${createHash("sha256").update(`${worker.tenantId}\u0000${worker.workerId}`).digest("hex").slice(0, 12)}-${chosen}`;
54
+ }
55
+ function checkScope(scope) {
56
+ const s = scope;
57
+ const ok = typeof scope === "object" &&
58
+ scope !== null &&
59
+ Array.isArray(s.tenantIds) &&
60
+ s.tenantIds.length > 0 &&
61
+ s.tenantIds.every((t) => typeof t === "string" && t !== "") &&
62
+ WORKER_TRUSTS.includes(s.maxTrust);
63
+ if (!ok) {
64
+ throw denied("a missing or malformed admin scope", "tenantIds as a non-empty list and a known maxTrust", "Pass the admin's company scope.");
65
+ }
66
+ return s;
67
+ }
68
+ function checkRequest(input) {
69
+ const r = input;
70
+ if (typeof input !== "object" || input === null)
71
+ throw invalid("a missing enrollment request", "tenantId, workerId, capabilities and trust");
72
+ if (typeof r.tenantId !== "string" || r.tenantId === "")
73
+ throw invalid("tenantId that is not a non-empty string", "a tenantId");
74
+ if (typeof r.workerId !== "string" || r.workerId === "")
75
+ throw invalid("workerId that is not a non-empty string", "a workerId");
76
+ const caps = r.capabilities;
77
+ if (!Array.isArray(caps) ||
78
+ caps.length === 0 ||
79
+ !caps.every((c) => WORKER_CAPABILITIES.includes(c)) ||
80
+ new Set(caps).size !== caps.length) {
81
+ throw invalid(`capabilities ${JSON.stringify(caps)}`, `a non-empty list of distinct ${WORKER_CAPABILITIES.join(", ")}`);
82
+ }
83
+ if (!WORKER_TRUSTS.includes(r.trust))
84
+ throw invalid(`trust ${JSON.stringify(r.trust)}`, WORKER_TRUSTS.join(" or "));
85
+ return { tenantId: r.tenantId, workerId: r.workerId, capabilities: [...caps], trust: r.trust };
86
+ }
87
+ function inScope(scope, tenantId, workerId) {
88
+ if (!scope.tenantIds.includes(tenantId)) {
89
+ throw denied(`worker ${workerId} in a company outside the admin's scope`, `a company in the admin's scope: ${scope.tenantIds.join(", ")}`, "Ask an admin of that company.");
90
+ }
91
+ }
92
+ function view(w) {
93
+ return {
94
+ workerId: w.workerId,
95
+ tenantId: w.tenantId,
96
+ capabilities: [...w.capabilities],
97
+ trust: w.trust,
98
+ status: w.status,
99
+ issuedAt: w.issuedAt,
100
+ enrolledAt: w.enrolledAt,
101
+ revokedAt: w.revokedAt,
102
+ };
103
+ }
104
+ /** Open a store directory as its controller, with the worker access layer on top. */
105
+ export function openDeliveryAccess(opts) {
106
+ const { credentialPolicy, credentialSource, ...controllerOpts } = opts;
107
+ return new DeliveryAccess(openDeliveryController(controllerOpts), credentialPolicy, credentialSource);
108
+ }
109
+ export class DeliveryAccess {
110
+ /** The underlying controller, for accepting runs and admin reads. Worker operations go through this class. */
111
+ controller;
112
+ policy;
113
+ source;
114
+ constructor(controller, policy, source) {
115
+ this.controller = controller;
116
+ this.policy = policy;
117
+ this.source = source;
118
+ }
119
+ /** Issue a one-time enrollment ticket. The worker is pending until it enrolls. */
120
+ issueEnrollment(scope, request) {
121
+ this.controller.assertOwner();
122
+ const s = checkScope(scope);
123
+ const r = checkRequest(request);
124
+ inScope(s, r.tenantId, r.workerId);
125
+ if (!trustAllows(s.maxTrust, r.trust)) {
126
+ throw rejected(`a request for ${r.trust} trust`, `trust up to the admin's ${s.maxTrust}`, "Issue the ticket with lower trust, or ask an admin who may grant it.");
127
+ }
128
+ const ticket = newSecret("enrollment");
129
+ this.controller.commitWorkers((workers, at) => {
130
+ if (workers.some((w) => w.workerId === r.workerId)) {
131
+ throw new DeliveryStoreError("DUPLICATE_CONFLICT", {
132
+ found: `worker ${r.workerId} already exists`,
133
+ expected: "a new workerId",
134
+ action: "Use a new workerId, or revoke and replace the worker under a new id. Nothing was written.",
135
+ });
136
+ }
137
+ workers.push({
138
+ workerId: r.workerId,
139
+ tenantId: r.tenantId,
140
+ capabilities: [...r.capabilities],
141
+ trust: r.trust,
142
+ status: "pending",
143
+ secretSha256: secretDigest(ticket),
144
+ issuedAt: at.now,
145
+ issuedEpoch: at.epoch,
146
+ enrolledAt: null,
147
+ enrolledEpoch: null,
148
+ revokedAt: null,
149
+ revokedEpoch: null,
150
+ });
151
+ });
152
+ return { ...r, ticket };
153
+ }
154
+ /**
155
+ * Redeem a ticket for a worker token. The request must name the ticket's
156
+ * company and stay within its capabilities and trust.
157
+ */
158
+ enroll(input) {
159
+ const r = checkRequest(input);
160
+ const ticket = input.ticket;
161
+ const notFound = denied(`no pending enrollment for worker ${r.workerId} with the presented ticket`, "the tenantId, workerId and unused ticket from issueEnrollment", "Check the ticket, or ask an admin to issue a new one.");
162
+ const matchTicket = (workers) => {
163
+ const found = workers.filter((w) => w.workerId === r.workerId);
164
+ const w = found[0];
165
+ if (found.length !== 1 ||
166
+ !w ||
167
+ w.status !== "pending" ||
168
+ w.tenantId !== r.tenantId ||
169
+ typeof ticket !== "string" ||
170
+ ticket === "" ||
171
+ !secretMatches(ticket, w.secretSha256)) {
172
+ throw notFound;
173
+ }
174
+ return w;
175
+ };
176
+ const pending = matchTicket(this.ownedRecords());
177
+ const extra = r.capabilities.filter((c) => !pending.capabilities.includes(c));
178
+ if (extra.length > 0) {
179
+ throw rejected(`a request for capabilities ${extra.join(", ")} beyond the ticket`, `capabilities within ${pending.capabilities.join(", ")}`, "Enroll with the ticket's capabilities, or ask for a new ticket.");
180
+ }
181
+ if (!trustAllows(pending.trust, r.trust)) {
182
+ throw rejected(`a request for ${r.trust} trust`, `trust up to the ticket's ${pending.trust}`, "Enroll with the ticket's trust, or ask for a new ticket.");
183
+ }
184
+ const token = newSecret("worker");
185
+ this.controller.commitWorkers((workers, at) => {
186
+ // Re-check in the commit: a revocation or another redemption may have landed since.
187
+ const w = matchTicket(workers);
188
+ w.capabilities = [...r.capabilities];
189
+ w.trust = r.trust;
190
+ w.status = "active";
191
+ w.secretSha256 = secretDigest(token);
192
+ w.enrolledAt = at.now;
193
+ w.enrolledEpoch = at.epoch;
194
+ });
195
+ return { workerId: r.workerId, token };
196
+ }
197
+ /** Revoke a worker. It can no longer claim, read or report. Revoking twice is a no-op. */
198
+ revoke(scope, workerId) {
199
+ this.controller.assertOwner();
200
+ const s = checkScope(scope);
201
+ const find = (workers) => {
202
+ const found = workers.filter((w) => w.workerId === workerId);
203
+ const w = found[0];
204
+ if (found.length !== 1 || !w || !s.tenantIds.includes(w.tenantId)) {
205
+ throw denied(`no worker ${String(workerId)} in the admin's scope`, "a workerId in a company the admin manages", "Check the workerId and the admin's scope.");
206
+ }
207
+ return w;
208
+ };
209
+ const current = find(this.ownedRecords());
210
+ if (current.status === "revoked")
211
+ return view(current);
212
+ // US-011 slice 4: the worker's open attempts are abandoned in the same commit, so its claims are freed
213
+ // at once. Its late reports are then refused (WORKER_REVOKED), and each job can be claimed again.
214
+ this.controller.commitRevocation(workerId, (workers, at) => {
215
+ const w = find(workers);
216
+ if (w.status === "revoked")
217
+ return;
218
+ w.status = "revoked";
219
+ w.revokedAt = at.now;
220
+ w.revokedEpoch = at.epoch;
221
+ });
222
+ return view(find(this.ownedRecords()));
223
+ }
224
+ /**
225
+ * US-011 slice 4: extend the lease of the worker's own open attempt. Needs
226
+ * "report". The claimant, the open attempt, the lease and that the worker is
227
+ * not revoked are checked again inside the commit. Refused with
228
+ * ATTEMPT_ABANDONED once the lease has expired.
229
+ */
230
+ renewLease(identity, attemptId) {
231
+ const worker = authenticate(this.ownedRecords(), identity, { capability: "report" });
232
+ const attempt = this.controller.attempts().find((a) => a.attempt.attemptId === attemptId);
233
+ if (!attempt) {
234
+ throw new DeliveryStoreError("UNKNOWN_ATTEMPT", {
235
+ found: `no attempt ${attemptId}`,
236
+ expected: "an attemptId returned by claim",
237
+ action: "Check the attemptId. Nothing was written.",
238
+ });
239
+ }
240
+ this.sameTenant(worker, attempt.attempt.tenantId, `attempt ${attemptId}`);
241
+ if (attempt.claimedBy !== worker.workerId)
242
+ throw notClaimant(worker.workerId, attemptId);
243
+ return this.controller.renewLease(attemptId, { guard: this.attemptGuard(identity, worker.tenantId, attemptId), workerId: worker.workerId });
244
+ }
245
+ /** Workers in the admin's scope, without secret digests. */
246
+ workers(scope) {
247
+ this.controller.assertOwner();
248
+ const s = checkScope(scope);
249
+ return this.controller
250
+ .workerRecords()
251
+ .filter((w) => s.tenantIds.includes(w.tenantId))
252
+ .map(view);
253
+ }
254
+ /** Read a run of the worker's own company and its jobs. Needs "read". */
255
+ readRun(identity, runId) {
256
+ const worker = authenticate(this.ownedRecords(), identity, { capability: "read" });
257
+ const run = this.controller.runs().find((r) => r.runId === runId);
258
+ if (!run) {
259
+ throw new DeliveryStoreError("UNKNOWN_RUN", {
260
+ found: `no accepted run ${runId}`,
261
+ expected: "an accepted runId",
262
+ action: "Check the runId. Nothing was written.",
263
+ });
264
+ }
265
+ this.sameTenant(worker, run.tenantId, `run ${runId}`);
266
+ return { run, jobs: this.controller.jobs(runId) };
267
+ }
268
+ /**
269
+ * Claim a ready job of the worker's own company. Needs "claim". A worker may
270
+ * choose the attemptId (US-011 slice 4 B): claiming again with the same id
271
+ * replays the stored claim instead of opening a second attempt, so a retry
272
+ * after a lost answer is safe. The id must be a safe name (it becomes a
273
+ * directory name on the worker).
274
+ */
275
+ claim(identity, jobId, opts = {}) {
276
+ const chosen = checkAttemptId(opts?.attemptId);
277
+ const { worker, guard } = this.prepareClaim(identity, jobId);
278
+ const attemptId = chosen === undefined ? undefined : scopedAttemptId(worker, chosen);
279
+ return this.controller.claim(jobId, { guard, workerId: worker.workerId, ...(attemptId === undefined ? {} : { attemptId }) });
280
+ }
281
+ /** Report the outcome of an attempt of the worker's own company. Needs "report". */
282
+ recordOutcome(identity, attemptId, outcome) {
283
+ const worker = authenticate(this.ownedRecords(), identity, { capability: "report" });
284
+ const attempt = this.controller.attempts().find((a) => a.attempt.attemptId === attemptId);
285
+ if (!attempt) {
286
+ throw new DeliveryStoreError("UNKNOWN_ATTEMPT", {
287
+ found: `no attempt ${attemptId}`,
288
+ expected: "an attemptId returned by claim",
289
+ action: "Check the attemptId. Nothing was written.",
290
+ });
291
+ }
292
+ this.sameTenant(worker, attempt.attempt.tenantId, `attempt ${attemptId}`);
293
+ if (attempt.claimedBy !== worker.workerId)
294
+ throw notClaimant(worker.workerId, attemptId);
295
+ return this.controller.recordOutcome(attemptId, outcome, { guard: this.attemptGuard(identity, worker.tenantId, attemptId) });
296
+ }
297
+ /** US-007: return an open attempt of the worker's own company unfinished, so its job can be claimed again. Needs "report". */
298
+ returnAttempt(identity, attemptId) {
299
+ const worker = authenticate(this.ownedRecords(), identity, { capability: "report" });
300
+ const attempt = this.controller.attempts().find((a) => a.attempt.attemptId === attemptId);
301
+ if (!attempt) {
302
+ throw new DeliveryStoreError("UNKNOWN_ATTEMPT", {
303
+ found: `no attempt ${attemptId}`,
304
+ expected: "an attemptId returned by claim",
305
+ action: "Check the attemptId. Nothing was written.",
306
+ });
307
+ }
308
+ this.sameTenant(worker, attempt.attempt.tenantId, `attempt ${attemptId}`);
309
+ if (attempt.claimedBy !== worker.workerId)
310
+ throw notClaimant(worker.workerId, attemptId);
311
+ return this.controller.returnAttempt(attemptId, { guard: this.attemptGuard(identity, worker.tenantId, attemptId) });
312
+ }
313
+ /**
314
+ * Claim a job and inject the credentials it may have. The request is planned
315
+ * first, so a rejected request looks nothing up; credentials are injected
316
+ * before the claim, so a lookup failure claims nothing.
317
+ */
318
+ dispatch(identity, jobId, request) {
319
+ const chosen = checkAttemptId(request?.attemptId);
320
+ const { worker, job, guard } = this.prepareClaim(identity, jobId);
321
+ const attemptId = chosen === undefined ? undefined : scopedAttemptId(worker, chosen);
322
+ const plan = planCredentials(this.policy, { job, workerTrust: worker.trust, requested: request?.credentials });
323
+ if (plan.refs.length > 0 && !this.source) {
324
+ throw new DeliveryStoreError("CREDENTIAL_UNAVAILABLE", {
325
+ found: `no credential source configured for ${plan.refs.join(", ")}`,
326
+ expected: "a credential source",
327
+ action: "Open the access layer with a credential source. Nothing was claimed.",
328
+ });
329
+ }
330
+ const claimOpts = { guard, workerId: worker.workerId, ...(attemptId === undefined ? {} : { attemptId }) };
331
+ // A replay is checked against the live claim before any credential is looked up (review C1):
332
+ // a refused replay resolves nothing. A new claim keeps the old order, so a lookup failure claims nothing.
333
+ if (attemptId !== undefined && this.controller.attempts().some((a) => a.attempt.attemptId === attemptId)) {
334
+ const claim = this.controller.claim(jobId, claimOpts);
335
+ return { claim, jobClass: plan.jobClass, credentials: injectCredentials(this.source ?? NO_CREDENTIALS, plan.refs) };
336
+ }
337
+ const credentials = injectCredentials(this.source ?? NO_CREDENTIALS, plan.refs);
338
+ const claim = this.controller.claim(jobId, claimOpts);
339
+ return { claim, jobClass: plan.jobClass, credentials };
340
+ }
341
+ /** The trust an authenticated worker was enrolled with. Needs "claim". */
342
+ workerTrust(identity) {
343
+ return authenticate(this.ownedRecords(), identity, { capability: "claim" }).trust;
344
+ }
345
+ /** The company of an authenticated worker. Needs "claim". */
346
+ workerTenant(identity) {
347
+ return authenticate(this.ownedRecords(), identity, { capability: "claim" }).tenantId;
348
+ }
349
+ /**
350
+ * Ready jobs of the worker's own company after `after`, in ledger order, at
351
+ * most `limit`. An unknown cursor starts from the beginning. Needs "claim".
352
+ * Read only: it claims nothing and never removes a job.
353
+ */
354
+ readyWork(identity, page) {
355
+ const worker = authenticate(this.ownedRecords(), identity, { capability: "claim" });
356
+ const limit = page?.limit;
357
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_READY_PAGE) {
358
+ throw invalid(`limit ${String(limit)}`, `an integer from 1 to ${MAX_READY_PAGE}`);
359
+ }
360
+ const own = this.controller.jobs().filter((j) => j.job.tenantId === worker.tenantId);
361
+ const at = page.after === null ? -1 : own.findIndex((j) => j.job.jobId === page.after);
362
+ const jobs = [];
363
+ for (const view of own.slice(at + 1)) {
364
+ if (view.state !== "ready")
365
+ continue;
366
+ jobs.push(view.job.jobId);
367
+ if (jobs.length === limit)
368
+ break;
369
+ }
370
+ return { jobs, cursor: jobs.length === limit ? jobs[jobs.length - 1] : null };
371
+ }
372
+ /**
373
+ * Check a notification against the committed ledger and return the jobs it
374
+ * may have made ready. A notification is a hint: it is accepted only when
375
+ * the ledger derives an event with the same id and the same values in every
376
+ * field, for the worker's own company. Needs "claim". Claims nothing.
377
+ *
378
+ * Another company's event is ACCESS_DENIED naming only the worker's company.
379
+ * Anything else that does not match is NOTIFICATION_UNVERIFIED, and the
380
+ * message does not repeat the presented ids.
381
+ */
382
+ verifyNotification(identity, event) {
383
+ const worker = authenticate(this.ownedRecords(), identity, { capability: "claim" });
384
+ this.sameTenant(worker, event.tenantId, "a notification");
385
+ const derived = this.controller
386
+ .ledgerEvents()
387
+ .find((e) => e.tenantId === worker.tenantId && e.eventId === event.eventId);
388
+ if (!derived || !sameEvent(derived, event)) {
389
+ throw new DeliveryStoreError("NOTIFICATION_UNVERIFIED", {
390
+ found: `a notification for ${worker.tenantId} that no committed ledger record matches`,
391
+ expected: "a notification equal to an event derived from the committed ledger",
392
+ action: "Ignore it; reconciliation reads ready work from the ledger. Nothing was written.",
393
+ });
394
+ }
395
+ if (derived.type === "job.accepted")
396
+ return [derived.jobId];
397
+ const dependents = this.controller
398
+ .jobs(derived.runId)
399
+ .filter((j) => j.dependsOn.includes(derived.jobId))
400
+ .map((j) => j.job.jobId);
401
+ return [derived.jobId, ...dependents];
402
+ }
403
+ /** Release ownership of the store. Idempotent. */
404
+ close() {
405
+ this.controller.close();
406
+ }
407
+ prepareClaim(identity, jobId) {
408
+ const worker = authenticate(this.ownedRecords(), identity, { capability: "claim" });
409
+ // One job, not every job's view: building them all made each claim O(jobs x attempts).
410
+ const view = this.controller.job(jobId);
411
+ if (!view) {
412
+ throw new DeliveryStoreError("UNKNOWN_JOB", {
413
+ found: `no accepted job ${jobId}`,
414
+ expected: "an accepted jobId",
415
+ action: "Check the jobId. Nothing was written.",
416
+ });
417
+ }
418
+ this.sameTenant(worker, view.job.tenantId, `job ${jobId}`);
419
+ // The release-trust rule is checked here so claim() and dispatch() enforce it alike.
420
+ assertJobTrust(this.policy, view.job, worker.trust);
421
+ const job = view.job;
422
+ const guard = (state) => {
423
+ const current = authenticate(state.workers, identity, { capability: "claim", tenantId: worker.tenantId });
424
+ assertJobTrust(this.policy, job, current.trust);
425
+ };
426
+ return { worker, job, guard };
427
+ }
428
+ /**
429
+ * Worker records, only while this handle owns the store. A superseded or
430
+ * closed handle still holds its last state in memory, which may list a
431
+ * worker the current owner has revoked; it must not authenticate or serve
432
+ * anything from that state (FENCED or STORE_CLOSED, read only).
433
+ */
434
+ ownedRecords() {
435
+ this.controller.assertOwner();
436
+ return this.controller.workerRecords();
437
+ }
438
+ /** Re-authenticates against the state being committed, so a revocation in flight wins. */
439
+ guard(identity, capability, tenantId) {
440
+ return (state) => {
441
+ authenticate(state.workers, identity, { capability, tenantId });
442
+ };
443
+ }
444
+ /** Re-authenticates for "report" and re-checks, inside the commit, that the caller claimed the attempt. */
445
+ attemptGuard(identity, tenantId, attemptId) {
446
+ return (state) => {
447
+ const worker = authenticate(state.workers, identity, { capability: "report", tenantId });
448
+ const a = state.attempts.find((x) => x.record.attemptId === attemptId);
449
+ if (!a || a.claimedBy !== worker.workerId)
450
+ throw notClaimant(worker.workerId, attemptId);
451
+ };
452
+ }
453
+ /** Deny work of another company. The message names the worker and its own company only. */
454
+ sameTenant(worker, tenantId, what) {
455
+ if (worker.tenantId === tenantId)
456
+ return;
457
+ throw denied(`worker ${worker.workerId} of ${worker.tenantId} asked for ${what}, which belongs to another company`, `work of the worker's own company ${worker.tenantId}`, "Use a worker enrolled in the company that owns the work.");
458
+ }
459
+ }
460
+ //# sourceMappingURL=enrollment.js.map
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Delivery of escalated deployment decisions (US-009).
3
+ *
4
+ * Same transactional-outbox model as outbox.ts: events are derived from the
5
+ * committed ledger, here one `deployment.escalated` per blocked deployment,
6
+ * so an event exists exactly when the decision commit exists. They go to the
7
+ * company's escalation topic (mqtt.ts escalationTopic), never to the worker
8
+ * event topic, so worker inboxes are unaffected. The publisher keeps only
9
+ * the ids the broker acked in its own sqlite file; delivery is at-least-once
10
+ * with stable event ids.
11
+ */
12
+ import type { DeliveryAccess } from "./enrollment.js";
13
+ import type { StoredDeployment } from "./migrations.js";
14
+ import { type NotificationBroker } from "./mqtt.js";
15
+ export declare const ESCALATION_SCHEMA = "hq-delivery.escalation.v1";
16
+ export interface EscalationEvent {
17
+ schemaVersion: typeof ESCALATION_SCHEMA;
18
+ eventId: string;
19
+ type: "deployment.escalated";
20
+ tenantId: string;
21
+ environment: string;
22
+ deploymentId: string;
23
+ code: string;
24
+ found: string;
25
+ escalateTo: string;
26
+ epoch: number;
27
+ }
28
+ /** Every escalation the committed ledger implies, in ledger order. */
29
+ export declare function escalationEvents(deployments: readonly StoredDeployment[]): EscalationEvent[];
30
+ export interface EscalationPublisherOptions {
31
+ access: DeliveryAccess;
32
+ broker: NotificationBroker;
33
+ /** The publisher's own sqlite file. Not the ledger. */
34
+ path: string;
35
+ }
36
+ export declare class EscalationPublisher {
37
+ private readonly access;
38
+ private readonly broker;
39
+ private readonly db;
40
+ private constructor();
41
+ static open(opts: EscalationPublisherOptions): EscalationPublisher;
42
+ pending(): EscalationEvent[];
43
+ /** Publish every pending escalation, oldest first. Stops at the first broker error. */
44
+ publishPending(): Promise<{
45
+ published: number;
46
+ remaining: number;
47
+ error: string | null;
48
+ }>;
49
+ close(): void;
50
+ }
51
+ //# sourceMappingURL=escalations.d.ts.map