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

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 (241) hide show
  1. package/CHANGELOG.md +206 -1
  2. package/README.md +45 -0
  3. package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
  4. package/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
  5. package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
  6. package/dist/command-catalog.generated.d.ts +105 -10
  7. package/dist/command-catalog.generated.js +127 -10
  8. package/dist/command-help.js +3 -1
  9. package/dist/command-registration-plan.d.ts +6 -0
  10. package/dist/command-registration-plan.js +1 -0
  11. package/dist/commands/auth.d.ts +1 -1
  12. package/dist/commands/auth.js +11 -52
  13. package/dist/commands/bot.js +75 -10
  14. package/dist/commands/capacity.d.ts +4 -1
  15. package/dist/commands/capacity.js +46 -10
  16. package/dist/commands/cloud-demote.d.ts +19 -4
  17. package/dist/commands/cloud-demote.js +85 -12
  18. package/dist/commands/cloud-provision.d.ts +5 -1
  19. package/dist/commands/cloud-provision.js +6 -2
  20. package/dist/commands/cloud.d.ts +36 -0
  21. package/dist/commands/cloud.js +110 -27
  22. package/dist/commands/core-delegate-w1b.js +15 -1
  23. package/dist/commands/core-policy.js +67 -8
  24. package/dist/commands/core.js +1 -0
  25. package/dist/commands/daemon.js +9 -1
  26. package/dist/commands/dm.js +7 -0
  27. package/dist/commands/doctor-usage.d.ts +8 -0
  28. package/dist/commands/doctor-usage.js +20 -0
  29. package/dist/commands/doctor.js +7 -1
  30. package/dist/commands/env.d.ts +18 -0
  31. package/dist/commands/env.js +82 -0
  32. package/dist/commands/files-browse.d.ts +11 -4
  33. package/dist/commands/files-browse.js +21 -4
  34. package/dist/commands/files.d.ts +1 -1
  35. package/dist/commands/files.js +25 -11
  36. package/dist/commands/install-global.js +2 -2
  37. package/dist/commands/integrations-auth-rules.d.ts +27 -0
  38. package/dist/commands/integrations-auth-rules.js +79 -0
  39. package/dist/commands/integrations-import.js +124 -12
  40. package/dist/commands/lanes.js +102 -26
  41. package/dist/commands/logout.d.ts +7 -0
  42. package/dist/commands/logout.js +41 -34
  43. package/dist/commands/mesh.d.ts +2 -0
  44. package/dist/commands/mesh.js +60 -35
  45. package/dist/commands/sources.d.ts +8 -2
  46. package/dist/commands/sources.js +65 -9
  47. package/dist/commands/sync-held.js +5 -2
  48. package/dist/commands/whoami.js +26 -1
  49. package/dist/data/command-states.json +15 -0
  50. package/dist/index.js +52 -4
  51. package/dist/lazy-commands.js +5 -6
  52. package/dist/lib/anywhere-person-setting.d.ts +2 -0
  53. package/dist/lib/anywhere-person-setting.js +6 -3
  54. package/dist/lib/billing/usage-card.d.ts +25 -4
  55. package/dist/lib/billing/usage-card.js +76 -9
  56. package/dist/lib/billing/usage-cost.d.ts +3 -3
  57. package/dist/lib/billing/usage-cost.js +35 -13
  58. package/dist/lib/billing/usage-only.js +4 -2
  59. package/dist/lib/billing/usage-rate-card.d.ts +2 -2
  60. package/dist/lib/billing/usage-rate-card.js +3 -0
  61. package/dist/lib/bot/fleet-cron.d.ts +8 -0
  62. package/dist/lib/bot/fleet-cron.js +126 -7
  63. package/dist/lib/bot/fleet-daemon.d.ts +46 -0
  64. package/dist/lib/bot/fleet-daemon.js +99 -1
  65. package/dist/lib/bot/inflight.d.ts +9 -0
  66. package/dist/lib/bot/inflight.js +10 -0
  67. package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
  68. package/dist/lib/bot/probe.js +7 -1
  69. package/dist/lib/bot/run.js +20 -1
  70. package/dist/lib/bot/runtime/codex.js +1 -1
  71. package/dist/lib/bot/runtime/grok-acp.d.ts +6 -1
  72. package/dist/lib/bot/runtime/grok-acp.js +32 -14
  73. package/dist/lib/bot/runtime/grok.js +1 -1
  74. package/dist/lib/bot/runtime/index.js +19 -9
  75. package/dist/lib/bot/runtime/messages-stream.js +2 -2
  76. package/dist/lib/bot/runtime/types.d.ts +15 -0
  77. package/dist/lib/bot/runtime/types.js +9 -0
  78. package/dist/lib/bot/runtime-failure.d.ts +23 -0
  79. package/dist/lib/bot/runtime-failure.js +43 -1
  80. package/dist/lib/capacity/accounts.d.ts +8 -0
  81. package/dist/lib/capacity/accounts.js +19 -0
  82. package/dist/lib/capacity/available.d.ts +154 -0
  83. package/dist/lib/capacity/available.js +905 -0
  84. package/dist/lib/capacity/codex-availability.d.ts +14 -1
  85. package/dist/lib/capacity/codex-availability.js +26 -1
  86. package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
  87. package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
  88. package/dist/lib/capacity/collectors/codex.js +10 -7
  89. package/dist/lib/capacity/ledger.d.ts +37 -1
  90. package/dist/lib/capacity/ledger.js +207 -30
  91. package/dist/lib/capacity/project.d.ts +26 -0
  92. package/dist/lib/capacity/project.js +137 -8
  93. package/dist/lib/capacity/refusal-rows.d.ts +31 -0
  94. package/dist/lib/capacity/refusal-rows.js +61 -0
  95. package/dist/lib/capacity/refusal.d.ts +53 -2
  96. package/dist/lib/capacity/refusal.js +284 -65
  97. package/dist/lib/capacity/route.js +46 -11
  98. package/dist/lib/capacity/widget.d.ts +12 -1
  99. package/dist/lib/capacity/widget.js +91 -3
  100. package/dist/lib/daemon/flag-monitor.d.ts +8 -0
  101. package/dist/lib/daemon/flag-monitor.js +17 -6
  102. package/dist/lib/daemon/flag.d.ts +65 -1
  103. package/dist/lib/daemon/flag.js +190 -40
  104. package/dist/lib/daemon/ops/policy.js +62 -5
  105. package/dist/lib/daemon/paths.d.ts +72 -2
  106. package/dist/lib/daemon/paths.js +154 -3
  107. package/dist/lib/daemon/resolver.d.ts +2 -0
  108. package/dist/lib/daemon/resolver.js +3 -0
  109. package/dist/lib/daemon/run.d.ts +9 -0
  110. package/dist/lib/daemon/run.js +79 -21
  111. package/dist/lib/daemon/selfcheck.d.ts +22 -0
  112. package/dist/lib/daemon/selfcheck.js +40 -1
  113. package/dist/lib/daemon/server.d.ts +5 -1
  114. package/dist/lib/daemon/server.js +17 -23
  115. package/dist/lib/daemon/state-file-switch.d.ts +57 -0
  116. package/dist/lib/daemon/state-file-switch.js +88 -0
  117. package/dist/lib/daemon/state-file.d.ts +198 -0
  118. package/dist/lib/daemon/state-file.js +419 -0
  119. package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
  120. package/dist/lib/daemon/tcc-eperm.js +310 -0
  121. package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
  122. package/dist/lib/daemon/timed-flag-monitors.js +75 -0
  123. package/dist/lib/delivery/admission.d.ts +86 -0
  124. package/dist/lib/delivery/admission.js +148 -0
  125. package/dist/lib/delivery/artifacts.d.ts +7 -1
  126. package/dist/lib/delivery/artifacts.js +29 -10
  127. package/dist/lib/delivery/attempt-id.d.ts +13 -0
  128. package/dist/lib/delivery/attempt-id.js +16 -0
  129. package/dist/lib/delivery/disposable-target.d.ts +42 -0
  130. package/dist/lib/delivery/disposable-target.js +111 -0
  131. package/dist/lib/delivery/effects.d.ts +136 -0
  132. package/dist/lib/delivery/effects.js +541 -0
  133. package/dist/lib/delivery/enrollment.d.ts +21 -17
  134. package/dist/lib/delivery/enrollment.js +83 -5
  135. package/dist/lib/delivery/escalations.d.ts +51 -0
  136. package/dist/lib/delivery/escalations.js +60 -0
  137. package/dist/lib/delivery/lease.d.ts +80 -0
  138. package/dist/lib/delivery/lease.js +134 -0
  139. package/dist/lib/delivery/migrations.d.ts +120 -4
  140. package/dist/lib/delivery/migrations.js +215 -15
  141. package/dist/lib/delivery/mqtt.d.ts +2 -0
  142. package/dist/lib/delivery/mqtt.js +7 -0
  143. package/dist/lib/delivery/reconciler.d.ts +65 -1
  144. package/dist/lib/delivery/reconciler.js +224 -13
  145. package/dist/lib/delivery/rpc/client.d.ts +22 -0
  146. package/dist/lib/delivery/rpc/client.js +159 -0
  147. package/dist/lib/delivery/rpc/port.d.ts +40 -0
  148. package/dist/lib/delivery/rpc/port.js +16 -0
  149. package/dist/lib/delivery/rpc/server.d.ts +30 -0
  150. package/dist/lib/delivery/rpc/server.js +205 -0
  151. package/dist/lib/delivery/rpc/wire.d.ts +85 -0
  152. package/dist/lib/delivery/rpc/wire.js +143 -0
  153. package/dist/lib/delivery/store.d.ts +2 -0
  154. package/dist/lib/delivery/store.js +4 -0
  155. package/dist/lib/delivery/windows-service-install.d.ts +262 -0
  156. package/dist/lib/delivery/windows-service-install.js +892 -0
  157. package/dist/lib/delivery/workers/macos.d.ts +16 -1
  158. package/dist/lib/delivery/workers/macos.js +54 -12
  159. package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
  160. package/dist/lib/delivery/workers/windows-service-live.js +711 -0
  161. package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
  162. package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
  163. package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
  164. package/dist/lib/delivery/workers/windows-service.js +584 -0
  165. package/dist/lib/delivery/workers/windows.d.ts +32 -22
  166. package/dist/lib/delivery/workers/windows.js +50 -64
  167. package/dist/lib/doctor/checks/host-core.d.ts +50 -0
  168. package/dist/lib/doctor/checks/host-core.js +269 -0
  169. package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
  170. package/dist/lib/doctor/checks/replay-recorder.js +261 -0
  171. package/dist/lib/doctor/registry.js +4 -0
  172. package/dist/lib/environment/profile.d.ts +239 -0
  173. package/dist/lib/environment/profile.js +251 -0
  174. package/dist/lib/hook-engine/reconcile.js +39 -13
  175. package/dist/lib/hook-engine/registration.d.ts +9 -0
  176. package/dist/lib/hook-engine/registration.js +19 -0
  177. package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
  178. package/dist/lib/hot-channels/adapters/meetings.js +36 -3
  179. package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
  180. package/dist/lib/hot-channels/adapters/slack.js +64 -21
  181. package/dist/lib/hot-channels/alert.d.ts +2 -0
  182. package/dist/lib/hot-channels/alert.js +8 -1
  183. package/dist/lib/hot-channels/contract.d.ts +12 -0
  184. package/dist/lib/hot-channels/contract.js +7 -0
  185. package/dist/lib/hot-channels/loop.js +1 -0
  186. package/dist/lib/hot-channels/run.d.ts +6 -0
  187. package/dist/lib/hot-channels/run.js +4 -0
  188. package/dist/lib/hot-channels/signals-pass.d.ts +74 -1
  189. package/dist/lib/hot-channels/signals-pass.js +82 -41
  190. package/dist/lib/hot-channels/signals-redo.js +10 -2
  191. package/dist/lib/install/claude-targets.d.ts +12 -1
  192. package/dist/lib/install/claude-targets.js +57 -5
  193. package/dist/lib/install/codex-targets.d.ts +2 -2
  194. package/dist/lib/install/codex-targets.js +36 -6
  195. package/dist/lib/install/hook-target.d.ts +3 -0
  196. package/dist/lib/install/hook-target.js +11 -0
  197. package/dist/lib/lanes/canonical-host.d.ts +35 -0
  198. package/dist/lib/lanes/canonical-host.js +65 -0
  199. package/dist/lib/lanes/host-capacity.d.ts +30 -0
  200. package/dist/lib/lanes/host-capacity.js +29 -3
  201. package/dist/lib/lanes/watcher.js +35 -0
  202. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  203. package/dist/lib/mesh/live/daemon/run.js +5 -2
  204. package/dist/lib/mesh/live/flush.d.ts +5 -1
  205. package/dist/lib/mesh/live/flush.js +12 -6
  206. package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
  207. package/dist/lib/mesh/live/reporting-privacy.js +56 -1
  208. package/dist/lib/mesh/live/spool.d.ts +7 -0
  209. package/dist/lib/mesh/live/spool.js +25 -0
  210. package/dist/lib/person-setting-cache.d.ts +38 -0
  211. package/dist/lib/person-setting-cache.js +98 -0
  212. package/dist/lib/safe-store.d.ts +245 -0
  213. package/dist/lib/safe-store.js +777 -0
  214. package/dist/lib/signals/engine.d.ts +29 -2
  215. package/dist/lib/signals/engine.js +103 -4
  216. package/dist/lib/signals/reply.js +73 -18
  217. package/dist/lib/signals/steps/adapters.js +7 -2
  218. package/dist/lib/signals/steps/extract.d.ts +13 -0
  219. package/dist/lib/signals/steps/extract.js +122 -6
  220. package/dist/main.js +46 -3
  221. package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
  222. package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
  223. package/dist/utils/auth-expiry.d.ts +8 -0
  224. package/dist/utils/auth-expiry.js +53 -0
  225. package/dist/utils/catalog-runtime-paths.d.ts +34 -0
  226. package/dist/utils/catalog-runtime-paths.js +53 -0
  227. package/dist/utils/cli-telemetry.d.ts +21 -0
  228. package/dist/utils/cli-telemetry.js +34 -0
  229. package/dist/utils/command-usage.d.ts +275 -0
  230. package/dist/utils/command-usage.js +797 -0
  231. package/dist/utils/files-browse-acl.js +1 -1
  232. package/dist/utils/hook-trust.d.ts +7 -0
  233. package/dist/utils/hook-trust.js +31 -4
  234. package/dist/utils/host-registration.d.ts +126 -0
  235. package/dist/utils/host-registration.js +378 -0
  236. package/dist/utils/resident-package-preload.js +2 -0
  237. package/package.json +10 -8
  238. package/scripts/bench-core.mjs +1096 -0
  239. package/scripts/check-function-manifest.mjs +702 -0
  240. package/dist/lib/delivery/workers/windows-boundary.d.ts +0 -453
  241. package/dist/lib/delivery/workers/windows-boundary.js +0 -693
