@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,567 @@
1
+ /**
2
+ * Content-addressed artifact store with signed provenance (US-008).
3
+ *
4
+ * Layout: blobs live under `<dir>/artifacts/<tenant>/<partition>/sha256/<digest>`,
5
+ * where `<tenant>` is a digest of the tenant id and `<partition>` is release or
6
+ * untrusted. Identical bytes from two companies are two files. Provenance
7
+ * records and cache entries live in the delivery store (state.json, store
8
+ * schema v4) and are written only through fenced controller commits.
9
+ *
10
+ * Write: bytes go to a fresh temp file in the blob directory (exclusive
11
+ * create, fsync), are read back and re-hashed, made read-only, then linked to
12
+ * the digest name, which never overwrites an existing file, and the directory
13
+ * is fsynced (except on Windows, which cannot fsync a directory). An existing blob with that name is re-hashed and reused only
14
+ * when it matches. A crash leaves at most a temp file or an unreferenced
15
+ * blob, never a referenced blob with other bytes.
16
+ *
17
+ * Trust: the builder is the authenticated worker. A release-trust worker
18
+ * writes to the release partition; any other worker writes to untrusted.
19
+ * Promotion refuses untrusted artifacts, needs a passed attempt, and
20
+ * re-verifies first.
21
+ *
22
+ * Tamper detection on every read, verify, cache hit and promotion: the HMAC
23
+ * signature over the record and provenance is checked with the key looked up
24
+ * from the credential source (the key is never stored), then the blob must be
25
+ * a regular file whose size and sha256 match. A failed cache hit is evicted.
26
+ *
27
+ * Promotion state (promotedAt, promotedEpoch) carries its own signature,
28
+ * re-signed by promote, so forging or clearing the flag is detected.
29
+ *
30
+ * Blob directories: every directory from the store directory down to the
31
+ * blob must be a real directory, not a symlink.
32
+ *
33
+ * Cache hits must point at an artifact whose signed tenant, partition and
34
+ * input digest yield the queried key; anything else is evicted as tampered.
35
+ *
36
+ * Cleanup: gc() removes blobs no record references and leftover temp files.
37
+ * openArtifactStore runs it, so a blob left by a put whose store commit
38
+ * failed is removed on the next open. Referenced blobs are never removed.
39
+ *
40
+ * Signing key: production reads the key ref from the config path
41
+ * PROVENANCE_SIGNING_KEY_REF_PATH (signingKeyRefFromConfig). There is no
42
+ * default key or ref; an unset ref refuses with SIGNING_KEY_UNCONFIGURED.
43
+ *
44
+ * Tenancy: reads, lookups and writes authenticate the worker and refuse
45
+ * another company's artifacts and attempts (ACCESS_DENIED). Admin calls take
46
+ * an AdminScope and refuse tenants outside it.
47
+ */
48
+ import { randomUUID } from "node:crypto";
49
+ import { closeSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, chmodSync, unlinkSync, writeSync, } from "node:fs";
50
+ import { join, relative, sep } from "node:path";
51
+ import { fsyncDirectory } from "../../utils/fsync-directory.js";
52
+ import { evictArtifact, findCacheEntry, recordCacheEntry } from "./cache.js";
53
+ import { DELIVERY_SCHEMA_VERSIONS, isSourcePin } from "./contracts.js";
54
+ import { authenticate, trustAllows } from "./identity.js";
55
+ import { DeliveryStoreError } from "./migrations.js";
56
+ import { leaseExpired } from "./reconciler.js";
57
+ import { PROVENANCE_SCHEMA_VERSION, cacheKey, cacheSlot, envDigest, inputDigest, partitionFor, sha256Hex, promotionMatches, signPromotion, signProvenance, signatureMatches, } from "./provenance.js";
58
+ export const ARTIFACTS_DIR = "artifacts";
59
+ /** Config path of the production provenance signing-key credential ref. */
60
+ export const PROVENANCE_SIGNING_KEY_REF_PATH = "delivery.artifacts.signingKeyRef";
61
+ /**
62
+ * The provenance signing-key credential ref from HQ config at
63
+ * PROVENANCE_SIGNING_KEY_REF_PATH. There is no default: an unset or blank ref
64
+ * refuses, so artifacts are never signed with a built-in key.
65
+ */
66
+ export function signingKeyRefFromConfig(config) {
67
+ const delivery = typeof config === "object" && config !== null ? config.delivery : undefined;
68
+ const artifacts = typeof delivery === "object" && delivery !== null ? delivery.artifacts : undefined;
69
+ const ref = typeof artifacts === "object" && artifacts !== null ? artifacts.signingKeyRef : undefined;
70
+ if (typeof ref !== "string" || ref.trim() === "") {
71
+ throw new DeliveryStoreError("SIGNING_KEY_UNCONFIGURED", {
72
+ found: `no provenance signing-key ref at ${PROVENANCE_SIGNING_KEY_REF_PATH}`,
73
+ expected: `${PROVENANCE_SIGNING_KEY_REF_PATH} set to the credential ref of the HMAC key (there is no default key)`,
74
+ action: `Provision the key with HQ secrets and set ${PROVENANCE_SIGNING_KEY_REF_PATH} to its ref. Nothing was signed or written.`,
75
+ });
76
+ }
77
+ return ref;
78
+ }
79
+ /** Blob path relative to the store directory. Used by backup and restore (US-010). */
80
+ export function blobRelativePath(tenantId, partition, digest) {
81
+ return join(ARTIFACTS_DIR, sha256Hex(`tenant:${tenantId}`).slice(0, 32), partition, "sha256", digest);
82
+ }
83
+ /** Open the artifact store and remove blobs left unreferenced by a failed commit. */
84
+ export function openArtifactStore(opts) {
85
+ const store = new ArtifactStore(opts);
86
+ store.gc();
87
+ return store;
88
+ }
89
+ function invalid(found, expected) {
90
+ return new DeliveryStoreError("INVALID_RECORD", { found, expected, action: "Fix the input. Nothing was written." });
91
+ }
92
+ function denied(found, expected) {
93
+ return new DeliveryStoreError("ACCESS_DENIED", {
94
+ found,
95
+ expected,
96
+ action: "Use a worker or admin scope of the company that owns the artifact. Nothing was read or written.",
97
+ });
98
+ }
99
+ function tampered(artifactId, found) {
100
+ return new DeliveryStoreError("ARTIFACT_TAMPERED", {
101
+ found: `artifact ${artifactId}: ${found}`,
102
+ expected: "a blob and provenance record that match what the builder stored",
103
+ action: "Do not use or promote this artifact. Rebuild it from source; investigate who changed the store directory.",
104
+ });
105
+ }
106
+ const isText = (v) => typeof v === "string" && v.trim() !== "";
107
+ const HEX64 = /^[0-9a-f]{64}$/;
108
+ function checkInputs(inputs) {
109
+ if (typeof inputs !== "object" || inputs === null)
110
+ throw invalid("no build inputs", "source, recipe, toolchain, platform, env and envAllowlist");
111
+ const pin = { repository: inputs.source?.repository, commitSha: inputs.source?.commitSha, verifiedOn: inputs.source?.ref };
112
+ if (!isSourcePin(pin))
113
+ throw invalid(`source ${JSON.stringify(inputs.source)}`, "a repository, 40-hex commitSha and refs/heads/ or refs/tags/ ref");
114
+ if (!isText(inputs.recipe?.recipeId) || !HEX64.test(String(inputs.recipe?.digest)))
115
+ throw invalid("a malformed recipe", "a recipeId and sha256 hex digest");
116
+ const tc = inputs.toolchain;
117
+ if (typeof tc !== "object" || tc === null || !Object.entries(tc).every(([k, v]) => k !== "" && isText(v))) {
118
+ throw invalid("a malformed toolchain", "a map of toolchain name to version");
119
+ }
120
+ if (!isText(inputs.platform?.os) || !isText(inputs.platform?.arch))
121
+ throw invalid("a malformed platform", "an os and arch");
122
+ if (!Array.isArray(inputs.envAllowlist) || !inputs.envAllowlist.every(isText))
123
+ throw invalid("a malformed envAllowlist", "a list of env keys");
124
+ if (typeof inputs.env !== "object" || inputs.env === null || !Object.values(inputs.env).every((v) => typeof v === "string")) {
125
+ throw invalid("a malformed env", "a map of env key to string value");
126
+ }
127
+ }
128
+ /** A put for an attempt that was abandoned or whose claim lease ran out. Nothing is written. */
129
+ function abandonedPut(attemptId, state) {
130
+ return new DeliveryStoreError("ATTEMPT_ABANDONED", {
131
+ found: `attempt ${attemptId} ${state}`,
132
+ expected: "an open attempt whose claim lease has not run out",
133
+ action: "Discard this build. Claim the job again to run a new attempt. Nothing was stored and the cache was not changed.",
134
+ });
135
+ }
136
+ function leaseState(a) {
137
+ return a.resolution === "abandoned" ? "was abandoned" : `lease expired at ${String(a.leaseExpiresAt)}`;
138
+ }
139
+ export class ArtifactStore {
140
+ access;
141
+ dir;
142
+ signing;
143
+ constructor(opts) {
144
+ if (!isText(opts?.signing?.ref))
145
+ throw invalid("no signing key ref", "a credential ref for the provenance HMAC key");
146
+ this.access = opts.access;
147
+ this.dir = opts.dir;
148
+ this.signing = opts.signing;
149
+ }
150
+ /**
151
+ * Store bytes built by `identity` during an open attempt of its own company. Needs "report".
152
+ * Expired claim leases are swept first, and the commit checks the lease again, so a holder
153
+ * whose lease has run out is refused with ATTEMPT_ABANDONED and the cache is not touched.
154
+ */
155
+ put(identity, input) {
156
+ const worker = this.worker(identity, "report");
157
+ if (!isText(input?.name))
158
+ throw invalid("an empty artifact name", "a non-empty name");
159
+ if (!(input.bytes instanceof Uint8Array))
160
+ throw invalid("artifact bytes that are not a Uint8Array", "a Buffer or Uint8Array");
161
+ checkInputs(input.inputs);
162
+ const controller = this.access.controller;
163
+ controller.expireLeases();
164
+ const view = controller.attempts().find((a) => a.attempt.attemptId === input.attemptId);
165
+ if (!view) {
166
+ throw new DeliveryStoreError("UNKNOWN_ATTEMPT", {
167
+ found: `no attempt ${String(input.attemptId)}`,
168
+ expected: "an attemptId returned by claim",
169
+ action: "Check the attemptId. Nothing was written.",
170
+ });
171
+ }
172
+ if (view.attempt.tenantId !== worker.tenantId) {
173
+ throw denied(`worker ${worker.workerId} of ${worker.tenantId} wrote to an attempt of another company`, `an attempt of ${worker.tenantId}`);
174
+ }
175
+ if (view.resolution === "abandoned")
176
+ throw abandonedPut(view.attempt.attemptId, "was abandoned");
177
+ if (view.resolution !== "open") {
178
+ throw new DeliveryStoreError("ATTEMPT_CONFLICT", {
179
+ found: `attempt ${view.attempt.attemptId} is ${view.resolution}`,
180
+ expected: "an open attempt",
181
+ action: "Store artifacts while the attempt is open, before reporting its outcome. Nothing was written.",
182
+ });
183
+ }
184
+ const bytes = Buffer.from(input.bytes);
185
+ const digest = sha256Hex(bytes);
186
+ const partition = partitionFor(worker.trust);
187
+ const path = this.blobPath(worker.tenantId, partition, digest);
188
+ this.writeBlob(path, bytes, digest);
189
+ const key = this.key();
190
+ const inDigest = inputDigest(input.inputs);
191
+ const env = envDigest(input.inputs.env, input.inputs.envAllowlist);
192
+ const artifactId = `artifact-${randomUUID()}`;
193
+ const { attempt } = view;
194
+ let invalidated = [];
195
+ let stored = null;
196
+ controller.commitArtifacts((draft, at) => {
197
+ // Re-check against the state being written, so a revocation or report in flight wins.
198
+ authenticate(draft.workers, identity, { capability: "report", tenantId: worker.tenantId });
199
+ const live = draft.attempts.find((a) => a.record.attemptId === attempt.attemptId);
200
+ if (live && (live.resolution === "abandoned" || leaseExpired(live, Date.parse(at.now)))) {
201
+ throw abandonedPut(attempt.attemptId, leaseState(live));
202
+ }
203
+ if (!live || live.resolution !== "open") {
204
+ throw new DeliveryStoreError("ATTEMPT_CONFLICT", {
205
+ found: `attempt ${attempt.attemptId} is no longer open`,
206
+ expected: "an open attempt",
207
+ action: "The attempt was resolved while storing. Nothing was written.",
208
+ });
209
+ }
210
+ const provenance = {
211
+ schemaVersion: PROVENANCE_SCHEMA_VERSION,
212
+ artifactId,
213
+ tenantId: worker.tenantId,
214
+ name: input.name,
215
+ partition,
216
+ digest: { algorithm: "sha256", value: digest },
217
+ size: bytes.length,
218
+ source: { ...input.inputs.source },
219
+ recipe: { ...input.inputs.recipe },
220
+ toolchain: { ...input.inputs.toolchain },
221
+ platform: { os: input.inputs.platform.os, arch: input.inputs.platform.arch },
222
+ envKeys: env.envKeys,
223
+ envDigest: env.envDigest,
224
+ inputDigest: inDigest,
225
+ builder: { workerId: worker.workerId, trust: worker.trust },
226
+ attempt: { attemptId: attempt.attemptId, jobId: attempt.jobId, runId: attempt.runId, number: attempt.number },
227
+ createdAt: at.now,
228
+ createdEpoch: at.epoch,
229
+ };
230
+ const record = {
231
+ schemaVersion: DELIVERY_SCHEMA_VERSIONS.artifact,
232
+ tenantId: worker.tenantId,
233
+ artifactId,
234
+ runId: attempt.runId,
235
+ sourcePin: { repository: provenance.source.repository, commitSha: provenance.source.commitSha, verifiedOn: provenance.source.ref },
236
+ deployedState: "unverified",
237
+ };
238
+ const signature = signProvenance(record, provenance, this.signing.ref, key);
239
+ const promotionSignature = signPromotion(artifactId, signature, { promotedAt: null, promotedEpoch: null }, this.signing.ref, key);
240
+ stored = { record, provenance, signature, promotedAt: null, promotedEpoch: null, promotionSignature };
241
+ draft.artifacts.push(stored);
242
+ invalidated = recordCacheEntry(draft.cache, {
243
+ cacheKey: cacheKey(worker.tenantId, partition, inDigest),
244
+ tenantId: worker.tenantId,
245
+ partition,
246
+ inputDigest: inDigest,
247
+ slot: cacheSlot(input.inputs),
248
+ artifactId,
249
+ createdAt: at.now,
250
+ createdEpoch: at.epoch,
251
+ });
252
+ });
253
+ return { ...this.view(stored), invalidatedCacheKeys: invalidated };
254
+ }
255
+ /** Verified bytes of an artifact of the worker's own company. Needs "read". */
256
+ read(identity, artifactId) {
257
+ const worker = this.worker(identity, "read");
258
+ const stored = this.find(artifactId);
259
+ this.sameTenant(worker.tenantId, stored, `worker ${worker.workerId} of ${worker.tenantId}`);
260
+ // verifyStored checks the promotion signature too, so promotedAt is as signed.
261
+ const bytes = this.verifyStored(stored);
262
+ return { bytes, provenance: structuredClone(stored.provenance), promotedAt: stored.promotedAt, provenanceSignature: stored.signature.value };
263
+ }
264
+ /** Re-check the signature and blob of an artifact in scope. Throws ARTIFACT_TAMPERED. */
265
+ verify(scope, artifactId) {
266
+ const stored = this.scoped(scope, artifactId);
267
+ this.verifyStored(stored);
268
+ return this.view(stored);
269
+ }
270
+ /** The stored record, unverified. */
271
+ describe(scope, artifactId) {
272
+ return this.view(this.scoped(scope, artifactId));
273
+ }
274
+ /**
275
+ * Mark a release artifact promoted. Verifies first; refuses untrusted
276
+ * artifacts and artifacts whose attempt has not passed. Idempotent.
277
+ */
278
+ promote(scope, artifactId) {
279
+ const stored = this.scoped(scope, artifactId);
280
+ if (!trustAllows(scope.maxTrust, "release")) {
281
+ throw new DeliveryStoreError("PRIVILEGE_REJECTED", {
282
+ found: `an admin scope with trust ${String(scope.maxTrust)}`,
283
+ expected: "release trust to promote",
284
+ action: "Ask an admin with release trust to promote. Nothing was written.",
285
+ });
286
+ }
287
+ this.verifyStored(stored);
288
+ const p = stored.provenance;
289
+ if (p.partition !== "release" || p.builder.trust !== "release") {
290
+ throw new DeliveryStoreError("PRIVILEGE_REJECTED", {
291
+ found: `artifact ${artifactId} was built by ${p.builder.trust} worker ${p.builder.workerId} into the ${p.partition} partition`,
292
+ expected: "an artifact built by a release-trust worker",
293
+ action: "Rebuild on a release worker. Untrusted results are never release-eligible. Nothing was written.",
294
+ });
295
+ }
296
+ if (stored.promotedAt !== null)
297
+ return this.view(stored);
298
+ const key = this.key();
299
+ const controller = this.access.controller;
300
+ controller.commitArtifacts((draft, at) => {
301
+ const attempt = draft.attempts.find((a) => a.record.attemptId === p.attempt.attemptId);
302
+ if (!attempt || attempt.record.outcome !== "passed") {
303
+ throw new DeliveryStoreError("ARTIFACT_NOT_PROMOTABLE", {
304
+ found: `attempt ${p.attempt.attemptId} is ${attempt ? attempt.record.outcome : "missing"}`,
305
+ expected: "a passed attempt",
306
+ action: "Promote only artifacts of a passed attempt. Nothing was written.",
307
+ });
308
+ }
309
+ const target = draft.artifacts.find((a) => a.provenance.artifactId === artifactId);
310
+ if (!target)
311
+ throw this.unknown(artifactId);
312
+ target.promotedAt = at.now;
313
+ target.promotedEpoch = at.epoch;
314
+ target.promotionSignature = signPromotion(artifactId, target.signature, { promotedAt: at.now, promotedEpoch: at.epoch }, this.signing.ref, key);
315
+ });
316
+ return this.view(this.find(artifactId));
317
+ }
318
+ /**
319
+ * Cache lookup for the worker's own company and trust partition. Returns a
320
+ * verified artifact or null. A hit that fails verification is evicted.
321
+ * Needs "read".
322
+ */
323
+ lookup(identity, inputs) {
324
+ const worker = this.worker(identity, "read");
325
+ checkInputs(inputs);
326
+ const partition = partitionFor(worker.trust);
327
+ const key = cacheKey(worker.tenantId, partition, inputDigest(inputs));
328
+ const entry = findCacheEntry(this.access.controller.artifactRecords().cache, { tenantId: worker.tenantId, partition, cacheKey: key });
329
+ if (!entry)
330
+ return null;
331
+ const stored = this.find(entry.artifactId);
332
+ try {
333
+ this.sameTenant(worker.tenantId, stored, `worker ${worker.workerId} of ${worker.tenantId}`);
334
+ this.verifyStored(stored);
335
+ // The signed provenance must yield the queried key; an entry repointed at another artifact is tampered.
336
+ const p = stored.provenance;
337
+ if (p.tenantId !== worker.tenantId || p.partition !== partition || cacheKey(p.tenantId, p.partition, p.inputDigest) !== key) {
338
+ throw tampered(p.artifactId, `cache entry ${key.slice(0, 12)}… points at an artifact signed for other inputs`);
339
+ }
340
+ }
341
+ catch (err) {
342
+ if (!(err instanceof DeliveryStoreError) || err.code !== "ARTIFACT_TAMPERED")
343
+ throw err;
344
+ this.access.controller.commitArtifacts((draft) => {
345
+ evictArtifact(draft.cache, entry.artifactId);
346
+ const i = draft.cache.findIndex((c) => c.cacheKey === key);
347
+ if (i !== -1)
348
+ draft.cache.splice(i, 1);
349
+ });
350
+ return null;
351
+ }
352
+ return this.view(stored);
353
+ }
354
+ /**
355
+ * Remove blob files no artifact record references, and leftover temp
356
+ * files. Only regular files under the artifacts directory are touched;
357
+ * symlinks and unknown entries are left alone. Returns the removed paths.
358
+ */
359
+ gc() {
360
+ this.access.controller.assertOwner();
361
+ const referenced = new Set(this.access.controller.artifactRecords().artifacts.map((a) => this.blobPath(a.provenance.tenantId, a.provenance.partition, a.provenance.digest.value)));
362
+ const removed = [];
363
+ const root = join(this.dir, ARTIFACTS_DIR);
364
+ const list = (dir) => {
365
+ try {
366
+ if (!lstatSync(dir).isDirectory())
367
+ return [];
368
+ return readdirSync(dir);
369
+ }
370
+ catch {
371
+ return [];
372
+ }
373
+ };
374
+ for (const tenant of list(root)) {
375
+ for (const partition of list(join(root, tenant))) {
376
+ const blobDir = join(root, tenant, partition, "sha256");
377
+ for (const name of list(blobDir)) {
378
+ const path = join(blobDir, name);
379
+ const isTemp = name.startsWith(".tmp-");
380
+ if (!isTemp && (!HEX64.test(name) || referenced.has(path)))
381
+ continue;
382
+ try {
383
+ if (!lstatSync(path).isFile())
384
+ continue;
385
+ unlinkSync(path);
386
+ removed.push(path);
387
+ }
388
+ catch {
389
+ // vanished or not removable; leave it for the next run
390
+ }
391
+ }
392
+ }
393
+ }
394
+ return { removed };
395
+ }
396
+ key() {
397
+ let value;
398
+ try {
399
+ value = this.signing.source.resolve(this.signing.ref);
400
+ }
401
+ catch {
402
+ value = "";
403
+ }
404
+ if (typeof value !== "string" || value === "") {
405
+ throw new DeliveryStoreError("CREDENTIAL_UNAVAILABLE", {
406
+ found: `no value for provenance key ${this.signing.ref}`,
407
+ expected: `a non-empty value for credential ${this.signing.ref}`,
408
+ action: `Configure credential ${this.signing.ref} in the credential source. Nothing was written.`,
409
+ });
410
+ }
411
+ return value;
412
+ }
413
+ worker(identity, capability) {
414
+ const controller = this.access.controller;
415
+ controller.assertOwner();
416
+ return authenticate(controller.workerRecords(), identity, { capability });
417
+ }
418
+ find(artifactId) {
419
+ this.access.controller.assertOwner();
420
+ const stored = this.access.controller.artifactRecords().artifacts.find((a) => a.provenance.artifactId === artifactId);
421
+ if (!stored)
422
+ throw this.unknown(artifactId);
423
+ return stored;
424
+ }
425
+ unknown(artifactId) {
426
+ return new DeliveryStoreError("ARTIFACT_UNKNOWN", {
427
+ found: `no artifact ${String(artifactId)}`,
428
+ expected: "an artifactId returned by put",
429
+ action: "Check the artifactId. Nothing was read or written.",
430
+ });
431
+ }
432
+ scoped(scope, artifactId) {
433
+ if (!scope || !Array.isArray(scope.tenantIds) || !scope.tenantIds.every(isText)) {
434
+ throw denied("a malformed admin scope", "an admin scope with tenantIds and maxTrust");
435
+ }
436
+ const stored = this.find(artifactId);
437
+ if (!scope.tenantIds.includes(stored.provenance.tenantId)) {
438
+ throw denied(`an admin scope for [${scope.tenantIds.join(", ")}] asked for an artifact of another company`, "an artifact of a tenant in scope");
439
+ }
440
+ return stored;
441
+ }
442
+ sameTenant(tenantId, stored, who) {
443
+ if (stored.provenance.tenantId !== tenantId) {
444
+ throw denied(`${who} asked for an artifact of another company`, `an artifact of ${tenantId}`);
445
+ }
446
+ }
447
+ /** Check the signature, then the blob. Returns the verified bytes. */
448
+ verifyStored(stored) {
449
+ const p = stored.provenance;
450
+ const key = this.key();
451
+ if (stored.signature.keyRef !== this.signing.ref || !signatureMatches(stored, key)) {
452
+ throw tampered(p.artifactId, "provenance signature does not match");
453
+ }
454
+ if (stored.promotionSignature.keyRef !== this.signing.ref || !promotionMatches(stored, key)) {
455
+ throw tampered(p.artifactId, "promotion signature does not match the promoted state");
456
+ }
457
+ const path = this.blobPath(p.tenantId, p.partition, p.digest.value);
458
+ let dir = this.dir;
459
+ for (const part of relative(this.dir, join(path, "..")).split(sep)) {
460
+ dir = join(dir, part);
461
+ let ds;
462
+ try {
463
+ ds = lstatSync(dir);
464
+ }
465
+ catch {
466
+ throw tampered(p.artifactId, `blob ${path} is missing`);
467
+ }
468
+ if (ds.isSymbolicLink())
469
+ throw tampered(p.artifactId, `blob directory ${dir} is a symlink`);
470
+ if (!ds.isDirectory())
471
+ throw tampered(p.artifactId, `blob directory ${dir} is not a directory`);
472
+ }
473
+ let stat;
474
+ try {
475
+ stat = lstatSync(path);
476
+ }
477
+ catch {
478
+ throw tampered(p.artifactId, `blob ${path} is missing`);
479
+ }
480
+ if (!stat.isFile())
481
+ throw tampered(p.artifactId, `blob ${path} is not a regular file`);
482
+ const bytes = readFileSync(path);
483
+ const actual = sha256Hex(bytes);
484
+ if (actual !== p.digest.value || bytes.length !== p.size) {
485
+ throw tampered(p.artifactId, `digest mismatch: blob has sha256 ${actual} (${bytes.length} bytes), provenance records ${p.digest.value} (${p.size} bytes)`);
486
+ }
487
+ return bytes;
488
+ }
489
+ blobPath(tenantId, partition, digest) {
490
+ return join(this.dir, blobRelativePath(tenantId, partition, digest));
491
+ }
492
+ writeBlob(path, bytes, digest) {
493
+ const dir = join(path, "..");
494
+ const tmp = join(dir, `.tmp-${randomUUID()}`);
495
+ try {
496
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
497
+ const fd = openSync(tmp, "wx", 0o600);
498
+ try {
499
+ let off = 0;
500
+ while (off < bytes.length)
501
+ off += writeSync(fd, bytes, off, bytes.length - off);
502
+ fsyncSync(fd);
503
+ }
504
+ finally {
505
+ closeSync(fd);
506
+ }
507
+ if (sha256Hex(readFileSync(tmp)) !== digest) {
508
+ throw new DeliveryStoreError("STORE_IO", {
509
+ found: `the bytes read back from ${tmp} do not match what was written`,
510
+ expected: `sha256 ${digest}`,
511
+ action: "Check the disk. Nothing was recorded; retry the write.",
512
+ });
513
+ }
514
+ chmodSync(tmp, 0o444);
515
+ try {
516
+ linkSync(tmp, path);
517
+ }
518
+ catch (err) {
519
+ if (err.code !== "EEXIST")
520
+ throw err;
521
+ const existing = lstatSync(path);
522
+ if (!existing.isFile() || sha256Hex(readFileSync(path)) !== digest) {
523
+ throw new DeliveryStoreError("ARTIFACT_TAMPERED", {
524
+ found: `blob ${path} already exists with other content`,
525
+ expected: `a blob with sha256 ${digest}`,
526
+ action: "Investigate who changed the store directory. Nothing was recorded.",
527
+ });
528
+ }
529
+ }
530
+ // Skipped on win32, which cannot fsync a directory (EPERM); NTFS journals the link.
531
+ fsyncDirectory(dir);
532
+ }
533
+ catch (err) {
534
+ if (err instanceof DeliveryStoreError)
535
+ throw err;
536
+ throw new DeliveryStoreError("STORE_IO", {
537
+ found: `writing blob ${path}: ${err.message}`,
538
+ expected: "a writable artifact directory",
539
+ action: "Check the store directory permissions and free space. Nothing was recorded.",
540
+ });
541
+ }
542
+ finally {
543
+ try {
544
+ unlinkSync(tmp);
545
+ }
546
+ catch {
547
+ // already gone
548
+ }
549
+ }
550
+ }
551
+ view(stored) {
552
+ const p = stored.provenance;
553
+ return {
554
+ artifactId: p.artifactId,
555
+ tenantId: p.tenantId,
556
+ partition: p.partition,
557
+ digest: p.digest.value,
558
+ size: p.size,
559
+ path: this.blobPath(p.tenantId, p.partition, p.digest.value),
560
+ cacheKey: cacheKey(p.tenantId, p.partition, p.inputDigest),
561
+ promoted: stored.promotedAt !== null,
562
+ provenance: structuredClone(p),
563
+ invalidatedCacheKeys: [],
564
+ };
565
+ }
566
+ }
567
+ //# sourceMappingURL=artifacts.js.map
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Attempt ids as path segments (US-011 slice 4 B).
3
+ *
4
+ * A worker uses the attempt id as a directory name, and since slice 4 B a
5
+ * worker may choose the id it claims with. Every id that is chosen by a
6
+ * worker, stored for one, or answered to one must therefore be a safe name:
7
+ * 1 to 128 letters, digits, dot, underscore or dash, starting with a letter
8
+ * or digit, and without "..".
9
+ */
10
+ /** The longest id a worker may choose; the stored id adds a 14-character worker scope. */
11
+ export declare const MAX_CHOSEN_ATTEMPT_ID = 100;
12
+ export declare function isSafeAttemptId(id: unknown): id is string;
13
+ //# sourceMappingURL=attempt-id.d.ts.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Attempt ids as path segments (US-011 slice 4 B).
3
+ *
4
+ * A worker uses the attempt id as a directory name, and since slice 4 B a
5
+ * worker may choose the id it claims with. Every id that is chosen by a
6
+ * worker, stored for one, or answered to one must therefore be a safe name:
7
+ * 1 to 128 letters, digits, dot, underscore or dash, starting with a letter
8
+ * or digit, and without "..".
9
+ */
10
+ const SAFE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
11
+ /** The longest id a worker may choose; the stored id adds a 14-character worker scope. */
12
+ export const MAX_CHOSEN_ATTEMPT_ID = 100;
13
+ export function isSafeAttemptId(id) {
14
+ return typeof id === "string" && SAFE.test(id) && !id.includes("..");
15
+ }
16
+ //# sourceMappingURL=attempt-id.js.map
@@ -0,0 +1,78 @@
1
+ import type { CredentialSource } from "./credentials.js";
2
+ import { DeliveryStoreError } from "./migrations.js";
3
+ export declare const BACKUP_FORMAT = "hq-delivery.backup.v1";
4
+ export declare const BACKUP_MANIFEST_FILE = "manifest.json";
5
+ export declare const BACKUP_BLOBS_DIR = "blobs";
6
+ /** Points where a test can simulate a crash, in order. */
7
+ export type BackupCrashStep = "snapshot" | "blobs-copied" | "manifest-written";
8
+ export interface BackupSigning {
9
+ ref: string;
10
+ source: CredentialSource;
11
+ }
12
+ export interface BackupArtifactEntry {
13
+ artifactId: string;
14
+ tenantId: string;
15
+ partition: string;
16
+ digest: string;
17
+ size: number;
18
+ /** Path inside the backup directory. */
19
+ file: string;
20
+ }
21
+ export interface BackupManifest {
22
+ format: typeof BACKUP_FORMAT;
23
+ backupId: string;
24
+ createdAt: string;
25
+ sourceDir: string;
26
+ storeSchemaVersion: string;
27
+ /** Store epoch at the snapshot. */
28
+ epoch: number;
29
+ stateSha256: string;
30
+ stateSize: number;
31
+ artifacts: BackupArtifactEntry[];
32
+ signature: {
33
+ algorithm: "hmac-sha256";
34
+ keyRef: string;
35
+ value: string;
36
+ };
37
+ }
38
+ export interface BackupOptions {
39
+ storeDir: string;
40
+ /** Directory holding one subdirectory per backup. */
41
+ backupRoot: string;
42
+ signing: BackupSigning;
43
+ /** Credential values that must never appear in a backup. Values are looked up, compared and dropped. */
44
+ secretProbe?: {
45
+ source: CredentialSource;
46
+ refs: string[];
47
+ };
48
+ clock?: () => number;
49
+ gateWaitMs?: number;
50
+ crashPoint?: (step: BackupCrashStep) => void;
51
+ }
52
+ export interface BackupReport {
53
+ backupId: string;
54
+ path: string;
55
+ manifest: BackupManifest;
56
+ }
57
+ export declare function backupInvalid(found: string, expected: string, action?: string): DeliveryStoreError;
58
+ export declare function resolveKey(signing: BackupSigning): string;
59
+ /** Write `bytes` to a new file, fsync it and make it read-only. */
60
+ export declare function writeFileDurable(path: string, bytes: Buffer, mode?: number): void;
61
+ export declare function fsyncDirectory(dir: string): void;
62
+ /** Create a verified backup of `storeDir` under `backupRoot`. */
63
+ export declare function createBackup(opts: BackupOptions): BackupReport;
64
+ /** Verify a finished backup from disk: manifest signature, state digest and load, every blob digest. */
65
+ export declare function verifyBackup(path: string, signing: BackupSigning): BackupManifest;
66
+ export interface BackupListing {
67
+ backupId: string;
68
+ path: string;
69
+ createdAt: string;
70
+ epoch: number;
71
+ }
72
+ /** Finished backups under `root`, oldest first. Partial directories are skipped. Not verified; use verifyBackup. */
73
+ export declare function listBackups(root: string): BackupListing[];
74
+ /** Retention: keep the newest `keep` (>= 1) backups, remove older ones and crash leftovers. Returns removed backup ids. */
75
+ export declare function pruneBackups(root: string, opts: {
76
+ keep: number;
77
+ }): string[];
78
+ //# sourceMappingURL=backup.d.ts.map