@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,187 @@
1
+ /**
2
+ * Transactional outbox for delivery notifications (US-005).
3
+ *
4
+ * The outbox is derived from the ledger, not stored beside it. Every event is
5
+ * a pure function of a committed ledger record: one `job.accepted` per stored
6
+ * job and one `attempt.resolved` per attempt that is no longer open. An event
7
+ * therefore exists exactly when the commit that wrote its record exists, and
8
+ * a commit that rolls back leaves no event. The store schema is unchanged.
9
+ *
10
+ * Event ids are stable (`<type>:<record id>`) so a republish after a crash
11
+ * carries the same id and the consumer inbox drops it.
12
+ *
13
+ * The publisher keeps only transport progress, in its own sqlite file: the
14
+ * ids the broker has acked. A row is written after the ack, so a crash between
15
+ * ack and write republishes (at-least-once). The ack is never a ledger
16
+ * transition, and published rows are never deleted.
17
+ */
18
+ import { loadBetterSqlite3 } from "../db/sqlite-binding.js";
19
+ import { notificationTopic } from "./mqtt.js";
20
+ export const NOTIFICATION_SCHEMA = "hq-delivery.notification.v1";
21
+ /** Larger payloads are refused unparsed. */
22
+ export const MAX_NOTIFICATION_BYTES = 16 * 1024;
23
+ const EVENT_KEYS = ["schemaVersion", "eventId", "type", "tenantId", "runId", "jobId", "attemptId", "epoch"];
24
+ /** Every event the committed ledger implies, in ledger order: accepted jobs, then resolved attempts. */
25
+ export function ledgerEvents(state) {
26
+ const events = [];
27
+ for (const j of state.jobs) {
28
+ events.push({
29
+ schemaVersion: NOTIFICATION_SCHEMA,
30
+ eventId: `job.accepted:${j.record.jobId}`,
31
+ type: "job.accepted",
32
+ tenantId: j.record.tenantId,
33
+ runId: j.record.runId,
34
+ jobId: j.record.jobId,
35
+ attemptId: null,
36
+ epoch: j.acceptedEpoch,
37
+ });
38
+ }
39
+ const tenantOf = new Map(state.jobs.map((j) => [j.record.jobId, j.record.tenantId]));
40
+ for (const a of state.attempts) {
41
+ if (a.resolution === "open")
42
+ continue;
43
+ const tenantId = tenantOf.get(a.record.jobId);
44
+ if (tenantId === undefined)
45
+ continue;
46
+ events.push({
47
+ schemaVersion: NOTIFICATION_SCHEMA,
48
+ eventId: `attempt.resolved:${a.record.attemptId}`,
49
+ type: "attempt.resolved",
50
+ tenantId,
51
+ runId: a.record.runId,
52
+ jobId: a.record.jobId,
53
+ attemptId: a.record.attemptId,
54
+ epoch: a.resolvedEpoch ?? a.claimedEpoch,
55
+ });
56
+ }
57
+ return events;
58
+ }
59
+ /** Strict parse of a notification payload. Anything else, including extra keys, is null. */
60
+ export function parseNotification(payload) {
61
+ if (typeof payload !== "string" || payload.length > MAX_NOTIFICATION_BYTES)
62
+ return null;
63
+ let value;
64
+ try {
65
+ value = JSON.parse(payload);
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ if (typeof value !== "object" || value === null || Array.isArray(value))
71
+ return null;
72
+ const v = value;
73
+ const keys = Object.keys(v).sort();
74
+ if (keys.length !== EVENT_KEYS.length || [...EVENT_KEYS].sort().some((k, i) => keys[i] !== k))
75
+ return null;
76
+ if (v.schemaVersion !== NOTIFICATION_SCHEMA)
77
+ return null;
78
+ if (v.type !== "job.accepted" && v.type !== "attempt.resolved")
79
+ return null;
80
+ for (const k of ["eventId", "tenantId", "runId", "jobId"]) {
81
+ if (typeof v[k] !== "string" || v[k] === "")
82
+ return null;
83
+ }
84
+ if (v.attemptId !== null && (typeof v.attemptId !== "string" || v.attemptId === ""))
85
+ return null;
86
+ if (typeof v.epoch !== "number" || !Number.isInteger(v.epoch) || v.epoch < 0)
87
+ return null;
88
+ return v;
89
+ }
90
+ /** True when two events carry the same values in every field. */
91
+ export function sameEvent(a, b) {
92
+ return EVENT_KEYS.every((k) => a[k] === b[k]);
93
+ }
94
+ /** Open a transport-side sqlite file (outbox progress or consumer inbox) with WAL and a busy timeout. */
95
+ export function openTransportDb(path) {
96
+ const Database = loadBetterSqlite3();
97
+ const db = new Database(path, { timeout: 5000 });
98
+ db.exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;");
99
+ return db;
100
+ }
101
+ export const DEFAULT_BACKOFF = { baseMs: 1000, maxMs: 60_000 };
102
+ export function backoffDelay(policy, failures) {
103
+ if (failures <= 0)
104
+ return 0;
105
+ return Math.min(policy.maxMs, policy.baseMs * 2 ** Math.min(failures - 1, 30));
106
+ }
107
+ export const MAX_BATCH = 1000;
108
+ export function checkBatch(size) {
109
+ if (!Number.isInteger(size) || size < 1 || size > MAX_BATCH) {
110
+ throw new RangeError(`batch size must be an integer from 1 to ${MAX_BATCH}`);
111
+ }
112
+ return size;
113
+ }
114
+ export class OutboxPublisher {
115
+ access;
116
+ broker;
117
+ db;
118
+ batchSize;
119
+ backoff;
120
+ clock;
121
+ testBarrier;
122
+ failures = 0;
123
+ crashAfterAck = false;
124
+ constructor(access, broker, db, batchSize, backoff, clock, testBarrier) {
125
+ this.access = access;
126
+ this.broker = broker;
127
+ this.db = db;
128
+ this.batchSize = batchSize;
129
+ this.backoff = backoff;
130
+ this.clock = clock;
131
+ this.testBarrier = testBarrier;
132
+ }
133
+ static open(opts) {
134
+ const batchSize = checkBatch(opts.batchSize ?? 100);
135
+ const db = openTransportDb(opts.path);
136
+ db.exec("CREATE TABLE IF NOT EXISTS published (event_id TEXT PRIMARY KEY, at INTEGER NOT NULL)");
137
+ return new OutboxPublisher(opts.access, opts.broker, db, batchSize, opts.backoff ?? DEFAULT_BACKOFF, opts.clock ?? Date.now, opts.testBarrier);
138
+ }
139
+ /** Committed events the broker has not acked yet, in ledger order. */
140
+ pending() {
141
+ const done = new Set(this.published());
142
+ return this.access.controller.ledgerEvents().filter((e) => !done.has(e.eventId));
143
+ }
144
+ /** Event ids the broker has acked, in ack order. */
145
+ published() {
146
+ return this.db.prepare("SELECT event_id FROM published ORDER BY rowid").all().map((r) => r.event_id);
147
+ }
148
+ /**
149
+ * Publish up to one batch of pending events, oldest first. Stops at the
150
+ * first broker error and reports a backoff delay; nothing is lost because
151
+ * the events stay derivable from the ledger.
152
+ */
153
+ async publishPending() {
154
+ const pending = this.pending();
155
+ const insert = this.db.prepare("INSERT OR IGNORE INTO published (event_id, at) VALUES (?, ?)");
156
+ let published = 0;
157
+ for (const event of pending.slice(0, this.batchSize)) {
158
+ try {
159
+ await this.broker.publish(notificationTopic(event.tenantId), JSON.stringify(event));
160
+ }
161
+ catch (err) {
162
+ this.failures += 1;
163
+ return {
164
+ published,
165
+ remaining: pending.length - published,
166
+ error: err instanceof Error ? err.message : "broker error",
167
+ nextDelayMs: backoffDelay(this.backoff, this.failures),
168
+ };
169
+ }
170
+ this.testBarrier?.("acked", event.eventId);
171
+ if (this.crashAfterAck)
172
+ throw new Error("simulated crash after broker ack");
173
+ insert.run(event.eventId, this.clock());
174
+ published += 1;
175
+ }
176
+ this.failures = 0;
177
+ return { published, remaining: pending.length - published, error: null, nextDelayMs: 0 };
178
+ }
179
+ /** Test hook: the next publishPending throws after the first broker ack and before its row is written. */
180
+ crashAfterAckForTest() {
181
+ this.crashAfterAck = true;
182
+ }
183
+ close() {
184
+ this.db.close();
185
+ }
186
+ }
187
+ //# sourceMappingURL=outbox.js.map
@@ -0,0 +1,129 @@
1
+ import type { Artifact } from "./contracts.js";
2
+ import type { WorkerTrust } from "./migrations.js";
3
+ export declare const PROVENANCE_SCHEMA_VERSION = "hq-delivery.provenance.v1";
4
+ /** release: written by a release-trust builder, eligible for promotion. untrusted: everything else. */
5
+ export type TrustPartition = "release" | "untrusted";
6
+ export declare const TRUST_PARTITIONS: readonly TrustPartition[];
7
+ export interface BuildSource {
8
+ repository: string;
9
+ /** Full 40-hex commit SHA. */
10
+ commitSha: string;
11
+ /** refs/heads/<name> or refs/tags/<name>. */
12
+ ref: string;
13
+ }
14
+ export interface BuildInputs {
15
+ source: BuildSource;
16
+ /** recipeId and the sha256 hex digest of the recipe content. */
17
+ recipe: {
18
+ recipeId: string;
19
+ digest: string;
20
+ };
21
+ /** Toolchain name -> installed version, as in a US-006/US-007 WorkerProfile. */
22
+ toolchain: Record<string, string>;
23
+ platform: {
24
+ os: string;
25
+ arch: string;
26
+ };
27
+ /** Build environment. Only keys in envAllowlist count; their values are hashed, never stored. */
28
+ env: Record<string, string>;
29
+ envAllowlist: string[];
30
+ }
31
+ export interface ArtifactProvenance {
32
+ schemaVersion: typeof PROVENANCE_SCHEMA_VERSION;
33
+ artifactId: string;
34
+ tenantId: string;
35
+ name: string;
36
+ partition: TrustPartition;
37
+ digest: {
38
+ algorithm: "sha256";
39
+ value: string;
40
+ };
41
+ size: number;
42
+ source: BuildSource;
43
+ recipe: {
44
+ recipeId: string;
45
+ digest: string;
46
+ };
47
+ toolchain: Record<string, string>;
48
+ platform: {
49
+ os: string;
50
+ arch: string;
51
+ };
52
+ /** Allowlisted env keys, sorted. */
53
+ envKeys: string[];
54
+ /** sha256 of the allowlisted env pairs. */
55
+ envDigest: string;
56
+ /** sha256 of every cache input except tenant and partition. */
57
+ inputDigest: string;
58
+ builder: {
59
+ workerId: string;
60
+ trust: WorkerTrust;
61
+ };
62
+ attempt: {
63
+ attemptId: string;
64
+ jobId: string;
65
+ runId: string;
66
+ number: number;
67
+ };
68
+ createdAt: string;
69
+ createdEpoch: number;
70
+ }
71
+ export interface ProvenanceSignature {
72
+ algorithm: "hmac-sha256";
73
+ /** Credential ref of the signing key. The key value is never stored. */
74
+ keyRef: string;
75
+ value: string;
76
+ }
77
+ export interface StoredArtifact {
78
+ /** The US-001 artifact contract record. */
79
+ record: Artifact;
80
+ provenance: ArtifactProvenance;
81
+ signature: ProvenanceSignature;
82
+ promotedAt: string | null;
83
+ promotedEpoch: number | null;
84
+ /**
85
+ * Signature over the promotion state (artifactId, the provenance signature,
86
+ * promotedAt and promotedEpoch). Written at put with null promotion and
87
+ * re-signed by promote, so setting or clearing the promoted flag in
88
+ * state.json fails verification.
89
+ */
90
+ promotionSignature: ProvenanceSignature;
91
+ }
92
+ export interface StoredCacheEntry {
93
+ cacheKey: string;
94
+ tenantId: string;
95
+ partition: TrustPartition;
96
+ inputDigest: string;
97
+ /**
98
+ * Digest of the source and recipe identity (repository, commit, ref,
99
+ * recipeId). A new entry in the same tenant, partition and slot with other
100
+ * inputs replaces the old one.
101
+ */
102
+ slot: string;
103
+ artifactId: string;
104
+ createdAt: string;
105
+ createdEpoch: number;
106
+ }
107
+ /** JSON with object keys sorted at every level, so equal values hash equally. */
108
+ export declare function canonicalJson(value: unknown): string;
109
+ export declare function sha256Hex(data: string | Uint8Array): string;
110
+ /** The allowlisted env keys, sorted, and a digest over their values. */
111
+ export declare function envDigest(env: Record<string, string>, allowlist: readonly string[]): {
112
+ envKeys: string[];
113
+ envDigest: string;
114
+ };
115
+ /** Digest of every build input that affects the output. */
116
+ export declare function inputDigest(inputs: BuildInputs): string;
117
+ export declare function cacheSlot(inputs: BuildInputs): string;
118
+ export declare function cacheKey(tenantId: string, partition: TrustPartition, digest: string): string;
119
+ export declare function partitionFor(trust: WorkerTrust): TrustPartition;
120
+ export declare function signProvenance(record: Artifact, provenance: ArtifactProvenance, keyRef: string, key: string): ProvenanceSignature;
121
+ export declare function signPromotion(artifactId: string, provenanceSignature: ProvenanceSignature, promotion: {
122
+ promotedAt: string | null;
123
+ promotedEpoch: number | null;
124
+ }, keyRef: string, key: string): ProvenanceSignature;
125
+ /** Constant-time check of the stored promotion signature against the given key. */
126
+ export declare function promotionMatches(stored: StoredArtifact, key: string): boolean;
127
+ /** Constant-time check of a stored signature against the given key. */
128
+ export declare function signatureMatches(stored: StoredArtifact, key: string): boolean;
129
+ //# sourceMappingURL=provenance.d.ts.map
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Artifact provenance records and cache keys (US-008).
3
+ *
4
+ * Pure functions and types only; nothing here touches the filesystem or the
5
+ * store. artifacts.ts writes blobs and commits these records; migrations.ts
6
+ * validates them on every load and write.
7
+ *
8
+ * Provenance names the content digest, source, recipe, toolchain, platform,
9
+ * builder, attempt and tenant of one artifact. It is signed with an
10
+ * HMAC-SHA256 key that the store never holds: only the key's credential ref is
11
+ * recorded, and the value is looked up from a CredentialSource each time a
12
+ * record is signed or verified. An edit to a stored record, even with the
13
+ * store checksum recomputed, fails the signature check.
14
+ *
15
+ * Cache keys cover the tenant, the trust partition and the full input digest
16
+ * (source repository, commit and ref, recipe id and digest, every toolchain
17
+ * name and version, platform os and arch, and the allowlisted environment).
18
+ * Environment keys outside the allowlist are ignored; allowlisted values are
19
+ * hashed and never stored.
20
+ */
21
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
22
+ export const PROVENANCE_SCHEMA_VERSION = "hq-delivery.provenance.v1";
23
+ export const TRUST_PARTITIONS = ["release", "untrusted"];
24
+ /** JSON with object keys sorted at every level, so equal values hash equally. */
25
+ export function canonicalJson(value) {
26
+ if (Array.isArray(value))
27
+ return `[${value.map(canonicalJson).join(",")}]`;
28
+ if (value !== null && typeof value === "object") {
29
+ const obj = value;
30
+ return `{${Object.keys(obj)
31
+ .sort()
32
+ .map((k) => `${JSON.stringify(k)}:${canonicalJson(obj[k])}`)
33
+ .join(",")}}`;
34
+ }
35
+ return JSON.stringify(value);
36
+ }
37
+ export function sha256Hex(data) {
38
+ return createHash("sha256").update(data).digest("hex");
39
+ }
40
+ /** The allowlisted env keys, sorted, and a digest over their values. */
41
+ export function envDigest(env, allowlist) {
42
+ const keys = [...new Set(allowlist)].sort();
43
+ const pairs = keys.map((k) => [k, Object.prototype.hasOwnProperty.call(env, k) ? env[k] : null]);
44
+ return { envKeys: keys.filter((k) => Object.prototype.hasOwnProperty.call(env, k)), envDigest: sha256Hex(canonicalJson(pairs)) };
45
+ }
46
+ /** Digest of every build input that affects the output. */
47
+ export function inputDigest(inputs) {
48
+ return sha256Hex(canonicalJson({
49
+ source: inputs.source,
50
+ recipe: inputs.recipe,
51
+ toolchain: inputs.toolchain,
52
+ platform: inputs.platform,
53
+ env: envDigest(inputs.env, inputs.envAllowlist).envDigest,
54
+ }));
55
+ }
56
+ export function cacheSlot(inputs) {
57
+ return sha256Hex(canonicalJson({ source: inputs.source, recipeId: inputs.recipe.recipeId }));
58
+ }
59
+ export function cacheKey(tenantId, partition, digest) {
60
+ return sha256Hex(canonicalJson({ tenantId, partition, inputDigest: digest }));
61
+ }
62
+ export function partitionFor(trust) {
63
+ return trust === "release" ? "release" : "untrusted";
64
+ }
65
+ function signedBytes(record, provenance, keyRef) {
66
+ return canonicalJson({ keyRef, provenance, record });
67
+ }
68
+ export function signProvenance(record, provenance, keyRef, key) {
69
+ const value = createHmac("sha256", key).update(signedBytes(record, provenance, keyRef)).digest("hex");
70
+ return { algorithm: "hmac-sha256", keyRef, value };
71
+ }
72
+ function promotionBytes(artifactId, provenanceSignature, promotedAt, promotedEpoch, keyRef) {
73
+ return canonicalJson({ kind: "promotion", artifactId, keyRef, promotedAt, promotedEpoch, provenanceSignature });
74
+ }
75
+ export function signPromotion(artifactId, provenanceSignature, promotion, keyRef, key) {
76
+ const bytes = promotionBytes(artifactId, provenanceSignature.value, promotion.promotedAt, promotion.promotedEpoch, keyRef);
77
+ return { algorithm: "hmac-sha256", keyRef, value: createHmac("sha256", key).update(bytes).digest("hex") };
78
+ }
79
+ /** Constant-time check of the stored promotion signature against the given key. */
80
+ export function promotionMatches(stored, key) {
81
+ const sig = stored.promotionSignature;
82
+ const bytes = promotionBytes(stored.provenance.artifactId, stored.signature.value, stored.promotedAt, stored.promotedEpoch, sig.keyRef);
83
+ const want = createHmac("sha256", key).update(bytes).digest();
84
+ const have = Buffer.from(sig.value, "hex");
85
+ return sig.algorithm === "hmac-sha256" && have.length === want.length && timingSafeEqual(have, want);
86
+ }
87
+ /** Constant-time check of a stored signature against the given key. */
88
+ export function signatureMatches(stored, key) {
89
+ const want = createHmac("sha256", key).update(signedBytes(stored.record, stored.provenance, stored.signature.keyRef)).digest();
90
+ const have = Buffer.from(stored.signature.value, "hex");
91
+ return stored.signature.algorithm === "hmac-sha256" && have.length === want.length && timingSafeEqual(have, want);
92
+ }
93
+ //# sourceMappingURL=provenance.js.map
@@ -0,0 +1,215 @@
1
+ import { type Attempt, type Job, type Run } from "./contracts.js";
2
+ import { DeliveryStoreError, type AttemptResolution, type StoredAttempt, type StoredDeployment, type StoredDeployPolicy, type StoredWorker, type StoreState } from "./migrations.js";
3
+ import { type LedgerEvent } from "./outbox.js";
4
+ import type { StoredArtifact, StoredCacheEntry } from "./provenance.js";
5
+ import { type OpenReport, type StoreOpenOptions } from "./store.js";
6
+ export { DeliveryStoreError } from "./migrations.js";
7
+ export interface ControllerOptions extends StoreOpenOptions {
8
+ /** Attempt id generator. Default `attempt-<uuid>`. */
9
+ ids?: () => string;
10
+ /** Lease of a worker's claim, in ms on the store clock. A positive integer. Default DEFAULT_CLAIM_LEASE_MS. */
11
+ claimLeaseMs?: number;
12
+ }
13
+ /** Default claim lease: 120 s. A worker renews it every third of that (startLeaseHeartbeat). */
14
+ export declare const DEFAULT_CLAIM_LEASE_MS = 120000;
15
+ /** True when `a` is open, has a lease, and the lease time has been reached at `nowMs`. */
16
+ export declare function leaseExpired(a: StoredAttempt, nowMs: number): boolean;
17
+ /** The result of renewLease: the attempt and its new lease time. */
18
+ export interface LeaseView {
19
+ attemptId: string;
20
+ leaseExpiresAt: string;
21
+ }
22
+ export interface JobInput {
23
+ job: Job;
24
+ /** jobIds in the same run that must pass first. */
25
+ dependsOn?: string[];
26
+ }
27
+ export type JobState = "waiting" | "ready" | "running" | "passed" | "failed";
28
+ export interface JobView {
29
+ job: Job;
30
+ dependsOn: string[];
31
+ state: JobState;
32
+ attempts: number;
33
+ }
34
+ export interface AttemptView {
35
+ attempt: Attempt;
36
+ resolution: AttemptResolution;
37
+ claimedEpoch: number;
38
+ /** workerId of the worker that claimed the attempt, or null. */
39
+ claimedBy: string | null;
40
+ }
41
+ /**
42
+ * Runs inside the commit against the state about to be written (or, for a
43
+ * replay or a repeated report, the committed state). Throwing refuses the
44
+ * operation and nothing is written.
45
+ */
46
+ export type CommitGuard = (state: Readonly<StoreState>) => void;
47
+ export interface ClaimResult extends AttemptView {
48
+ /** True when attemptId was already stored and nothing was written. */
49
+ replayed: boolean;
50
+ }
51
+ export interface AcceptResult {
52
+ runId: string;
53
+ /** Jobs written by this call. */
54
+ acceptedJobIds: string[];
55
+ /** True when the run and every job were already stored identically and nothing was written. */
56
+ replayed: boolean;
57
+ }
58
+ export interface RecoveryReport extends OpenReport {
59
+ /** Attempts abandoned on this open under the recovery rule. */
60
+ abandonedAttemptIds: string[];
61
+ }
62
+ /** Open a store directory as its single controller and apply the recovery rule. */
63
+ export declare function openDeliveryController(opts: ControllerOptions): DeliveryController;
64
+ export declare class DeliveryController {
65
+ readonly recovery: RecoveryReport;
66
+ private readonly store;
67
+ private readonly ids;
68
+ private readonly leaseMs;
69
+ private constructor();
70
+ static open(opts: ControllerOptions): DeliveryController;
71
+ /** The fencing epoch this controller writes with. */
72
+ get epoch(): number;
73
+ /** ISO timestamp from the store clock, the one commits are stamped with. */
74
+ now(): string;
75
+ runs(): Run[];
76
+ jobs(runId?: string): JobView[];
77
+ /** One job's view, or undefined when no such job was accepted. Scans the attempts once, not once per job. */
78
+ job(jobId: string): JobView | undefined;
79
+ /** Jobs whose state is "ready", in accept order. */
80
+ claimable(runId?: string): JobView[];
81
+ attempts(jobId?: string): AttemptView[];
82
+ jobState(jobId: string): JobState;
83
+ /**
84
+ * Accept a run and its jobs in one commit. Replaying an identical accept is
85
+ * a no-op; a different run or job under an existing id is DUPLICATE_CONFLICT.
86
+ */
87
+ acceptRun(input: {
88
+ run: Run;
89
+ jobs: JobInput[];
90
+ }): AcceptResult;
91
+ /** Add jobs to an accepted run in one commit. Dependencies may name existing jobs in the run. */
92
+ acceptJobs(input: {
93
+ tenantId: string;
94
+ runId: string;
95
+ jobs: JobInput[];
96
+ }): AcceptResult;
97
+ private admit;
98
+ /**
99
+ * Claim a ready job by committing a new open attempt. With a known
100
+ * attemptId for the same job, returns the stored attempt (replayed: true).
101
+ */
102
+ claim(jobId: string, opts?: {
103
+ attemptId?: string;
104
+ guard?: CommitGuard;
105
+ workerId?: string;
106
+ }): ClaimResult;
107
+ /** Report the outcome of an open attempt. Repeating the same report is a no-op. */
108
+ recordOutcome(attemptId: string, outcome: "passed" | "failed", opts?: {
109
+ guard?: CommitGuard;
110
+ }): AttemptView;
111
+ /**
112
+ * US-007: return an open attempt unfinished, so its job can run again. The
113
+ * attempt is marked abandoned (outcome "failed") in one fenced commit, the
114
+ * same state the recovery rule leaves a stale attempt in: the job allows
115
+ * exactly one new attempt and a late report is refused with
116
+ * ATTEMPT_ABANDONED. Returning an abandoned attempt again is a no-op; a
117
+ * reported attempt cannot be returned.
118
+ */
119
+ returnAttempt(attemptId: string, opts?: {
120
+ guard?: CommitGuard;
121
+ }): AttemptView;
122
+ /**
123
+ * Extend the lease of an open attempt to now + claimLeaseMs on the store clock.
124
+ * Refused with ATTEMPT_ABANDONED when the lease has already expired (at
125
+ * exactly leaseExpiresAt it has), with ATTEMPT_CONFLICT for a reported attempt
126
+ * or one without a lease, and ACCESS_DENIED for another claimant. The guard and
127
+ * every check run again inside the commit, so the renewal and the expiry it
128
+ * races are decided once, at one clock reading.
129
+ */
130
+ renewLease(attemptId: string, opts?: {
131
+ guard?: CommitGuard;
132
+ workerId?: string;
133
+ }): LeaseView;
134
+ /** The lease time of an attempt, or null when it has none. */
135
+ leaseExpiresAt(attemptId: string): string | null;
136
+ /** The claim lease length in ms that this controller gives a worker's claim. A heartbeat derives its period from it. */
137
+ get claimLeaseMs(): number;
138
+ /** True when the attempt is open under a lease that has run out on the store clock, but has not been swept yet. */
139
+ leaseLapsed(attemptId: string): boolean;
140
+ /**
141
+ * Abandon every open attempt whose lease has run out at the store clock's
142
+ * current time, in one commit. Returns the abandoned attemptIds (none: no commit).
143
+ */
144
+ expireLeases(): string[];
145
+ /** Abandon the attempts whose lease has run out at `nowMs`. One commit, or none when nothing has expired. */
146
+ private expireDue;
147
+ /**
148
+ * Revoke a worker and abandon its open attempts in the same fenced commit, so
149
+ * a revoked worker's claims are freed at once. `mutate` changes the worker
150
+ * records and may throw to refuse; nothing is written then. Returns the
151
+ * abandoned attemptIds.
152
+ * @internal Used by enrollment.ts revoke().
153
+ */
154
+ commitRevocation(workerId: string, mutate: (workers: StoredWorker[], at: {
155
+ epoch: number;
156
+ now: string;
157
+ }) => void): string[];
158
+ /**
159
+ * Throw unless this handle still owns the store: STORE_CLOSED for a closed
160
+ * or failed handle, FENCED when another controller has taken over. Read only.
161
+ */
162
+ assertOwner(): void;
163
+ /**
164
+ * The notification events the committed ledger implies (US-005), in ledger
165
+ * order. Derived from committed records only, so an event exists exactly
166
+ * when its transition was committed. Only an owning handle may serve them.
167
+ */
168
+ ledgerEvents(): LedgerEvent[];
169
+ /** Copies of the stored worker records, including secret digests. For the US-004 access layer. */
170
+ workerRecords(): StoredWorker[];
171
+ /**
172
+ * Change worker records in one fenced store commit. `mutate` may throw to
173
+ * refuse; nothing is written then.
174
+ * @internal Used by enrollment.ts; callers outside the access layer must not write workers.
175
+ */
176
+ commitWorkers(mutate: (workers: StoredWorker[], at: {
177
+ epoch: number;
178
+ now: string;
179
+ }) => void): void;
180
+ /** US-008: copies of the artifact provenance records and cache entries. */
181
+ artifactRecords(): {
182
+ artifacts: StoredArtifact[];
183
+ cache: StoredCacheEntry[];
184
+ };
185
+ /**
186
+ * Change artifact and cache records in one fenced store commit. `mutate`
187
+ * gets the whole draft so it can re-check workers and attempts against the
188
+ * state being written; it may throw to refuse, and nothing is written then.
189
+ * @internal Used by artifacts.ts; other callers must not write artifacts.
190
+ */
191
+ commitArtifacts(mutate: (draft: StoreState, at: {
192
+ epoch: number;
193
+ now: string;
194
+ }) => void): void;
195
+ /** US-009: copies of the deployment ledger. */
196
+ deploymentRecords(): StoredDeployment[];
197
+ /** US-009: copies of the stored company deploy policies. */
198
+ deployPolicyRecords(): StoredDeployPolicy[];
199
+ /**
200
+ * Change the deployment ledger in one fenced store commit. `mutate` gets the
201
+ * whole draft so it can re-check attempts against the state being written;
202
+ * it may throw to refuse, and nothing is written then.
203
+ * @internal Used by effects.ts; other callers must not write deployments.
204
+ */
205
+ commitDeployments(mutate: (draft: StoreState, at: {
206
+ epoch: number;
207
+ now: string;
208
+ }) => void): void;
209
+ /** Release ownership of the store. Idempotent. */
210
+ close(): void;
211
+ private unknownJob;
212
+ }
213
+ /** An attempt claimed by a different worker. Names only the caller and the attemptId it presented. */
214
+ export declare function notClaimant(workerId: string | undefined, attemptId: string): DeliveryStoreError;
215
+ //# sourceMappingURL=reconciler.d.ts.map