@@ -0,0 +1,148 @@
1
+ import { DeliveryStoreError } from "./migrations.js";
2
+ import { canonicalJson, sha256Hex } from "./provenance.js";
3
+ /** A request carries no policy: the policy is loaded from the store, where only an authenticated company admin writes it. */
4
+ const REQUEST_KEYS = ["artifactId", "attemptId", "digest", "environment"];
5
+ const HEX64 = /^[0-9a-f]{64}$/;
6
+ const isText = (v) => typeof v === "string" && v.trim() !== "";
7
+ /** Shape check of a policy an admin is about to store. Returns the problem, or null. */
8
+ export function deployPolicyProblem(p) {
9
+ return policyProblem(p);
10
+ }
11
+ /** Refuse a malformed request before anything is recorded. */
12
+ export function checkRequest(input) {
13
+ const r = input;
14
+ const keys = typeof input === "object" && input !== null ? Object.keys(input).sort().join(",") : "";
15
+ if (keys !== REQUEST_KEYS.join(",")) {
16
+ throw new DeliveryStoreError("INVALID_RECORD", {
17
+ found: `a deploy request with fields [${keys}]`,
18
+ expected: `exactly [${REQUEST_KEYS.join(",")}]; there is no override or bypass field`,
19
+ action: "Send the exact artifact, environment and policy. Nothing was recorded or deployed.",
20
+ });
21
+ }
22
+ for (const k of ["attemptId", "artifactId", "environment"]) {
23
+ if (!isText(r[k])) {
24
+ throw new DeliveryStoreError("INVALID_RECORD", { found: `${k} ${JSON.stringify(r[k])}`, expected: `a non-empty ${k}`, action: "Fix the request. Nothing was recorded or deployed." });
25
+ }
26
+ }
27
+ if (typeof r.digest !== "string" || !HEX64.test(r.digest)) {
28
+ throw new DeliveryStoreError("INVALID_RECORD", {
29
+ found: `digest ${JSON.stringify(r.digest)}`,
30
+ expected: "the sha256 hex digest of the exact artifact",
31
+ action: "Name the exact artifact digest. Nothing was recorded or deployed.",
32
+ });
33
+ }
34
+ return r;
35
+ }
36
+ function policyProblem(p) {
37
+ if (typeof p !== "object" || p === null)
38
+ return "no policy object";
39
+ const policy = p;
40
+ if (!isText(policy.policyId) || !isText(policy.tenantId))
41
+ return "policy without policyId or tenantId";
42
+ if (!Number.isInteger(policy.version) || policy.version < 1)
43
+ return "policy without a positive integer version";
44
+ if (typeof policy.environments !== "object" || policy.environments === null)
45
+ return "policy without environments";
46
+ for (const [name, env] of Object.entries(policy.environments)) {
47
+ const e = env;
48
+ if (typeof e !== "object" || e === null || typeof e.approved !== "boolean" || !isText(e.targetId) || !Array.isArray(e.allowedRepositories) || !e.allowedRepositories.every(isText)) {
49
+ return `environment ${name} is not { approved, targetId, allowedRepositories }`;
50
+ }
51
+ }
52
+ return null;
53
+ }
54
+ function digestOf(v) {
55
+ try {
56
+ return sha256Hex(canonicalJson(v));
57
+ }
58
+ catch {
59
+ return null;
60
+ }
61
+ }
62
+ /** Decide one request. Pure apart from the verified artifact read. */
63
+ export function admit(input) {
64
+ const { request: r, worker } = input;
65
+ const tenantId = worker.tenantId;
66
+ const stored = input.storedPolicy;
67
+ const problem = stored ? policyProblem(stored.policy) : null;
68
+ const usable = stored !== null && problem === null && input.policyVerified && stored.policy.tenantId === tenantId;
69
+ const pol = stored?.policy;
70
+ const snapshot = {
71
+ policy: usable ? structuredClone(pol) : null,
72
+ policyDigest: stored ? digestOf(stored.policy) : null,
73
+ policyTenantId: stored ? stored.tenantId : null,
74
+ policySetBy: stored ? stored.setBy : null,
75
+ policySignature: stored ? stored.signature.value : null,
76
+ artifact: { artifactId: r.artifactId, digest: null, partition: null, promoted: false, promotedAt: null, repository: null, commitSha: null, builder: null, provenanceSignature: null },
77
+ context: {
78
+ tenantId,
79
+ environment: r.environment,
80
+ workerId: worker.workerId,
81
+ attemptId: r.attemptId,
82
+ targetId: null,
83
+ requestedDigest: r.digest,
84
+ controllerEpoch: input.controllerEpoch,
85
+ requestedAt: input.now,
86
+ },
87
+ };
88
+ const block = (code, found) => ({ ok: false, snapshot, code, found });
89
+ if (stored === null)
90
+ return block("POLICY_MISSING", `no deploy policy has been set for ${tenantId} by its admin`);
91
+ if (!input.policyVerified || stored.tenantId !== tenantId)
92
+ return block("POLICY_TAMPERED", `the stored deploy policy of ${tenantId} does not match its admin signature`);
93
+ if (problem !== null)
94
+ return block("POLICY_INVALID", problem);
95
+ if (!usable)
96
+ return block("POLICY_TAMPERED", `the stored deploy policy of ${tenantId} names another company`);
97
+ const env = Object.prototype.hasOwnProperty.call(pol.environments, r.environment) ? pol.environments[r.environment] : undefined;
98
+ if (!env)
99
+ return block("ENVIRONMENT_UNLISTED", `policy ${pol.policyId} v${pol.version} does not list environment ${r.environment}`);
100
+ snapshot.context.targetId = env.targetId;
101
+ if (env.approved !== true)
102
+ return block("ENVIRONMENT_UNAPPROVED", `policy ${pol.policyId} v${pol.version} does not approve environment ${r.environment}`);
103
+ if (env.targetId !== input.targetId)
104
+ return block("TARGET_MISMATCH", `environment ${r.environment} deploys to ${env.targetId}, this deployer targets ${input.targetId}`);
105
+ const a = input.attempt;
106
+ if (!a || a.attempt.tenantId !== tenantId || a.resolution !== "open" || a.claimedBy !== worker.workerId || a.claimedEpoch !== input.controllerEpoch) {
107
+ const state = a ? `${a.resolution}, claimed by ${String(a.claimedBy)} at epoch ${a.claimedEpoch}` : "missing";
108
+ return block("ATTEMPT_NOT_CURRENT", `deploy attempt ${r.attemptId} is ${state}; current epoch ${input.controllerEpoch}`);
109
+ }
110
+ let read;
111
+ try {
112
+ read = input.artifacts.read(input.identity, r.artifactId);
113
+ }
114
+ catch (err) {
115
+ if (!(err instanceof DeliveryStoreError))
116
+ throw err;
117
+ if (err.code === "ACCESS_DENIED")
118
+ return block("ARTIFACT_OTHER_TENANT", `artifact ${r.artifactId} is not an artifact of ${tenantId}`);
119
+ if (err.code === "ARTIFACT_UNKNOWN")
120
+ return block("ARTIFACT_UNKNOWN", `no artifact ${r.artifactId}`);
121
+ if (err.code === "ARTIFACT_TAMPERED")
122
+ return block("ARTIFACT_UNTRUSTED", `verified read failed: ${err.message}`);
123
+ throw err;
124
+ }
125
+ const p = read.provenance;
126
+ Object.assign(snapshot.artifact, {
127
+ digest: p.digest.value,
128
+ partition: p.partition,
129
+ promoted: read.promotedAt !== null,
130
+ promotedAt: read.promotedAt,
131
+ repository: p.source.repository,
132
+ commitSha: p.source.commitSha,
133
+ builder: `${p.builder.workerId}:${p.builder.trust}`,
134
+ provenanceSignature: read.provenanceSignature,
135
+ });
136
+ if (p.digest.value !== r.digest)
137
+ return block("ARTIFACT_CHANGED", `artifact ${r.artifactId} has sha256 ${p.digest.value}, the request names ${r.digest}`);
138
+ if (p.partition !== "release" || p.builder.trust !== "release") {
139
+ return block("ARTIFACT_UNTRUSTED", `artifact ${r.artifactId} was built by ${p.builder.trust} worker ${p.builder.workerId} into the ${p.partition} partition`);
140
+ }
141
+ if (read.promotedAt === null)
142
+ return block("ARTIFACT_UNPROMOTED", `artifact ${r.artifactId} is not promoted`);
143
+ if (!env.allowedRepositories.includes(p.source.repository)) {
144
+ return block("SOURCE_NOT_ALLOWED", `environment ${r.environment} does not allow source ${p.source.repository}`);
145
+ }
146
+ return { ok: true, snapshot, bytes: read.bytes, provenance: p };
147
+ }
148
+ //# sourceMappingURL=admission.js.map
@@ -54,12 +54,18 @@ export declare class ArtifactStore {
54
54
  private readonly dir;
55
55
  private readonly signing;
56
56
  constructor(opts: ArtifactStoreOptions);
57
- /** Store bytes built by `identity` during an open attempt of its own company. Needs "report". */
57
+ /**
58
+ * Store bytes built by `identity` during an open attempt of its own company. Needs "report".
59
+ * Expired claim leases are swept first, and the commit checks the lease again, so a holder
60
+ * whose lease has run out is refused with ATTEMPT_ABANDONED and the cache is not touched.
61
+ */
58
62
  put(identity: WorkerIdentity, input: PutInput): ArtifactView;
59
63
  /** Verified bytes of an artifact of the worker's own company. Needs "read". */
60
64
  read(identity: WorkerIdentity, artifactId: string): {
61
65
  bytes: Buffer;
62
66
  provenance: ArtifactProvenance;
67
+ promotedAt: string | null;
68
+ provenanceSignature: string;
63
69
  };
64
70
  /** Re-check the signature and blob of an artifact in scope. Throws ARTIFACT_TAMPERED. */
65
71
  verify(scope: AdminScope, artifactId: string): ArtifactView;
@@ -10,7 +10,7 @@
10
10
  * Write: bytes go to a fresh temp file in the blob directory (exclusive
11
11
  * create, fsync), are read back and re-hashed, made read-only, then linked to
12
12
  * the digest name, which never overwrites an existing file, and the directory
13
- * is fsynced. An existing blob with that name is re-hashed and reused only
13
+ * is fsynced (except on Windows, which cannot fsync a directory). An existing blob with that name is re-hashed and reused only
14
14
  * when it matches. A crash leaves at most a temp file or an unreferenced
15
15
  * blob, never a referenced blob with other bytes.
16
16
  *
@@ -48,10 +48,12 @@
48
48
  import { randomUUID } from "node:crypto";
49
49
  import { closeSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, chmodSync, unlinkSync, writeSync, } from "node:fs";
50
50
  import { join, relative, sep } from "node:path";
51
+ import { fsyncDirectory } from "../../utils/fsync-directory.js";
51
52
  import { evictArtifact, findCacheEntry, recordCacheEntry } from "./cache.js";
52
53
  import { DELIVERY_SCHEMA_VERSIONS, isSourcePin } from "./contracts.js";
53
54
  import { authenticate, trustAllows } from "./identity.js";
54
55
  import { DeliveryStoreError } from "./migrations.js";
56
+ import { leaseExpired } from "./reconciler.js";
55
57
  import { PROVENANCE_SCHEMA_VERSION, cacheKey, cacheSlot, envDigest, inputDigest, partitionFor, sha256Hex, promotionMatches, signPromotion, signProvenance, signatureMatches, } from "./provenance.js";
56
58
  export const ARTIFACTS_DIR = "artifacts";
57
59
  /** Config path of the production provenance signing-key credential ref. */
@@ -123,6 +125,17 @@ function checkInputs(inputs) {
123
125
  throw invalid("a malformed env", "a map of env key to string value");
124
126
  }
125
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
+ }
126
139
  export class ArtifactStore {
127
140
  access;
128
141
  dir;
@@ -134,7 +147,11 @@ export class ArtifactStore {
134
147
  this.dir = opts.dir;
135
148
  this.signing = opts.signing;
136
149
  }
137
- /** Store bytes built by `identity` during an open attempt of its own company. Needs "report". */
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
+ */
138
155
  put(identity, input) {
139
156
  const worker = this.worker(identity, "report");
140
157
  if (!isText(input?.name))
@@ -143,6 +160,7 @@ export class ArtifactStore {
143
160
  throw invalid("artifact bytes that are not a Uint8Array", "a Buffer or Uint8Array");
144
161
  checkInputs(input.inputs);
145
162
  const controller = this.access.controller;
163
+ controller.expireLeases();
146
164
  const view = controller.attempts().find((a) => a.attempt.attemptId === input.attemptId);
147
165
  if (!view) {
148
166
  throw new DeliveryStoreError("UNKNOWN_ATTEMPT", {
@@ -154,6 +172,8 @@ export class ArtifactStore {
154
172
  if (view.attempt.tenantId !== worker.tenantId) {
155
173
  throw denied(`worker ${worker.workerId} of ${worker.tenantId} wrote to an attempt of another company`, `an attempt of ${worker.tenantId}`);
156
174
  }
175
+ if (view.resolution === "abandoned")
176
+ throw abandonedPut(view.attempt.attemptId, "was abandoned");
157
177
  if (view.resolution !== "open") {
158
178
  throw new DeliveryStoreError("ATTEMPT_CONFLICT", {
159
179
  found: `attempt ${view.attempt.attemptId} is ${view.resolution}`,
@@ -177,6 +197,9 @@ export class ArtifactStore {
177
197
  // Re-check against the state being written, so a revocation or report in flight wins.
178
198
  authenticate(draft.workers, identity, { capability: "report", tenantId: worker.tenantId });
179
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
+ }
180
203
  if (!live || live.resolution !== "open") {
181
204
  throw new DeliveryStoreError("ATTEMPT_CONFLICT", {
182
205
  found: `attempt ${attempt.attemptId} is no longer open`,
@@ -234,8 +257,9 @@ export class ArtifactStore {
234
257
  const worker = this.worker(identity, "read");
235
258
  const stored = this.find(artifactId);
236
259
  this.sameTenant(worker.tenantId, stored, `worker ${worker.workerId} of ${worker.tenantId}`);
260
+ // verifyStored checks the promotion signature too, so promotedAt is as signed.
237
261
  const bytes = this.verifyStored(stored);
238
- return { bytes, provenance: structuredClone(stored.provenance) };
262
+ return { bytes, provenance: structuredClone(stored.provenance), promotedAt: stored.promotedAt, provenanceSignature: stored.signature.value };
239
263
  }
240
264
  /** Re-check the signature and blob of an artifact in scope. Throws ARTIFACT_TAMPERED. */
241
265
  verify(scope, artifactId) {
@@ -503,13 +527,8 @@ export class ArtifactStore {
503
527
  });
504
528
  }
505
529
  }
506
- const dfd = openSync(dir, "r");
507
- try {
508
- fsyncSync(dfd);
509
- }
510
- finally {
511
- closeSync(dfd);
512
- }
530
+ // Skipped on win32, which cannot fsync a directory (EPERM); NTFS journals the link.
531
+ fsyncDirectory(dir);
513
532
  }
514
533
  catch (err) {
515
534
  if (err instanceof DeliveryStoreError)
@@ -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,42 @@
1
+ export interface ApplyRequest {
2
+ deploymentId: string;
3
+ tenantId: string;
4
+ environment: string;
5
+ fence: number;
6
+ digest: string;
7
+ bytes: Buffer;
8
+ }
9
+ export type ApplyOutcome = {
10
+ kind: "applied";
11
+ fence: number;
12
+ digest: string;
13
+ } | {
14
+ kind: "rejected";
15
+ detail: string;
16
+ } | {
17
+ kind: "unknown";
18
+ detail: string;
19
+ };
20
+ export type Observation = {
21
+ kind: "applied";
22
+ fence: number;
23
+ digest: string;
24
+ } | {
25
+ kind: "absent";
26
+ floor: number;
27
+ };
28
+ export interface DeploymentTarget {
29
+ readonly targetId: string;
30
+ apply(req: ApplyRequest, timeoutMs: number): Promise<ApplyOutcome>;
31
+ observe(req: {
32
+ deploymentId: string;
33
+ tenantId: string;
34
+ environment: string;
35
+ fence: number;
36
+ }, timeoutMs: number): Promise<Observation>;
37
+ }
38
+ export declare function disposableTarget(opts: {
39
+ targetId: string;
40
+ baseUrl: string;
41
+ }): DeploymentTarget;
42
+ //# sourceMappingURL=disposable-target.d.ts.map
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Deployment target client (US-009).
3
+ *
4
+ * A DeploymentTarget applies one artifact to one tenant/environment under a
5
+ * fence, and answers what it actually applied. The target, not the deployer,
6
+ * is the last check on a stale effect: it refuses any fence at or below the
7
+ * highest it has seen for that environment.
8
+ *
9
+ * apply() returns one of three outcomes and never guesses:
10
+ * - applied: the target answered with the fence and digest it applied.
11
+ * - rejected: the target refused (stale fence, digest mismatch); nothing was applied.
12
+ * - unknown: no answer (timeout, dropped connection, crash). The effect may
13
+ * or may not have happened; the caller must reconcile before any retry.
14
+ *
15
+ * observe() is the reconcile query. It first raises the environment's fence
16
+ * floor to the given fence, so a request still in transit with that fence or
17
+ * lower cannot land after the answer, then reports whether the deployment was
18
+ * applied. If the target cannot be reached it throws TARGET_UNREACHABLE and
19
+ * the caller keeps the outcome unknown.
20
+ *
21
+ * disposableTarget() talks HTTP to the disposable app of the delivery
22
+ * harness and only to a loopback address: this story deploys to disposable
23
+ * local targets only.
24
+ */
25
+ import { DeliveryStoreError } from "./migrations.js";
26
+ const LOOPBACK = new Set(["127.0.0.1", "[::1]", "localhost"]);
27
+ function describe(err) {
28
+ if (err instanceof Error) {
29
+ const cause = err.cause;
30
+ const c = cause instanceof Error ? `: ${cause.message}` : "";
31
+ return `${err.name}: ${err.message}${c}`;
32
+ }
33
+ return String(err);
34
+ }
35
+ export function disposableTarget(opts) {
36
+ const url = new URL(opts.baseUrl);
37
+ if (url.protocol !== "http:" || !LOOPBACK.has(url.hostname)) {
38
+ throw new DeliveryStoreError("INVALID_RECORD", {
39
+ found: `deployment target ${opts.baseUrl}`,
40
+ expected: "an http loopback address of a disposable target",
41
+ action: "Deploy only to a disposable local target. Nothing was sent.",
42
+ });
43
+ }
44
+ const base = url.origin;
45
+ return {
46
+ targetId: opts.targetId,
47
+ async apply(req, timeoutMs) {
48
+ let res;
49
+ let body;
50
+ try {
51
+ res = await fetch(`${base}/deploy`, {
52
+ method: "POST",
53
+ headers: { "content-type": "application/json" },
54
+ body: JSON.stringify({
55
+ deploymentId: req.deploymentId,
56
+ tenantId: req.tenantId,
57
+ environment: req.environment,
58
+ fence: req.fence,
59
+ digest: req.digest,
60
+ bytes: req.bytes.toString("base64"),
61
+ }),
62
+ signal: AbortSignal.timeout(timeoutMs),
63
+ });
64
+ body = (await res.json());
65
+ }
66
+ catch (err) {
67
+ return { kind: "unknown", detail: `no answer from ${opts.targetId} (${describe(err)})` };
68
+ }
69
+ if (res.status === 200 && body.applied === true) {
70
+ if (body.fence !== req.fence || body.digest !== req.digest || body.deploymentId !== req.deploymentId) {
71
+ return { kind: "unknown", detail: `target answered for another effect: ${JSON.stringify(body)}` };
72
+ }
73
+ return { kind: "applied", fence: req.fence, digest: req.digest };
74
+ }
75
+ if (res.status === 409 || res.status === 400)
76
+ return { kind: "rejected", detail: `target refused (${res.status}): ${JSON.stringify(body)}` };
77
+ return { kind: "unknown", detail: `unexpected target answer ${res.status}: ${JSON.stringify(body)}` };
78
+ },
79
+ async observe(req, timeoutMs) {
80
+ let res;
81
+ let body;
82
+ try {
83
+ res = await fetch(`${base}/deploy/reconcile`, {
84
+ method: "POST",
85
+ headers: { "content-type": "application/json" },
86
+ body: JSON.stringify(req),
87
+ signal: AbortSignal.timeout(timeoutMs),
88
+ });
89
+ body = (await res.json());
90
+ }
91
+ catch (err) {
92
+ throw unreachable(opts.targetId, describe(err));
93
+ }
94
+ if (res.status === 200 && body.state === "applied" && typeof body.fence === "number" && typeof body.digest === "string") {
95
+ return { kind: "applied", fence: body.fence, digest: body.digest };
96
+ }
97
+ if (res.status === 200 && body.state === "absent" && typeof body.floor === "number" && body.floor >= req.fence) {
98
+ return { kind: "absent", floor: body.floor };
99
+ }
100
+ throw unreachable(opts.targetId, `unexpected answer ${res.status}: ${JSON.stringify(body)}`);
101
+ },
102
+ };
103
+ }
104
+ function unreachable(targetId, detail) {
105
+ return new DeliveryStoreError("TARGET_UNREACHABLE", {
106
+ found: `target ${targetId} could not be queried (${detail})`,
107
+ expected: "the target's answer on whether the deployment was applied",
108
+ action: "The outcome stays unknown and no retry is allowed. Bring the target back and reconcile again.",
109
+ });
110
+ }
111
+ //# sourceMappingURL=disposable-target.js.map
@@ -0,0 +1,136 @@
1
+ import { type DeployPolicy, type DeployRequest } from "./admission.js";
2
+ import type { ArtifactStore } from "./artifacts.js";
3
+ import type { CredentialSource } from "./credentials.js";
4
+ import type { ApplyOutcome, DeploymentTarget } from "./disposable-target.js";
5
+ import type { AdminScope, DeliveryAccess } from "./enrollment.js";
6
+ import { type WorkerIdentity } from "./identity.js";
7
+ import { type DeploymentDecision, type DeploymentObservation, type DeploymentSnapshot, type DeploymentStatus, type StoredDeployPolicy } from "./migrations.js";
8
+ export interface DeploymentManagerOptions {
9
+ access: DeliveryAccess;
10
+ artifacts: ArtifactStore;
11
+ target: DeploymentTarget;
12
+ /** Bound on each target call, in ms. Default 5000. */
13
+ timeoutMs?: number;
14
+ /**
15
+ * Longest an in-flight deployment may hold its environment, in ms from requestedAt. Past it
16
+ * the deployment is lease-lost (unknown) and must be reconciled. Must exceed timeoutMs.
17
+ * Default: env HQ_DELIVERY_DEPLOY_MAX_HOLD_MS, else DEFAULT_DEPLOY_MAX_HOLD_MS (15 minutes).
18
+ */
19
+ maxHoldMs?: number;
20
+ ids?: () => string;
21
+ /** Provenance signing key (the US-008 key ref): signs stored policies and deployment snapshots. */
22
+ signing: {
23
+ ref: string;
24
+ source: CredentialSource;
25
+ };
26
+ /**
27
+ * Company admin credentials for setPolicy: the credential at refPrefix + "/" + tenantId
28
+ * authenticates an admin of that company. Workers never hold it.
29
+ */
30
+ policyAdmin: {
31
+ refPrefix: string;
32
+ source: CredentialSource;
33
+ };
34
+ }
35
+ /** What a worker holds between request and publish. */
36
+ export interface DeploymentTicket {
37
+ deploymentId: string;
38
+ tenantId: string;
39
+ environment: string;
40
+ fence: number;
41
+ digest: string;
42
+ attemptId: string;
43
+ workerId: string;
44
+ /** Controller epoch that issued the fence. */
45
+ epoch: number;
46
+ targetId: string;
47
+ /** Verified artifact bytes from ArtifactStore.read(). */
48
+ bytes: Buffer;
49
+ }
50
+ export interface DeploymentView {
51
+ deploymentId: string;
52
+ tenantId: string;
53
+ environment: string;
54
+ artifactId: string;
55
+ digest: string;
56
+ workerId: string;
57
+ attemptId: string;
58
+ targetId: string | null;
59
+ fence: number | null;
60
+ /** An in-flight deployment from an earlier controller epoch, or whose worker lost its attempt, shows as unknown. */
61
+ status: DeploymentStatus;
62
+ snapshot: DeploymentSnapshot;
63
+ snapshotDigest: string;
64
+ /** True when snapshotSignature verifies with the signing key. */
65
+ snapshotVerified: boolean;
66
+ decision: DeploymentDecision | null;
67
+ observation: DeploymentObservation | null;
68
+ requestedAt: string;
69
+ requestedEpoch: number;
70
+ resolvedAt: string | null;
71
+ }
72
+ /** Default max hold of an in-flight deployment: 15 minutes, well above the request-perform-publish time of a live worker. */
73
+ export declare const DEFAULT_DEPLOY_MAX_HOLD_MS: number;
74
+ /** Environment variable that overrides the default max hold, in whole ms. */
75
+ export declare const DEPLOY_MAX_HOLD_ENV = "HQ_DELIVERY_DEPLOY_MAX_HOLD_MS";
76
+ export declare function openDeploymentManager(opts: DeploymentManagerOptions): DeploymentManager;
77
+ export declare class DeploymentManager {
78
+ private readonly access;
79
+ private readonly artifacts;
80
+ private readonly target;
81
+ private readonly timeoutMs;
82
+ /** Longest an in-flight deployment holds its environment, in ms from requestedAt. */
83
+ readonly maxHoldMs: number;
84
+ private readonly ids;
85
+ private readonly signing;
86
+ private readonly policyAdmin;
87
+ constructor(opts: DeploymentManagerOptions);
88
+ /**
89
+ * Admit a deployment and issue its fence. Throws DEPLOY_BLOCKED after
90
+ * recording the decision, ENV_BUSY or DEPLOY_OUTCOME_UNKNOWN when the
91
+ * environment has an open deployment, INVALID_RECORD for a malformed request.
92
+ */
93
+ request(identity: WorkerIdentity, raw: DeployRequest): DeploymentTicket;
94
+ /** Send the fenced effect to the target. Worker side: writes nothing to the store. */
95
+ perform(ticket: DeploymentTicket): Promise<ApplyOutcome>;
96
+ /**
97
+ * Record the outcome of a performed effect. Refuses a stale publisher
98
+ * (STALE_PUBLICATION) and then leaves the deployment unknown.
99
+ */
100
+ publish(identity: WorkerIdentity, ticket: DeploymentTicket, outcome: ApplyOutcome): DeploymentView;
101
+ /** request, perform and publish. Returns the recorded outcome; unknown means reconcile next. */
102
+ deploy(identity: WorkerIdentity, req: DeployRequest): Promise<DeploymentView>;
103
+ /**
104
+ * Resolve an unknown deployment from the target's actual state. The target
105
+ * raises its fence floor to this deployment's fence before answering.
106
+ * Throws TARGET_UNREACHABLE (the outcome stays unknown) if it cannot ask.
107
+ */
108
+ reconcile(scope: AdminScope, deploymentId: string): Promise<DeploymentView>;
109
+ /** Deployments and decisions of the companies in scope, oldest first. */
110
+ deployments(scope: AdminScope): DeploymentView[];
111
+ private record;
112
+ private view;
113
+ /**
114
+ * Set a company's deploy policy. The caller must present that company's
115
+ * admin credential (the value at policyAdmin.refPrefix/<tenantId> in the
116
+ * credential source); the scope alone is not trusted. The version must
117
+ * increase. The stored record is signed with the provenance signing key.
118
+ */
119
+ setPolicy(admin: {
120
+ scope: AdminScope;
121
+ token: string;
122
+ }, policy: DeployPolicy): StoredDeployPolicy;
123
+ /** The stored policy of a company in scope (the first in scope by default), or null. */
124
+ policy(scope: AdminScope, tenantId?: string): (StoredDeployPolicy & {
125
+ policy: DeployPolicy;
126
+ verified: boolean;
127
+ }) | null;
128
+ private key;
129
+ private sign;
130
+ private verifies;
131
+ private policyVerifies;
132
+ private toView;
133
+ /** True while the worker that requested `d` still holds its deploy attempt in the current epoch. */
134
+ private held;
135
+ }
136
+ //# sourceMappingURL=effects.d.ts.map