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

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 (161) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/bin/hq-auth-refresh.js +2 -1
  3. package/dist/command-catalog.generated.d.ts +442 -50
  4. package/dist/command-catalog.generated.js +541 -50
  5. package/dist/commands/agent-inbox.d.ts +11 -1
  6. package/dist/commands/agent-inbox.js +128 -38
  7. package/dist/commands/agent-kit.js +2 -2
  8. package/dist/commands/agents.d.ts +51 -1
  9. package/dist/commands/agents.js +154 -2
  10. package/dist/commands/bot-jobs.d.ts +2 -15
  11. package/dist/commands/bot-jobs.js +2 -94
  12. package/dist/commands/bot-runtime.d.ts +46 -5
  13. package/dist/commands/bot-runtime.js +228 -18
  14. package/dist/commands/bot.d.ts +16 -9
  15. package/dist/commands/bot.js +169 -51
  16. package/dist/commands/cloud.d.ts +66 -13
  17. package/dist/commands/cloud.js +120 -39
  18. package/dist/commands/company-restore.d.ts +23 -0
  19. package/dist/commands/company-restore.js +128 -0
  20. package/dist/commands/company.js +2 -0
  21. package/dist/commands/core-handoff.js +1 -0
  22. package/dist/commands/core-hq-session-native.js +2 -2
  23. package/dist/commands/core-pin-native.js +1 -1
  24. package/dist/commands/core-policy.js +1 -1
  25. package/dist/commands/core-resolve-company-native.js +1 -1
  26. package/dist/commands/core-sentry-report-fast.d.ts +2 -0
  27. package/dist/commands/core-sentry-report-fast.js +3 -1
  28. package/dist/commands/daemon.js +11 -1
  29. package/dist/commands/integrations-connect.d.ts +17 -4
  30. package/dist/commands/integrations-connect.js +224 -26
  31. package/dist/commands/lanes-link.js +10 -5
  32. package/dist/commands/lanes.js +26 -9
  33. package/dist/commands/rescue.js +13 -0
  34. package/dist/commands/secrets.d.ts +11 -0
  35. package/dist/commands/secrets.js +41 -7
  36. package/dist/commands/sources.js +6 -0
  37. package/dist/commands/storage-offload.d.ts +12 -0
  38. package/dist/commands/storage-offload.js +41 -3
  39. package/dist/commands/sync-mode.js +5 -0
  40. package/dist/commands/whoami.js +4 -0
  41. package/dist/index.js +2 -0
  42. package/dist/lazy-commands.js +2 -0
  43. package/dist/lib/agent-kit/inbox-fetch.d.ts +122 -1
  44. package/dist/lib/agent-kit/inbox-fetch.js +215 -3
  45. package/dist/lib/agent-kit/inbox-redact.js +1 -1
  46. package/dist/lib/agent-kit/inbox-state.d.ts +98 -1
  47. package/dist/lib/agent-kit/inbox-state.js +261 -4
  48. package/dist/lib/agent-kit/mcp/tools.d.ts +3 -3
  49. package/dist/lib/agent-kit/mcp/tools.js +68 -25
  50. package/dist/lib/agent-kit/run/inbox.js +4 -2
  51. package/dist/lib/agent-kit/skills.js +4 -1
  52. package/dist/lib/agent-kit/wake.d.ts +9 -1
  53. package/dist/lib/agent-kit/wake.js +10 -3
  54. package/dist/lib/bot/config.d.ts +1 -0
  55. package/dist/lib/bot/config.js +10 -0
  56. package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
  57. package/dist/lib/bot/eventbridge-cron.js +104 -0
  58. package/dist/lib/bot/fleet-cron.js +193 -14
  59. package/dist/lib/bot/fleet-download.d.ts +2 -0
  60. package/dist/lib/bot/fleet-download.js +23 -0
  61. package/dist/lib/bot/fleet-local.d.ts +34 -1
  62. package/dist/lib/bot/fleet-local.js +254 -37
  63. package/dist/lib/bot/fleet-python.d.ts +3 -0
  64. package/dist/lib/bot/fleet-python.js +34 -4
  65. package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
  66. package/dist/lib/bot/fleet-runtime-sources.js +30 -0
  67. package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
  68. package/dist/lib/bot/legacy-provider-login.js +19 -2
  69. package/dist/lib/bot/prompt.js +1 -1
  70. package/dist/lib/bot/readiness.d.ts +8 -0
  71. package/dist/lib/bot/readiness.js +17 -3
  72. package/dist/lib/bot/runtime-auth.d.ts +30 -0
  73. package/dist/lib/bot/runtime-auth.js +94 -3
  74. package/dist/lib/bot/status.d.ts +2 -0
  75. package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
  76. package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
  77. package/dist/lib/capacity/collectors/grok.d.ts +5 -0
  78. package/dist/lib/capacity/collectors/grok.js +56 -5
  79. package/dist/lib/core-utils/session-id.d.ts +1 -1
  80. package/dist/lib/core-utils/session-id.js +4 -0
  81. package/dist/lib/daemon/catalog.js +11 -1
  82. package/dist/lib/daemon/run.js +9 -1
  83. package/dist/lib/daemon/updater.d.ts +34 -2
  84. package/dist/lib/daemon/updater.js +51 -2
  85. package/dist/lib/db/sqlite-binding.d.ts +1 -0
  86. package/dist/lib/db/sqlite-binding.js +1 -1
  87. package/dist/lib/delivery/artifacts.d.ts +99 -0
  88. package/dist/lib/delivery/artifacts.js +548 -0
  89. package/dist/lib/delivery/backup.d.ts +78 -0
  90. package/dist/lib/delivery/backup.js +343 -0
  91. package/dist/lib/delivery/cache.d.ts +29 -0
  92. package/dist/lib/delivery/cache.js +33 -0
  93. package/dist/lib/delivery/contracts.d.ts +142 -0
  94. package/dist/lib/delivery/contracts.js +289 -0
  95. package/dist/lib/delivery/credentials.d.ts +54 -0
  96. package/dist/lib/delivery/credentials.js +119 -0
  97. package/dist/lib/delivery/enrollment.d.ts +142 -0
  98. package/dist/lib/delivery/enrollment.js +382 -0
  99. package/dist/lib/delivery/identity.d.ts +25 -0
  100. package/dist/lib/delivery/identity.js +82 -0
  101. package/dist/lib/delivery/inbox.d.ts +116 -0
  102. package/dist/lib/delivery/inbox.js +260 -0
  103. package/dist/lib/delivery/migrations.d.ts +139 -0
  104. package/dist/lib/delivery/migrations.js +623 -0
  105. package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
  106. package/dist/lib/delivery/mqtt-adapter.js +242 -0
  107. package/dist/lib/delivery/mqtt.d.ts +61 -0
  108. package/dist/lib/delivery/mqtt.js +112 -0
  109. package/dist/lib/delivery/outbox.d.ts +95 -0
  110. package/dist/lib/delivery/outbox.js +187 -0
  111. package/dist/lib/delivery/provenance.d.ts +129 -0
  112. package/dist/lib/delivery/provenance.js +93 -0
  113. package/dist/lib/delivery/reconciler.d.ts +151 -0
  114. package/dist/lib/delivery/reconciler.js +492 -0
  115. package/dist/lib/delivery/restore.d.ts +35 -0
  116. package/dist/lib/delivery/restore.js +134 -0
  117. package/dist/lib/delivery/store.d.ts +161 -0
  118. package/dist/lib/delivery/store.js +940 -0
  119. package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
  120. package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
  121. package/dist/lib/delivery/workers/macos.d.ts +176 -0
  122. package/dist/lib/delivery/workers/macos.js +901 -0
  123. package/dist/lib/delivery/workers/windows-boundary.d.ts +453 -0
  124. package/dist/lib/delivery/workers/windows-boundary.js +693 -0
  125. package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
  126. package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
  127. package/dist/lib/delivery/workers/windows.d.ts +241 -0
  128. package/dist/lib/delivery/workers/windows.js +608 -0
  129. package/dist/lib/doctor/checks/release-links.d.ts +50 -8
  130. package/dist/lib/doctor/checks/release-links.js +260 -24
  131. package/dist/lib/doctor/fix/apply.js +24 -8
  132. package/dist/lib/doctor/fix/remediation.js +15 -5
  133. package/dist/lib/install/provider-wrappers.d.ts +2 -0
  134. package/dist/lib/install/provider-wrappers.js +68 -3
  135. package/dist/lib/lanes/autopilot-registry.d.ts +14 -0
  136. package/dist/lib/lanes/autopilot-registry.js +59 -7
  137. package/dist/lib/lanes/links.d.ts +14 -0
  138. package/dist/lib/lanes/links.js +320 -25
  139. package/dist/lib/lanes/outpost-pruner-install.d.ts +10 -0
  140. package/dist/lib/lanes/outpost-pruner-install.js +4 -3
  141. package/dist/main.js +3 -1
  142. package/dist/sentry-init.d.ts +2 -0
  143. package/dist/sentry-init.js +13 -2
  144. package/dist/sentry.d.ts +2 -0
  145. package/dist/sentry.js +5 -1
  146. package/dist/utils/cli-network-lifecycle.d.ts +9 -0
  147. package/dist/utils/cli-network-lifecycle.js +52 -0
  148. package/dist/utils/cognito-callback-port.d.ts +14 -0
  149. package/dist/utils/cognito-callback-port.js +24 -0
  150. package/dist/utils/cognito-session.js +3 -3
  151. package/dist/utils/deleted-company-notice.d.ts +59 -0
  152. package/dist/utils/deleted-company-notice.js +156 -0
  153. package/dist/utils/login-browser.d.ts +1 -1
  154. package/dist/utils/login-browser.js +7 -5
  155. package/dist/utils/resident-package-preload.js +30 -15
  156. package/dist/utils/safe-link.d.ts +63 -0
  157. package/dist/utils/safe-link.js +246 -0
  158. package/dist/utils/sentry-keepalive-transport.d.ts +28 -0
  159. package/dist/utils/sentry-keepalive-transport.js +70 -0
  160. package/dist/utils/vault-api.js +7 -0
  161. package/package.json +7 -7
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Portable delivery contracts (US-001).
3
+ *
4
+ * Provider-neutral, versioned records for HQ delivery. Nothing here names a
5
+ * cloud or forge provider; adapters translate these records at the edges.
6
+ */
7
+ export const DELIVERY_SCHEMA_VERSIONS = {
8
+ tenant: "hq-delivery.tenant.v1",
9
+ run: "hq-delivery.run.v1",
10
+ job: "hq-delivery.job.v1",
11
+ attempt: "hq-delivery.attempt.v1",
12
+ lease: "hq-delivery.lease.v1",
13
+ recipe: "hq-delivery.recipe.v1",
14
+ policy: "hq-delivery.policy.v1",
15
+ artifact: "hq-delivery.artifact.v1",
16
+ };
17
+ function isObject(v) {
18
+ return typeof v === "object" && v !== null && !Array.isArray(v);
19
+ }
20
+ function nonEmpty(v) {
21
+ return typeof v === "string" && v.trim().length > 0;
22
+ }
23
+ const RUN_STATUSES = ["queued", "running", "succeeded", "failed", "cancelled"];
24
+ const ATTEMPT_OUTCOMES = ["pending", "passed", "failed"];
25
+ const ISO_TIMESTAMP = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-](\d{2}):(\d{2}))$/;
26
+ function isStringArray(v) {
27
+ return Array.isArray(v) && v.every((s) => typeof s === "string");
28
+ }
29
+ function isKnownKind(v) {
30
+ return typeof v === "string" && Object.prototype.hasOwnProperty.call(DELIVERY_SCHEMA_VERSIONS, v);
31
+ }
32
+ function describeValue(v) {
33
+ return typeof v === "string" ? JSON.stringify(v) : typeof v;
34
+ }
35
+ /**
36
+ * Strict ISO-8601 timestamp. The date must exist on the calendar (2026-02-30
37
+ * is rejected rather than rolled over to March), and hours, minutes, seconds
38
+ * and offsets must be in range.
39
+ */
40
+ function isStrictTimestamp(v) {
41
+ if (typeof v !== "string")
42
+ return false;
43
+ const m = ISO_TIMESTAMP.exec(v);
44
+ if (!m)
45
+ return false;
46
+ const [year, month, day, hour, minute, second] = m.slice(1, 7).map(Number);
47
+ if (hour > 23 || minute > 59 || second > 59)
48
+ return false;
49
+ if (m[9] !== undefined && (Number(m[9]) > 23 || Number(m[10]) > 59))
50
+ return false;
51
+ const date = new Date(Date.UTC(year, month - 1, day));
52
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
53
+ }
54
+ const REQUIRED_FIELDS = {
55
+ tenant: ["displayName"],
56
+ run: ["runId", "recipeId", "status"],
57
+ job: ["jobId", "runId", "name"],
58
+ attempt: ["attemptId", "jobId", "runId"],
59
+ lease: ["leaseId", "runId", "holder", "expiresAt"],
60
+ recipe: ["recipeId"],
61
+ policy: ["policyId"],
62
+ artifact: ["artifactId", "runId"],
63
+ };
64
+ /** Fields present on every record kind. */
65
+ const BASE_FIELDS = ["schemaVersion", "tenantId"];
66
+ /**
67
+ * Every field each kind declares in its contract, besides BASE_FIELDS.
68
+ *
69
+ * Unknown-field policy: reject. validateRecord returns an error for any field
70
+ * that is not declared here, on every record kind, and NESTED_FIELDS applies
71
+ * the same rule to nested objects such as sourcePin. A nested error names the
72
+ * full path ("artifact: unknown field sourcePin.<name>"). isSourcePin rejects
73
+ * undeclared pin fields the same way. The rule is generic: it does not look
74
+ * for particular names, so any undeclared field (provider-specific or not)
75
+ * fails validation instead of riding along in a portable record.
76
+ */
77
+ const DECLARED_FIELDS = {
78
+ tenant: ["displayName"],
79
+ run: ["runId", "recipeId", "status"],
80
+ job: ["jobId", "runId", "name"],
81
+ attempt: ["attemptId", "jobId", "runId", "number", "outcome"],
82
+ lease: ["leaseId", "runId", "holder", "expiresAt"],
83
+ recipe: ["recipeId", "steps"],
84
+ policy: ["policyId", "rules"],
85
+ artifact: ["artifactId", "runId", "sourcePin", "deployedState"],
86
+ };
87
+ const SOURCE_PIN_FIELDS = ["repository", "commitSha", "verifiedOn"];
88
+ /** Timestamp fields per kind; each is checked with isStrictTimestamp. */
89
+ const TIMESTAMP_FIELDS = {
90
+ lease: ["expiresAt"],
91
+ };
92
+ const NESTED_FIELDS = {
93
+ artifact: { sourcePin: { fields: SOURCE_PIN_FIELDS } },
94
+ };
95
+ function undeclaredFields(input, declared) {
96
+ return Object.keys(input).filter((field) => !declared.includes(field));
97
+ }
98
+ /**
99
+ * Dotted paths of every undeclared field in `input`, at every nesting level
100
+ * described by `nested`. A top-level field is reported by name ("notes"); a
101
+ * nested one by its full path ("sourcePin.notes").
102
+ */
103
+ function undeclaredFieldPaths(input, declared, nested = {}, prefix = "") {
104
+ const paths = undeclaredFields(input, declared).map((field) => prefix + field);
105
+ for (const [field, shape] of Object.entries(nested)) {
106
+ const child = input[field];
107
+ if (isObject(child)) {
108
+ paths.push(...undeclaredFieldPaths(child, shape.fields, shape.nested, `${prefix}${field}.`));
109
+ }
110
+ }
111
+ return paths;
112
+ }
113
+ /**
114
+ * Validate one record. Never throws: an unknown kind or a non-object record
115
+ * returns `{ ok: false, errors }`.
116
+ */
117
+ export function validateRecord(kind, input) {
118
+ const errors = [];
119
+ if (!isKnownKind(kind)) {
120
+ return { ok: false, errors: [`unknown kind ${describeValue(kind)}`] };
121
+ }
122
+ if (!isObject(input)) {
123
+ return { ok: false, errors: [`${kind}: record must be an object`] };
124
+ }
125
+ const expected = DELIVERY_SCHEMA_VERSIONS[kind];
126
+ if (input.schemaVersion !== expected) {
127
+ errors.push(`${kind}: unsupported schemaVersion ${JSON.stringify(input.schemaVersion)} (expected ${expected})`);
128
+ }
129
+ if (!nonEmpty(input.tenantId)) {
130
+ errors.push(`${kind}: missing tenant identity`);
131
+ }
132
+ for (const field of REQUIRED_FIELDS[kind]) {
133
+ if (!nonEmpty(input[field]))
134
+ errors.push(`${kind}: missing ${field}`);
135
+ }
136
+ for (const path of undeclaredFieldPaths(input, [...BASE_FIELDS, ...DECLARED_FIELDS[kind]], NESTED_FIELDS[kind])) {
137
+ errors.push(`${kind}: unknown field ${path}`);
138
+ }
139
+ if (kind === "run" && !RUN_STATUSES.includes(input.status)) {
140
+ errors.push(`run: unsupported status ${JSON.stringify(input.status)}`);
141
+ }
142
+ if (kind === "attempt") {
143
+ if (!(Number.isInteger(input.number) && input.number >= 1)) {
144
+ errors.push("attempt: number must be a positive integer");
145
+ }
146
+ if (!ATTEMPT_OUTCOMES.includes(input.outcome)) {
147
+ errors.push(`attempt: unsupported outcome ${JSON.stringify(input.outcome)}`);
148
+ }
149
+ }
150
+ if (kind === "recipe" && !isStringArray(input.steps)) {
151
+ errors.push("recipe: steps must be an array of strings");
152
+ }
153
+ if (kind === "policy" && !isStringArray(input.rules)) {
154
+ errors.push("policy: rules must be an array of strings");
155
+ }
156
+ for (const field of TIMESTAMP_FIELDS[kind] ?? []) {
157
+ if (nonEmpty(input[field]) && !isStrictTimestamp(input[field])) {
158
+ errors.push(`${kind}: ${field} must be an ISO-8601 timestamp`);
159
+ }
160
+ }
161
+ if (kind === "artifact") {
162
+ // Only an absent deployedState defaults to unverified; null is not a declared value.
163
+ const ds = input.deployedState === undefined ? "unverified" : input.deployedState;
164
+ if (ds !== "unverified" && ds !== "verified") {
165
+ errors.push("artifact: deployedState must be unverified or verified");
166
+ }
167
+ if (input.sourcePin !== undefined && !isSourcePin(input.sourcePin)) {
168
+ errors.push("artifact: sourcePin is malformed");
169
+ }
170
+ }
171
+ if (errors.length > 0)
172
+ return { ok: false, errors };
173
+ const value = kind === "artifact" ? { ...input, deployedState: input.deployedState ?? "unverified" } : { ...input };
174
+ return { ok: true, value: value };
175
+ }
176
+ const BUNDLE_CHILD_KINDS = ["job", "attempt", "lease", "recipe", "policy", "artifact"];
177
+ /**
178
+ * Validate a run with its children. Every child must share the run's tenant
179
+ * and run, a recipe child must match the run's recipeId, and run or tenant
180
+ * records are not allowed as children. On success the returned bundle holds
181
+ * the normalized records from validateRecord. Never throws: malformed input
182
+ * returns `{ ok: false, errors }`.
183
+ */
184
+ export function validateBundle(bundle) {
185
+ if (!isObject(bundle))
186
+ return { ok: false, errors: ["bundle: must be an object"] };
187
+ const errors = [];
188
+ const run = validateRecord("run", bundle.run);
189
+ if (!run.ok)
190
+ errors.push(...run.errors);
191
+ const rawChildren = bundle.children;
192
+ if (!Array.isArray(rawChildren)) {
193
+ errors.push("bundle: children must be an array");
194
+ return { ok: false, errors };
195
+ }
196
+ const children = [];
197
+ rawChildren.forEach((child, index) => {
198
+ if (!isObject(child)) {
199
+ errors.push(`bundle: child ${index} must be an object`);
200
+ return;
201
+ }
202
+ const kind = child.kind;
203
+ if (!isKnownKind(kind)) {
204
+ errors.push(`bundle: child ${index} has unknown kind ${describeValue(kind)}`);
205
+ return;
206
+ }
207
+ if (!BUNDLE_CHILD_KINDS.includes(kind)) {
208
+ errors.push(`${kind}: not allowed as a bundle child`);
209
+ return;
210
+ }
211
+ const res = validateRecord(kind, child.record);
212
+ if (!res.ok) {
213
+ errors.push(...res.errors);
214
+ return;
215
+ }
216
+ if (run.ok && res.value.tenantId !== run.value.tenantId) {
217
+ errors.push(`${kind}: tenantId ${res.value.tenantId} does not match run tenant ${run.value.tenantId}`);
218
+ }
219
+ const childRunId = res.value.runId;
220
+ if (run.ok && childRunId !== undefined && childRunId !== run.value.runId) {
221
+ errors.push(`${kind}: runId ${String(childRunId)} does not match run ${run.value.runId}`);
222
+ }
223
+ const childRecipeId = res.value.recipeId;
224
+ if (run.ok && kind === "recipe" && childRecipeId !== run.value.recipeId) {
225
+ errors.push(`recipe: recipeId ${String(childRecipeId)} does not match run recipeId ${run.value.recipeId}`);
226
+ }
227
+ children.push({ kind: kind, record: res.value });
228
+ });
229
+ if (!run.ok || errors.length > 0)
230
+ return { ok: false, errors };
231
+ return { ok: true, value: { run: run.value, children } };
232
+ }
233
+ const FULL_SHA = /^[0-9a-f]{40}$/;
234
+ const REMOTE_REF = /^refs\/(heads|tags)\/[A-Za-z0-9._/-]+$/;
235
+ /**
236
+ * Shape check for an attested remote ref: `refs/heads/<name>` or
237
+ * `refs/tags/<name>`, following git ref-name rules (no empty, dot-leading or
238
+ * `.lock` segments, no `..`, no trailing dot). Placeholders such as
239
+ * "local-only" or a bare branch name fail. This checks the string only; it
240
+ * does not confirm that the ref exists on any remote.
241
+ */
242
+ function isRemoteRefShape(v) {
243
+ if (typeof v !== "string" || !REMOTE_REF.test(v) || v.includes("..") || v.endsWith("."))
244
+ return false;
245
+ return v
246
+ .split("/")
247
+ .slice(2)
248
+ .every((segment) => segment.length > 0 && !segment.startsWith(".") && !segment.endsWith(".lock"));
249
+ }
250
+ /**
251
+ * Shape check for a source pin: non-empty repository, full 40-hex commit SHA,
252
+ * a remote-ref-shaped `verifiedOn`, and no undeclared fields. The pin is the
253
+ * writer's attestation; this check cannot prove provenance.
254
+ */
255
+ export function isSourcePin(v) {
256
+ return (isObject(v) &&
257
+ undeclaredFields(v, SOURCE_PIN_FIELDS).length === 0 &&
258
+ nonEmpty(v.repository) &&
259
+ typeof v.commitSha === "string" &&
260
+ FULL_SHA.test(v.commitSha) &&
261
+ isRemoteRefShape(v.verifiedOn));
262
+ }
263
+ /** Next owner recorded for any blocked entry that does not name a non-empty one. */
264
+ export const UNRESOLVED_NEXT_OWNER = "unresolved; project lead/root to identify";
265
+ export function checkReadiness(entry) {
266
+ // Anything other than an explicit "verified" (absent, null, unknown) reads as unverified.
267
+ const deployedState = entry.deployedState === "verified" ? "verified" : "unverified";
268
+ if (entry.unresolved !== undefined) {
269
+ // An unresolved entry is always blocked; empty metadata is replaced, never passed through.
270
+ const unresolved = isObject(entry.unresolved) ? entry.unresolved : {};
271
+ return {
272
+ id: entry.id,
273
+ status: "blocked",
274
+ reason: nonEmpty(unresolved.reason) ? unresolved.reason : "unresolved entry has no recorded reason",
275
+ nextOwner: nonEmpty(unresolved.nextOwner) ? unresolved.nextOwner : UNRESOLVED_NEXT_OWNER,
276
+ deployedState,
277
+ };
278
+ }
279
+ if (entry.sourcePin && isSourcePin(entry.sourcePin)) {
280
+ return { id: entry.id, status: "ready", sourcePin: entry.sourcePin, deployedState };
281
+ }
282
+ const why = entry.completionFlag
283
+ ? "predecessor completion flag is not a source pin"
284
+ : entry.localCheckout
285
+ ? "unpinned local checkout is not a source pin"
286
+ : "no verified source pin";
287
+ return { id: entry.id, status: "blocked", reason: why, nextOwner: UNRESOLVED_NEXT_OWNER, deployedState };
288
+ }
289
+ //# sourceMappingURL=contracts.js.map
@@ -0,0 +1,54 @@
1
+ import type { Job } from "./contracts.js";
2
+ import { type WorkerTrust } from "./migrations.js";
3
+ export interface CredentialSpec {
4
+ /** The only tenant whose jobs may receive this credential. */
5
+ tenantId: string;
6
+ ref: string;
7
+ /** release credentials go only to release jobs run by release workers. */
8
+ class: "standard" | "release";
9
+ }
10
+ export interface CredentialPolicy {
11
+ credentials: CredentialSpec[];
12
+ /** Job names that are release jobs. Every other job is untrusted. */
13
+ releaseJobNames: string[];
14
+ }
15
+ /** Looks up a credential value by ref. Called only for refs a plan allowed. */
16
+ export interface CredentialSource {
17
+ resolve(ref: string): string;
18
+ }
19
+ export type JobClass = "release" | "untrusted";
20
+ export interface CredentialPlan {
21
+ jobClass: JobClass;
22
+ refs: string[];
23
+ }
24
+ /** Injected credential values. Serializing or inspecting this shows refs only. */
25
+ export interface InjectedCredentials {
26
+ readonly refs: readonly string[];
27
+ has(ref: string): boolean;
28
+ get(ref: string): string;
29
+ }
30
+ /** A job is a release job only when the policy lists its name. */
31
+ export declare function classifyJob(policy: CredentialPolicy | undefined, job: Job): JobClass;
32
+ /**
33
+ * The one release-trust rule, shared by claim and dispatch: a release job may
34
+ * be taken only by a release-trust worker. Returns the job class, or throws
35
+ * PRIVILEGE_REJECTED.
36
+ */
37
+ export declare function assertJobTrust(policy: CredentialPolicy | undefined, job: Job, workerTrust: WorkerTrust): JobClass;
38
+ /**
39
+ * Decide which credentials a dispatch may receive. Throws PRIVILEGE_REJECTED
40
+ * for a release job run by a standard worker, and for any requested ref that
41
+ * is malformed, repeated, undeclared, or beyond the job class or worker trust.
42
+ */
43
+ export declare function planCredentials(policy: CredentialPolicy | undefined, input: {
44
+ job: Job;
45
+ workerTrust: WorkerTrust;
46
+ requested: unknown;
47
+ }): CredentialPlan;
48
+ /**
49
+ * Look up each planned ref once and return the values behind a redacting
50
+ * wrapper. A lookup failure or an empty value is CREDENTIAL_UNAVAILABLE naming
51
+ * the ref only; the source's own error is dropped so it cannot leak a value.
52
+ */
53
+ export declare function injectCredentials(source: CredentialSource, refs: readonly string[]): InjectedCredentials;
54
+ //# sourceMappingURL=credentials.d.ts.map
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Credential boundaries for dispatched jobs (US-004).
3
+ *
4
+ * A credential policy names each credential by tenant, ref and class, and
5
+ * lists the job names that are release jobs. Every other job is untrusted.
6
+ * A credential is granted only to jobs of its own tenant; a credential with
7
+ * no tenant is granted to none. Release job names apply in every tenant the
8
+ * access layer serves, which only adds the release-worker requirement. A dispatch
9
+ * first plans which refs it may receive and rejects, never downgrades, any
10
+ * request beyond the job class or the worker's trust. Only then are values
11
+ * looked up and injected. Values live in a closure and are redacted from
12
+ * JSON, inspect and string output; errors name refs, never values.
13
+ */
14
+ import { inspect } from "node:util";
15
+ import { trustAllows } from "./identity.js";
16
+ import { DeliveryStoreError } from "./migrations.js";
17
+ const REDACTED = "[credentials redacted]";
18
+ function rejected(found, expected, action) {
19
+ return new DeliveryStoreError("PRIVILEGE_REJECTED", {
20
+ found,
21
+ expected,
22
+ action: `${action} No credential was looked up and nothing was written.`,
23
+ });
24
+ }
25
+ function unavailable(ref, found) {
26
+ return new DeliveryStoreError("CREDENTIAL_UNAVAILABLE", {
27
+ found,
28
+ expected: `a non-empty value for credential ${ref}`,
29
+ action: `Check that credential ${ref} is configured in the credential source. Nothing was claimed.`,
30
+ });
31
+ }
32
+ /** A job is a release job only when the policy lists its name. */
33
+ export function classifyJob(policy, job) {
34
+ return policy?.releaseJobNames.includes(job.name) ? "release" : "untrusted";
35
+ }
36
+ /**
37
+ * The one release-trust rule, shared by claim and dispatch: a release job may
38
+ * be taken only by a release-trust worker. Returns the job class, or throws
39
+ * PRIVILEGE_REJECTED.
40
+ */
41
+ export function assertJobTrust(policy, job, workerTrust) {
42
+ const jobClass = classifyJob(policy, job);
43
+ if (jobClass === "release" && !trustAllows(workerTrust, "release")) {
44
+ throw rejected(`a ${workerTrust} worker asked to run release job ${job.jobId}`, "a release worker for a release job", "Give release jobs only to workers enrolled with release trust.");
45
+ }
46
+ return jobClass;
47
+ }
48
+ /**
49
+ * Decide which credentials a dispatch may receive. Throws PRIVILEGE_REJECTED
50
+ * for a release job run by a standard worker, and for any requested ref that
51
+ * is malformed, repeated, undeclared, or beyond the job class or worker trust.
52
+ */
53
+ export function planCredentials(policy, input) {
54
+ const jobClass = assertJobTrust(policy, input.job, input.workerTrust);
55
+ const requested = input.requested;
56
+ if (!Array.isArray(requested) || !requested.every((r) => typeof r === "string" && r !== "")) {
57
+ throw rejected("a credential request that is not a list of refs", "a list of credential refs", "Pass credentials as a list of declared refs.");
58
+ }
59
+ const seen = new Set();
60
+ for (const ref of requested) {
61
+ if (seen.has(ref)) {
62
+ throw rejected(`credential ${ref} requested twice`, "each credential ref once", `Remove the repeated ${ref}.`);
63
+ }
64
+ seen.add(ref);
65
+ // Another tenant's ref is answered exactly like an undeclared one.
66
+ const spec = policy?.credentials.find((c) => c.ref === ref && typeof c.tenantId === "string" && c.tenantId !== "" && c.tenantId === input.job.tenantId);
67
+ if (!spec) {
68
+ throw rejected(`credential ${ref}, which ${policy ? `the credential policy does not declare for tenant ${input.job.tenantId}` : "cannot be granted because no credential policy is configured"}`, "a credential declared in the credential policy for the job's tenant", `Declare ${ref} in the credential policy, or stop requesting it.`);
69
+ }
70
+ if (spec.class === "release" && jobClass !== "release") {
71
+ throw rejected(`release credential ${ref} requested for untrusted job ${input.job.jobId}`, "release credentials only on release jobs", `Ordinary build and test jobs never receive ${ref}; remove it from the request.`);
72
+ }
73
+ if (spec.class === "release" && !trustAllows(input.workerTrust, "release")) {
74
+ throw rejected(`release credential ${ref} requested by a ${input.workerTrust} worker`, "a release worker", `Only workers enrolled with release trust may receive ${ref}.`);
75
+ }
76
+ }
77
+ return { jobClass, refs: [...requested] };
78
+ }
79
+ /**
80
+ * Look up each planned ref once and return the values behind a redacting
81
+ * wrapper. A lookup failure or an empty value is CREDENTIAL_UNAVAILABLE naming
82
+ * the ref only; the source's own error is dropped so it cannot leak a value.
83
+ */
84
+ export function injectCredentials(source, refs) {
85
+ const values = new Map();
86
+ for (const ref of refs) {
87
+ let value;
88
+ try {
89
+ value = source.resolve(ref);
90
+ }
91
+ catch {
92
+ throw unavailable(ref, `the lookup of credential ${ref} failed`);
93
+ }
94
+ if (typeof value !== "string" || value === "")
95
+ throw unavailable(ref, `an empty or non-text value for credential ${ref}`);
96
+ values.set(ref, value);
97
+ }
98
+ const list = Object.freeze([...values.keys()]);
99
+ const describe = () => `${REDACTED}: ${list.join(", ")}`;
100
+ return Object.freeze({
101
+ refs: list,
102
+ has: (ref) => values.has(ref),
103
+ get: (ref) => {
104
+ const v = values.get(ref);
105
+ if (v === undefined) {
106
+ throw new DeliveryStoreError("CREDENTIAL_UNAVAILABLE", {
107
+ found: `credential ${ref}, which was not injected into this dispatch`,
108
+ expected: `one of: ${list.join(", ") || "no credentials"}`,
109
+ action: "Request the credential at dispatch, within the job's class and the worker's trust.",
110
+ });
111
+ }
112
+ return v;
113
+ },
114
+ toJSON: () => ({ refs: [...list], values: REDACTED }),
115
+ toString: describe,
116
+ [inspect.custom]: describe,
117
+ });
118
+ }
119
+ //# sourceMappingURL=credentials.js.map
@@ -0,0 +1,142 @@
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 type { Run } from "./contracts.js";
16
+ import { type CredentialPolicy, type CredentialSource, type InjectedCredentials, type JobClass } from "./credentials.js";
17
+ import { type WorkerIdentity } from "./identity.js";
18
+ import { type WorkerCapability, type WorkerStatus, type WorkerTrust } from "./migrations.js";
19
+ import { type LedgerEvent } from "./outbox.js";
20
+ import { type AttemptView, type ClaimResult, type ControllerOptions, type DeliveryController, type JobView } from "./reconciler.js";
21
+ export type AccessOptions = ControllerOptions & {
22
+ credentialPolicy?: CredentialPolicy;
23
+ credentialSource?: CredentialSource;
24
+ };
25
+ /** What an admin may manage: these tenants, up to this trust. */
26
+ export interface AdminScope {
27
+ tenantIds: string[];
28
+ maxTrust: WorkerTrust;
29
+ }
30
+ export interface EnrollmentRequest {
31
+ tenantId: string;
32
+ workerId: string;
33
+ capabilities: WorkerCapability[];
34
+ trust: WorkerTrust;
35
+ }
36
+ export interface IssuedEnrollment extends EnrollmentRequest {
37
+ /** One-time secret the worker presents to enroll. Only its digest is stored. */
38
+ ticket: string;
39
+ }
40
+ export interface WorkerView {
41
+ workerId: string;
42
+ tenantId: string;
43
+ capabilities: WorkerCapability[];
44
+ trust: WorkerTrust;
45
+ status: WorkerStatus;
46
+ issuedAt: string;
47
+ enrolledAt: string | null;
48
+ revokedAt: string | null;
49
+ }
50
+ /** One page of a tenant's ready work, for bounded reconciliation (US-005). */
51
+ export interface ReadyPage {
52
+ /** Ready jobIds after the cursor, in ledger order. */
53
+ jobs: string[];
54
+ /** The last jobId returned when the page is full, else null (the scan reached the end). */
55
+ cursor: string | null;
56
+ }
57
+ export declare const MAX_READY_PAGE = 1000;
58
+ export interface Dispatch {
59
+ claim: ClaimResult;
60
+ jobClass: JobClass;
61
+ credentials: InjectedCredentials;
62
+ }
63
+ /** Open a store directory as its controller, with the worker access layer on top. */
64
+ export declare function openDeliveryAccess(opts: AccessOptions): DeliveryAccess;
65
+ export declare class DeliveryAccess {
66
+ /** The underlying controller, for accepting runs and admin reads. Worker operations go through this class. */
67
+ readonly controller: DeliveryController;
68
+ private readonly policy;
69
+ private readonly source;
70
+ constructor(controller: DeliveryController, policy?: CredentialPolicy, source?: CredentialSource);
71
+ /** Issue a one-time enrollment ticket. The worker is pending until it enrolls. */
72
+ issueEnrollment(scope: AdminScope, request: EnrollmentRequest): IssuedEnrollment;
73
+ /**
74
+ * Redeem a ticket for a worker token. The request must name the ticket's
75
+ * company and stay within its capabilities and trust.
76
+ */
77
+ enroll(input: EnrollmentRequest & {
78
+ ticket: string;
79
+ }): WorkerIdentity;
80
+ /** Revoke a worker. It can no longer claim, read or report. Revoking twice is a no-op. */
81
+ revoke(scope: AdminScope, workerId: string): WorkerView;
82
+ /** Workers in the admin's scope, without secret digests. */
83
+ workers(scope: AdminScope): WorkerView[];
84
+ /** Read a run of the worker's own company and its jobs. Needs "read". */
85
+ readRun(identity: WorkerIdentity, runId: string): {
86
+ run: Run;
87
+ jobs: JobView[];
88
+ };
89
+ /** Claim a ready job of the worker's own company. Needs "claim". */
90
+ claim(identity: WorkerIdentity, jobId: string): ClaimResult;
91
+ /** Report the outcome of an attempt of the worker's own company. Needs "report". */
92
+ recordOutcome(identity: WorkerIdentity, attemptId: string, outcome: "passed" | "failed"): AttemptView;
93
+ /** US-007: return an open attempt of the worker's own company unfinished, so its job can be claimed again. Needs "report". */
94
+ returnAttempt(identity: WorkerIdentity, attemptId: string): AttemptView;
95
+ /**
96
+ * Claim a job and inject the credentials it may have. The request is planned
97
+ * first, so a rejected request looks nothing up; credentials are injected
98
+ * before the claim, so a lookup failure claims nothing.
99
+ */
100
+ dispatch(identity: WorkerIdentity, jobId: string, request: {
101
+ credentials: string[];
102
+ }): Dispatch;
103
+ /** The company of an authenticated worker. Needs "claim". */
104
+ workerTenant(identity: WorkerIdentity): string;
105
+ /**
106
+ * Ready jobs of the worker's own company after `after`, in ledger order, at
107
+ * most `limit`. An unknown cursor starts from the beginning. Needs "claim".
108
+ * Read only: it claims nothing and never removes a job.
109
+ */
110
+ readyWork(identity: WorkerIdentity, page: {
111
+ after: string | null;
112
+ limit: number;
113
+ }): ReadyPage;
114
+ /**
115
+ * Check a notification against the committed ledger and return the jobs it
116
+ * may have made ready. A notification is a hint: it is accepted only when
117
+ * the ledger derives an event with the same id and the same values in every
118
+ * field, for the worker's own company. Needs "claim". Claims nothing.
119
+ *
120
+ * Another company's event is ACCESS_DENIED naming only the worker's company.
121
+ * Anything else that does not match is NOTIFICATION_UNVERIFIED, and the
122
+ * message does not repeat the presented ids.
123
+ */
124
+ verifyNotification(identity: WorkerIdentity, event: LedgerEvent): string[];
125
+ /** Release ownership of the store. Idempotent. */
126
+ close(): void;
127
+ private prepareClaim;
128
+ /**
129
+ * Worker records, only while this handle owns the store. A superseded or
130
+ * closed handle still holds its last state in memory, which may list a
131
+ * worker the current owner has revoked; it must not authenticate or serve
132
+ * anything from that state (FENCED or STORE_CLOSED, read only).
133
+ */
134
+ private ownedRecords;
135
+ /** Re-authenticates against the state being committed, so a revocation in flight wins. */
136
+ private guard;
137
+ /** Re-authenticates for "report" and re-checks, inside the commit, that the caller claimed the attempt. */
138
+ private attemptGuard;
139
+ /** Deny work of another company. The message names the worker and its own company only. */
140
+ private sameTenant;
141
+ }
142
+ //# sourceMappingURL=enrollment.d.ts.map