@harperfast/harper 5.2.13 → 5.3.0-beta.1

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 (655) hide show
  1. package/agent/mcpTools.ts +1 -1
  2. package/agent/session.ts +25 -14
  3. package/bin/cliOperations.ts +58 -9
  4. package/bin/copyDb.ts +282 -59
  5. package/bin/deploySetup.ts +16 -5
  6. package/bin/harper.ts +1 -1
  7. package/bin/help.ts +4 -1
  8. package/bin/lite.ts +4 -1
  9. package/bin/restart.ts +120 -4
  10. package/bin/run.ts +6 -11
  11. package/bin/upgrade.js +7 -3
  12. package/bin/workloadIdentity.ts +119 -0
  13. package/components/Application.ts +3436 -242
  14. package/components/ApplicationScope.ts +8 -0
  15. package/components/EntryHandler.ts +59 -39
  16. package/components/OptionsWatcher.ts +440 -98
  17. package/components/RuntimeModuleTracker.ts +38 -7
  18. package/components/Scope.ts +56 -15
  19. package/components/awaitRestart.ts +84 -0
  20. package/components/componentLoader.ts +381 -32
  21. package/components/componentPreparationLock.ts +16 -5
  22. package/components/deploymentOperations.ts +4 -1
  23. package/components/deploymentRecorder.ts +9 -2
  24. package/components/mcp/adapters/harperHttp.ts +4 -0
  25. package/components/mcp/listChanged.ts +4 -0
  26. package/components/mcp/toolRegistry.ts +2 -0
  27. package/components/mcp/tools/operations.ts +9 -0
  28. package/components/mcp/tools/schemas/operationDescriptions.ts +2 -2
  29. package/components/operations.js +537 -113
  30. package/components/operationsValidation.js +98 -3
  31. package/components/packageComponent.ts +25 -1
  32. package/components/requestRestart.ts +11 -0
  33. package/components/status/ComponentStatusRegistry.ts +59 -0
  34. package/config/RootConfigWatcher.ts +240 -40
  35. package/config/configReadRetry.ts +62 -0
  36. package/config/configUtils.ts +357 -48
  37. package/config/harperConfigEnvVars.ts +170 -27
  38. package/config/parseConfigFile.ts +34 -0
  39. package/config/readConfigFileSync.ts +44 -0
  40. package/config/watcherArming.ts +59 -0
  41. package/config-root.schema.json +33 -0
  42. package/dataLayer/blobBackup.ts +160 -50
  43. package/dataLayer/delete.ts +6 -1
  44. package/dataLayer/harperBridge/ResourceBridge.ts +80 -10
  45. package/dataLayer/harperBridge/lmdbBridge/lmdbMethods/DeleteAuditLogsBeforeResults.js +3 -1
  46. package/dataLayer/hdbInfoController.ts +34 -1
  47. package/dataLayer/insert.ts +44 -1
  48. package/dataLayer/rocksdbBackup.ts +53 -10
  49. package/dataLayer/schema.ts +11 -1
  50. package/dataLayer/schemaDescribe.ts +8 -1
  51. package/dist/agent/mcpTools.js +1 -1
  52. package/dist/agent/mcpTools.js.map +1 -1
  53. package/dist/agent/session.d.ts +22 -0
  54. package/dist/agent/session.js +26 -15
  55. package/dist/agent/session.js.map +1 -1
  56. package/dist/bin/cliOperations.js +61 -9
  57. package/dist/bin/cliOperations.js.map +1 -1
  58. package/dist/bin/copyDb.d.ts +12 -1
  59. package/dist/bin/copyDb.js +248 -60
  60. package/dist/bin/copyDb.js.map +1 -1
  61. package/dist/bin/deploySetup.d.ts +2 -0
  62. package/dist/bin/deploySetup.js +11 -3
  63. package/dist/bin/deploySetup.js.map +1 -1
  64. package/dist/bin/harper.js +1 -1
  65. package/dist/bin/harper.js.map +1 -1
  66. package/dist/bin/help.js +4 -1
  67. package/dist/bin/help.js.map +1 -1
  68. package/dist/bin/lite.js +4 -1
  69. package/dist/bin/lite.js.map +1 -1
  70. package/dist/bin/restart.js +91 -6
  71. package/dist/bin/restart.js.map +1 -1
  72. package/dist/bin/run.js +4 -10
  73. package/dist/bin/run.js.map +1 -1
  74. package/dist/bin/upgrade.js +4 -3
  75. package/dist/bin/upgrade.js.map +1 -1
  76. package/dist/bin/workloadIdentity.d.ts +18 -0
  77. package/dist/bin/workloadIdentity.js +100 -0
  78. package/dist/bin/workloadIdentity.js.map +1 -0
  79. package/dist/components/Application.d.ts +235 -17
  80. package/dist/components/Application.js +3038 -238
  81. package/dist/components/Application.js.map +1 -1
  82. package/dist/components/ApplicationScope.d.ts +8 -0
  83. package/dist/components/ApplicationScope.js +7 -0
  84. package/dist/components/ApplicationScope.js.map +1 -1
  85. package/dist/components/EntryHandler.js +26 -10
  86. package/dist/components/EntryHandler.js.map +1 -1
  87. package/dist/components/OptionsWatcher.d.ts +4 -0
  88. package/dist/components/OptionsWatcher.js +440 -99
  89. package/dist/components/OptionsWatcher.js.map +1 -1
  90. package/dist/components/RuntimeModuleTracker.js +40 -6
  91. package/dist/components/RuntimeModuleTracker.js.map +1 -1
  92. package/dist/components/Scope.js +52 -13
  93. package/dist/components/Scope.js.map +1 -1
  94. package/dist/components/awaitRestart.d.ts +33 -0
  95. package/dist/components/awaitRestart.js +61 -0
  96. package/dist/components/awaitRestart.js.map +1 -0
  97. package/dist/components/componentLoader.d.ts +38 -1
  98. package/dist/components/componentLoader.js +313 -24
  99. package/dist/components/componentLoader.js.map +1 -1
  100. package/dist/components/componentPreparationLock.d.ts +5 -0
  101. package/dist/components/componentPreparationLock.js +14 -6
  102. package/dist/components/componentPreparationLock.js.map +1 -1
  103. package/dist/components/deploymentOperations.js +4 -1
  104. package/dist/components/deploymentOperations.js.map +1 -1
  105. package/dist/components/deploymentRecorder.d.ts +4 -2
  106. package/dist/components/deploymentRecorder.js +1 -0
  107. package/dist/components/deploymentRecorder.js.map +1 -1
  108. package/dist/components/mcp/adapters/harperHttp.js +4 -0
  109. package/dist/components/mcp/adapters/harperHttp.js.map +1 -1
  110. package/dist/components/mcp/listChanged.js +5 -0
  111. package/dist/components/mcp/listChanged.js.map +1 -1
  112. package/dist/components/mcp/toolRegistry.d.ts +1 -0
  113. package/dist/components/mcp/toolRegistry.js.map +1 -1
  114. package/dist/components/mcp/tools/operations.d.ts +5 -0
  115. package/dist/components/mcp/tools/operations.js +9 -0
  116. package/dist/components/mcp/tools/operations.js.map +1 -1
  117. package/dist/components/mcp/tools/schemas/operationDescriptions.js +2 -2
  118. package/dist/components/mcp/tools/schemas/operationDescriptions.js.map +1 -1
  119. package/dist/components/operations.d.ts +28 -0
  120. package/dist/components/operations.js +476 -113
  121. package/dist/components/operations.js.map +1 -1
  122. package/dist/components/operationsValidation.js +97 -3
  123. package/dist/components/operationsValidation.js.map +1 -1
  124. package/dist/components/packageComponent.js +24 -0
  125. package/dist/components/packageComponent.js.map +1 -1
  126. package/dist/components/requestRestart.d.ts +1 -0
  127. package/dist/components/requestRestart.js +7 -0
  128. package/dist/components/requestRestart.js.map +1 -1
  129. package/dist/components/status/ComponentStatusRegistry.d.ts +0 -4
  130. package/dist/components/status/ComponentStatusRegistry.js +63 -0
  131. package/dist/components/status/ComponentStatusRegistry.js.map +1 -1
  132. package/dist/config/RootConfigWatcher.d.ts +9 -1
  133. package/dist/config/RootConfigWatcher.js +228 -37
  134. package/dist/config/RootConfigWatcher.js.map +1 -1
  135. package/dist/config/configReadRetry.d.ts +8 -0
  136. package/dist/config/configReadRetry.js +62 -0
  137. package/dist/config/configReadRetry.js.map +1 -0
  138. package/dist/config/configUtils.d.ts +11 -2
  139. package/dist/config/configUtils.js +304 -47
  140. package/dist/config/configUtils.js.map +1 -1
  141. package/dist/config/harperConfigEnvVars.d.ts +16 -0
  142. package/dist/config/harperConfigEnvVars.js +162 -25
  143. package/dist/config/harperConfigEnvVars.js.map +1 -1
  144. package/dist/config/parseConfigFile.d.ts +4 -0
  145. package/dist/config/parseConfigFile.js +35 -0
  146. package/dist/config/parseConfigFile.js.map +1 -0
  147. package/dist/config/readConfigFileSync.d.ts +1 -0
  148. package/dist/config/readConfigFileSync.js +47 -0
  149. package/dist/config/readConfigFileSync.js.map +1 -0
  150. package/dist/config/watcherArming.d.ts +15 -0
  151. package/dist/config/watcherArming.js +59 -0
  152. package/dist/config/watcherArming.js.map +1 -0
  153. package/dist/dataLayer/blobBackup.d.ts +49 -20
  154. package/dist/dataLayer/blobBackup.js +139 -50
  155. package/dist/dataLayer/blobBackup.js.map +1 -1
  156. package/dist/dataLayer/delete.js +1 -1
  157. package/dist/dataLayer/delete.js.map +1 -1
  158. package/dist/dataLayer/harperBridge/ResourceBridge.d.ts +14 -1
  159. package/dist/dataLayer/harperBridge/ResourceBridge.js +72 -12
  160. package/dist/dataLayer/harperBridge/ResourceBridge.js.map +1 -1
  161. package/dist/dataLayer/harperBridge/lmdbBridge/lmdbMethods/DeleteAuditLogsBeforeResults.d.ts +3 -1
  162. package/dist/dataLayer/harperBridge/lmdbBridge/lmdbMethods/DeleteAuditLogsBeforeResults.js +3 -1
  163. package/dist/dataLayer/harperBridge/lmdbBridge/lmdbMethods/DeleteAuditLogsBeforeResults.js.map +1 -1
  164. package/dist/dataLayer/hdbInfoController.d.ts +10 -0
  165. package/dist/dataLayer/hdbInfoController.js +30 -1
  166. package/dist/dataLayer/hdbInfoController.js.map +1 -1
  167. package/dist/dataLayer/insert.d.ts +9 -1
  168. package/dist/dataLayer/insert.js +30 -0
  169. package/dist/dataLayer/insert.js.map +1 -1
  170. package/dist/dataLayer/rocksdbBackup.d.ts +2 -2
  171. package/dist/dataLayer/rocksdbBackup.js +45 -8
  172. package/dist/dataLayer/rocksdbBackup.js.map +1 -1
  173. package/dist/dataLayer/schema.js +8 -0
  174. package/dist/dataLayer/schema.js.map +1 -1
  175. package/dist/dataLayer/schemaDescribe.js +8 -1
  176. package/dist/dataLayer/schemaDescribe.js.map +1 -1
  177. package/dist/index.d.ts +2 -1
  178. package/dist/index.js +4 -1
  179. package/dist/index.js.map +1 -1
  180. package/dist/json/systemSchema.json +55 -0
  181. package/dist/resources/DatabaseTransaction.d.ts +77 -0
  182. package/dist/resources/DatabaseTransaction.js +586 -54
  183. package/dist/resources/DatabaseTransaction.js.map +1 -1
  184. package/dist/resources/LMDBTransaction.d.ts +2 -1
  185. package/dist/resources/LMDBTransaction.js +43 -6
  186. package/dist/resources/LMDBTransaction.js.map +1 -1
  187. package/dist/resources/PrimaryRocksDatabase.d.ts +1 -0
  188. package/dist/resources/PrimaryRocksDatabase.js +49 -5
  189. package/dist/resources/PrimaryRocksDatabase.js.map +1 -1
  190. package/dist/resources/RecordEncoder.d.ts +20 -0
  191. package/dist/resources/RecordEncoder.js +110 -9
  192. package/dist/resources/RecordEncoder.js.map +1 -1
  193. package/dist/resources/RequestTarget.d.ts +2 -0
  194. package/dist/resources/RequestTarget.js.map +1 -1
  195. package/dist/resources/Resource.js +117 -24
  196. package/dist/resources/Resource.js.map +1 -1
  197. package/dist/resources/ResourceInterface.d.ts +28 -1
  198. package/dist/resources/ResourceInterface.js.map +1 -1
  199. package/dist/resources/RocksIndexStore.d.ts +6 -1
  200. package/dist/resources/RocksIndexStore.js +24 -9
  201. package/dist/resources/RocksIndexStore.js.map +1 -1
  202. package/dist/resources/RocksTransactionLogStore.d.ts +24 -1
  203. package/dist/resources/RocksTransactionLogStore.js +160 -49
  204. package/dist/resources/RocksTransactionLogStore.js.map +1 -1
  205. package/dist/resources/Table.d.ts +165 -10
  206. package/dist/resources/Table.js +1805 -303
  207. package/dist/resources/Table.js.map +1 -1
  208. package/dist/resources/analytics/write.js +10 -3
  209. package/dist/resources/analytics/write.js.map +1 -1
  210. package/dist/resources/auditStore.d.ts +181 -2
  211. package/dist/resources/auditStore.js +640 -29
  212. package/dist/resources/auditStore.js.map +1 -1
  213. package/dist/resources/blob.d.ts +129 -9
  214. package/dist/resources/blob.js +992 -114
  215. package/dist/resources/blob.js.map +1 -1
  216. package/dist/resources/branchDatabase.d.ts +48 -0
  217. package/dist/resources/branchDatabase.js +892 -0
  218. package/dist/resources/branchDatabase.js.map +1 -0
  219. package/dist/resources/crdt.js +50 -12
  220. package/dist/resources/crdt.js.map +1 -1
  221. package/dist/resources/dataLoader.js +3 -4
  222. package/dist/resources/dataLoader.js.map +1 -1
  223. package/dist/resources/databases.d.ts +157 -14
  224. package/dist/resources/databases.js +1462 -325
  225. package/dist/resources/databases.js.map +1 -1
  226. package/dist/resources/defineTable.d.ts +10 -2
  227. package/dist/resources/defineTable.js +9 -1
  228. package/dist/resources/defineTable.js.map +1 -1
  229. package/dist/resources/derivedIndexRegistry.d.ts +5 -0
  230. package/dist/resources/derivedIndexRegistry.js +68 -0
  231. package/dist/resources/derivedIndexRegistry.js.map +1 -0
  232. package/dist/resources/derivedIndexRuntime.d.ts +215 -0
  233. package/dist/resources/derivedIndexRuntime.js +2027 -0
  234. package/dist/resources/derivedIndexRuntime.js.map +1 -0
  235. package/dist/resources/graphql.d.ts +1 -1
  236. package/dist/resources/graphql.js +52 -16
  237. package/dist/resources/graphql.js.map +1 -1
  238. package/dist/resources/indexes/HierarchicalNavigableSmallWorld.d.ts +103 -9
  239. package/dist/resources/indexes/HierarchicalNavigableSmallWorld.js +854 -41
  240. package/dist/resources/indexes/HierarchicalNavigableSmallWorld.js.map +1 -1
  241. package/dist/resources/indexes/hnswDerivedIndex.d.ts +67 -0
  242. package/dist/resources/indexes/hnswDerivedIndex.js +464 -0
  243. package/dist/resources/indexes/hnswDerivedIndex.js.map +1 -0
  244. package/dist/resources/indexes/hnswPlaneBinding.d.ts +65 -0
  245. package/dist/resources/indexes/hnswPlaneBinding.js +91 -0
  246. package/dist/resources/indexes/hnswPlaneBinding.js.map +1 -0
  247. package/dist/resources/longLivedTransactions.d.ts +71 -0
  248. package/dist/resources/longLivedTransactions.js +358 -0
  249. package/dist/resources/longLivedTransactions.js.map +1 -0
  250. package/dist/resources/models/backendRegistry.d.ts +26 -0
  251. package/dist/resources/models/backendRegistry.js +60 -2
  252. package/dist/resources/models/backendRegistry.js.map +1 -1
  253. package/dist/resources/models/bootstrap.d.ts +33 -1
  254. package/dist/resources/models/bootstrap.js +416 -31
  255. package/dist/resources/models/bootstrap.js.map +1 -1
  256. package/dist/resources/nodeIdMapping.d.ts +5 -0
  257. package/dist/resources/nodeIdMapping.js +49 -0
  258. package/dist/resources/nodeIdMapping.js.map +1 -1
  259. package/dist/resources/recordLock.d.ts +123 -0
  260. package/dist/resources/recordLock.js +315 -0
  261. package/dist/resources/recordLock.js.map +1 -0
  262. package/dist/resources/recordLockCoordinator.d.ts +557 -0
  263. package/dist/resources/recordLockCoordinator.js +2565 -0
  264. package/dist/resources/recordLockCoordinator.js.map +1 -0
  265. package/dist/resources/replayLogs.d.ts +14 -1
  266. package/dist/resources/replayLogs.js +157 -24
  267. package/dist/resources/replayLogs.js.map +1 -1
  268. package/dist/resources/replayLogsGuards.d.ts +94 -7
  269. package/dist/resources/replayLogsGuards.js +111 -7
  270. package/dist/resources/replayLogsGuards.js.map +1 -1
  271. package/dist/resources/replicatedApplyFailure.d.ts +16 -0
  272. package/dist/resources/replicatedApplyFailure.js +63 -0
  273. package/dist/resources/replicatedApplyFailure.js.map +1 -0
  274. package/dist/resources/scheduler/scheduler.js +3 -3
  275. package/dist/resources/scheduler/scheduler.js.map +1 -1
  276. package/dist/resources/search.d.ts +10 -4
  277. package/dist/resources/search.js +283 -37
  278. package/dist/resources/search.js.map +1 -1
  279. package/dist/resources/tracked.d.ts +5 -1
  280. package/dist/resources/tracked.js +74 -23
  281. package/dist/resources/tracked.js.map +1 -1
  282. package/dist/resources/transactionBroadcast.d.ts +1 -1
  283. package/dist/resources/transactionBroadcast.js +2 -2
  284. package/dist/resources/transactionBroadcast.js.map +1 -1
  285. package/dist/security/auth.js +61 -30
  286. package/dist/security/auth.js.map +1 -1
  287. package/dist/security/authn/oidc/claims.d.ts +22 -0
  288. package/dist/security/authn/oidc/claims.js +71 -0
  289. package/dist/security/authn/oidc/claims.js.map +1 -0
  290. package/dist/security/authn/oidc/identityToken.d.ts +27 -0
  291. package/dist/security/authn/oidc/identityToken.js +111 -0
  292. package/dist/security/authn/oidc/identityToken.js.map +1 -0
  293. package/dist/security/authn/oidc/jwks.d.ts +25 -0
  294. package/dist/security/authn/oidc/jwks.js +261 -0
  295. package/dist/security/authn/oidc/jwks.js.map +1 -0
  296. package/dist/security/authn/oidc/providers/generic.d.ts +13 -0
  297. package/dist/security/authn/oidc/providers/generic.js +34 -0
  298. package/dist/security/authn/oidc/providers/generic.js.map +1 -0
  299. package/dist/security/authn/oidc/providers/githubActions.d.ts +11 -0
  300. package/dist/security/authn/oidc/providers/githubActions.js +129 -0
  301. package/dist/security/authn/oidc/providers/githubActions.js.map +1 -0
  302. package/dist/security/authn/oidc/providers/index.d.ts +37 -0
  303. package/dist/security/authn/oidc/providers/index.js +24 -0
  304. package/dist/security/authn/oidc/providers/index.js.map +1 -0
  305. package/dist/security/authn/oidc/tokenExchange.d.ts +12 -0
  306. package/dist/security/authn/oidc/tokenExchange.js +306 -0
  307. package/dist/security/authn/oidc/tokenExchange.js.map +1 -0
  308. package/dist/security/authn/oidc/trustPolicyOperations.d.ts +49 -0
  309. package/dist/security/authn/oidc/trustPolicyOperations.js +358 -0
  310. package/dist/security/authn/oidc/trustPolicyOperations.js.map +1 -0
  311. package/dist/security/authn/oidc/types.d.ts +38 -0
  312. package/dist/security/authn/oidc/types.js +6 -0
  313. package/dist/security/authn/oidc/types.js.map +1 -0
  314. package/dist/security/certificateVerification/index.js +40 -11
  315. package/dist/security/certificateVerification/index.js.map +1 -1
  316. package/dist/security/certificateVerification/trustedIssuers.d.ts +24 -0
  317. package/dist/security/certificateVerification/trustedIssuers.js +79 -0
  318. package/dist/security/certificateVerification/trustedIssuers.js.map +1 -0
  319. package/dist/security/certificateVerification/types.d.ts +1 -0
  320. package/dist/security/credentialProvenance.d.ts +35 -0
  321. package/dist/security/credentialProvenance.js +51 -0
  322. package/dist/security/credentialProvenance.js.map +1 -0
  323. package/dist/security/credentialRejection.d.ts +4 -0
  324. package/dist/security/credentialRejection.js +24 -0
  325. package/dist/security/credentialRejection.js.map +1 -0
  326. package/dist/security/deferredAuthentication.d.ts +36 -0
  327. package/dist/security/deferredAuthentication.js +70 -0
  328. package/dist/security/deferredAuthentication.js.map +1 -0
  329. package/dist/security/impersonation.d.ts +21 -0
  330. package/dist/security/impersonation.js +108 -9
  331. package/dist/security/impersonation.js.map +1 -1
  332. package/dist/security/jsLoader.d.ts +6 -0
  333. package/dist/security/jsLoader.js +77 -15
  334. package/dist/security/jsLoader.js.map +1 -1
  335. package/dist/security/keys.js +301 -71
  336. package/dist/security/keys.js.map +1 -1
  337. package/dist/security/operationScope.d.ts +21 -0
  338. package/dist/security/operationScope.js +36 -0
  339. package/dist/security/operationScope.js.map +1 -0
  340. package/dist/security/permissionsTranslator.js +21 -0
  341. package/dist/security/permissionsTranslator.js.map +1 -1
  342. package/dist/security/tokenAuthentication.d.ts +19 -1
  343. package/dist/security/tokenAuthentication.js +191 -10
  344. package/dist/security/tokenAuthentication.js.map +1 -1
  345. package/dist/security/user.js +4 -3
  346. package/dist/security/user.js.map +1 -1
  347. package/dist/server/DurableSubscriptionsSession.d.ts +2 -2
  348. package/dist/server/DurableSubscriptionsSession.js +67 -10
  349. package/dist/server/DurableSubscriptionsSession.js.map +1 -1
  350. package/dist/server/REST.js +106 -2
  351. package/dist/server/REST.js.map +1 -1
  352. package/dist/server/graphqlQuerying.js +4 -0
  353. package/dist/server/graphqlQuerying.js.map +1 -1
  354. package/dist/server/http.d.ts +16 -1
  355. package/dist/server/http.js +122 -17
  356. package/dist/server/http.js.map +1 -1
  357. package/dist/server/itc/serverHandlers.js +8 -1
  358. package/dist/server/itc/serverHandlers.js.map +1 -1
  359. package/dist/server/jobs/jobProcess.js +6 -2
  360. package/dist/server/jobs/jobProcess.js.map +1 -1
  361. package/dist/server/jobs/jobs.js +4 -1
  362. package/dist/server/jobs/jobs.js.map +1 -1
  363. package/dist/server/liveSubscriptionAuth.d.ts +26 -4
  364. package/dist/server/liveSubscriptionAuth.js +105 -39
  365. package/dist/server/liveSubscriptionAuth.js.map +1 -1
  366. package/dist/server/loadRootComponents.js +49 -10
  367. package/dist/server/loadRootComponents.js.map +1 -1
  368. package/dist/server/mqtt.d.ts +2 -0
  369. package/dist/server/mqtt.js +165 -30
  370. package/dist/server/mqtt.js.map +1 -1
  371. package/dist/server/nodeName.d.ts +2 -0
  372. package/dist/server/nodeName.js +107 -23
  373. package/dist/server/nodeName.js.map +1 -1
  374. package/dist/server/serverHelpers/Headers.d.ts +27 -0
  375. package/dist/server/serverHelpers/Headers.js +145 -1
  376. package/dist/server/serverHelpers/Headers.js.map +1 -1
  377. package/dist/server/serverHelpers/NodeAdapterResponse.d.ts +48 -0
  378. package/dist/server/serverHelpers/NodeAdapterResponse.js +220 -0
  379. package/dist/server/serverHelpers/NodeAdapterResponse.js.map +1 -0
  380. package/dist/server/serverHelpers/Request.d.ts +5 -10
  381. package/dist/server/serverHelpers/Request.js +38 -136
  382. package/dist/server/serverHelpers/Request.js.map +1 -1
  383. package/dist/server/serverHelpers/contentTypes.d.ts +11 -0
  384. package/dist/server/serverHelpers/contentTypes.js +221 -40
  385. package/dist/server/serverHelpers/contentTypes.js.map +1 -1
  386. package/dist/server/serverHelpers/deployValidationState.d.ts +3 -0
  387. package/dist/server/serverHelpers/deployValidationState.js +9 -19
  388. package/dist/server/serverHelpers/deployValidationState.js.map +1 -1
  389. package/dist/server/serverHelpers/operationAuthorizationState.d.ts +12 -0
  390. package/dist/server/serverHelpers/operationAuthorizationState.js +24 -2
  391. package/dist/server/serverHelpers/operationAuthorizationState.js.map +1 -1
  392. package/dist/server/serverHelpers/registeredOperations.d.ts +5 -4
  393. package/dist/server/serverHelpers/registeredOperations.js +74 -21
  394. package/dist/server/serverHelpers/registeredOperations.js.map +1 -1
  395. package/dist/server/serverHelpers/requestSanitization.d.ts +11 -0
  396. package/dist/server/serverHelpers/requestSanitization.js +20 -0
  397. package/dist/server/serverHelpers/requestSanitization.js.map +1 -0
  398. package/dist/server/serverHelpers/serverHandlers.js +6 -3
  399. package/dist/server/serverHelpers/serverHandlers.js.map +1 -1
  400. package/dist/server/serverHelpers/serverUtilities.d.ts +18 -0
  401. package/dist/server/serverHelpers/serverUtilities.js +178 -29
  402. package/dist/server/serverHelpers/serverUtilities.js.map +1 -1
  403. package/dist/server/serverHelpers/sharedMessageEncoding.d.ts +67 -0
  404. package/dist/server/serverHelpers/sharedMessageEncoding.js +280 -0
  405. package/dist/server/serverHelpers/sharedMessageEncoding.js.map +1 -0
  406. package/dist/server/serverHelpers/uwsServer.js +19 -1
  407. package/dist/server/serverHelpers/uwsServer.js.map +1 -1
  408. package/dist/server/static.js +24 -28
  409. package/dist/server/static.js.map +1 -1
  410. package/dist/server/storageReclamation.d.ts +5 -0
  411. package/dist/server/storageReclamation.js +17 -1
  412. package/dist/server/storageReclamation.js.map +1 -1
  413. package/dist/server/threads/isolatedApplications.d.ts +47 -0
  414. package/dist/server/threads/isolatedApplications.js +171 -0
  415. package/dist/server/threads/isolatedApplications.js.map +1 -0
  416. package/dist/server/threads/itc.d.ts +7 -2
  417. package/dist/server/threads/itc.js +5 -1
  418. package/dist/server/threads/itc.js.map +1 -1
  419. package/dist/server/threads/logRotationTransport.d.ts +1 -0
  420. package/dist/server/threads/logRotationTransport.js +33 -0
  421. package/dist/server/threads/logRotationTransport.js.map +1 -0
  422. package/dist/server/threads/manageThreads.d.ts +83 -3
  423. package/dist/server/threads/manageThreads.js +769 -75
  424. package/dist/server/threads/manageThreads.js.map +1 -1
  425. package/dist/server/threads/socketRouter.d.ts +1 -0
  426. package/dist/server/threads/socketRouter.js +277 -31
  427. package/dist/server/threads/socketRouter.js.map +1 -1
  428. package/dist/server/threads/threadHeapMemory.d.ts +2 -0
  429. package/dist/server/threads/threadHeapMemory.js +31 -0
  430. package/dist/server/threads/threadHeapMemory.js.map +1 -0
  431. package/dist/server/threads/threadServer.js +76 -22
  432. package/dist/server/threads/threadServer.js.map +1 -1
  433. package/dist/sqlEngine/config.d.ts +1 -3
  434. package/dist/sqlEngine/config.js +19 -16
  435. package/dist/sqlEngine/config.js.map +1 -1
  436. package/dist/sqlTranslator/index.d.ts +1 -1
  437. package/dist/sqlTranslator/index.js +30 -7
  438. package/dist/sqlTranslator/index.js.map +1 -1
  439. package/dist/upgrade/directives/5-3-0.d.ts +7 -0
  440. package/dist/upgrade/directives/5-3-0.js +148 -0
  441. package/dist/upgrade/directives/5-3-0.js.map +1 -0
  442. package/dist/upgrade/directives/directivesController.js +2 -1
  443. package/dist/upgrade/directives/directivesController.js.map +1 -1
  444. package/dist/utility/OperationFunctionCaller.js +2 -1
  445. package/dist/utility/OperationFunctionCaller.js.map +1 -1
  446. package/dist/utility/common_utils.d.ts +16 -0
  447. package/dist/utility/common_utils.js +32 -6
  448. package/dist/utility/common_utils.js.map +1 -1
  449. package/dist/utility/componentNames.d.ts +8 -0
  450. package/dist/utility/componentNames.js +12 -1
  451. package/dist/utility/componentNames.js.map +1 -1
  452. package/dist/utility/environment/environmentManager.js +3 -6
  453. package/dist/utility/environment/environmentManager.js.map +1 -1
  454. package/dist/utility/environment/systemInformation.d.ts +1 -0
  455. package/dist/utility/environment/systemInformation.js +1 -0
  456. package/dist/utility/environment/systemInformation.js.map +1 -1
  457. package/dist/utility/errors/commonErrors.d.ts +2 -0
  458. package/dist/utility/errors/commonErrors.js +2 -0
  459. package/dist/utility/errors/commonErrors.js.map +1 -1
  460. package/dist/utility/errors/hdbError.d.ts +33 -0
  461. package/dist/utility/errors/hdbError.js +58 -1
  462. package/dist/utility/errors/hdbError.js.map +1 -1
  463. package/dist/utility/globalSchema.d.ts +18 -0
  464. package/dist/utility/hdbTerms.d.ts +18 -0
  465. package/dist/utility/hdbTerms.js +20 -2
  466. package/dist/utility/hdbTerms.js.map +1 -1
  467. package/dist/utility/logging/harper_logger.d.ts +2 -0
  468. package/dist/utility/logging/harper_logger.js +286 -30
  469. package/dist/utility/logging/harper_logger.js.map +1 -1
  470. package/dist/utility/logging/logGenerationCoordinator.d.ts +35 -0
  471. package/dist/utility/logging/logGenerationCoordinator.js +184 -0
  472. package/dist/utility/logging/logGenerationCoordinator.js.map +1 -0
  473. package/dist/utility/logging/logRotation.d.ts +46 -0
  474. package/dist/utility/logging/logRotation.js +365 -0
  475. package/dist/utility/logging/logRotation.js.map +1 -0
  476. package/dist/utility/logging/logRotator.d.ts +1 -1
  477. package/dist/utility/logging/logRotator.js +192 -85
  478. package/dist/utility/logging/logRotator.js.map +1 -1
  479. package/dist/utility/nodeIdentity.d.ts +9 -0
  480. package/dist/utility/nodeIdentity.js +58 -0
  481. package/dist/utility/nodeIdentity.js.map +1 -0
  482. package/dist/utility/npmUtilities.js +11 -7
  483. package/dist/utility/npmUtilities.js.map +1 -1
  484. package/dist/utility/operationPermissions.d.ts +3 -1
  485. package/dist/utility/operationPermissions.js +16 -1
  486. package/dist/utility/operationPermissions.js.map +1 -1
  487. package/dist/utility/operation_authorization.d.ts +10 -7
  488. package/dist/utility/operation_authorization.js +212 -41
  489. package/dist/utility/operation_authorization.js.map +1 -1
  490. package/dist/utility/watchPath.d.ts +29 -0
  491. package/dist/utility/watchPath.js +68 -0
  492. package/dist/utility/watchPath.js.map +1 -0
  493. package/dist/utility/watcherFallback.d.ts +41 -0
  494. package/dist/utility/watcherFallback.js +153 -0
  495. package/dist/utility/watcherFallback.js.map +1 -1
  496. package/dist/validation/configValidator.d.ts +12 -0
  497. package/dist/validation/configValidator.js +205 -75
  498. package/dist/validation/configValidator.js.map +1 -1
  499. package/dist/validation/installValidator.js +12 -0
  500. package/dist/validation/installValidator.js.map +1 -1
  501. package/dist/validation/validationWrapper.d.ts +11 -0
  502. package/dist/validation/validationWrapper.js +16 -3
  503. package/dist/validation/validationWrapper.js.map +1 -1
  504. package/index.ts +8 -0
  505. package/json/systemSchema.json +55 -0
  506. package/npm-shrinkwrap.json +286 -194
  507. package/package.json +15 -7
  508. package/resources/DESIGN.md +219 -52
  509. package/resources/DatabaseTransaction.ts +657 -52
  510. package/resources/LMDBTransaction.ts +46 -6
  511. package/resources/PrimaryRocksDatabase.ts +46 -7
  512. package/resources/RecordEncoder.ts +124 -9
  513. package/resources/RequestTarget.ts +2 -0
  514. package/resources/Resource.ts +114 -22
  515. package/resources/ResourceInterface.ts +31 -0
  516. package/resources/RocksIndexStore.ts +30 -9
  517. package/resources/RocksTransactionLogStore.ts +188 -51
  518. package/resources/Table.ts +1960 -301
  519. package/resources/analytics/write.ts +10 -3
  520. package/resources/auditStore.ts +647 -32
  521. package/resources/blob.ts +1029 -110
  522. package/resources/branchDatabase.ts +941 -0
  523. package/resources/crdt.ts +76 -12
  524. package/resources/dataLoader.ts +3 -4
  525. package/resources/databases.ts +1584 -320
  526. package/resources/defineTable.ts +18 -2
  527. package/resources/derivedIndexRegistry.ts +56 -0
  528. package/resources/derivedIndexRuntime.ts +2292 -0
  529. package/resources/graphql.ts +72 -17
  530. package/resources/indexes/HierarchicalNavigableSmallWorld.ts +911 -48
  531. package/resources/indexes/hnswDerivedIndex.ts +531 -0
  532. package/resources/indexes/hnswPlaneBinding.ts +174 -0
  533. package/resources/longLivedTransactions.ts +360 -0
  534. package/resources/models/backendRegistry.ts +84 -2
  535. package/resources/models/bootstrap.ts +473 -28
  536. package/resources/nodeIdMapping.ts +50 -0
  537. package/resources/recordLock.ts +419 -0
  538. package/resources/recordLockCoordinator.ts +3043 -0
  539. package/resources/replayLogs.ts +152 -26
  540. package/resources/replayLogsGuards.ts +171 -8
  541. package/resources/replicatedApplyFailure.ts +77 -0
  542. package/resources/scheduler/scheduler.ts +4 -4
  543. package/resources/search.ts +288 -46
  544. package/resources/tracked.ts +73 -22
  545. package/resources/transactionBroadcast.ts +3 -3
  546. package/security/auth.ts +68 -29
  547. package/security/authn/oidc/claims.ts +72 -0
  548. package/security/authn/oidc/identityToken.ts +129 -0
  549. package/security/authn/oidc/jwks.ts +260 -0
  550. package/security/authn/oidc/providers/generic.ts +40 -0
  551. package/security/authn/oidc/providers/githubActions.ts +137 -0
  552. package/security/authn/oidc/providers/index.ts +52 -0
  553. package/security/authn/oidc/tokenExchange.ts +300 -0
  554. package/security/authn/oidc/trustPolicyOperations.ts +343 -0
  555. package/security/authn/oidc/types.ts +41 -0
  556. package/security/certificateVerification/index.ts +54 -13
  557. package/security/certificateVerification/trustedIssuers.ts +76 -0
  558. package/security/certificateVerification/types.ts +1 -0
  559. package/security/credentialProvenance.ts +47 -0
  560. package/security/credentialRejection.ts +22 -0
  561. package/security/deferredAuthentication.ts +71 -0
  562. package/security/impersonation.ts +117 -12
  563. package/security/jsLoader.ts +83 -18
  564. package/security/keys.ts +298 -72
  565. package/security/operationScope.ts +33 -0
  566. package/security/permissionsTranslator.js +23 -0
  567. package/security/tokenAuthentication.ts +233 -12
  568. package/security/user.ts +4 -3
  569. package/server/DESIGN.md +194 -16
  570. package/server/DurableSubscriptionsSession.ts +71 -11
  571. package/server/REST.ts +115 -4
  572. package/server/graphqlQuerying.ts +4 -0
  573. package/server/http.ts +133 -20
  574. package/server/itc/serverHandlers.js +8 -1
  575. package/server/jobs/jobProcess.ts +8 -2
  576. package/server/jobs/jobs.ts +4 -1
  577. package/server/liveSubscriptionAuth.ts +129 -46
  578. package/server/loadRootComponents.js +50 -8
  579. package/server/mqtt.ts +179 -38
  580. package/server/nodeName.ts +103 -21
  581. package/server/serverHelpers/Headers.ts +135 -0
  582. package/server/serverHelpers/NodeAdapterResponse.ts +221 -0
  583. package/server/serverHelpers/Request.ts +33 -131
  584. package/server/serverHelpers/contentTypes.ts +217 -36
  585. package/server/serverHelpers/deployValidationState.ts +24 -13
  586. package/server/serverHelpers/operationAuthorizationState.ts +34 -3
  587. package/server/serverHelpers/registeredOperations.ts +79 -22
  588. package/server/serverHelpers/requestSanitization.ts +15 -0
  589. package/server/serverHelpers/serverHandlers.js +6 -3
  590. package/server/serverHelpers/serverUtilities.ts +232 -40
  591. package/server/serverHelpers/sharedMessageEncoding.ts +307 -0
  592. package/server/serverHelpers/uwsServer.ts +17 -2
  593. package/server/static.ts +23 -29
  594. package/server/storageReclamation.ts +15 -2
  595. package/server/threads/isolatedApplications.ts +157 -0
  596. package/server/threads/itc.js +11 -1
  597. package/server/threads/logRotationTransport.ts +40 -0
  598. package/server/threads/manageThreads.js +771 -66
  599. package/server/threads/socketRouter.ts +291 -30
  600. package/server/threads/threadHeapMemory.ts +26 -0
  601. package/server/threads/threadServer.js +73 -22
  602. package/sqlTranslator/index.ts +31 -8
  603. package/studio/web/assets/{Chat-4RrB5134.js → Chat-D3j-1yY1.js} +1 -1
  604. package/studio/web/assets/{FloatingChat-omlNMDcJ.js → FloatingChat-BxJGYcfB.js} +3 -3
  605. package/studio/web/assets/{apiToken-Bke3wvfZ.js → apiToken-CT55oWOe.js} +1 -1
  606. package/studio/web/assets/{applications-DvFDYJgK.js → applications-D9Ct9_vm.js} +1 -1
  607. package/studio/web/assets/{cssMode-C1vRa7zh.js → cssMode-DV8H7VwA.js} +1 -1
  608. package/studio/web/assets/{editor-3XRWEDWX.js → editor-uatc0unt.js} +1 -1
  609. package/studio/web/assets/{html-CTY5tdMr.js → html-Bm6D6paN.js} +1 -1
  610. package/studio/web/assets/{htmlMode-CG1vSD9t.js → htmlMode-CEn7tpLG.js} +1 -1
  611. package/studio/web/assets/{index-Dfpeofdu.js → index-BIXW6Pu4.js} +5 -5
  612. package/studio/web/assets/{index.lazy-B1VOIv-t.js → index.lazy-UI7L-Vrk.js} +1 -1
  613. package/studio/web/assets/{javascript-CJeJzGnI.js → javascript-CJ0G3AFZ.js} +1 -1
  614. package/studio/web/assets/{jsonMode-CYPBwM82.js → jsonMode-DQADAYEa.js} +1 -1
  615. package/studio/web/assets/{languageServices-IKH4GUHl.js → languageServices-CAQJXWcI.js} +1 -1
  616. package/studio/web/assets/{lspLanguageFeatures-BC8_gxKG.js → lspLanguageFeatures-CCQ8P5sY.js} +1 -1
  617. package/studio/web/assets/{notifications-BfKBpYcq.js → notifications-BbxTU6Aw.js} +1 -1
  618. package/studio/web/assets/{notifications-DFbArTfC.js → notifications-Cvb3P1lB.js} +1 -1
  619. package/studio/web/assets/{profile-Q4-T6c-S.js → profile-Yyb7gsvL.js} +1 -1
  620. package/studio/web/assets/{regions-CtkV0xje.js → regions-OgjGHlU5.js} +1 -1
  621. package/studio/web/assets/{register-1ZZuMsiA.js → register-6qwNEOY3.js} +2 -2
  622. package/studio/web/assets/{setComponentFile-ZWLcWv5X.js → setComponentFile-BilDMtgB.js} +1 -1
  623. package/studio/web/assets/{setup-DWprJyJy.js → setup-J6qJ7OIU.js} +2 -2
  624. package/studio/web/assets/{status--aNm8isn.js → status-0RWGcfyD.js} +1 -1
  625. package/studio/web/assets/{toggleHighContrast-Cq_lt3XD.js → toggleHighContrast-BIn-vErT.js} +1 -1
  626. package/studio/web/assets/{tsMode-pjgytARx.js → tsMode-DgUXku4d.js} +1 -1
  627. package/studio/web/assets/{typescript-Cdg0mqUh.js → typescript-C9orXcsM.js} +1 -1
  628. package/studio/web/assets/{useEntityRestURL-RZhaY8Rn.js → useEntityRestURL-BEoXXbUB.js} +1 -1
  629. package/studio/web/assets/{workers-BgoXIqQe.js → workers-JVzSDmgx.js} +1 -1
  630. package/studio/web/assets/{xml-BwSeDMiP.js → xml-Cq-S8S4X.js} +1 -1
  631. package/studio/web/assets/{yaml-DotCUG5l.js → yaml-sfoRdh1M.js} +1 -1
  632. package/studio/web/index.html +1 -1
  633. package/upgrade/directives/5-3-0.ts +132 -0
  634. package/upgrade/directives/directivesController.ts +2 -1
  635. package/utility/OperationFunctionCaller.ts +2 -1
  636. package/utility/common_utils.ts +30 -5
  637. package/utility/componentNames.ts +12 -0
  638. package/utility/environment/environmentManager.ts +3 -7
  639. package/utility/environment/systemInformation.ts +7 -0
  640. package/utility/errors/commonErrors.ts +4 -0
  641. package/utility/errors/hdbError.ts +57 -0
  642. package/utility/hdbTerms.ts +19 -0
  643. package/utility/logging/harper_logger.ts +278 -26
  644. package/utility/logging/logGenerationCoordinator.ts +196 -0
  645. package/utility/logging/logRotation.ts +367 -0
  646. package/utility/logging/logRotator.ts +213 -81
  647. package/utility/nodeIdentity.ts +45 -0
  648. package/utility/npmUtilities.ts +12 -8
  649. package/utility/operationPermissions.ts +18 -1
  650. package/utility/operation_authorization.ts +231 -42
  651. package/utility/watchPath.ts +63 -0
  652. package/utility/watcherFallback.ts +148 -0
  653. package/validation/configValidator.ts +215 -75
  654. package/validation/installValidator.ts +15 -0
  655. package/validation/validationWrapper.ts +18 -4
@@ -36,16 +36,38 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.Application = exports.GIT_CREDENTIAL_HELPER_PATH = exports.ASIDE_STAGING_DIR = exports.InvalidCredentialEntryError = exports.InvalidCredentialsPropertyError = exports.InvalidInstallTimeoutError = exports.InvalidInstallCommandError = exports.InvalidInstallPropertyError = exports.InvalidPackageIdentifierError = void 0;
39
+ exports.Application = exports.GIT_CREDENTIAL_HELPER_PATH = exports.DEPLOY_STAGING_DIR = exports.ASIDE_STAGING_DIR = exports.InvalidCredentialEntryError = exports.InvalidBranchedDatabasesError = exports.InvalidCredentialsPropertyError = exports.InvalidInstallTimeoutError = exports.InvalidInstallCommandError = exports.InvalidInstallPropertyError = exports.InvalidPackageIdentifierError = void 0;
40
40
  exports.assertApplicationConfig = assertApplicationConfig;
41
+ exports.assertIsolationConfig = assertIsolationConfig;
42
+ exports.assertBranchedDatabases = assertBranchedDatabases;
41
43
  exports.isSSHAuthFailure = isSSHAuthFailure;
42
44
  exports.parseGitReference = parseGitReference;
45
+ exports.packageHasProductionInstallWork = packageHasProductionInstallWork;
46
+ exports.packageHasAutomaticInstallWork = packageHasAutomaticInstallWork;
43
47
  exports.readInstalledPackageMetadata = readInstalledPackageMetadata;
44
48
  exports.installedPackageMetadataEqual = installedPackageMetadataEqual;
45
49
  exports.installedRuntimeChanged = installedRuntimeChanged;
46
50
  exports.extractApplication = extractApplication;
51
+ exports.getStagingRetentionMaxCount = getStagingRetentionMaxCount;
52
+ exports.pruneDormantBuilds = pruneDormantBuilds;
53
+ exports.candidateApplicationPath = candidateApplicationPath;
54
+ exports.makeRollbackPlaceholderMovable = makeRollbackPlaceholderMovable;
55
+ exports.publishClaimOwnership = publishClaimOwnership;
56
+ exports.splitAttributionOwners = splitAttributionOwners;
57
+ exports.unsettleableComponentsFromDisk = unsettleableComponentsFromDisk;
58
+ exports.recoverInterruptedActivations = recoverInterruptedActivations;
59
+ exports.reconcileDormantBuilds = reconcileDormantBuilds;
60
+ exports.markCandidateComplete = markCandidateComplete;
61
+ exports.activateCandidateApplication = activateCandidateApplication;
62
+ exports.buildCandidateApplication = buildCandidateApplication;
63
+ exports.recoverInterruptedComponentExtractions = recoverInterruptedComponentExtractions;
64
+ exports.recoverInterruptedComponentExtraction = recoverInterruptedComponentExtraction;
65
+ exports.retireComponentExtractionStaging = retireComponentExtractionStaging;
66
+ exports.dropComponentDirectory = dropComponentDirectory;
67
+ exports.packageManagerInstallArguments = packageManagerInstallArguments;
47
68
  exports.installApplication = installApplication;
48
69
  exports.derivePackageIdentifier = derivePackageIdentifier;
70
+ exports.shouldPackLocalDirectory = shouldPackLocalDirectory;
49
71
  exports.prepareApplication = prepareApplication;
50
72
  exports.installApplications = installApplications;
51
73
  exports.recordApplicationPreparation = recordApplicationPreparation;
@@ -59,6 +81,7 @@ exports.terminateProcessTree = terminateProcessTree;
59
81
  exports.getEnvBuiltInComponents = getEnvBuiltInComponents;
60
82
  const configUtils_ts_1 = require("../config/configUtils.js");
61
83
  const hdbTerms_ts_1 = require("../utility/hdbTerms.js");
84
+ const hdbError_ts_1 = require("../utility/errors/hdbError.js");
62
85
  const harper_logger_ts_1 = __importStar(require("../utility/logging/harper_logger.js"));
63
86
  const deployLifecycle_ts_1 = require("./deployLifecycle.js");
64
87
  const componentPreparationLock_ts_1 = require("./componentPreparationLock.js");
@@ -109,6 +132,12 @@ class InvalidCredentialsPropertyError extends TypeError {
109
132
  }
110
133
  }
111
134
  exports.InvalidCredentialsPropertyError = InvalidCredentialsPropertyError;
135
+ class InvalidBranchedDatabasesError extends TypeError {
136
+ constructor(applicationName, detail) {
137
+ super(`Invalid 'branchedDatabases' for application ${applicationName}: ${detail}`);
138
+ }
139
+ }
140
+ exports.InvalidBranchedDatabasesError = InvalidBranchedDatabasesError;
112
141
  class InvalidCredentialEntryError extends TypeError {
113
142
  constructor(applicationName) {
114
143
  super(`Invalid 'credentials' entry for application ${applicationName}: expected a { registry, secret, scope? } ` +
@@ -117,6 +146,15 @@ class InvalidCredentialEntryError extends TypeError {
117
146
  }
118
147
  exports.InvalidCredentialEntryError = InvalidCredentialEntryError;
119
148
  function assertApplicationConfig(applicationName, applicationConfig) {
149
+ // The deploy staging directory holds a candidate tree under the component's own name beside dot-prefixed
150
+ // control files, so a dot-prefixed component name collides with one of them — and an application named
151
+ // `.activation.json` puts its tree on the journal path, where the journal write takes EEXIST as "a retry
152
+ // of this activation" and the swap proceeds with no journal at all. Rejected HERE rather than tolerated
153
+ // downstream: nothing else validates a root-config application key.
154
+ if (!isJoinableComponentName(applicationName)) {
155
+ throw new Error(`Invalid application name '${applicationName}': it must be a single path segment and must not begin ` +
156
+ `with a dot, which is reserved for Harper's own deploy control files`);
157
+ }
120
158
  if (typeof applicationConfig.package !== 'string') {
121
159
  throw new InvalidPackageIdentifierError(applicationName, applicationConfig.package);
122
160
  }
@@ -162,6 +200,44 @@ function assertApplicationConfig(applicationName, applicationConfig) {
162
200
  }
163
201
  }
164
202
  }
203
+ assertBranchedDatabases(applicationName, applicationConfig.branchedDatabases);
204
+ assertIsolationConfig(applicationName, applicationConfig.isolated);
205
+ }
206
+ function assertIsolationConfig(applicationName, isolated) {
207
+ if (isolated !== undefined && typeof isolated !== 'boolean') {
208
+ throw new TypeError(`Invalid 'isolated' for application ${applicationName}: expected a boolean, got ${typeof isolated}`);
209
+ }
210
+ }
211
+ /**
212
+ * A branch that cannot be honoured fails the application's load: falling back would hand it the
213
+ * shared database it asked not to have, with no signal that it happened.
214
+ */
215
+ function assertBranchedDatabases(applicationName, value) {
216
+ if (value === undefined || value === true)
217
+ return;
218
+ if (!Array.isArray(value)) {
219
+ throw new InvalidBranchedDatabasesError(applicationName, `expected an array or true, got ${typeof value}`);
220
+ }
221
+ const seen = new Set();
222
+ for (const name of value) {
223
+ if (typeof name !== 'string' || name === '') {
224
+ throw new InvalidBranchedDatabasesError(applicationName, `expected database names, got ${typeof name}`);
225
+ }
226
+ // A branch is a directory named by this value; a separator or traversal segment would escape
227
+ // the reserved branch root.
228
+ if (name.includes('/') || name.includes('\\') || name === '.' || name === '..') {
229
+ throw new InvalidBranchedDatabasesError(applicationName, `'${name}' is not a usable database name`);
230
+ }
231
+ // `system` carries the instance's own catalog, users and jobs; a private fork of it would give
232
+ // the application a divergent view of the instance rather than of its data.
233
+ if (name === 'system') {
234
+ throw new InvalidBranchedDatabasesError(applicationName, `the 'system' database cannot be branched`);
235
+ }
236
+ if (seen.has(name)) {
237
+ throw new InvalidBranchedDatabasesError(applicationName, `'${name}' is listed more than once`);
238
+ }
239
+ seen.add(name);
240
+ }
165
241
  }
166
242
  /**
167
243
  * Returns true when npm/git stderr indicates an SSH authentication failure —
@@ -406,10 +482,42 @@ async function runNpmPack(application, packArgs, cwd, gitCredentialEnv) {
406
482
  // during a deploy swap (see extractApplication). The leading dot keeps
407
483
  // loadComponentDirectories from loading its contents as components.
408
484
  exports.ASIDE_STAGING_DIR = '.deploy-aside';
485
+ // Hidden directory under the components root holding per-deployment candidate builds. A candidate is
486
+ // extracted, installed AND validated here, and only then renamed into the live path, so the previous
487
+ // version keeps serving through the slow, failure-prone work. Dot-prefixed so the three scans over the
488
+ // components root (componentLoader, componentEnvPrepass, resolvePreload) skip it.
489
+ exports.DEPLOY_STAGING_DIR = '.deploy-staging';
490
+ const IN_PROGRESS_ASIDE_PREFIX = '.in-progress-';
491
+ const RETIRED_ASIDE_PREFIX = '.retired-';
492
+ const PRIOR_ABSENT_RECORD_SUFFIX = '-prior-absent';
409
493
  const DEFAULT_COMMAND_TIMEOUT_MS = 60 * 60 * 1000;
410
494
  const COMPONENT_PREPARATION_WAIT_MARGIN_MS = 30000;
495
+ const COMPONENT_RECOVERY_WAIT_TIMEOUT_MS = 30000;
496
+ const COMPONENT_RECOVERY_TRY_TIMEOUT_MS = 250;
497
+ /**
498
+ * Lock terms for the boot-time activation scan. It runs before every component load on every thread, so it
499
+ * probes rather than queues: the default is a two-hour wait that RENEWS while the holder is alive, which
500
+ * would park a respawning worker behind a deploy's `npm install` and load no components at all until it
501
+ * finished. A held lock means a live deploy, and a live deploy settles its own journal.
502
+ */
503
+ const RECOVERY_LOCK_WAIT = {
504
+ timeoutMs: COMPONENT_RECOVERY_TRY_TIMEOUT_MS,
505
+ renewTimeoutWhileOwnerAlive: false,
506
+ };
507
+ const COMPONENT_RECOVERY_LOCK_PURPOSE = 'component-recovery';
411
508
  const MAX_GIT_EXTRACTION_COMMANDS = 4;
412
509
  const MAX_INSTALL_COMMANDS = 2;
510
+ const PRODUCTION_DEPENDENCY_FIELDS = ['dependencies', 'optionalDependencies', 'peerDependencies'];
511
+ const INSTALL_LIFECYCLE_SCRIPTS = new Set([
512
+ 'preinstall',
513
+ 'install',
514
+ 'postinstall',
515
+ 'prepublish',
516
+ 'preprepare',
517
+ 'prepare',
518
+ 'postprepare',
519
+ 'dependencies',
520
+ ]);
413
521
  // The credential helper git executes for a private git-reference deploy. It ships alongside this
414
522
  // module (both in source and in dist), holds no secret, and is inert without a live session.
415
523
  exports.GIT_CREDENTIAL_HELPER_PATH = (0, node_path_1.join)(__dirname, 'gitCredentialHelper.js');
@@ -421,6 +529,47 @@ const PACKAGE_LOCK_FILES = [
421
529
  'bun.lock',
422
530
  'bun.lockb',
423
531
  ];
532
+ function dependencyFieldHasWork(packageJSON, field) {
533
+ if (!packageJSON || typeof packageJSON !== 'object' || !Object.hasOwn(packageJSON, field))
534
+ return false;
535
+ const value = packageJSON[field];
536
+ return !value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length > 0;
537
+ }
538
+ function packageHasProductionInstallWork(packageJSON) {
539
+ if (packageJSON === undefined)
540
+ return false;
541
+ if (!packageJSON || typeof packageJSON !== 'object' || Array.isArray(packageJSON))
542
+ return true;
543
+ if (PRODUCTION_DEPENDENCY_FIELDS.some((field) => dependencyFieldHasWork(packageJSON, field)))
544
+ return true;
545
+ if (!Object.hasOwn(packageJSON, 'workspaces'))
546
+ return false;
547
+ const workspaces = packageJSON.workspaces;
548
+ if (Array.isArray(workspaces))
549
+ return workspaces.length > 0;
550
+ if (!workspaces || typeof workspaces !== 'object' || !Object.hasOwn(workspaces, 'packages'))
551
+ return true;
552
+ return !Array.isArray(workspaces.packages) || workspaces.packages.length > 0;
553
+ }
554
+ function packageHasExplicitNonNpmManager(packageJSON) {
555
+ const packageManager = packageJSON?.devEngines?.packageManager;
556
+ return !!packageManager && packageManager.name !== 'npm';
557
+ }
558
+ function packageHasAutomaticInstallWork(packageJSON) {
559
+ return packageHasProductionInstallWork(packageJSON) || packageHasExplicitNonNpmManager(packageJSON);
560
+ }
561
+ function packageHasAllowedInstallLifecycleWork(packageJSON) {
562
+ if (!packageJSON || typeof packageJSON !== 'object' || !Object.hasOwn(packageJSON, 'scripts'))
563
+ return false;
564
+ const scripts = packageJSON.scripts;
565
+ if (!scripts || typeof scripts !== 'object' || Array.isArray(scripts))
566
+ return true;
567
+ return [...INSTALL_LIFECYCLE_SCRIPTS].some((name) => {
568
+ if (!Object.hasOwn(scripts, name))
569
+ return false;
570
+ return typeof scripts[name] !== 'string' || scripts[name].trim().length > 0;
571
+ });
572
+ }
424
573
  async function readInstalledPackageMetadata(directory) {
425
574
  const files = new Map();
426
575
  let readable = true;
@@ -456,13 +605,7 @@ async function readInstalledPackageMetadata(directory) {
456
605
  files,
457
606
  readable,
458
607
  hasLockfile: PACKAGE_LOCK_FILES.some((filename) => files.has(filename)),
459
- hasInstallableDependencies: ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'].some((field) => {
460
- const dependencies = packageJSON?.[field];
461
- return (typeof dependencies === 'object' &&
462
- dependencies !== null &&
463
- !Array.isArray(dependencies) &&
464
- Object.keys(dependencies).length > 0);
465
- }),
608
+ hasInstallableDependencies: packageHasAutomaticInstallWork(packageJSON),
466
609
  };
467
610
  }
468
611
  function installedPackageMetadataEqual(previous, current) {
@@ -489,26 +632,8 @@ function canonicalizeJSON(value) {
489
632
  canonical[key] = canonicalizeJSON(value[key]);
490
633
  return canonical;
491
634
  }
492
- /**
493
- * Extract an application given payload (content of the application) or package (npm-compatible identifier to the application).
494
- *
495
- * Only one of `application.payload` or `application.package` should be specified; otherwise, an error is thrown.
496
- *
497
- * Writes the application to the configured components root directory using the `application.name` and overwrites any existing directory.
498
- *
499
- * This method may be called from any Harper thread. Same-component calls are serialized across
500
- * threads by the preparation lock below.
501
- */
502
- async function extractApplication(application, deferCommit = false) {
503
- // Can't specify neither
504
- if (!application.payload && !application.packageIdentifier) {
505
- throw new Error('Either payload or package must be provided');
506
- }
507
- // Can't specify both
508
- if (application.payload && application.packageIdentifier) {
509
- throw new Error('Both payload and package cannot be provided');
510
- }
511
- // Resolve the tarball from the input
635
+ /** Resolve `payload` or `package` into a tarball stream. Touches neither the live tree nor staging. */
636
+ async function resolveApplicationTarball(application) {
512
637
  let tarballPath;
513
638
  let tarball;
514
639
  let shouldDeleteTarball = false;
@@ -530,6 +655,8 @@ async function extractApplication(application, deferCommit = false) {
530
655
  else {
531
656
  // Given a package, there are a a couple options
532
657
  const parentDirPath = (0, node_path_1.dirname)(application.dirPath);
658
+ let packageIdentifierForPack = application.packageIdentifier;
659
+ let packageNeedsPacking = true;
533
660
  // If the package identifier is a file path we need to check if its a tarball or a directory
534
661
  if (application.packageIdentifier.startsWith('file:')) {
535
662
  const packagePath = application.packageIdentifier.slice(5);
@@ -537,20 +664,29 @@ async function extractApplication(application, deferCommit = false) {
537
664
  // Have to remove the 'file:' prefix in order to use fs methods
538
665
  const stats = await (0, promises_1.stat)(packagePath);
539
666
  if (stats.isDirectory()) {
540
- // If its a directory, symlink
541
- await (0, promises_1.symlink)(packagePath, application.dirPath, 'dir');
542
- // And return early since we're done; no extraction needed
543
- return;
667
+ if (!application.packLocalDirectory) {
668
+ // Reported, not performed — the caller decides where the link goes, so a candidate build
669
+ // links at the candidate path rather than onto the live one.
670
+ return { kind: 'link', sourceDirPath: packagePath };
671
+ }
672
+ // Bare absolute Windows directory inputs historically materialize a copy through npm pack;
673
+ // explicit file: and relative directories remain live links.
674
+ packageIdentifierForPack = packagePath;
675
+ application.logger.debug?.('Packaging local component directory instead of linking it on Windows');
544
676
  }
545
- if (!stats.isFile()) {
546
- throw new Error(`File path specified in package identifier is not a file or directory: ${packagePath}`);
677
+ else {
678
+ if (!stats.isFile()) {
679
+ throw new Error(`File path specified in package identifier is not a file or directory: ${packagePath}`);
680
+ }
681
+ // If its a file, we assume it can be unzipped and extracted.
682
+ // We are using maybe-gunzip to handle both gzipped and non-gzipped tarballs
683
+ // And then we are happy to let the `tar-fs` library handle the extraction.
684
+ // Maybe worth adding some detection or at least some error handling if that step below fails.
685
+ tarballPath = packagePath;
686
+ tarball = (0, node_fs_1.createReadStream)(tarballPath);
687
+ packageNeedsPacking = false;
688
+ application.logger.debug?.('Using local component archive directly without npm pack');
547
689
  }
548
- // If its a file, we assume it can be unzipped and extracted.
549
- // We are using maybe-gunzip to handle both gzipped and non-gzipped tarballs
550
- // And then we are happy to let the `tar-fs` library handle the extraction.
551
- // Maybe worth adding some detection or at least some error handling if that step below fails.
552
- tarballPath = packagePath;
553
- tarball = (0, node_fs_1.createReadStream)(tarballPath);
554
690
  }
555
691
  catch (err) {
556
692
  if (err.code === 'ENOENT') {
@@ -561,7 +697,7 @@ async function extractApplication(application, deferCommit = false) {
561
697
  }
562
698
  }
563
699
  }
564
- else {
700
+ if (packageNeedsPacking) {
565
701
  // `npm pack --json` writes a JSON array describing the packed tarball(s). This is also the
566
702
  // spawn that clones a git-reference package, so it is the only one given the git credential
567
703
  // environment.
@@ -584,188 +720,2706 @@ async function extractApplication(application, deferCommit = false) {
584
720
  // packGitReferenceWithoutScripts), which is exactly what Node 22's bundled npm ships. For a
585
721
  // recognized git-reference identifier, clone and pack it ourselves with scripts stripped
586
722
  // instead, sidestepping that npm code path entirely.
587
- const gitRef = allowScripts ? null : parseGitReference(application.packageIdentifier);
588
- if (!allowScripts && !gitRef && looksLikeGitReference(application.packageIdentifier)) {
723
+ const gitRef = allowScripts ? null : parseGitReference(packageIdentifierForPack);
724
+ if (!allowScripts && !gitRef && looksLikeGitReference(packageIdentifierForPack)) {
589
725
  // Recognized as git, but a form the reclone-and-strip-scripts path above can't safely
590
726
  // handle (a `#path:` committish, or a hosted shorthand other than a plain `owner/repo`) —
591
727
  // fail loudly rather than silently falling through to the unreliable `npm pack
592
728
  // --ignore-scripts` below.
593
- throw new Error(`Cannot deploy git-reference package '${application.packageIdentifier}' with install scripts disallowed: this identifier's form (e.g. a '#path:' committish, or a hosted shorthand other than a plain 'owner/repo') isn't one this repo's script-suppression handling supports. Set install.allowInstallScripts to true, or use a plain git URL with a branch/tag/commit committish instead.`);
729
+ throw new Error(`Cannot deploy git-reference package '${packageIdentifierForPack}' with install scripts disallowed: this identifier's form (e.g. a '#path:' committish, or a hosted shorthand other than a plain 'owner/repo') isn't one this repo's script-suppression handling supports. Set install.allowInstallScripts to true, or use a plain git URL with a branch/tag/commit committish instead.`);
730
+ }
731
+ if (gitRef) {
732
+ tarballPath = await packGitReferenceWithoutScripts(application, gitRef, parentDirPath);
733
+ }
734
+ else {
735
+ const packArgs = ['pack', '--json', packageIdentifierForPack];
736
+ if (!allowScripts) {
737
+ packArgs.push('--ignore-scripts');
738
+ }
739
+ else if (application.gitCredentialEnv) {
740
+ application.logger.warn(`Deploying ${application.name} from a git reference with install scripts enabled: the repository's ` +
741
+ `prepare/build scripts and its dependencies' install scripts run on this node during the clone and ` +
742
+ `can read the git credential. Unset install_allow_scripts to keep the credential out of their reach.`);
743
+ }
744
+ tarballPath = await runNpmPack(application, packArgs, parentDirPath, application.gitCredentialEnv);
745
+ }
746
+ shouldDeleteTarball = true;
747
+ tarball = (0, node_fs_1.createReadStream)(tarballPath);
748
+ }
749
+ }
750
+ return { kind: 'tarball', tarball, tarballPath, shouldDeleteTarball };
751
+ }
752
+ /**
753
+ * Extract a tarball into `targetDirPath`, flattening the single wrapping directory npm pack produces.
754
+ * `scratchDirPath` must be on the same filesystem as the target: the flatten is done by renaming the
755
+ * wrapper out and back rather than copying, so it stays atomic per entry. Windows moves the children
756
+ * individually because renaming a directory over its own parent's path fails there.
757
+ */
758
+ async function extractTarballInto(tarball, targetDirPath, scratchDirPath) {
759
+ await (0, promises_1.mkdir)(targetDirPath, { recursive: true });
760
+ await (0, promises_2.pipeline)(tarball, (0, gunzip_maybe_1.default)(), (0, tar_fs_1.extract)(targetDirPath));
761
+ const extracted = await (0, promises_1.readdir)(targetDirPath, { withFileTypes: true });
762
+ if (extracted.length === 1 && extracted[0].isDirectory()) {
763
+ const topLevelDirPath = (0, node_path_1.join)(targetDirPath, extracted[0].name);
764
+ if (process.platform === 'win32') {
765
+ for (const childName of await (0, promises_1.readdir)(topLevelDirPath)) {
766
+ await (0, promises_1.rename)((0, node_path_1.join)(topLevelDirPath, childName), (0, node_path_1.join)(targetDirPath, childName));
767
+ }
768
+ await (0, promises_1.rmdir)(topLevelDirPath);
769
+ }
770
+ else {
771
+ const tempDirPath = (0, node_path_1.join)(scratchDirPath, `.normalize-${process.pid}-${Date.now()}-${(0, node_crypto_1.randomUUID)()}`);
772
+ await (0, promises_1.rename)(topLevelDirPath, tempDirPath);
773
+ await (0, promises_1.rmdir)(targetDirPath);
774
+ await (0, promises_1.rename)(tempDirPath, targetDirPath);
775
+ return tempDirPath;
776
+ }
777
+ }
778
+ return undefined;
779
+ }
780
+ /**
781
+ * Extract an application given payload (content of the application) or package (npm-compatible identifier to the application).
782
+ *
783
+ * Only one of `application.payload` or `application.package` should be specified; otherwise, an error is thrown.
784
+ *
785
+ * Writes the application to the configured components root directory using the `application.name` and overwrites any existing directory.
786
+ *
787
+ * This method may be called from any Harper thread. Same-component calls are serialized across
788
+ * threads by the preparation lock below.
789
+ */
790
+ async function extractApplication(application, deferCommit = false) {
791
+ // Can't specify neither
792
+ if (!application.payload && !application.packageIdentifier) {
793
+ throw new Error('Either payload or package must be provided');
794
+ }
795
+ // Can't specify both
796
+ if (application.payload && application.packageIdentifier) {
797
+ throw new Error('Both payload and package cannot be provided');
798
+ }
799
+ // Resolve the tarball from the input
800
+ const resolved = await resolveApplicationTarball(application);
801
+ if (resolved.kind === 'link') {
802
+ // Unchanged behavior for this path: a `file:` directory is linked in place, no extraction.
803
+ await (0, promises_1.symlink)(resolved.sourceDirPath, application.dirPath, 'dir');
804
+ return;
805
+ }
806
+ const { tarball, tarballPath, shouldDeleteTarball } = resolved;
807
+ // Replace any existing component directory atomically instead of clearing it in
808
+ // place. A previous version's worker can still be running and actively writing
809
+ // into this directory — e.g. a live Next.js app writing into `.next/cache` — and
810
+ // an in-place recursive rm races that writer: rm empties `.next`, then its leaf
811
+ // `rmdir('.next')` fails with ENOTEMPTY because the worker just re-created a cache
812
+ // entry. (`force: true` only suppresses ENOENT; ENOTEMPTY is not retried unless
813
+ // `maxRetries` is set, and a continuously-writing app would outlast retries
814
+ // anyway.) Renaming the old directory aside is atomic and immune to the race: the
815
+ // still-running worker keeps writing into the renamed inode harmlessly until it's
816
+ // replaced on restart. The aside remains the rollback/recovery record until commit
817
+ // marks it retired and cleanup removes it.
818
+ //
819
+ // The aside lives under a hidden, component-scoped staging directory inside the
820
+ // components root: same filesystem as the source so the rename stays atomic, the
821
+ // leading dot keeps loadComponentDirectories from picking it up as a phantom
822
+ // component, and the per-component path means a sibling component never collides
823
+ // with (or sweeps) another's aside.
824
+ const asideStagingDir = extractionStagingDirectory(application.dirPath);
825
+ const transactionPaths = new Set();
826
+ let asidePath;
827
+ let recoveryRecordPath;
828
+ try {
829
+ await ensureExtractionStagingDirectory(asideStagingDir);
830
+ await recoverOrCleanupStaleExtractionPaths(application, asideStagingDir);
831
+ let componentExists = true;
832
+ try {
833
+ await (0, promises_1.lstat)(application.dirPath);
834
+ }
835
+ catch (error) {
836
+ if (error.code !== 'ENOENT')
837
+ throw error;
838
+ componentExists = false;
839
+ }
840
+ if (componentExists) {
841
+ await ensureExtractionStagingDirectory(asideStagingDir);
842
+ asidePath = (0, node_path_1.join)(asideStagingDir, `${IN_PROGRESS_ASIDE_PREFIX}${Date.now()}-${process.pid}-${(0, node_crypto_1.randomUUID)()}`);
843
+ await (0, promises_1.rename)(application.dirPath, asidePath);
844
+ transactionPaths.add(asidePath);
845
+ recoveryRecordPath = asidePath;
846
+ }
847
+ else {
848
+ await ensureExtractionStagingDirectory(asideStagingDir);
849
+ recoveryRecordPath = (0, node_path_1.join)(asideStagingDir, `${IN_PROGRESS_ASIDE_PREFIX}${Date.now()}-${process.pid}-${(0, node_crypto_1.randomUUID)()}${PRIOR_ABSENT_RECORD_SUFFIX}`);
850
+ await (0, promises_1.writeFile)(recoveryRecordPath, '', { flag: 'wx', mode: 0o600 });
851
+ transactionPaths.add(recoveryRecordPath);
852
+ }
853
+ if (asidePath)
854
+ application.isNewComponent = false;
855
+ try {
856
+ // The scratch dir for the pack-wrapper flatten has to be on the component root's filesystem, and
857
+ // is a transaction path so a crash mid-flatten is cleaned up with the rest.
858
+ await ensureExtractionStagingDirectory(asideStagingDir);
859
+ const normalizeTempPath = await extractTarballInto(tarball, application.dirPath, asideStagingDir);
860
+ if (normalizeTempPath)
861
+ transactionPaths.add(normalizeTempPath);
862
+ }
863
+ catch (error) {
864
+ try {
865
+ await rollbackExtractedDirectory(application, asideStagingDir, asidePath, transactionPaths, false);
866
+ }
867
+ catch (rollbackError) {
868
+ throw new AggregateError([error, rollbackError], `Failed to extract ${application.name}: ${errorMessage(error)}; ` +
869
+ `also failed to restore its previous component directory: ${errorMessage(rollbackError)}`);
870
+ }
871
+ throw error;
872
+ }
873
+ }
874
+ finally {
875
+ if (!tarball.destroyed)
876
+ tarball.destroy();
877
+ if (shouldDeleteTarball && tarballPath) {
878
+ await (0, promises_1.rm)(tarballPath, { force: true }).catch((error) => application.logger.warn(`Failed to remove temporary package ${tarballPath}:`, error));
879
+ }
880
+ }
881
+ let settled = false;
882
+ const transaction = {
883
+ async commit() {
884
+ if (settled)
885
+ return;
886
+ const retiredMarkerPath = await retireExtractionAside(recoveryRecordPath);
887
+ transactionPaths.add(retiredMarkerPath);
888
+ settled = true;
889
+ await cleanupExtractionPaths(application, asideStagingDir, transactionPaths);
890
+ },
891
+ async rollback() {
892
+ if (settled)
893
+ return;
894
+ await rollbackExtractedDirectory(application, asideStagingDir, asidePath, transactionPaths, true);
895
+ settled = true;
896
+ },
897
+ };
898
+ if (deferCommit)
899
+ return transaction;
900
+ await transaction.commit();
901
+ }
902
+ // Written into a candidate's deployment directory once its build and its validation have BOTH succeeded.
903
+ // Roll-forward authority: recovery may activate an interrupted candidate only if this is present.
904
+ // Every control file is dot-prefixed, and `isJoinableComponentName` rejects a leading dot: a deployment
905
+ // directory holds the candidate tree under the COMPONENT'S name beside these, so an undotted name would
906
+ // share that namespace. A component named `activation.json` would put its tree on the journal path, the
907
+ // journal write would take EEXIST as "a retry of this activation", and the swap would proceed with no
908
+ // journal to hold the legacy pass back; one named `unsettled` would make every settle throw on a
909
+ // non-recursive `rm` of a directory. `assertApplicationConfig` rejects any name `isJoinableComponentName`
910
+ // rejects, so the collision is unreachable from a root-config key as well as from a deploy.
911
+ const CANDIDATE_COMPLETE_MARKER = '.complete';
912
+ // Records activation intent beside the candidate, so recovery finishes or undoes the whole transaction —
913
+ // tree and configuration together — instead of inferring intent from filesystem shape alone.
914
+ const ACTIVATION_JOURNAL = '.activation.json';
915
+ // The component this deployment directory belongs to, as plain text in its own file. Redundant with the
916
+ // journal on purpose: after the swap the candidate has moved to the live path, so a journal that cannot be
917
+ // parsed leaves nothing to infer the component from — and a failure keyed by deployment id fails NOTHING
918
+ // closed, letting the component load over state nobody reconciled.
919
+ const CANDIDATE_COMPONENT_FILE = '.component';
920
+ // Written by main-thread recovery when it could not settle an activation whose journal is otherwise
921
+ // well-formed. Workers cannot infer that case: a well-formed journal is indistinguishable from one belonging
922
+ // to a deploy in flight, so without a record they would treat an unsettled component as healthy and load it.
923
+ const UNSETTLED_MARKER = '.unsettled';
924
+ // Everything the build decided that a later activation cannot re-derive: the root-config entry to publish,
925
+ // whether the installation is opaque to metadata comparison, and the isolation intent that was admitted.
926
+ // Written before `.complete`, so the marker vouches for it. An OPTIONAL record would not do: it could not
927
+ // distinguish a payload build, which owns no root config, from a package build whose record was lost.
928
+ const CANDIDATE_ARTIFACT_FILE = '.artifact.json';
929
+ const ACTIVATION_JOURNAL_VERSION = 1;
930
+ const ARTIFACT_DESCRIPTOR_VERSION = 1;
931
+ const DEFAULT_STAGING_RETENTION_MAX_COUNT = 5;
932
+ /** `deployment_stagingRetention_maxCount`; 0 keeps none. Only a number or numeric string counts, so `true`/`[]`/blank cannot become "keep nothing". */
933
+ function getStagingRetentionMaxCount() {
934
+ const configured = (0, configUtils_ts_1.getConfigValue)(hdbTerms_ts_1.CONFIG_PARAMS.DEPLOYMENT_STAGINGRETENTION_MAXCOUNT);
935
+ if (typeof configured !== 'number' && typeof configured !== 'string')
936
+ return DEFAULT_STAGING_RETENTION_MAX_COUNT;
937
+ if (typeof configured === 'string' && configured.trim() === '')
938
+ return DEFAULT_STAGING_RETENTION_MAX_COUNT;
939
+ const parsed = Number(configured);
940
+ return Number.isFinite(parsed) && parsed >= 0 ? Math.floor(parsed) : DEFAULT_STAGING_RETENTION_MAX_COUNT;
941
+ }
942
+ async function presentOrAbsent(path) {
943
+ return (0, promises_1.lstat)(path).catch((error) => {
944
+ if (error?.code === 'ENOENT')
945
+ return undefined;
946
+ throw error;
947
+ });
948
+ }
949
+ /**
950
+ * A dormant build: complete, tree present, no journal. Activation writes `.complete` moments before its
951
+ * journal under the owner's preparation lock, so only a read under that lock is a verdict. A stale
952
+ * `.unsettled` makes it residue instead, since only removing the directory clears that marker for workers.
953
+ * Only ENOENT is absence; any other read error propagates so the caller preserves the entry.
954
+ */
955
+ async function dormantBuildAt(deploymentDirPath, owner) {
956
+ const complete = await presentOrAbsent((0, node_path_1.join)(deploymentDirPath, CANDIDATE_COMPLETE_MARKER));
957
+ if (!complete)
958
+ return undefined;
959
+ if (await presentOrAbsent((0, node_path_1.join)(deploymentDirPath, UNSETTLED_MARKER)))
960
+ return undefined;
961
+ const tree = await presentOrAbsent((0, node_path_1.join)(deploymentDirPath, owner));
962
+ if (!tree || !(tree.isDirectory() || tree.isSymbolicLink()))
963
+ return undefined;
964
+ return { deploymentDirPath, deploymentId: (0, node_path_1.basename)(deploymentDirPath), completedAt: complete.mtimeMs };
965
+ }
966
+ /**
967
+ * Remove the oldest dormant builds beyond `maxCount`. The caller must hold the component's preparation lock;
968
+ * every catalogued build is re-derived under it before the kept set is chosen, so a catalog read unlocked
969
+ * cannot hold or miss a slot. Never throws: a failure must neither fail a component closed nor replace a
970
+ * deploy's own error.
971
+ *
972
+ * `pinnedDeploymentId` is never evicted. A delayed activation runs this preamble under the same lock it is
973
+ * about to activate under, so without the pin retention would delete the artifact the request named —
974
+ * immediately, when the knob is `0`. The pin is applied after the kept set is chosen, so a pinned build in
975
+ * the eviction tail leaves `maxCount + 1` on disk for the life of the request; the next preamble that does
976
+ * not pin it brings the count back down.
977
+ */
978
+ async function pruneDormantBuilds(componentName, builds, maxCount, pinnedDeploymentId) {
979
+ const current = [];
980
+ for (const build of builds) {
981
+ try {
982
+ const fresh = await dormantBuildAt(build.deploymentDirPath, componentName);
983
+ if (fresh && !(await presentOrAbsent((0, node_path_1.join)(build.deploymentDirPath, ACTIVATION_JOURNAL))))
984
+ current.push(fresh);
985
+ }
986
+ catch (error) {
987
+ harper_logger_ts_1.default.warn(`Leaving deploy staging ${build.deploymentDirPath} out of retention; it could not be read:`, (0, harper_logger_ts_1.errorForLog)(error));
988
+ }
989
+ }
990
+ const evictions = current
991
+ .sort((left, right) => right.completedAt - left.completedAt ||
992
+ (left.deploymentId < right.deploymentId ? -1 : left.deploymentId > right.deploymentId ? 1 : 0))
993
+ .slice(Math.max(0, maxCount))
994
+ .filter((build) => build.deploymentId !== pinnedDeploymentId);
995
+ for (const build of evictions) {
996
+ try {
997
+ await (0, promises_1.rm)(build.deploymentDirPath, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
998
+ harper_logger_ts_1.default.debug?.(`Pruned dormant staged build ${build.deploymentId} of ${componentName} beyond deployment_stagingRetention_maxCount=${maxCount}`);
999
+ }
1000
+ catch (error) {
1001
+ harper_logger_ts_1.default.warn(`Could not prune dormant staged build ${build.deploymentDirPath} of ${componentName}; it remains beyond ` +
1002
+ `deployment_stagingRetention_maxCount=${maxCount}:`, (0, harper_logger_ts_1.errorForLog)(error));
1003
+ }
1004
+ }
1005
+ }
1006
+ /** Every dormant build a component owns; an unreadable directory is left out and logged. */
1007
+ async function dormantBuildsOf(componentsRootDirPath, componentName) {
1008
+ const stagingRoot = (0, node_path_1.join)(componentsRootDirPath, exports.DEPLOY_STAGING_DIR);
1009
+ let deployments;
1010
+ try {
1011
+ deployments = await (0, promises_1.readdir)(stagingRoot, { withFileTypes: true });
1012
+ }
1013
+ catch (error) {
1014
+ if (error.code === 'ENOENT')
1015
+ return [];
1016
+ throw error;
1017
+ }
1018
+ const builds = [];
1019
+ for (const deployment of deployments) {
1020
+ if (!deployment.isDirectory())
1021
+ continue;
1022
+ const deploymentDirPath = (0, node_path_1.join)(stagingRoot, deployment.name);
1023
+ try {
1024
+ if ((await candidateComponentName(deploymentDirPath)) !== componentName)
1025
+ continue;
1026
+ if (await presentOrAbsent((0, node_path_1.join)(deploymentDirPath, ACTIVATION_JOURNAL)))
1027
+ continue;
1028
+ const build = await dormantBuildAt(deploymentDirPath, componentName);
1029
+ if (build)
1030
+ builds.push(build);
1031
+ }
1032
+ catch (error) {
1033
+ harper_logger_ts_1.default.warn(`Leaving deploy staging ${deploymentDirPath} out of retention; it could not be read:`, (0, harper_logger_ts_1.errorForLog)(error));
1034
+ }
1035
+ }
1036
+ return builds;
1037
+ }
1038
+ /**
1039
+ * Best-effort fsync of a directory. Best-effort by necessity — Node cannot fsync a directory on Windows —
1040
+ * which is why roll-forward requires journal + candidate + complete marker to all be observable: a lost
1041
+ * directory update then degrades to a roll back, never to a wrong decision. See DESIGN.md.
1042
+ */
1043
+ async function syncDirectory(dirPath) {
1044
+ let handle;
1045
+ try {
1046
+ handle = await (0, promises_1.open)(dirPath, 'r');
1047
+ }
1048
+ catch (error) {
1049
+ // Same split as `sync` below and as the file path: Windows cannot open a directory for fsync at all,
1050
+ // and a directory removed by cleanup is not a fault either — but an EIO opening it is.
1051
+ if (!isUnsupportedSync(error) && error?.code !== 'ENOENT')
1052
+ throw error;
1053
+ harper_logger_ts_1.default.trace?.(`Directory sync of ${dirPath} unavailable: ${errorMessage(error)}`);
1054
+ return;
1055
+ }
1056
+ try {
1057
+ await handle.sync();
1058
+ }
1059
+ catch (error) {
1060
+ // A platform that will not sync directories is tolerated, a storage failure is not: suppressing
1061
+ // EIO/ENOSPC here would let a lost directory entry look durable. The `finally` closes the handle.
1062
+ if (!isUnsupportedSync(error))
1063
+ throw error;
1064
+ harper_logger_ts_1.default.trace?.(`Directory sync of ${dirPath} unsupported: ${errorMessage(error)}`);
1065
+ }
1066
+ finally {
1067
+ // Swallowed: this runs outside any compensation block, so a rejecting close would surface as an
1068
+ // activation failure for something already best-effort.
1069
+ await handle.close().catch((error) => harper_logger_ts_1.default.trace?.(`Closing ${dirPath} failed: ${errorMessage(error)}`));
1070
+ }
1071
+ }
1072
+ /**
1073
+ * A rename changes an entry in BOTH parents, so both are synced: a surviving source entry reads as
1074
+ * "candidate still there" and would roll an already-completed activation forward twice.
1075
+ */
1076
+ async function syncRenameParents(fromPath, toPath) {
1077
+ const parents = new Set([(0, node_path_1.dirname)(fromPath), (0, node_path_1.dirname)(toPath)]);
1078
+ for (const parent of parents)
1079
+ await syncDirectory(parent);
1080
+ }
1081
+ // Deliberately NOT `EEXIST`/`ENOTEMPTY`/`ENOTDIR`/`EISDIR`: those say the destination exists, which
1082
+ // nothing here clears between attempts, so waiting on them would only delay reporting a tree something
1083
+ // recreated — the case `settleInterruptedActivation` fails closed rather than guessing.
1084
+ // `rollbackExtractedDirectory` does retry them, because its placeholder logic repairs the destination.
1085
+ const TRANSIENT_RENAME_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']);
1086
+ const RENAME_RETRY_BUDGET_MS = 5000;
1087
+ const RENAME_RETRY_INITIAL_DELAY_MS = 10;
1088
+ const RENAME_RETRY_MAX_DELAY_MS = 500;
1089
+ /**
1090
+ * Rename, waiting out a holder that has not let go yet — on Windows a rename is refused outright while
1091
+ * anything still has a handle in the source tree.
1092
+ *
1093
+ * `onBackoff` replaces the sleep between attempts; `deadline` lets a rename it performs share this
1094
+ * call's budget instead of opening its own.
1095
+ */
1096
+ async function renameThroughTransientHolder(fromPath, toPath, options = {}) {
1097
+ const deadline = options.deadline ?? performance.now() + RENAME_RETRY_BUDGET_MS;
1098
+ let delayMs = RENAME_RETRY_INITIAL_DELAY_MS;
1099
+ for (let attempts = 1;; attempts++) {
1100
+ try {
1101
+ await (0, promises_1.rename)(fromPath, toPath);
1102
+ if (attempts > 1) {
1103
+ harper_logger_ts_1.default.warn(`Renamed ${fromPath} to ${toPath} only on attempt ${attempts}; something was holding it`);
1104
+ }
1105
+ return;
1106
+ }
1107
+ catch (error) {
1108
+ const code = error.code ?? '';
1109
+ if (!TRANSIENT_RENAME_CODES.has(code))
1110
+ throw error;
1111
+ if (performance.now() >= deadline) {
1112
+ // Which side was still there separates a holder on the source from a destination something
1113
+ // recreated, and neither survives on the rethrown error. A failed probe reports its own code:
1114
+ // an `EPERM` reading the destination is itself evidence, and calling it absent would send the
1115
+ // next investigation the wrong way.
1116
+ const state = async (path) => (0, promises_1.lstat)(path).then(() => 'present', (probeError) => probeError?.code ?? 'unreadable');
1117
+ harper_logger_ts_1.default.warn(`Could not rename ${fromPath} to ${toPath}: ${code} after ${attempts} attempts ` +
1118
+ `(source ${await state(fromPath)}, destination ${await state(toPath)})`);
1119
+ throw error;
1120
+ }
1121
+ if (options.onBackoff)
1122
+ await options.onBackoff(delayMs, deadline);
1123
+ else
1124
+ await (0, promises_3.setTimeout)(delayMs);
1125
+ delayMs = Math.min(delayMs * 2, RENAME_RETRY_MAX_DELAY_MS);
1126
+ }
1127
+ }
1128
+ }
1129
+ /**
1130
+ * Write a control file so its final name NEVER exists with partial contents. Opening the final path with
1131
+ * `wx` publishes the directory entry before anything is written, so a crash in between leaves a zero-byte
1132
+ * file — which for the journal means "unreadable", failing a component closed over a deploy that had not
1133
+ * actually started. Contents land in a temp name, are fsynced, and only then renamed into place.
1134
+ */
1135
+ async function writeControlFileDurably(filePath, contents) {
1136
+ const tempPath = `${filePath}.partial-${process.pid}-${(0, node_crypto_1.randomUUID)()}`;
1137
+ const handle = await (0, promises_1.open)(tempPath, 'wx', 0o600);
1138
+ try {
1139
+ await handle.writeFile(contents, 'utf8');
1140
+ await handle.sync();
1141
+ }
1142
+ finally {
1143
+ await handle.close();
1144
+ }
1145
+ try {
1146
+ // `wx` on the temp name plus this rename keeps the EEXIST semantics callers rely on to detect a
1147
+ // retry of the same activation.
1148
+ await (0, promises_1.link)(tempPath, filePath);
1149
+ }
1150
+ finally {
1151
+ await (0, promises_1.rm)(tempPath, { force: true });
1152
+ }
1153
+ await syncDirectory((0, node_path_1.dirname)(filePath));
1154
+ }
1155
+ function candidateCompleteMarkerPath(componentDirPath, deploymentId) {
1156
+ return (0, node_path_1.join)(candidateDeploymentDirPath(componentDirPath, deploymentId), CANDIDATE_COMPLETE_MARKER);
1157
+ }
1158
+ function candidateComponentFilePath(componentDirPath, deploymentId) {
1159
+ return (0, node_path_1.join)(candidateDeploymentDirPath(componentDirPath, deploymentId), CANDIDATE_COMPONENT_FILE);
1160
+ }
1161
+ function activationJournalPath(componentDirPath, deploymentId) {
1162
+ return (0, node_path_1.join)(candidateDeploymentDirPath(componentDirPath, deploymentId), ACTIVATION_JOURNAL);
1163
+ }
1164
+ function candidateArtifactFilePath(componentDirPath, deploymentId) {
1165
+ return (0, node_path_1.join)(candidateDeploymentDirPath(componentDirPath, deploymentId), CANDIDATE_ARTIFACT_FILE);
1166
+ }
1167
+ /**
1168
+ * Read and fully validate a staged artifact's descriptor. Every field is checked, not just the ones the
1169
+ * caller happens to use: a descriptor is activation input for a build this process did not make, possibly
1170
+ * not even on this node, so a partially-checked one is a way to activate under someone else's intent.
1171
+ * Absence is `undefined`; anything present but unusable throws, because a staged artifact that cannot
1172
+ * describe itself must be refused rather than activated under defaults.
1173
+ */
1174
+ async function readArtifactDescriptor(deploymentDirPath, componentName) {
1175
+ const descriptorPath = (0, node_path_1.join)(deploymentDirPath, CANDIDATE_ARTIFACT_FILE);
1176
+ // The artifact the caller named exists and is theirs, but does not describe a build this can activate —
1177
+ // a conflict with what is on disk, not a server fault.
1178
+ const unusable = (message) => new hdbError_ts_1.ClientError(message, 409);
1179
+ const raw = await (0, promises_1.readFile)(descriptorPath, 'utf8').catch((error) => {
1180
+ if (error?.code === 'ENOENT')
1181
+ return undefined;
1182
+ throw error;
1183
+ });
1184
+ if (raw === undefined)
1185
+ return undefined;
1186
+ let parsed;
1187
+ try {
1188
+ parsed = JSON.parse(raw);
1189
+ }
1190
+ catch (error) {
1191
+ throw unusable(`Artifact descriptor ${descriptorPath} is not readable JSON: ${errorMessage(error)}`);
1192
+ }
1193
+ if (!parsed || typeof parsed !== 'object' || parsed.v !== ARTIFACT_DESCRIPTOR_VERSION) {
1194
+ throw unusable(`Artifact descriptor ${descriptorPath} is version ${parsed?.v}, which this build cannot activate`);
1195
+ }
1196
+ if (!isJoinableComponentName(parsed.component) || parsed.component !== componentName) {
1197
+ throw unusable(`Artifact descriptor ${descriptorPath} names component '${parsed.component}', not '${componentName}'`);
1198
+ }
1199
+ if (typeof parsed.installationIsOpaque !== 'boolean' || typeof parsed.isolated !== 'boolean') {
1200
+ throw unusable(`Artifact descriptor ${descriptorPath} does not record its build's runtime decisions`);
1201
+ }
1202
+ if (parsed.rootConfig !== null && (typeof parsed.rootConfig !== 'object' || Array.isArray(parsed.rootConfig))) {
1203
+ throw unusable(`Artifact descriptor ${descriptorPath} does not record a root-config entry or its absence`);
1204
+ }
1205
+ // Admission reads one field and publication writes the other, so two authorities that disagree would
1206
+ // admit one isolation and then publish the opposite.
1207
+ if (parsed.rootConfig && Boolean(parsed.rootConfig.isolated) !== parsed.isolated) {
1208
+ throw unusable(`Artifact descriptor ${descriptorPath} admits isolated=${parsed.isolated} but publishes ` +
1209
+ `isolated=${Boolean(parsed.rootConfig.isolated)}`);
1210
+ }
1211
+ return parsed;
1212
+ }
1213
+ const SEPARATORS_IN_LINK_TARGETS = process.platform === 'win32' ? /[\\/]/ : /\//;
1214
+ // `node_modules/harper` and `node_modules/harperdb` are links the LOADER owns: it points them at the
1215
+ // running install on every non-root component load and repairs them when they are missing or stale. They
1216
+ // are outside the artifact by construction and by design, so they are the one external link a staged
1217
+ // artifact may carry.
1218
+ const LOADER_OWNED_LINKS = new Set(['harper', 'harperdb']);
1219
+ /**
1220
+ * Reject a staged artifact that reaches outside itself.
1221
+ *
1222
+ * Certification fsyncs the tree but follows no links, and the post-swap relocation repair deliberately
1223
+ * leaves external targets alone — so a symlink into a directory this artifact does not own is a hole in
1224
+ * "activate exactly the bytes that were certified": the target can be edited, or replaced wholesale,
1225
+ * between the stage and the activation. An immediate deploy is not exposed to this, because certification
1226
+ * and activation happen within one call; the delay is what makes it reachable.
1227
+ *
1228
+ */
1229
+ async function assertOwnedArtifactTree(candidateDirPath, componentName, action = 'stage') {
1230
+ // The operator supplied a component that cannot be staged (400); or the artifact they named exists and is
1231
+ // theirs but is no longer what was certified (409). Neither is a server fault, and both reached the
1232
+ // operations handler as a bare 500 until a live run showed what that looks like to a caller.
1233
+ const refuse = (message) => new hdbError_ts_1.ClientError(message, action === 'stage' ? 400 : 409);
1234
+ const ownedRoot = await (0, promises_1.realpath)(candidateDirPath);
1235
+ // The loader repairs the component's OWN `node_modules/harper`, not a copy nested inside a dependency,
1236
+ // so only that one path is exempt. Matching the name at any depth would let `dep/node_modules/harper`
1237
+ // point anywhere and still pass.
1238
+ const loaderOwnedDir = (0, node_path_1.join)(candidateDirPath, 'node_modules');
1239
+ const walk = async (dirPath) => {
1240
+ const entries = await (0, promises_1.readdir)(dirPath, { withFileTypes: true });
1241
+ for (const entry of entries) {
1242
+ const entryPath = (0, node_path_1.join)(dirPath, entry.name);
1243
+ if (entry.isDirectory()) {
1244
+ await walk(entryPath);
1245
+ continue;
1246
+ }
1247
+ // Junctions report as symbolic links here, which is what makes this cover Windows.
1248
+ if (!entry.isSymbolicLink())
1249
+ continue;
1250
+ if (LOADER_OWNED_LINKS.has(entry.name) && dirPath === loaderOwnedDir)
1251
+ continue;
1252
+ // An unresolvable link is rejected for the same reason a foreign one is: nothing certified what
1253
+ // it will resolve to by the time somebody activates it.
1254
+ const target = await (0, promises_1.realpath)(entryPath).catch(() => undefined);
1255
+ if (target === undefined || (target !== ownedRoot && !target.startsWith(ownedRoot + node_path_1.sep))) {
1256
+ throw refuse(`Cannot ${action} ${componentName}: ${entryPath} links outside the build to ${target ?? 'a missing target'}, ` +
1257
+ `so the bytes activated later would not be the bytes this build certified`);
1258
+ }
1259
+ // `repairRelocatedDependencyLinks` re-points links after the swap, but it runs PAST THE COMMIT
1260
+ // POINT and can only warn — it logs and continues on a failed re-point, and skips a whole subtree
1261
+ // on EACCES/EMFILE — so a component could go live holding a link to a path that no longer exists
1262
+ // while the operation reports success. Staging fails closed instead. The cost: npm writes absolute
1263
+ // junctions under `node_modules` on Windows for a `file:`/workspace dependency, so such a component
1264
+ // deploys immediately but cannot be staged until its links are relative.
1265
+ const linkTarget = await (0, promises_1.readlink)(entryPath);
1266
+ if ((0, node_path_1.isAbsolute)(linkTarget)) {
1267
+ throw refuse(`Cannot ${action} ${componentName}: ${entryPath} names its target inside the build by absolute path ` +
1268
+ `(${linkTarget}), which activation moves. Re-link it relatively — on Windows, npm ` +
1269
+ `writes absolute junctions for 'file:' and workspace dependencies, so those have to be relative ` +
1270
+ `before the component can be staged.`);
1271
+ }
1272
+ // Where the link ENDS UP is not enough: a target that leaves the candidate and comes back resolves
1273
+ // inside it today and somewhere else once activation renames the tree, because the same relative
1274
+ // expression is then evaluated from `components/<component>/…`. Counting `..` segments does not
1275
+ // catch it either, since an intermediate symlink (`up -> ..`) reduces depth without spelling it.
1276
+ // So every PREFIX of the walk is resolved, with symlinks followed as the filesystem will follow
1277
+ // them, and each one has to still be inside the candidate.
1278
+ let prefix = (0, node_path_1.dirname)(entryPath);
1279
+ // Only Windows treats a backslash as a separator. On POSIX it is an ordinary filename character, so
1280
+ // splitting on it there turns a link to the single legal entry `..\asset` — which resolves inside
1281
+ // the candidate and keeps resolving there after relocation — into `..` plus `asset`, and refuses a
1282
+ // component that never left its own tree.
1283
+ for (const segment of linkTarget.split(SEPARATORS_IN_LINK_TARGETS)) {
1284
+ if (segment === '' || segment === '.')
1285
+ continue;
1286
+ prefix = await (0, promises_1.realpath)((0, node_path_1.join)(prefix, segment)).catch(() => (0, node_path_1.join)(prefix, segment));
1287
+ if (prefix !== ownedRoot && !prefix.startsWith(ownedRoot + node_path_1.sep)) {
1288
+ throw refuse(`Cannot ${action} ${componentName}: ${entryPath} reaches ${prefix} on its way to ${linkTarget}, ` +
1289
+ `leaving the build — after activation moves the tree that path resolves somewhere else`);
1290
+ }
1291
+ }
1292
+ }
1293
+ };
1294
+ await walk(candidateDirPath);
1295
+ }
1296
+ /** Record the build's decisions beside the candidate. Called before `.complete`, which vouches for it. */
1297
+ async function writeArtifactDescriptor(componentDirPath, deploymentId, descriptor) {
1298
+ try {
1299
+ await writeControlFileDurably(candidateArtifactFilePath(componentDirPath, deploymentId), JSON.stringify(descriptor));
1300
+ }
1301
+ catch (error) {
1302
+ // An existing descriptor belongs to this same artifact — the id is claimed exclusively, so nothing
1303
+ // else can have written one — which makes this a retry of its own stage rather than a conflict.
1304
+ if (error.code !== 'EEXIST')
1305
+ throw error;
1306
+ }
1307
+ }
1308
+ /**
1309
+ * A component name safe to join onto the components root: no separator, no traversal, not dot-prefixed.
1310
+ * Applied to EVERY source of the name — the journal and the sidecar — because validating one and trusting
1311
+ * the other is how a corrupt record reaches an unrelated directory.
1312
+ */
1313
+ function isJoinableComponentName(name) {
1314
+ return (typeof name === 'string' &&
1315
+ name.length > 0 &&
1316
+ name === (0, node_path_1.basename)(name) &&
1317
+ name !== '.' &&
1318
+ name !== '..' &&
1319
+ !name.startsWith('.'));
1320
+ }
1321
+ /**
1322
+ * Read an activation journal. Absent is `undefined` — no activation was attempted. Anything else THROWS:
1323
+ * a truncated or unknown-version journal is an interrupted activation whose intent cannot be read, and
1324
+ * both guesses are destructive (publish a rejected release, or discard a good one), so the component is
1325
+ * failed closed instead.
1326
+ */
1327
+ async function readActivationJournal(journalPath) {
1328
+ let raw;
1329
+ try {
1330
+ raw = await (0, promises_1.readFile)(journalPath, 'utf8');
1331
+ }
1332
+ catch (error) {
1333
+ if (error.code === 'ENOENT')
1334
+ return undefined;
1335
+ throw error;
1336
+ }
1337
+ let parsed;
1338
+ try {
1339
+ parsed = JSON.parse(raw);
1340
+ }
1341
+ catch (error) {
1342
+ throw new Error(`Activation journal ${journalPath} could not be parsed: ${errorMessage(error)}`);
1343
+ }
1344
+ if (parsed?.v !== ACTIVATION_JOURNAL_VERSION) {
1345
+ throw new Error(`Activation journal ${journalPath} has version ${JSON.stringify(parsed?.v)}, expected ${ACTIVATION_JOURNAL_VERSION}`);
1346
+ }
1347
+ if (!isJoinableComponentName(parsed.component) || typeof parsed.candidateId !== 'string') {
1348
+ throw new Error(`Activation journal ${journalPath} does not identify its component and candidate`);
1349
+ }
1350
+ // The journal must describe the directory it sits in. A syntactically valid journal naming someone
1351
+ // else's deployment would otherwise let recovery act on a component from the wrong record.
1352
+ if (parsed.candidateId !== (0, node_path_1.basename)((0, node_path_1.dirname)(journalPath))) {
1353
+ throw new Error(`Activation journal ${journalPath} names candidate '${parsed.candidateId}', which is not its own deployment`);
1354
+ }
1355
+ return parsed;
1356
+ }
1357
+ /**
1358
+ * The deployment directory holding one candidate build: `<root>/.deploy-staging/<deploymentId>`.
1359
+ *
1360
+ * The id is asserted here rather than only at the request boundary because every caller funnels through
1361
+ * this one join, and the id is now operator-supplied (`deployment_id`) or replication-supplied
1362
+ * (`_deploymentId`). A traversal-bearing id would otherwise direct both the build and its removal outside
1363
+ * `.deploy-staging`.
1364
+ */
1365
+ function candidateDeploymentDirPath(componentDirPath, deploymentId) {
1366
+ if (typeof deploymentId !== 'string' ||
1367
+ deploymentId.length === 0 ||
1368
+ deploymentId !== (0, node_path_1.basename)(deploymentId) ||
1369
+ // `basename` returns these unchanged, so the comparison above admits both.
1370
+ deploymentId === '.' ||
1371
+ deploymentId === '..') {
1372
+ throw new Error(`Deployment id '${deploymentId}' is not a single path segment`);
1373
+ }
1374
+ return (0, node_path_1.join)((0, node_path_1.dirname)(componentDirPath), exports.DEPLOY_STAGING_DIR, deploymentId);
1375
+ }
1376
+ /** Where a candidate build lives: `<root>/.deploy-staging/<deploymentId>/<component>`. */
1377
+ function candidateApplicationPath(componentDirPath, deploymentId) {
1378
+ return (0, node_path_1.join)(candidateDeploymentDirPath(componentDirPath, deploymentId), (0, node_path_1.basename)(componentDirPath));
1379
+ }
1380
+ function extractionStagingDirectory(componentDirPath) {
1381
+ return (0, node_path_1.join)((0, node_path_1.dirname)(componentDirPath), exports.ASIDE_STAGING_DIR, (0, node_path_1.basename)(componentDirPath));
1382
+ }
1383
+ function retiredMarkerForAside(asidePath) {
1384
+ return (0, node_path_1.join)((0, node_path_1.dirname)(asidePath), `${RETIRED_ASIDE_PREFIX}${(0, node_path_1.basename)(asidePath).slice(IN_PROGRESS_ASIDE_PREFIX.length)}`);
1385
+ }
1386
+ async function retireExtractionAside(asidePath) {
1387
+ const retiredMarkerPath = retiredMarkerForAside(asidePath);
1388
+ try {
1389
+ await (0, promises_1.writeFile)(retiredMarkerPath, '', { flag: 'wx', mode: 0o600 });
1390
+ }
1391
+ catch (error) {
1392
+ if (error.code !== 'EEXIST')
1393
+ throw error;
1394
+ }
1395
+ return retiredMarkerPath;
1396
+ }
1397
+ function errorMessage(error) {
1398
+ return error instanceof Error ? error.message : String(error);
1399
+ }
1400
+ async function makeRollbackPlaceholderMovable(applicationDirPath, placeholderIdentity) {
1401
+ if (!placeholderIdentity)
1402
+ return;
1403
+ try {
1404
+ const current = await (0, promises_1.lstat)(applicationDirPath, { bigint: true });
1405
+ if (current.dev === placeholderIdentity.dev && current.ino === placeholderIdentity.ino) {
1406
+ await (0, promises_1.chmod)(applicationDirPath, 0o700);
1407
+ }
1408
+ }
1409
+ catch (error) {
1410
+ if (error.code !== 'ENOENT')
1411
+ throw error;
1412
+ }
1413
+ }
1414
+ async function identifyRollbackPlaceholder(applicationDirPath) {
1415
+ const userId = process.getuid?.();
1416
+ if (process.platform === 'win32' || userId === undefined || userId === 0)
1417
+ return undefined;
1418
+ try {
1419
+ const current = await (0, promises_1.lstat)(applicationDirPath, { bigint: true });
1420
+ const permissions = Number(current.mode) & 0o777;
1421
+ if ((current.isDirectory() || current.isFile()) &&
1422
+ current.uid === BigInt(userId) &&
1423
+ (permissions === 0 || (current.isDirectory() && (permissions === 0o100 || permissions === 0o300)))) {
1424
+ return { dev: current.dev, ino: current.ino };
1425
+ }
1426
+ }
1427
+ catch (error) {
1428
+ if (error.code !== 'ENOENT')
1429
+ throw error;
1430
+ }
1431
+ return undefined;
1432
+ }
1433
+ /**
1434
+ * Create a hidden staging directory and confirm it is the one we created: a real directory rather than a
1435
+ * symlink or junction substituted underneath us, restricted to the owner. Re-checked at every use rather
1436
+ * than once per deploy, because the gap between checking and writing is the exploitable part.
1437
+ */
1438
+ async function ensureSecureStagingDirectory(stagingDir) {
1439
+ await (0, promises_1.mkdir)(stagingDir, { recursive: true, mode: 0o700 });
1440
+ const stagingStat = await (0, promises_1.lstat)(stagingDir);
1441
+ if (!stagingStat.isDirectory() || stagingStat.isSymbolicLink()) {
1442
+ throw new Error(`Component deploy staging path is not a directory: ${stagingDir}`);
1443
+ }
1444
+ if (process.platform !== 'win32' && (stagingStat.mode & 0o777) !== 0o700) {
1445
+ await (0, promises_1.chmod)(stagingDir, 0o700).catch((error) => harper_logger_ts_1.default.warn(`Could not restrict component deploy staging permissions for ${stagingDir}:`, (0, harper_logger_ts_1.errorForLog)(error)));
1446
+ }
1447
+ }
1448
+ /**
1449
+ * Claim a deployment directory for this build, EXCLUSIVELY. The id is the public deployment id, which an
1450
+ * operator can repeat and a redelivered replication can repeat for them, so tolerating an existing
1451
+ * directory would let a replayed stage rewrite the bytes under an existing `.complete` and descriptor —
1452
+ * and a crash mid-rebuild would leave a partial tree that still reads as certified.
1453
+ *
1454
+ * The caller holds the component's preparation lock, which is what makes the EEXIST verdicts sound: no
1455
+ * other preparation of THIS component is running, and a directory belonging to another component is not
1456
+ * this lock's to touch.
1457
+ */
1458
+ async function claimDeploymentDirectory(deploymentDirPath, componentName) {
1459
+ // Every refusal below is a conflict over an id that already exists, which is the caller's to resolve by
1460
+ // naming a different one — not a server fault, and not the 500 a bare Error reaches the caller as.
1461
+ const taken = (message) => new hdbError_ts_1.ClientError(message, 409);
1462
+ try {
1463
+ await (0, promises_1.mkdir)(deploymentDirPath, { mode: 0o700 });
1464
+ }
1465
+ catch (error) {
1466
+ if (error.code !== 'EEXIST')
1467
+ throw error;
1468
+ const owner = await candidateComponentName(deploymentDirPath);
1469
+ if (owner !== undefined && owner !== componentName) {
1470
+ throw taken(`Deployment id ${(0, node_path_1.basename)(deploymentDirPath)} already holds a build of '${owner}'; a deployment id ` +
1471
+ `names one artifact for its lifetime`);
1472
+ }
1473
+ // Ownership has to be POSITIVE to reclaim, and EMPTINESS IS NOT A VERDICT. The sidecar below is
1474
+ // written as part of the claim, so a directory naming nobody is another component between its own
1475
+ // mkdir and that write, and a deploy can hold a nearly empty one for minutes while it resolves and
1476
+ // packs. Nothing on disk separates that from a claim that got no further, and the lock that
1477
+ // serializes it is not this one, so only the exclusive create may conclude the id is free: the
1478
+ // directory can also have been discarded by a failed build between the first mkdir and this read,
1479
+ // and another component can claim it in that same gap.
1480
+ if (owner === undefined) {
1481
+ await (0, promises_1.mkdir)(deploymentDirPath, { mode: 0o700 }).catch((retry) => {
1482
+ if (retry?.code !== 'EEXIST')
1483
+ throw retry;
1484
+ throw taken(`Deployment id ${(0, node_path_1.basename)(deploymentDirPath)} is already claimed by a build that has not named its ` +
1485
+ `component yet. If no deploy of any component is in flight, that directory is abandoned and has ` +
1486
+ `to be removed by hand; deploying again without a deployment_id mints a fresh id`);
1487
+ });
1488
+ }
1489
+ else {
1490
+ if (await presentOrAbsent((0, node_path_1.join)(deploymentDirPath, CANDIDATE_COMPLETE_MARKER))) {
1491
+ throw taken(`Deployment id ${(0, node_path_1.basename)(deploymentDirPath)} already holds a completed build of '${componentName}'; ` +
1492
+ `deploy it with deployment_id, or deploy again to build a new one`);
1493
+ }
1494
+ // This component's own preparation lock serializes the claim and nothing certified it, so nothing
1495
+ // is lost by rebuilding over it.
1496
+ await (0, promises_1.rm)(deploymentDirPath, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
1497
+ await (0, promises_1.mkdir)(deploymentDirPath, { mode: 0o700 });
1498
+ }
1499
+ }
1500
+ const claimed = await (0, promises_1.lstat)(deploymentDirPath);
1501
+ if (!claimed.isDirectory() || claimed.isSymbolicLink()) {
1502
+ throw new Error(`Component deploy staging path is not a directory: ${deploymentDirPath}`);
1503
+ }
1504
+ if (process.platform !== 'win32' && (claimed.mode & 0o777) !== 0o700) {
1505
+ await (0, promises_1.chmod)(deploymentDirPath, 0o700).catch((error) => harper_logger_ts_1.default.warn(`Could not restrict component deploy staging permissions for ${deploymentDirPath}:`, (0, harper_logger_ts_1.errorForLog)(error)));
1506
+ }
1507
+ await publishClaimOwnership(deploymentDirPath, componentName);
1508
+ }
1509
+ /**
1510
+ * Name the component that owns a deployment directory THIS CALL created, and take the directory back if that
1511
+ * cannot be recorded.
1512
+ *
1513
+ * Ownership is published as part of the claim rather than at certification, because resolving and packing can
1514
+ * take minutes and until a tree exists to infer an owner from, a directory answering to nobody is one another
1515
+ * component will take for abandoned. Unattributed is a permanent refusal, though, so a failure here — a full
1516
+ * disk, an EIO on the temp write or its sync — would burn this deployment id for good, every retry refused by
1517
+ * its own wreckage. The removal is scoped to the directory this invocation made, and deliberately not
1518
+ * broadened to one found by EEXIST: that directory may be another claimant's, and removing it is the race the
1519
+ * refusal exists to prevent. Best-effort, because the claim failure is what the caller needs to see.
1520
+ *
1521
+ * `write` is a parameter so the failure is testable without a filesystem that can be made to fail on exactly
1522
+ * this write and nothing else.
1523
+ */
1524
+ async function publishClaimOwnership(deploymentDirPath, componentName, write = writeControlFileDurably) {
1525
+ try {
1526
+ await write((0, node_path_1.join)(deploymentDirPath, CANDIDATE_COMPONENT_FILE), componentName);
1527
+ }
1528
+ catch (error) {
1529
+ await (0, promises_1.rm)(deploymentDirPath, { recursive: true, force: true }).catch((cleanupError) => harper_logger_ts_1.default.warn(`Could not remove the deployment directory ${deploymentDirPath} after failing to publish its ` +
1530
+ `ownership; the id stays unusable until it is removed:`, (0, harper_logger_ts_1.errorForLog)(cleanupError)));
1531
+ throw error;
1532
+ }
1533
+ }
1534
+ async function ensureExtractionStagingDirectory(asideStagingDir) {
1535
+ for (const stagingDir of [(0, node_path_1.dirname)(asideStagingDir), asideStagingDir]) {
1536
+ await ensureSecureStagingDirectory(stagingDir);
1537
+ }
1538
+ }
1539
+ /** The single component directory inside a candidate deployment directory, when there is exactly one. */
1540
+ async function candidateComponentName(deploymentDirPath) {
1541
+ // The sidecar first: it is the only source that still works once the candidate has been renamed to the
1542
+ // live path, which is exactly when an unreadable journal would otherwise be unattributable.
1543
+ // Only ENOENT is absence. Swallowing every error here reported "unowned", which is a licence to act:
1544
+ // the worker verdict dropped a failure and loaded a component main had failed closed, and a deploy
1545
+ // skipped a journaled activation it owns and stalled the component in the legacy pass instead.
1546
+ const recorded = await (0, promises_1.readFile)((0, node_path_1.join)(deploymentDirPath, CANDIDATE_COMPONENT_FILE), 'utf8').catch((error) => {
1547
+ if (error?.code === 'ENOENT')
1548
+ return '';
1549
+ throw error;
1550
+ });
1551
+ const named = recorded.trim();
1552
+ if (isJoinableComponentName(named))
1553
+ return named;
1554
+ const entries = await (0, promises_1.readdir)(deploymentDirPath, { withFileTypes: true }).catch((error) => {
1555
+ if (error?.code === 'ENOENT')
1556
+ return [];
1557
+ throw error;
1558
+ });
1559
+ // Symlinks count: a `file:<directory>` candidate is deliberately a link, and activation already accepts
1560
+ // one. Filtering to real directories here left those candidates with no owner, so residue removal took
1561
+ // no lock and could delete a build in flight.
1562
+ //
1563
+ // Validated, because this infers an owner from a NAME. A directory-shaped control file — a corrupt
1564
+ // `.activation.json` that is a directory — would otherwise be returned as the owning component, which
1565
+ // both licenses a restore against it and is a name no component can have.
1566
+ const components = entries.filter((entry) => (entry.isDirectory() || entry.isSymbolicLink()) && isJoinableComponentName(entry.name));
1567
+ return components.length === 1 ? components[0].name : undefined;
1568
+ }
1569
+ /**
1570
+ * The deployment directory of an activation journal this component still owns, if any.
1571
+ *
1572
+ * The journal is the authority for an interrupted activation. The legacy `.deploy-aside` pass would
1573
+ * otherwise restore the displaced tree over a candidate a completed activation already renamed live, so it
1574
+ * consults this before restoring rather than relying on being sequenced after settlement: a worker
1575
+ * auto-restarted mid-activation reaches it with no settlement in front of it, and settlement that FAILS
1576
+ * deliberately keeps the journal for the next start while the same boot carries on into the legacy pass.
1577
+ */
1578
+ async function journaledDeploymentForComponent(componentsRootDirPath, componentName) {
1579
+ const stagingRoot = (0, node_path_1.join)(componentsRootDirPath, exports.DEPLOY_STAGING_DIR);
1580
+ let deployments;
1581
+ try {
1582
+ deployments = await (0, promises_1.readdir)(stagingRoot, { withFileTypes: true });
1583
+ }
1584
+ catch (error) {
1585
+ if (error.code === 'ENOENT')
1586
+ return undefined;
1587
+ throw error;
1588
+ }
1589
+ for (const deployment of deployments) {
1590
+ if (!deployment.isDirectory())
1591
+ continue;
1592
+ const deploymentDirPath = (0, node_path_1.join)(stagingRoot, deployment.name);
1593
+ const journalPath = (0, node_path_1.join)(deploymentDirPath, ACTIVATION_JOURNAL);
1594
+ // NOTHING is swallowed here. This is the gate that authorizes restoring an old tree over what may be
1595
+ // a committed candidate, so "could not tell" has to fail closed — treating an unreadable deployment
1596
+ // as "no journal for this component" is exactly the clobber the journal exists to prevent. The blast
1597
+ // radius is narrow because the gate is only consulted where a restorable record already exists.
1598
+ //
1599
+ // Presence, not parseability: an unreadable journal is precisely the ambiguous case.
1600
+ const journaled = await (0, promises_1.lstat)(journalPath).then(() => true, (error) => {
1601
+ if (error.code === 'ENOENT')
1602
+ return false;
1603
+ throw error;
1604
+ });
1605
+ if (!journaled)
1606
+ continue;
1607
+ // EITHER name blocks, while settlement acts only when both agree. The destructive step takes the
1608
+ // conservative union; the corrective one takes the precise intersection, so a journal whose two
1609
+ // attributions disagree stalls the restore instead of licensing it, and startup recovery — which
1610
+ // keys on the journal — is what clears it. The sidecar also covers a component legitimately named
1611
+ // `component`, whose candidate path collides with the sidecar's and makes every sidecar read fail.
1612
+ const journalOwner = (await readActivationJournal(journalPath).catch(() => undefined))?.component;
1613
+ if (journalOwner === componentName)
1614
+ return deploymentDirPath;
1615
+ const sidecarOwner = await candidateComponentName(deploymentDirPath);
1616
+ if (sidecarOwner === componentName)
1617
+ return deploymentDirPath;
1618
+ // A journal nobody can attribute blocks EVERY component. It is a rare, genuinely broken state — an
1619
+ // unparseable journal whose deployment no longer holds a tree to infer from — and the alternative is
1620
+ // letting the restore proceed against a candidate this journal may well have committed. There is no
1621
+ // automated way out of it, by construction: nothing on disk says which component it belongs to. The
1622
+ // error the caller raises names the directory an operator has to resolve.
1623
+ if (journalOwner === undefined && sidecarOwner === undefined)
1624
+ return deploymentDirPath;
1625
+ }
1626
+ return undefined;
1627
+ }
1628
+ /**
1629
+ * The components a deployment's evidence implicates, when its journal and its ownership sidecar disagree
1630
+ * about whose it is — or `undefined` when there is no disagreement to act on.
1631
+ *
1632
+ * A sidecar that cannot answer is NOT disagreement: the journal names its own component and can settle it,
1633
+ * so an unreadable sidecar must not block that. Only a sidecar that reads and names something else is the
1634
+ * wedge, and then BOTH names are returned, sidecar first, because both are stuck — see
1635
+ * `splitAttributionError`.
1636
+ *
1637
+ * Separated from either call site so the decision is testable on its own: the paths that reach it include
1638
+ * one that requires a journal to appear between two reads under a lock, which no test can stage.
1639
+ */
1640
+ function splitAttributionOwners(journalOwner, sidecarOwner) {
1641
+ if (sidecarOwner === undefined || sidecarOwner === journalOwner)
1642
+ return undefined;
1643
+ return [sidecarOwner, journalOwner];
1644
+ }
1645
+ /**
1646
+ * The error for a deployment its journal and its ownership sidecar attribute to different components.
1647
+ *
1648
+ * Both names are wedged, so both are failed: the restore gate takes the union and blocks the sidecar's
1649
+ * component, while settlement needs the intersection and so can never clear the journal owner's. Neither
1650
+ * component's own deploy can resolve it, which is why the message names the directory to remove.
1651
+ */
1652
+ function splitAttributionError(deploymentDirPath, journalOwner, sidecarOwner) {
1653
+ return new Error(`Deploy staging ${deploymentDirPath} is attributed to two different components: its journal names ` +
1654
+ `'${journalOwner}' and its sidecar names '${sidecarOwner}'. Neither can settle it; remove that ` +
1655
+ `directory once you have determined which tree is current.`);
1656
+ }
1657
+ /** In-progress rollback records in a component's aside directory, newest first. */
1658
+ async function inProgressAsideRecords(asideStagingDir) {
1659
+ // ENOENT is "no aside directory yet"; anything else would report "no records" and let roll-forward
1660
+ // remove the journal while the records it should have retired are still there and still authoritative.
1661
+ const entries = await (0, promises_1.readdir)(asideStagingDir, { withFileTypes: true }).catch((error) => {
1662
+ if (error?.code === 'ENOENT')
1663
+ return [];
1664
+ throw error;
1665
+ });
1666
+ // Retired records excluded, the same rule `recoverOrCleanupStaleExtractionPaths` applies. A record whose
1667
+ // retire succeeded but whose best-effort sweep did not is settled, not displaced — counting it would let
1668
+ // an ordinary pre-swap state look like the "live path recreated" ambiguity and fail a healthy component
1669
+ // closed with an operator-only exit.
1670
+ const entryNames = new Set(entries.map((entry) => entry.name));
1671
+ return entries
1672
+ .filter((entry) => entry.name.startsWith(IN_PROGRESS_ASIDE_PREFIX) &&
1673
+ !entryNames.has(`${RETIRED_ASIDE_PREFIX}${entry.name.slice(IN_PROGRESS_ASIDE_PREFIX.length)}`))
1674
+ .map((entry) => (0, node_path_1.join)(asideStagingDir, entry.name))
1675
+ .sort()
1676
+ .reverse();
1677
+ }
1678
+ /**
1679
+ * Settle journaled activations for ONE component, and bound its dormant staged builds, assuming the caller
1680
+ * already holds its preparation lock.
1681
+ *
1682
+ * Exists because the journal-first rule has to hold at every entry point, not just startup. A deploy runs
1683
+ * `recoverOrCleanupStaleExtractionPaths` first. After an activation whose retirement failed, the aside
1684
+ * still names the DISPLACED tree, so restoring it would put the old version back over the new one. That
1685
+ * pass refuses to restore against a surviving journal, but refusing is a stalled component; settling first
1686
+ * is what lets the deploy proceed.
1687
+ */
1688
+ async function settleStagingForComponent(componentsRootDirPath, componentName, pinnedDeploymentId) {
1689
+ const stagingRoot = (0, node_path_1.join)(componentsRootDirPath, exports.DEPLOY_STAGING_DIR);
1690
+ let deployments;
1691
+ try {
1692
+ deployments = await (0, promises_1.readdir)(stagingRoot, { withFileTypes: true });
1693
+ }
1694
+ catch (error) {
1695
+ if (error.code === 'ENOENT')
1696
+ return;
1697
+ throw error;
1698
+ }
1699
+ const dormant = [];
1700
+ for (const deployment of deployments) {
1701
+ if (!deployment.isDirectory())
1702
+ continue;
1703
+ const deploymentDirPath = (0, node_path_1.join)(stagingRoot, deployment.name);
1704
+ // Ownership BEFORE parsing. Reading every journal first meant a truncated journal belonging to another
1705
+ // component threw here — blocking the deploy of a healthy component because an unrelated one is
1706
+ // broken. The sidecar names the owner without parsing anything, and a deployment that does not name
1707
+ // this component is none of this deploy's business; startup recovery reports it instead.
1708
+ //
1709
+ // An ownership read that FAILS is the same situation, and skipping is safe here specifically because
1710
+ // settlement is the corrective half: if that entry does turn out to be this component's, the restore
1711
+ // gate — which takes the union and fails closed on anything it cannot attribute — is what stops the
1712
+ // legacy pass acting on it. Failing the deploy instead lets one unreadable sibling block every
1713
+ // neighbour's deploys, which is the outage this ordering exists to prevent.
1714
+ let owner;
1715
+ let ownerUnreadable = false;
1716
+ try {
1717
+ owner = await candidateComponentName(deploymentDirPath);
1718
+ }
1719
+ catch (error) {
1720
+ ownerUnreadable = true;
1721
+ harper_logger_ts_1.default.trace?.(`Ownership of ${deploymentDirPath} is unreadable while settling ${componentName}, falling back to ` +
1722
+ `its journal: ${errorMessage(error)}`);
1723
+ }
1724
+ if (!ownerUnreadable && owner !== componentName)
1725
+ continue;
1726
+ const journal = await readActivationJournal((0, node_path_1.join)(deploymentDirPath, ACTIVATION_JOURNAL));
1727
+ // A journal-less directory is what a SUCCESSFUL settlement leaves when its best-effort sweep fails, so
1728
+ // this must not fail closed. An unattributable *activation* still does: `readActivationJournal` throws
1729
+ // on a journal that exists but cannot be read.
1730
+ if (!journal) {
1731
+ if (ownerUnreadable)
1732
+ continue;
1733
+ try {
1734
+ const build = await dormantBuildAt(deploymentDirPath, componentName);
1735
+ if (build)
1736
+ dormant.push(build);
1737
+ }
1738
+ catch (error) {
1739
+ harper_logger_ts_1.default.warn(`Leaving staged ${componentName} build ${deploymentDirPath} out of retention; it could not be read:`, (0, harper_logger_ts_1.errorForLog)(error));
1740
+ }
1741
+ continue;
1742
+ }
1743
+ // The journal decides, not the sidecar. Skipping on an unreadable sidecar alone would leave this
1744
+ // component's own unsettled activation in place while a new deploy proceeded over it, and an
1745
+ // activation interrupted before B1 has no rollback record for the restore gate to catch.
1746
+ if (journal.component !== componentName)
1747
+ continue;
1748
+ await settleInterruptedActivation(componentsRootDirPath, deploymentDirPath, journal);
1749
+ }
1750
+ const maxCount = getStagingRetentionMaxCount();
1751
+ if (dormant.length > maxCount)
1752
+ await pruneDormantBuilds(componentName, dormant, maxCount, pinnedDeploymentId);
1753
+ }
1754
+ /**
1755
+ * Components that on-disk evidence says were left in a state nobody settled — determined READ-ONLY, so any
1756
+ * thread can reach the same verdict.
1757
+ *
1758
+ * Recovery runs on the main thread only, but the components it could not settle still have to be failed
1759
+ * closed on the workers that actually serve them, and a worker cannot be handed main's verdict: it boots
1760
+ * through its own `loadRootComponents(true)`, potentially before main finished. Recovery deliberately KEEPS
1761
+ * the evidence for anything it could not settle, so a worker can read it instead of being told.
1762
+ *
1763
+ * Only unambiguous evidence counts. A well-formed journal is NOT evidence — every healthy deploy has one
1764
+ * in flight — so this reports a journal that cannot be read at all (corrupt, unknown version, or naming
1765
+ * something other than its own deployment), which no in-flight deploy ever produces.
1766
+ */
1767
+ async function unsettleableComponentsFromDisk(componentsRootDirPath) {
1768
+ const unsettleable = new Map();
1769
+ const stagingRoot = (0, node_path_1.join)(componentsRootDirPath, exports.DEPLOY_STAGING_DIR);
1770
+ let deployments;
1771
+ try {
1772
+ deployments = await (0, promises_1.readdir)(stagingRoot, { withFileTypes: true });
1773
+ }
1774
+ catch (error) {
1775
+ if (error.code === 'ENOENT')
1776
+ return unsettleable;
1777
+ throw error;
1778
+ }
1779
+ for (const deployment of deployments) {
1780
+ if (!deployment.isDirectory())
1781
+ continue;
1782
+ const deploymentDirPath = (0, node_path_1.join)(stagingRoot, deployment.name);
1783
+ // Per deployment. `candidateComponentName` propagates every non-ENOENT error now, and this pass runs
1784
+ // where the CALLER only warns — so one unreadable deployment escaping here would drop the verdict for
1785
+ // every other component and let each of them load with no evidence checked at all.
1786
+ try {
1787
+ await verdictFor(deploymentDirPath, deployment.name, unsettleable);
1788
+ }
1789
+ catch (error) {
1790
+ const failure = error instanceof Error ? error : new Error(String(error));
1791
+ if (!unsettleable.has(deployment.name))
1792
+ unsettleable.set(deployment.name, failure);
1793
+ }
1794
+ }
1795
+ return unsettleable;
1796
+ }
1797
+ /** One deployment's read-only verdict. Throws rather than guessing; the caller scopes that to this entry. */
1798
+ async function verdictFor(deploymentDirPath, deploymentName, unsettleable) {
1799
+ // Recorded by main when it failed to settle a well-formed journal. Checked first, because that case is
1800
+ // invisible to a worker otherwise.
1801
+ //
1802
+ // Only ENOENT is absence. A marker that exists but cannot be read (EIO, EACCES) must not be taken as
1803
+ // "no verdict" — that classifies the well-formed journal beside it as a healthy in-flight deploy and
1804
+ // lets the worker load a component main failed closed.
1805
+ let recorded;
1806
+ try {
1807
+ recorded = await (0, promises_1.readFile)((0, node_path_1.join)(deploymentDirPath, UNSETTLED_MARKER), 'utf8');
1808
+ }
1809
+ catch (error) {
1810
+ if (error.code !== 'ENOENT') {
1811
+ const failure = error instanceof Error ? error : new Error(String(error));
1812
+ return record(unsettleable, await attribute(deploymentDirPath, deploymentName), failure);
1813
+ }
1814
+ }
1815
+ if (recorded !== undefined) {
1816
+ const component = await attribute(deploymentDirPath, deploymentName);
1817
+ return record(unsettleable, component, new Error(recorded.trim() || `Activation of ${component} could not be settled`));
1818
+ }
1819
+ try {
1820
+ await readActivationJournal((0, node_path_1.join)(deploymentDirPath, ACTIVATION_JOURNAL));
1821
+ }
1822
+ catch (error) {
1823
+ const failure = error instanceof Error ? error : new Error(String(error));
1824
+ record(unsettleable, await attribute(deploymentDirPath, deploymentName), failure);
1825
+ }
1826
+ }
1827
+ /**
1828
+ * Who a deployment's evidence belongs to. Falls back to the deployment id when nothing names it: a verdict
1829
+ * attributed to nothing is a verdict nobody acts on, and the id is at least something an operator can find
1830
+ * on disk. A read that FAILS is not "nothing names it" — that propagates, and the caller records it against
1831
+ * the id, so an unreadable deployment is reported rather than dropped.
1832
+ */
1833
+ async function attribute(deploymentDirPath, deploymentName) {
1834
+ return (await candidateComponentName(deploymentDirPath)) ?? deploymentName;
1835
+ }
1836
+ function record(unsettleable, component, failure) {
1837
+ if (!unsettleable.has(component))
1838
+ unsettleable.set(component, failure);
1839
+ }
1840
+ /**
1841
+ * Settle activations a crash interrupted, before anything loads. Runs at startup on main and on every
1842
+ * worker — a worker can be respawned mid-activation, long after main's pass.
1843
+ *
1844
+ * Returns failures keyed by COMPONENT so the caller can fail exactly those closed and still load every
1845
+ * healthy sibling — a single unreadable journal must not take down the whole node, and must not let a
1846
+ * component load over state nobody reconciled.
1847
+ *
1848
+ */
1849
+ async function recoverInterruptedActivations(componentsRootDirPath) {
1850
+ const failures = new Map();
1851
+ const stagingRoot = (0, node_path_1.join)(componentsRootDirPath, exports.DEPLOY_STAGING_DIR);
1852
+ let deployments;
1853
+ try {
1854
+ deployments = await (0, promises_1.readdir)(stagingRoot, { withFileTypes: true });
1855
+ }
1856
+ catch (error) {
1857
+ if (error.code === 'ENOENT')
1858
+ return failures;
1859
+ throw error;
1860
+ }
1861
+ const dormant = new Map();
1862
+ const catalogue = (owner, build) => {
1863
+ const builds = dormant.get(owner);
1864
+ if (builds)
1865
+ builds.push(build);
1866
+ else
1867
+ dormant.set(owner, [build]);
1868
+ };
1869
+ for (const deployment of deployments) {
1870
+ if (!deployment.isDirectory())
1871
+ continue;
1872
+ const deploymentDirPath = (0, node_path_1.join)(stagingRoot, deployment.name);
1873
+ const journalPath = (0, node_path_1.join)(deploymentDirPath, ACTIVATION_JOURNAL);
1874
+ const fail = (component, error) => recordUnsettled(failures, component, error, deploymentDirPath);
1875
+ let journal;
1876
+ try {
1877
+ journal = await readActivationJournal(journalPath);
1878
+ }
1879
+ catch (error) {
1880
+ // The journal itself is unreadable, so its component has to be inferred from the tree it was
1881
+ // going to activate. A deployment directory holding no component tree leaves only its id.
1882
+ const attributed = await candidateComponentName(deploymentDirPath).catch(() => undefined);
1883
+ await fail(attributed ?? deployment.name, error);
1884
+ continue;
1885
+ }
1886
+ if (!journal) {
1887
+ // No activation was attempted: build residue, or a candidate abandoned mid-build. The legacy
1888
+ // in-place recovery owns any aside it left, so there is nothing to settle.
1889
+ //
1890
+ // Removed UNDER the component's lock, and only after re-checking that no journal appeared in the
1891
+ // meantime. A reload cycle can run this pass while another deploy is mid-build — its candidate
1892
+ // has no journal yet, because the journal is written after build and validation — so an unlocked
1893
+ // delete here removes a live build out from under it.
1894
+ let owner;
1895
+ // Who to fail, if what went wrong under the lock turns out to concern an ACTIVATION rather than
1896
+ // this branch's opportunistic cleanup. Left unset for a sweep that could not remove a settled
1897
+ // directory and for a lock a live deploy is holding: neither is an unsettled activation.
1898
+ let activationToFail;
1899
+ // Set when the journal that appears under the lock names someone other than the sidecar owner
1900
+ // whose lock we took. Both names are failed, exactly as on the journaled path.
1901
+ let splitOwners;
1902
+ const removeResidue = async () => {
1903
+ // Re-read UNDER the lock, and do not swallow: the first scan raced a deploy that can publish a
1904
+ // journal before releasing the lock, so a journal found now must be settled rather than deleted.
1905
+ // Treating a read error as "no journal" would delete the evidence instead.
1906
+ let appeared;
1907
+ try {
1908
+ appeared = await readActivationJournal((0, node_path_1.join)(deploymentDirPath, ACTIVATION_JOURNAL));
1909
+ }
1910
+ catch (error) {
1911
+ // A journal published between the scan's read and this one, which then cannot be READ, is an
1912
+ // activation whose intent is unknowable — the one thing in this branch that has to fail
1913
+ // closed. Attributed to the sidecar's owner, since the journal cannot name itself.
1914
+ activationToFail = owner ?? deployment.name;
1915
+ throw error;
1916
+ }
1917
+ if (appeared) {
1918
+ // The lock held here was taken on the SIDECAR's owner. A journal naming someone else must not
1919
+ // be settled under it: `settleInterruptedActivation` renames and removes that other
1920
+ // component's trees, whose own deploy may hold its own lock and be mid-flight. It is also the
1921
+ // same split evidence the journaled path fails closed for both names, so it takes the same
1922
+ // route rather than a second opinion here.
1923
+ const splitNames = splitAttributionOwners(appeared.component, owner);
1924
+ if (splitNames) {
1925
+ splitOwners = splitNames;
1926
+ throw splitAttributionError(deploymentDirPath, appeared.component, splitNames[0]);
1927
+ }
1928
+ activationToFail = appeared.component;
1929
+ await settleInterruptedActivation(componentsRootDirPath, deploymentDirPath, appeared);
1930
+ // Settled. Anything that fails after this — releasing the lock, say — is not this
1931
+ // activation's, and attributing it here would fail a correctly settled component closed.
1932
+ activationToFail = undefined;
1933
+ return;
1934
+ }
1935
+ // Re-classified UNDER the lock: the unlocked read that routed this here can predate the `.complete`
1936
+ // a deploy wrote before dying, and that is a retainable build, not residue.
1937
+ const build = await dormantBuildAt(deploymentDirPath, owner);
1938
+ if (build) {
1939
+ catalogue(owner, build);
1940
+ return;
1941
+ }
1942
+ // A DESCRIBED artifact carrying a stale verdict is settled, not residue. `fail()` only ever writes
1943
+ // `.unsettled` beside a journal it keeps, so a marker with no journal says settlement finished
1944
+ // and only the marker's own removal was lost — which is exactly what a crash between a dormant
1945
+ // return's two unlinks leaves, and the barrier that orders them cannot run on Windows. Deleting
1946
+ // here would destroy a build somebody staged deliberately, whose payload may already have been
1947
+ // reclaimed, on the strength of a verdict that no longer applies. Clearing the marker is the
1948
+ // idempotent completion of the settlement that wrote it; an undescribed build stays disposable.
1949
+ if (await presentOrAbsent((0, node_path_1.join)(deploymentDirPath, CANDIDATE_ARTIFACT_FILE))) {
1950
+ // A fault clearing the marker is not a licence to delete what it is attached to — and not a
1951
+ // licence to say nothing either. The marker survives, every worker fails the component closed
1952
+ // on it, and main reporting success is the split where main serves what every worker refuses.
1953
+ // Failing the component brings main to the workers' verdict instead, the rule the settled tail
1954
+ // follows, and leaves the artifact for the next pass to clear.
1955
+ try {
1956
+ await clearUnsettledVerdict(deploymentDirPath, owner);
1957
+ }
1958
+ catch (error) {
1959
+ activationToFail = owner;
1960
+ throw error;
1961
+ }
1962
+ const settled = await dormantBuildAt(deploymentDirPath, owner);
1963
+ if (settled) {
1964
+ harper_logger_ts_1.default.info?.(`Cleared a stale unsettled verdict from the staged build ${(0, node_path_1.basename)(deploymentDirPath)} of ` +
1965
+ `${owner}; its activation was already settled`);
1966
+ catalogue(owner, settled);
1967
+ return;
1968
+ }
1969
+ // Cleared, and still not a retainable build — an incomplete or treeless staged directory. That
1970
+ // is residue like any other, so it falls through to the removal below.
1971
+ }
1972
+ // Cleanup, not settlement. There was no activation here — this is most often the residue a
1973
+ // SUCCESSFUL settlement leaves when its own sweep failed — so a sweep that fails again cannot
1974
+ // make anything unsettled, and recording it would refuse a live component on every worker
1975
+ // until the filesystem fault cleared.
1976
+ await (0, promises_1.rm)(deploymentDirPath, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }).catch((error) => harper_logger_ts_1.default.warn(`Could not clean up deploy staging ${deploymentDirPath}:`, (0, harper_logger_ts_1.errorForLog)(error)));
1977
+ };
1978
+ // Attribution FIRST, in its own scope, and its failure is not a verdict. A journal-less directory
1979
+ // is what a successful settlement leaves when its best-effort sweep fails, so a `fail()` here
1980
+ // wrote `.unsettled` keyed by the deployment id for a deployment that never held an unsettled
1981
+ // activation — and nothing ever cleared it, because settlement never runs for a journal-less
1982
+ // directory. If that sidecar later became readable as `web`, the stale marker was attributed to
1983
+ // the live `web` and every worker refused it permanently. This is the same shape the deploy path
1984
+ // skips; the two paths now agree.
1985
+ try {
1986
+ owner = await candidateComponentName(deploymentDirPath);
1987
+ }
1988
+ catch (error) {
1989
+ harper_logger_ts_1.default.trace?.(`Leaving deploy staging ${deploymentDirPath} in place: it holds no activation journal and its ` +
1990
+ `ownership cannot be read: ${errorMessage(error)}`);
1991
+ continue;
1992
+ }
1993
+ // Catalogued WITHOUT the lock and left alone: a retained build is never removed here, so a per-directory
1994
+ // lock would recur on every pass and contend with sibling threads for a component nothing is deploying.
1995
+ if (owner) {
1996
+ let build;
1997
+ try {
1998
+ build = await dormantBuildAt(deploymentDirPath, owner);
1999
+ }
2000
+ catch (error) {
2001
+ harper_logger_ts_1.default.warn(`Leaving deploy staging ${deploymentDirPath} in place; it could not be read:`, (0, harper_logger_ts_1.errorForLog)(error));
2002
+ continue;
2003
+ }
2004
+ if (build) {
2005
+ catalogue(owner, build);
2006
+ continue;
2007
+ }
2008
+ }
2009
+ // Scoped to THIS deployment, like the journaled branch below: a lock timeout or an EIO here used to
2010
+ // abort the entire scan, leaving every later deployment unsettled and unmarked.
2011
+ try {
2012
+ if (owner) {
2013
+ await (0, componentPreparationLock_ts_1.withComponentPreparationLock)((0, node_path_1.join)(componentsRootDirPath, owner), removeResidue, {
2014
+ purpose: 'activation-recovery',
2015
+ ...RECOVERY_LOCK_WAIT,
2016
+ // Without this a ticket left by a CRASHED worker looks live — same pid, same process
2017
+ // instance — so recovery waits out the multi-hour default instead of reclaiming it.
2018
+ isOwnerAlive: (lockOwner) => lockOwner.pid !== process.pid || (0, manageThreads_js_1.isThreadRunning)(lockOwner.threadId),
2019
+ });
2020
+ }
2021
+ else {
2022
+ // NOT removed. `buildCandidateApplication` creates the deployment directory and can then spend
2023
+ // minutes resolving or packing before the candidate tree and its sidecar exist, so "no owner"
2024
+ // includes "a live build that has not got that far yet" — and deleting it races the extraction
2025
+ // and fails a valid deploy. Unowned residue is left for a later pass, once an owner is knowable.
2026
+ harper_logger_ts_1.default.trace?.(`Leaving unowned deploy staging ${deploymentDirPath} in place: no component names it`);
2027
+ }
2028
+ }
2029
+ catch (error) {
2030
+ // A verdict only when an activation was actually involved; a directory that cannot be swept is
2031
+ // not one. A lock TIMEOUT is still recorded, because it is the signal `componentLoader` uses
2032
+ // to defer this component until the deploy holding that lock finishes — and it leaves nothing
2033
+ // durable behind, since `fail()` writes no marker for a deferral.
2034
+ if (splitOwners) {
2035
+ for (const name of splitOwners)
2036
+ await fail(name, error);
2037
+ }
2038
+ else if (activationToFail)
2039
+ await fail(activationToFail, error);
2040
+ else if (error instanceof componentPreparationLock_ts_1.ComponentPreparationLockTimeoutError)
2041
+ await fail(owner ?? deployment.name, error);
2042
+ else
2043
+ harper_logger_ts_1.default.warn(`Could not settle deploy staging ${deploymentDirPath}, which holds no activation journal:`, (0, harper_logger_ts_1.errorForLog)(error instanceof Error ? error : new Error(String(error))));
2044
+ }
2045
+ continue;
2046
+ }
2047
+ try {
2048
+ // Disagreeing attributions are the one case with no automated way out: the restore gate blocks the
2049
+ // SIDECAR's component (it takes the union, because restoring is destructive) while settlement
2050
+ // keys the journal, so neither name's deploy could ever clear it. Reported as unsettleable
2051
+ // against the sidecar's name, which is the component actually stalled, instead of stalling it
2052
+ // silently on every boot.
2053
+ // Unreadable is not disagreement. The journal is the authority on this path — it named its
2054
+ // component and can settle it — so a sidecar that cannot be read must not block that; only one
2055
+ // that CAN be read and names something else is the wedge below.
2056
+ const sidecarOwner = await candidateComponentName(deploymentDirPath).catch(() => undefined);
2057
+ const splitNames = splitAttributionOwners(journal.component, sidecarOwner);
2058
+ if (splitNames) {
2059
+ const split = splitAttributionError(deploymentDirPath, journal.component, splitNames[0]);
2060
+ for (const name of splitNames)
2061
+ await fail(name, split);
2062
+ continue;
2063
+ }
2064
+ const settling = journal;
2065
+ await (0, componentPreparationLock_ts_1.withComponentPreparationLock)((0, node_path_1.join)(componentsRootDirPath, settling.component), () => settleInterruptedActivation(componentsRootDirPath, deploymentDirPath, settling), {
2066
+ purpose: 'activation-recovery',
2067
+ ...RECOVERY_LOCK_WAIT,
2068
+ isOwnerAlive: (lockOwner) => lockOwner.pid !== process.pid || (0, manageThreads_js_1.isThreadRunning)(lockOwner.threadId),
2069
+ });
2070
+ }
2071
+ catch (error) {
2072
+ // The journal named its component, so attribution is exact however the settle failed.
2073
+ await fail(journal.component, error);
2074
+ }
2075
+ }
2076
+ const maxCount = getStagingRetentionMaxCount();
2077
+ for (const [owner, builds] of dormant) {
2078
+ for (const [component, error] of await reconcileDormantBuilds(componentsRootDirPath, owner, builds, maxCount)) {
2079
+ if (!failures.has(component))
2080
+ failures.set(component, error);
2081
+ }
2082
+ }
2083
+ return failures;
2084
+ }
2085
+ /**
2086
+ * Record a settlement failure against a component. A lock TIMEOUT is a deferral, not a verdict, and only
2087
+ * verdicts go on disk: a held lock means a live deploy, which settles its own journal, and a marker written
2088
+ * here would outlive it and have `unsettleableComponentsFromDisk` fail a healthy component closed on every
2089
+ * worker. Everything else is written so workers reach the same verdict — a well-formed journal this pass
2090
+ * could not settle looks exactly like a deploy in flight otherwise. Marker write is best-effort.
2091
+ */
2092
+ async function recordUnsettled(failures, component, error, deploymentDirPath) {
2093
+ const failure = error instanceof Error ? error : new Error(String(error));
2094
+ if (!failures.has(component))
2095
+ failures.set(component, failure);
2096
+ harper_logger_ts_1.default.error(`Could not settle the interrupted activation of ${component}:`, (0, harper_logger_ts_1.errorForLog)(failure));
2097
+ if (failure instanceof componentPreparationLock_ts_1.ComponentPreparationLockTimeoutError)
2098
+ return;
2099
+ await (0, promises_1.writeFile)((0, node_path_1.join)(deploymentDirPath, UNSETTLED_MARKER), failure.message, { mode: 0o600 }).catch((markerError) => harper_logger_ts_1.default.warn(`Could not record the unsettled activation of ${component}: ${errorMessage(markerError)}`));
2100
+ }
2101
+ /**
2102
+ * Finish one owner's catalogued dormant builds after the scan. The catalog was read without the lock, so a
2103
+ * deploy may have published a journal into one of these directories since — and if it then died mid-swap,
2104
+ * only settlement brings the component back. So: settle any journal that appeared, then bound what is still
2105
+ * dormant. The lock is taken only when there is something to do; a lock a live deploy holds is the same
2106
+ * deferral the residue branch records.
2107
+ */
2108
+ async function reconcileDormantBuilds(componentsRootDirPath, owner, builds, maxCount) {
2109
+ const failures = new Map();
2110
+ let journaled;
2111
+ for (const build of builds) {
2112
+ // Anything but a clean ENOENT means "read it properly, under the lock".
2113
+ const appeared = await presentOrAbsent((0, node_path_1.join)(build.deploymentDirPath, ACTIVATION_JOURNAL)).then((stats) => stats !== undefined, () => true);
2114
+ if (appeared) {
2115
+ journaled = build;
2116
+ break;
2117
+ }
2118
+ }
2119
+ if (!journaled && builds.length <= maxCount)
2120
+ return failures;
2121
+ try {
2122
+ await (0, componentPreparationLock_ts_1.withComponentPreparationLock)((0, node_path_1.join)(componentsRootDirPath, owner), async () => {
2123
+ const stillDormant = [];
2124
+ for (const build of builds) {
2125
+ let journal;
2126
+ try {
2127
+ journal = await readActivationJournal((0, node_path_1.join)(build.deploymentDirPath, ACTIVATION_JOURNAL));
2128
+ }
2129
+ catch (error) {
2130
+ await recordUnsettled(failures, owner, error, build.deploymentDirPath);
2131
+ continue;
2132
+ }
2133
+ if (!journal) {
2134
+ stillDormant.push(build);
2135
+ continue;
2136
+ }
2137
+ // The lock held here is the SIDECAR owner's, as in the residue branch: a journal naming someone
2138
+ // else is not settled under it, and both names are failed.
2139
+ const splitNames = splitAttributionOwners(journal.component, owner);
2140
+ if (splitNames) {
2141
+ const split = splitAttributionError(build.deploymentDirPath, journal.component, splitNames[0]);
2142
+ for (const name of splitNames)
2143
+ await recordUnsettled(failures, name, split, build.deploymentDirPath);
2144
+ continue;
2145
+ }
2146
+ try {
2147
+ await settleInterruptedActivation(componentsRootDirPath, build.deploymentDirPath, journal);
2148
+ }
2149
+ catch (error) {
2150
+ await recordUnsettled(failures, journal.component, error, build.deploymentDirPath);
2151
+ }
2152
+ }
2153
+ if (stillDormant.length > maxCount)
2154
+ await pruneDormantBuilds(owner, stillDormant, maxCount);
2155
+ }, {
2156
+ purpose: 'activation-recovery',
2157
+ ...RECOVERY_LOCK_WAIT,
2158
+ isOwnerAlive: (lockOwner) => lockOwner.pid !== process.pid || (0, manageThreads_js_1.isThreadRunning)(lockOwner.threadId),
2159
+ });
2160
+ }
2161
+ catch (error) {
2162
+ // With a journal in view this is an activation that could not be settled — recorded exactly as the
2163
+ // scan records one it saw directly (a timeout defers, anything else is a verdict). Without one it is
2164
+ // hygiene that could not run, unless a live deploy holds the lock, which defers as everywhere else.
2165
+ if (journaled) {
2166
+ await recordUnsettled(failures, owner, error, journaled.deploymentDirPath);
2167
+ return failures;
2168
+ }
2169
+ const failure = error instanceof Error ? error : new Error(String(error));
2170
+ if (failure instanceof componentPreparationLock_ts_1.ComponentPreparationLockTimeoutError) {
2171
+ if (!failures.has(owner))
2172
+ failures.set(owner, failure);
2173
+ harper_logger_ts_1.default.info?.(`Deferred pruning the dormant staged builds of ${owner}: a deploy holds its lock`);
2174
+ }
2175
+ else {
2176
+ harper_logger_ts_1.default.warn(`Could not prune the dormant staged builds of ${owner}:`, (0, harper_logger_ts_1.errorForLog)(failure));
2177
+ }
2178
+ }
2179
+ return failures;
2180
+ }
2181
+ /**
2182
+ * Retire and sweep the rollback records a settled activation leaves. Retiring throws — it is what makes a
2183
+ * record non-authoritative, so a caller that removed the journal without it re-creates the inversion the
2184
+ * journal prevents. Sweeping the displaced tree only costs disk, so it is logged.
2185
+ */
2186
+ async function sweepAsideRecords(records, componentName, liveDirPath, asideStagingDir) {
2187
+ for (const record of records) {
2188
+ // RETIRING IS CORRECTNESS, not hygiene: the retired marker is what stops the legacy pass treating this
2189
+ // record as authoritative and restoring the displaced tree over the candidate that was just rolled
2190
+ // forward, once the journal that would otherwise hold it back is gone. A record left un-retired while the journal is removed re-creates exactly
2191
+ // the inversion this protocol exists to prevent, so a failure here PROPAGATES — the caller keeps the
2192
+ // journal and the next start retries.
2193
+ const retiredMarkerPath = await retireExtractionAside(record);
2194
+ // Sweeping the displaced tree is hygiene: it bounds disk, and a failure costs space rather than
2195
+ // correctness, so it is logged. The retired marker above already makes the record non-authoritative.
2196
+ await cleanupExtractionPaths({ name: componentName, dirPath: liveDirPath, logger: harper_logger_ts_1.default }, asideStagingDir, new Set([record, retiredMarkerPath])).catch((error) => harper_logger_ts_1.default.warn(`Settled ${componentName} but could not sweep ${record}:`, (0, harper_logger_ts_1.errorForLog)(error)));
2197
+ }
2198
+ }
2199
+ /**
2200
+ * Clear an earlier failed recovery's verdict once this settlement has decided. Treated as CORRECTNESS, not
2201
+ * cleanup: main would report the component settled and load it while every worker read the stale marker and
2202
+ * failed it closed, so a failure here throws and lets main reach the same verdict. The journal outlives it
2203
+ * either way, so the next start settles again.
2204
+ */
2205
+ async function clearUnsettledVerdict(deploymentDirPath, componentName) {
2206
+ try {
2207
+ await (0, promises_1.rm)((0, node_path_1.join)(deploymentDirPath, UNSETTLED_MARKER), { force: true });
2208
+ // Flushed here, not with whatever follows: the journal's removal must never be the one that survives
2209
+ // a crash alone, or the verdict outlives the only thing that would settle it again.
2210
+ await syncDirectory(deploymentDirPath);
2211
+ }
2212
+ catch (error) {
2213
+ throw new Error(`Could not clear the stale unsettled marker of ${componentName} at ` +
2214
+ `${(0, node_path_1.join)(deploymentDirPath, UNSETTLED_MARKER)}; the component stays failed closed on every thread ` +
2215
+ `until that file can be removed: ${errorMessage(error)}`, { cause: error });
2216
+ }
2217
+ }
2218
+ /**
2219
+ * One interrupted activation, under the component preparation lock. Ambiguity exists only while the live
2220
+ * path is absent, and there the `complete` marker is the roll-forward authority: without it the candidate
2221
+ * was never validated, so the committed tree in the aside wins. Every branch is idempotent, so a crash
2222
+ * during recovery is settled by the next run.
2223
+ */
2224
+ async function settleInterruptedActivation(componentsRootDirPath, deploymentDirPath, journal) {
2225
+ const liveDirPath = (0, node_path_1.join)(componentsRootDirPath, journal.component);
2226
+ const candidateDirPath = (0, node_path_1.join)(deploymentDirPath, journal.component);
2227
+ const asideStagingDir = extractionStagingDirectory(liveDirPath);
2228
+ const journalPath = (0, node_path_1.join)(deploymentDirPath, ACTIVATION_JOURNAL);
2229
+ const exists = async (path) => (0, promises_1.lstat)(path).then(() => true, (error) => {
2230
+ if (error.code === 'ENOENT')
2231
+ return false;
2232
+ throw error;
2233
+ });
2234
+ const liveExists = await exists(liveDirPath);
2235
+ const candidateExists = await exists(candidateDirPath);
2236
+ const candidateComplete = await exists((0, node_path_1.join)(deploymentDirPath, CANDIDATE_COMPLETE_MARKER));
2237
+ const asideRecords = await inProgressAsideRecords(asideStagingDir);
2238
+ const rollForward = async () => {
2239
+ if (!liveExists)
2240
+ await renameThroughTransientHolder(candidateDirPath, liveDirPath);
2241
+ // Unconditional, not only when THIS pass performed the rename: a crash after normal activation
2242
+ // renamed the candidate but before it repaired the links leaves live present with stale targets, and
2243
+ // gating the repair on the rename would skip exactly that case. Idempotent when there is nothing to
2244
+ // re-point.
2245
+ await repairRelocatedDependencyLinks(liveDirPath, candidateDirPath);
2246
+ await syncRenameParents(candidateDirPath, liveDirPath);
2247
+ // Retiring PROPAGATES from here: the retired marker is what stops the legacy pass restoring the tree
2248
+ // this roll-forward just displaced. Failing the component closed and retrying at the next start is
2249
+ // the cheaper mistake — the journal survives, so the verdict is re-derivable. Only the disk sweep
2250
+ // inside is best-effort.
2251
+ await sweepAsideRecords(asideRecords, journal.component, liveDirPath, asideStagingDir);
2252
+ };
2253
+ const rollBack = async (restoreFrom) => {
2254
+ if (restoreFrom) {
2255
+ await renameThroughTransientHolder(restoreFrom, liveDirPath);
2256
+ await syncRenameParents(restoreFrom, liveDirPath);
2257
+ }
2258
+ for (const record of asideRecords) {
2259
+ try {
2260
+ await (0, promises_1.rm)(record, { recursive: true, force: true });
2261
+ }
2262
+ catch (error) {
2263
+ // A record that survives removal is still AUTHORITATIVE to the legacy pass, and settlement is
2264
+ // about to remove the journal that holds that pass back — so it would restore this older tree
2265
+ // over the component just rolled back. Retiring is what makes a record non-authoritative, so
2266
+ // do that instead of logging and moving on. A retire that ALSO fails propagates: the journal
2267
+ // then survives and the next start retries, which is the same contract roll-forward uses.
2268
+ harper_logger_ts_1.default.warn(`Rolled ${journal.component} back but could not remove ${record}:`, (0, harper_logger_ts_1.errorForLog)(error));
2269
+ await retireExtractionAside(record);
2270
+ }
2271
+ }
2272
+ };
2273
+ if (!liveExists) {
2274
+ if (candidateExists && candidateComplete) {
2275
+ await rollForward();
2276
+ }
2277
+ else {
2278
+ // The tree that was moved aside is the last committed one. A `-prior-absent` record means there
2279
+ // was nothing live to begin with, so rolling back means leaving the component absent.
2280
+ const restorable = asideRecords.find((record) => !record.endsWith(PRIOR_ABSENT_RECORD_SUFFIX));
2281
+ if (!restorable && !asideRecords.length) {
2282
+ throw new Error(`Cannot settle the interrupted activation of ${journal.component}: it has neither a live tree, ` +
2283
+ `a complete candidate, nor a rollback record, so no version of it can be recovered`);
2284
+ }
2285
+ await rollBack(restorable);
2286
+ }
2287
+ }
2288
+ else if (candidateExists) {
2289
+ // Live and candidate both present normally means B1 never ran: the swap had not started, so the live
2290
+ // tree stands and the candidate goes.
2291
+ //
2292
+ // Unless a rollback record says B1 DID run. Then the committed tree is the one in the aside, and
2293
+ // whatever sits at the live path was put there afterwards — a previous-version worker recreating its
2294
+ // own directory, the case the extraction path guards with `identifyRollbackPlaceholder`. Rolling back
2295
+ // there deletes the committed tree AND the validated candidate and leaves that stub serving, so this
2296
+ // fails closed instead: both trees stay on disk for an operator to choose between.
2297
+ // NOT conditioned on the candidate being complete. `rollBack()` below removes every aside record, and
2298
+ // with a record present that tree is the last committed one — so deleting it destroys the only
2299
+ // surviving copy of the previous release whether or not the candidate was ever validated. What
2300
+ // `.complete` decides is which tree we would prefer, not whether discarding the other is safe.
2301
+ const displaced = asideRecords.find((record) => !record.endsWith(PRIOR_ABSENT_RECORD_SUFFIX));
2302
+ if (displaced) {
2303
+ throw new Error(`Cannot settle the interrupted activation of ${journal.component}: its previous tree was moved to ` +
2304
+ `${displaced}, but ${liveDirPath} exists again — something recreated it after the deploy moved ` +
2305
+ `it aside, so which tree is current cannot be determined without losing one of them. Remove ` +
2306
+ `whichever of the two is not the release you want once you have determined which that is.`);
2307
+ }
2308
+ // A STAGED artifact is not a disposable build. `rollBack()` removes the whole deployment directory,
2309
+ // which is right for an immediate deploy — the candidate came from a payload the operator still has —
2310
+ // but wrong for one somebody staged deliberately and may have had its payload reclaimed. The
2311
+ // descriptor is what tells the two apart, and it is on disk precisely so recovery can. Returning the
2312
+ // artifact to dormant by removing only the journal leaves it exactly as `deployment_id` expects it.
2313
+ if (await presentOrAbsent((0, node_path_1.join)(deploymentDirPath, CANDIDATE_ARTIFACT_FILE))) {
2314
+ // This branch returns early and so reaches none of the settled tail below — which can be careless
2315
+ // about both, because it removes the whole directory afterwards. This one keeps it, so the order
2316
+ // the two unlinks REACH STORAGE decides whether the artifact survives: `.unsettled` with no
2317
+ // journal is a verdict nothing will ever settle and the next retention pass deletes the build on.
2318
+ // Its flush is the barrier between the two unlinks: skipping it would let the journal's removal
2319
+ // persist alone, leaving a verdict nothing will settle again. Throwing is safe here and leaves the
2320
+ // journal, so the next start settles again. Windows cannot fsync a directory, which is why the
2321
+ // residue pass also refuses to read this state as disposable — see DESIGN.md.
2322
+ await clearUnsettledVerdict(deploymentDirPath, journal.component);
2323
+ await (0, promises_1.rm)(journalPath, { force: true });
2324
+ // Nothing may throw past the journal removal, the rule the settled tail follows: the caller
2325
+ // records a failure by writing `.unsettled`, which is the state this branch exists to avoid. An
2326
+ // unflushed removal is the safe direction — a power loss resurrects a journal that settles again.
2327
+ await syncDirectory(deploymentDirPath).catch((error) => harper_logger_ts_1.default.warn(`Returned the staged build ${(0, node_path_1.basename)(deploymentDirPath)} of ${journal.component} to dormant but ` +
2328
+ `could not flush that to storage; a power loss could resurrect its activation journal:`, (0, harper_logger_ts_1.errorForLog)(error)));
2329
+ harper_logger_ts_1.default.info?.(`Returned the staged build ${(0, node_path_1.basename)(deploymentDirPath)} of ${journal.component} to dormant after an ` +
2330
+ `activation that never moved its live tree aside`);
2331
+ return;
2332
+ }
2333
+ await rollBack();
2334
+ }
2335
+ else {
2336
+ // The candidate is already live; only the tail of the transaction was lost.
2337
+ await rollForward();
2338
+ }
2339
+ // The same ordering barrier normal activation uses, and for the same reason: the journal is the only
2340
+ // thing left telling the legacy pass not to restore an aside. Removing it while an
2341
+ // `.in-progress-*` record still names the displaced tree — because the retire or the sweep did not
2342
+ // reach storage — lets that pass put the old version back over the new one at the next start. Flush the
2343
+ // aside directory first, and leave the journal in place if that cannot be confirmed; recovery is
2344
+ // idempotent, so the next run settles it again.
2345
+ try {
2346
+ await syncDirectory(asideStagingDir);
2347
+ await syncDirectory((0, node_path_1.dirname)(asideStagingDir));
2348
+ }
2349
+ catch (error) {
2350
+ harper_logger_ts_1.default.warn(`Settled the interrupted activation of ${journal.component} but could not flush its rollback record; ` +
2351
+ `leaving the journal for the next start: ${errorMessage(error)}`);
2352
+ return;
2353
+ }
2354
+ // Best-effort, matching the activation path: the activation is settled by this point, so a transient
2355
+ // EBUSY removing staging must not throw out of the recovery pass and take the other components with it.
2356
+ // An earlier failed recovery may have left an unsettled marker here. Cleared BEFORE the journal and
2357
+ // treated as correctness: main would report this component settled and load it, while every worker read
2358
+ // the stale marker and failed it closed.
2359
+ await clearUnsettledVerdict(deploymentDirPath, journal.component);
2360
+ await (0, promises_1.rm)(journalPath, { force: true }).catch((error) => harper_logger_ts_1.default.warn(`Settled ${journal.component} but could not remove its activation journal:`, (0, harper_logger_ts_1.errorForLog)(error)));
2361
+ await (0, promises_1.rm)(deploymentDirPath, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }).catch((error) => harper_logger_ts_1.default.warn(`Settled ${journal.component} but could not clean up its staging directory:`, (0, harper_logger_ts_1.errorForLog)(error)));
2362
+ await (0, promises_1.rmdir)((0, node_path_1.dirname)(deploymentDirPath)).catch(() => { });
2363
+ }
2364
+ /** Mark a candidate build+validation complete. Idempotent, so a retried activation is not a failure. */
2365
+ /**
2366
+ * fsync the candidate's contents before `.complete` vouches for them — otherwise the control files can
2367
+ * outlive the tree after a power loss and recovery rolls forward onto a truncated one.
2368
+ */
2369
+ // Codes that mean "this platform or filesystem will not fsync this handle", as opposed to "the write did
2370
+ // not reach storage". Windows raises EPERM fsyncing perfectly healthy files, and network/overlay mounts
2371
+ // return EINVAL or ENOTSUP — none of which say anything about durability, and all of which would otherwise
2372
+ // fail every deploy on those platforms.
2373
+ const UNSUPPORTED_SYNC_CODES = new Set(['EPERM', 'EINVAL', 'ENOTSUP', 'EOPNOTSUPP', 'EBADF', 'EISDIR']);
2374
+ function isUnsupportedSync(error) {
2375
+ return UNSUPPORTED_SYNC_CODES.has(error?.code ?? '');
2376
+ }
2377
+ // How many file syncs run at once while flushing a candidate. Serial open/sync/close over a large
2378
+ // dependency tree adds seconds to every activation, all of it under the component preparation lock; a small
2379
+ // fan-out keeps the ordering guarantee (everything is synced before `.complete` is written) without paying
2380
+ // per-file latency one file at a time.
2381
+ const CANDIDATE_SYNC_CONCURRENCY = 16;
2382
+ // Directories walked at once when re-pointing dependency links after a swap; a pnpm or monorepo tree is
2383
+ // thousands of directories and a serial depth-first walk after every activation is a real cost.
2384
+ const LINK_REPAIR_CONCURRENCY = 8;
2385
+ async function syncTreeContents(rootPath, foreignTree = false) {
2386
+ // Real durability failures propagate: the deploy fails, which is safe because the live tree is
2387
+ // untouched. Platform "cannot fsync this handle" codes do not — treating those as durability failures
2388
+ // fails every deploy on Windows.
2389
+ const entries = await (0, promises_1.readdir)(rootPath, { withFileTypes: true }).catch((error) => {
2390
+ // Same reasoning as the per-file tolerance below: a directory inside a foreign tree that this uid
2391
+ // cannot list is not ours to make durable, and failing here fails a deploy over a directory the
2392
+ // deploy never wrote.
2393
+ if (foreignTree && error?.code === 'EACCES') {
2394
+ harper_logger_ts_1.default.trace?.(`Sync of ${rootPath} unavailable: ${errorMessage(error)}`);
2395
+ return undefined;
2396
+ }
2397
+ throw error;
2398
+ });
2399
+ if (!entries)
2400
+ return;
2401
+ const syncFile = async (entryPath) => {
2402
+ let handle;
2403
+ try {
2404
+ handle = await (0, promises_1.open)(entryPath, 'r');
2405
+ }
2406
+ catch (error) {
2407
+ // `foreignTree`: a `file:<directory>` candidate is a symlink to a tree this deploy does not own,
2408
+ // so it can hold files the Harper uid cannot open. Those are not ours to make durable and their
2409
+ // EACCES says nothing about whether the install output beside them reached storage — while
2410
+ // failing here would fail an otherwise valid deploy over a file the deploy never touched. The
2411
+ // install output itself is written as this uid, so it is readable and still fsynced.
2412
+ //
2413
+ // The limit of that: this cannot tell a developer's unreadable source file from an install
2414
+ // script that deliberately made its OWN output unreadable, so `.complete` could certify output
2415
+ // that was never synced. Only for a `file:` candidate, and only for a script that chmods its
2416
+ // own artifacts away from the uid that has to run them.
2417
+ if (isUnsupportedSync(error) || (foreignTree && error?.code === 'EACCES')) {
2418
+ harper_logger_ts_1.default.trace?.(`Sync of ${entryPath} unavailable: ${errorMessage(error)}`);
2419
+ return;
2420
+ }
2421
+ throw error;
2422
+ }
2423
+ try {
2424
+ await handle.sync();
2425
+ }
2426
+ catch (error) {
2427
+ if (!isUnsupportedSync(error))
2428
+ throw error;
2429
+ harper_logger_ts_1.default.trace?.(`Sync of ${entryPath} unsupported: ${errorMessage(error)}`);
2430
+ }
2431
+ finally {
2432
+ await handle.close().catch(() => { });
2433
+ }
2434
+ };
2435
+ const pending = [];
2436
+ for (const entry of entries) {
2437
+ const entryPath = (0, node_path_1.join)(rootPath, entry.name);
2438
+ if (entry.isDirectory()) {
2439
+ await syncTreeContents(entryPath, foreignTree);
2440
+ }
2441
+ else if (entry.isFile()) {
2442
+ pending.push(syncFile(entryPath));
2443
+ if (pending.length >= CANDIDATE_SYNC_CONCURRENCY) {
2444
+ await Promise.all(pending.splice(0));
2445
+ }
2446
+ }
2447
+ }
2448
+ await Promise.all(pending);
2449
+ await syncDirectory(rootPath);
2450
+ }
2451
+ async function markCandidateComplete(componentDirPath, deploymentId, componentName) {
2452
+ // Contents first: `.complete` is roll-forward AUTHORITY, so it must not be durable before the tree it
2453
+ // vouches for.
2454
+ //
2455
+ // A `file:<directory>` candidate IS a symlink to a tree this deploy does not own, but the dependency
2456
+ // install writes THROUGH it — so the tree still has to be walked, or the install output `.complete`
2457
+ // vouches for is never made durable. Only the foreign files alongside it are tolerated: see
2458
+ // `syncTreeContents`.
2459
+ const candidatePath = candidateApplicationPath(componentDirPath, deploymentId);
2460
+ const candidateIsLink = await (0, promises_1.lstat)(candidatePath).then((stats) => stats.isSymbolicLink(), (error) => {
2461
+ if (error.code === 'ENOENT')
2462
+ return false;
2463
+ throw error;
2464
+ });
2465
+ await syncTreeContents(candidatePath, candidateIsLink);
2466
+ try {
2467
+ await writeControlFileDurably(candidateComponentFilePath(componentDirPath, deploymentId), componentName);
2468
+ }
2469
+ catch (error) {
2470
+ if (error.code !== 'EEXIST')
2471
+ throw error;
2472
+ }
2473
+ try {
2474
+ await writeControlFileDurably(candidateCompleteMarkerPath(componentDirPath, deploymentId), '');
2475
+ }
2476
+ catch (error) {
2477
+ if (error.code !== 'EEXIST')
2478
+ throw error;
2479
+ }
2480
+ }
2481
+ /**
2482
+ * Make the newly created ancestors of a deployment directory durable, child-first.
2483
+ *
2484
+ * Only a staged artifact needs this. A deploy's own candidate is transient — power loss just abandons a
2485
+ * build nobody was told about — but a stage is ACKNOWLEDGED, and `writeControlFileDurably` flushes only the
2486
+ * control file's immediate parent while `ensureSecureStagingDirectory` flushes none. Without this a stage
2487
+ * can report success before the `.deploy-staging/<id>` entry exists on storage, and the automatic payload
2488
+ * reclaim may already have dropped the tarball it could have been rebuilt from. Best-effort on Windows, like
2489
+ * every other directory sync here.
2490
+ */
2491
+ async function syncArtifactAncestors(deploymentDirPath) {
2492
+ const stagingRoot = (0, node_path_1.dirname)(deploymentDirPath);
2493
+ for (const directory of [deploymentDirPath, stagingRoot, (0, node_path_1.dirname)(stagingRoot)]) {
2494
+ await syncDirectory(directory);
2495
+ }
2496
+ }
2497
+ /**
2498
+ * Make a built and validated candidate live, as one compensating transaction over two effects: the live tree
2499
+ * moves aside, then the candidate takes its place. Root config is NOT one of them — for an immediate deploy
2500
+ * it is still published before the build, unchanged, and making it transactional is tracked separately
2501
+ * (#2315). A delayed activation hands its artifact's recorded entry in as `afterJournal`, which publishes it
2502
+ * from inside the window a crash rolls forward from — see that call site.
2503
+ *
2504
+ * The candidate must ALREADY be certified: `markCandidateComplete` is the caller's, so a delayed activation
2505
+ * does not re-walk and re-fsync a whole dependency tree it certified when it was built. The activation
2506
+ * journal is still written and fsynced BEFORE the first rename, so a crash anywhere below is recoverable —
2507
+ * see `settleInterruptedActivation` for the state matrix. The second rename is the COMMIT POINT: nothing
2508
+ * after it may compensate, because the live path holds the candidate and renaming the aside back over it
2509
+ * cannot succeed.
2510
+ */
2511
+ async function activateCandidateApplication(application, deploymentId, options = {}) {
2512
+ const liveDirPath = application.dirPath;
2513
+ const candidateDirPath = candidateApplicationPath(liveDirPath, deploymentId);
2514
+ const deploymentDirPath = candidateDeploymentDirPath(liveDirPath, deploymentId);
2515
+ const asideStagingDir = extractionStagingDirectory(liveDirPath);
2516
+ // A symlink counts: a `file:<directory>` deploy links the source rather than extracting it, and that
2517
+ // link is what gets swapped into the live path.
2518
+ const candidateStat = await (0, promises_1.lstat)(candidateDirPath).catch((error) => {
2519
+ if (error.code === 'ENOENT')
2520
+ return undefined;
2521
+ throw error;
2522
+ });
2523
+ if (!candidateStat || !(candidateStat.isDirectory() || candidateStat.isSymbolicLink())) {
2524
+ throw new Error(`Cannot activate ${application.name}: no candidate build at ${candidateDirPath}`);
2525
+ }
2526
+ const journalPath = activationJournalPath(liveDirPath, deploymentId);
2527
+ // B1 — the live tree moves aside. It stays the rollback source until B4 retires it.
2528
+ let asidePath;
2529
+ let priorAbsentRecordPath;
2530
+ // The swap below moves the previous tree back and forth around every wait, so a chosen aside path no
2531
+ // longer implies the tree is at it — and compensation needs to know which.
2532
+ let liveIsDisplaced = false;
2533
+ const restoreLive = async () => {
2534
+ if (liveIsDisplaced) {
2535
+ await renameThroughTransientHolder(asidePath, liveDirPath);
2536
+ liveIsDisplaced = false;
2537
+ }
2538
+ else if (priorAbsentRecordPath)
2539
+ await (0, promises_1.rm)(priorAbsentRecordPath, { force: true });
2540
+ // Nothing was displaced and no record was written, so there is nothing to put back and no rename to
2541
+ // flush — the failure happened before the first effect.
2542
+ if (asidePath || priorAbsentRecordPath) {
2543
+ await syncRenameParents(asidePath ?? priorAbsentRecordPath, liveDirPath);
2544
+ }
2545
+ };
2546
+ /**
2547
+ * Put a compensated candidate back to DORMANT — complete, described, no journal — so it is a retryable
2548
+ * artifact rather than one the next preparation destroys.
2549
+ *
2550
+ * Without this, a failure that leaves the journal in place makes `settleStagingForComponent` read
2551
+ * live-plus-candidate as an activation that never got there and remove the whole deployment directory;
2552
+ * for a first deploy the restored state is live-ABSENT, and it rolls the candidate forward instead,
2553
+ * ahead of the caller's own verification. Both destroy an artifact whose whole purpose is to be
2554
+ * activated again.
2555
+ *
2556
+ * The unlink needs its own barrier: syncing the aside directories persists the rollback record's
2557
+ * disposal, not the journal's, so without this sync a power loss resurrects a journal the operator was
2558
+ * told had been rolled back. Best-effort by necessity — failing here must not replace the activation
2559
+ * failure the caller is reporting — so a failure says explicitly that the artifact is not retryable, and
2560
+ * the surviving journal is exactly what startup recovery settles.
2561
+ */
2562
+ const returnToDormant = async () => {
2563
+ try {
2564
+ await (0, promises_1.rm)(journalPath, { force: true });
2565
+ }
2566
+ catch (error) {
2567
+ application.logger.warn(`Restored ${application.name} after a failed activation, but its staged build ${deploymentId} still ` +
2568
+ `carries an activation journal and is not retryable until recovery settles it:`, error);
2569
+ return;
2570
+ }
2571
+ // The journal is gone in this process, so the artifact is retryable now; what is uncertain is whether
2572
+ // its removal reached storage.
2573
+ await syncDirectory(deploymentDirPath).catch((error) => application.logger.warn(`Restored ${application.name} and returned its staged build ${deploymentId} to a retryable state, but ` +
2574
+ `could not flush that to storage; a power loss could resurrect its activation journal:`, error));
2575
+ };
2576
+ /**
2577
+ * One pre-commit failure boundary, with the journal write inside it: every step from there to the commit
2578
+ * rename leaves a journal behind if it only rethrows, and the next settlement then deletes a certified
2579
+ * artifact, or (first deploy, live absent) activates it with nobody asking. Nothing below the commit
2580
+ * rename may enter this catch — see B2.
2581
+ */
2582
+ let pendingEffect = 'record the activation';
2583
+ let undoAfterJournal;
2584
+ try {
2585
+ try {
2586
+ await writeControlFileDurably(journalPath, JSON.stringify({
2587
+ v: ACTIVATION_JOURNAL_VERSION,
2588
+ component: application.name,
2589
+ candidateId: deploymentId,
2590
+ }));
2591
+ }
2592
+ catch (error) {
2593
+ // An existing journal is a retry of this same activation, not a conflict.
2594
+ if (error.code !== 'EEXIST')
2595
+ throw error;
2596
+ }
2597
+ pendingEffect = 'prepare the component staging directory';
2598
+ await ensureExtractionStagingDirectory(asideStagingDir);
2599
+ pendingEffect = 'read the live component directory';
2600
+ const liveExists = await (0, promises_1.lstat)(liveDirPath).then(() => true, (error) => {
2601
+ if (error.code === 'ENOENT')
2602
+ return false;
2603
+ throw error;
2604
+ });
2605
+ application.isNewComponent = !liveExists;
2606
+ pendingEffect = 'move the previous version aside';
2607
+ if (liveExists) {
2608
+ asidePath = (0, node_path_1.join)(asideStagingDir, `${IN_PROGRESS_ASIDE_PREFIX}${Date.now()}-${process.pid}-${(0, node_crypto_1.randomUUID)()}`);
2609
+ await renameThroughTransientHolder(liveDirPath, asidePath);
2610
+ liveIsDisplaced = true;
2611
+ }
2612
+ else {
2613
+ priorAbsentRecordPath = (0, node_path_1.join)(asideStagingDir, `${IN_PROGRESS_ASIDE_PREFIX}${Date.now()}-${process.pid}-${(0, node_crypto_1.randomUUID)()}${PRIOR_ABSENT_RECORD_SUFFIX}`);
2614
+ await (0, promises_1.writeFile)(priorAbsentRecordPath, '', { flag: 'wx', mode: 0o600 });
2615
+ }
2616
+ // Letting a storage failure escape here leaves live already moved aside, and the caller reads an
2617
+ // uncompensated throw as an ordinary build failure and discards the candidate, its `.complete` marker
2618
+ // and its journal: the component ends up with no version at all and nothing saying how to get one back.
2619
+ pendingEffect = 'record the displaced component directory';
2620
+ await syncRenameParents(liveDirPath, asidePath ?? priorAbsentRecordPath);
2621
+ // Config is published HERE — after B1, before the commit — because this is the only point where the
2622
+ // on-disk state recovery would find rolls FORWARD to the certified artifact: live is displaced, the
2623
+ // candidate is complete, and the rollback record exists. Publishing before B1 (with or without the
2624
+ // journal) leaves live present and the candidate present with no rollback record, which settlement
2625
+ // reads as an activation that never started: it deletes the deployment directory, and the next boot
2626
+ // re-resolves the published package identifier from the registry instead — the substitution this step
2627
+ // exists to prevent.
2628
+ //
2629
+ // A crash in the remaining window — after the roll-forward state exists but before this publish — is
2630
+ // the inverse hazard: `rollForward()` renames the candidate live and publishes nothing, so the
2631
+ // certified artifact serves under the PREVIOUS release's config. That includes its ISOLATION intent,
2632
+ // which is a containment boundary and not just a version string: a component staged to run isolated
2633
+ // comes back non-isolated after an ordinary crash, with nothing in the operation reporting it.
2634
+ // Closing it needs config to be an effect of the journal itself, which is #2315 step 3.
2635
+ pendingEffect = 'publish the root configuration';
2636
+ undoAfterJournal = await options.afterJournal?.();
2637
+ // B2 — the candidate becomes live. THE RENAME IS THE COMMIT POINT: nothing after it may compensate,
2638
+ // because the live path now holds the candidate and renaming the aside back over it cannot succeed. A
2639
+ // compensating step there fails its own rollback and reports a failure for a deploy that is live. It is
2640
+ // the LAST statement in this block for that reason.
2641
+ pendingEffect = 'move the candidate into place';
2642
+ await renameThroughTransientHolder(candidateDirPath, liveDirPath, {
2643
+ // The previous version occupies the live path through the wait rather than the component being
2644
+ // absent for the whole budget: a read of a component file, and any concurrent scan of the
2645
+ // components root, still finds the last committed tree. (Watchers are already paused for the
2646
+ // deploy, so they are not what this protects.) A first-ever deploy has nothing to put back.
2647
+ onBackoff: async (delayMs, deadline) => {
2648
+ if (!liveIsDisplaced)
2649
+ return (0, promises_3.setTimeout)(delayMs);
2650
+ await renameThroughTransientHolder(asidePath, liveDirPath, { deadline });
2651
+ liveIsDisplaced = false;
2652
+ await syncRenameParents(asidePath, liveDirPath);
2653
+ await (0, promises_3.setTimeout)(delayMs);
2654
+ await renameThroughTransientHolder(liveDirPath, asidePath, { deadline });
2655
+ liveIsDisplaced = true;
2656
+ await syncRenameParents(liveDirPath, asidePath);
2657
+ },
2658
+ });
2659
+ }
2660
+ catch (error) {
2661
+ // Whether the journal can still carry this activation forward, decided BEFORE compensation removes the
2662
+ // evidence it is read from. Only a first-ever deploy qualifies: `restoreLive` leaves the live path
2663
+ // absent, and recovery reads absent-plus-complete-candidate as a roll forward. A component that
2664
+ // already had a tree gets that tree back and loses its rollback record with it, so the next settle
2665
+ // reads live-plus-candidate-with-no-record and returns the artifact to dormant whatever the journal
2666
+ // says — keeping it there defers the same verdict to the next start and strands config until then.
2667
+ const recoveryCanRollForward = priorAbsentRecordPath !== undefined;
2668
+ await compensate(error, pendingEffect, restoreLive, application);
2669
+ let configRestored = true;
2670
+ if (undoAfterJournal) {
2671
+ configRestored = await undoAfterJournal().then(() => true, (undoError) => {
2672
+ application.logger.warn(`Restored ${application.name} after a failed activation but could not restore its root config, ` +
2673
+ `which still names deployment ${deploymentId}` +
2674
+ (recoveryCanRollForward
2675
+ ? '; keeping its activation journal so recovery can roll the certified build forward instead:'
2676
+ : '. The certified build stays dormant and the previous release stays live, so the two ' +
2677
+ 'disagree until an operator republishes the component or activates it again:'), undoError);
2678
+ return false;
2679
+ });
2680
+ }
2681
+ // Kept only where it changes the outcome. Config is stranded either way for a component that already
2682
+ // had a tree — the durable-config window #2315 step 3 closes — and a journal that recovery will only
2683
+ // settle back to dormant buys nothing for holding it.
2684
+ if (configRestored || !recoveryCanRollForward)
2685
+ await returnToDormant();
2686
+ throw error;
2687
+ }
2688
+ // Past the point of no return: each failure below leaves a state recovery settles forward, so they are
2689
+ // logged, not thrown.
2690
+ let swapDurable = true;
2691
+ try {
2692
+ await syncRenameParents(candidateDirPath, liveDirPath);
2693
+ }
2694
+ catch (error) {
2695
+ // The rename may not have reached storage. Retiring the record and removing the journal WOULD reach
2696
+ // it, and a power loss then leaves no live entry, no rollback record, and nothing saying to roll
2697
+ // forward. Both are skipped so the journal carries the activation to the next start.
2698
+ swapDurable = false;
2699
+ application.logger.warn(`Deployed ${application.name} but could not flush the swap to storage:`, error);
2700
+ }
2701
+ // The tree moved, so any dependency link that named its build path is now dangling.
2702
+ await repairRelocatedDependencyLinks(liveDirPath, candidateDirPath);
2703
+ const settledRecord = asidePath ?? priorAbsentRecordPath;
2704
+ let retired = false;
2705
+ // Skipped entirely when the swap is not known to be on storage, so the journal below survives.
2706
+ if (swapDurable) {
2707
+ try {
2708
+ const retiredMarkerPath = await retireExtractionAside(settledRecord);
2709
+ // Retiring only MARKS the displaced tree disposable. Without this sweep the tree every deploy
2710
+ // displaces stays under `.deploy-aside/<component>` forever, so the components root grows by a
2711
+ // whole component version per deploy.
2712
+ await cleanupExtractionPaths(application, asideStagingDir, new Set([settledRecord, retiredMarkerPath]));
2713
+ // Before the journal goes: if the journal's removal persists but the record's does not, startup sees
2714
+ // an in-progress aside with no journal and the legacy pass restores the old tree over the new one.
2715
+ await syncDirectory(asideStagingDir);
2716
+ await syncDirectory((0, node_path_1.dirname)(asideStagingDir));
2717
+ retired = true;
2718
+ }
2719
+ catch (error) {
2720
+ application.logger.warn(`Deployed ${application.name} but could not retire its rollback record:`, error);
2721
+ }
2722
+ }
2723
+ // The journal goes LAST, and only once the rollback record is settled: removing it while an
2724
+ // `.in-progress-*` record still names the displaced tree lets the legacy pass restore the old tree.
2725
+ if (retired) {
2726
+ await (0, promises_1.rm)(journalPath, { force: true }).catch((error) => application.logger.warn(`Deployed ${application.name} but could not remove its activation journal:`, error));
2727
+ await (0, promises_1.rm)(deploymentDirPath, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }).catch((error) => application.logger.warn(`Deployed ${application.name} but could not clean up its staging directory:`, error));
2728
+ await (0, promises_1.rmdir)((0, node_path_1.dirname)(deploymentDirPath)).catch(() => { });
2729
+ }
2730
+ }
2731
+ /**
2732
+ * Marks a failure where compensation ITSELF failed, so the previous version is not back and the live path
2733
+ * may be absent. The candidate, its `.complete` marker and its journal are then the only way back — recovery
2734
+ * rolls that state forward — so they must survive, and the caller keys on this to skip discarding them.
2735
+ */
2736
+ const COMPENSATION_INCOMPLETE = Symbol('compensationIncomplete');
2737
+ function compensationIncomplete(error) {
2738
+ return Boolean(error?.[COMPENSATION_INCOMPLETE]);
2739
+ }
2740
+ /**
2741
+ * Undo an activation effect, folding a compensation failure into the original error rather than replacing
2742
+ * it — the first error is what the operator needs, the second is why the node still needs attention.
2743
+ */
2744
+ async function compensate(error, what, undo, application) {
2745
+ try {
2746
+ await undo();
2747
+ }
2748
+ catch (undoError) {
2749
+ // Whatever blocked the original operation plausibly blocks its undo too — a rename into a path
2750
+ // something else holds open fails the same way twice.
2751
+ const failure = new AggregateError([error, undoError], `Failed to ${what} for ${application.name}: ${errorMessage(error)}; ` +
2752
+ `also failed to restore the previous version: ${errorMessage(undoError)}`);
2753
+ failure[COMPENSATION_INCOMPLETE] = true;
2754
+ throw failure;
2755
+ }
2756
+ }
2757
+ /**
2758
+ * Re-point dependency links that name the candidate's build path, now that it has become live. npm links a
2759
+ * `file:` dependency relatively on POSIX (survives the rename) but as an ABSOLUTE junction on Windows, which
2760
+ * then names a staging path that no longer exists. Rewriting beats `--install-links`, which would change
2761
+ * dependency semantics on every platform to fix one.
2762
+ */
2763
+ async function repairRelocatedDependencyLinks(liveDirPath, builtAtPath) {
2764
+ const relinkOne = async (entryPath) => {
2765
+ let target;
2766
+ try {
2767
+ target = await (0, promises_1.readlink)(entryPath);
2768
+ }
2769
+ catch {
2770
+ return;
2771
+ }
2772
+ const normalized = stripExtendedLengthPrefix(target);
2773
+ // Containment, not a prefix match: `startsWith` classifies `<build>-shared` as inside `<build>` and
2774
+ // would rewrite it to an unrelated live path.
2775
+ const within = (0, node_path_1.relative)(builtAtPath, normalized);
2776
+ if (within.startsWith('..') || (0, node_path_1.isAbsolute)(within))
2777
+ return;
2778
+ const repaired = (0, node_path_1.join)(liveDirPath, within);
2779
+ // The replacement is created BEFORE the old link is dropped, and swapped in by rename. A
2780
+ // remove-then-create loses the dependency outright when the create fails.
2781
+ const stagedLink = `${entryPath}.relink-${process.pid}-${(0, node_crypto_1.randomUUID)()}`;
2782
+ try {
2783
+ await (0, promises_1.symlink)(repaired, stagedLink, 'junction');
2784
+ try {
2785
+ await (0, promises_1.rename)(stagedLink, entryPath);
2786
+ }
2787
+ catch (renameError) {
2788
+ // Windows cannot rename over an existing junction, so the old one has to go first — and if the
2789
+ // second rename then fails the same way, the original target is put back rather than leaving
2790
+ // nothing behind.
2791
+ if (process.platform !== 'win32')
2792
+ throw renameError;
2793
+ await (0, promises_1.rm)(entryPath, { recursive: true, force: true });
2794
+ try {
2795
+ await (0, promises_1.rename)(stagedLink, entryPath);
2796
+ }
2797
+ catch (secondError) {
2798
+ await (0, promises_1.symlink)(normalized, entryPath, 'junction').catch(() => { });
2799
+ throw secondError;
2800
+ }
2801
+ }
2802
+ }
2803
+ catch (error) {
2804
+ await (0, promises_1.rm)(stagedLink, { recursive: true, force: true }).catch(() => { });
2805
+ harper_logger_ts_1.default.warn(`Could not re-point ${entryPath} after activation: ${errorMessage(error)}`);
2806
+ }
2807
+ };
2808
+ // ONE bounded pool over a shared queue, not per-directory concurrency: bounding each parent
2809
+ // independently let every one of N workers start N more, so a deep pnpm or monorepo tree fanned out to
2810
+ // thousands of simultaneous opens. An EMFILE there would surface as skipped subtrees and dangling links.
2811
+ const pending = [(0, node_path_1.join)(liveDirPath, 'node_modules')];
2812
+ let active = 0;
2813
+ const visit = async (dirPath) => {
2814
+ let entries;
2815
+ try {
2816
+ entries = await (0, promises_1.readdir)(dirPath, { withFileTypes: true });
2817
+ }
2818
+ catch (error) {
2819
+ // Not silent. A missing directory is ordinary — the tree has no `node_modules`, or an install
2820
+ // removed one — but an EACCES or EMFILE here means links under it were never examined, which is
2821
+ // exactly the state that leaves a component running against a dangling dependency.
2822
+ if (error?.code !== 'ENOENT') {
2823
+ harper_logger_ts_1.default.warn(`Could not scan ${dirPath} for links to re-point after activation:`, (0, harper_logger_ts_1.errorForLog)(error));
594
2824
  }
595
- if (gitRef) {
596
- tarballPath = await packGitReferenceWithoutScripts(application, gitRef, parentDirPath);
2825
+ return;
2826
+ }
2827
+ // Every directory, not just `@scope` containers and nested `node_modules`: a dependency installed from
2828
+ // outside the tree can be linked from deeper in.
2829
+ for (const entry of entries) {
2830
+ const entryPath = (0, node_path_1.join)(dirPath, entry.name);
2831
+ if (entry.isSymbolicLink())
2832
+ await relinkOne(entryPath);
2833
+ else if (entry.isDirectory())
2834
+ pending.push(entryPath);
2835
+ }
2836
+ };
2837
+ const worker = async () => {
2838
+ for (;;) {
2839
+ const next = pending.pop();
2840
+ if (next === undefined) {
2841
+ // Another worker may still be about to enqueue children, so only stop once nothing is in flight.
2842
+ if (active === 0)
2843
+ return;
2844
+ await new Promise((resolve) => setImmediate(resolve));
2845
+ continue;
597
2846
  }
598
- else {
599
- const packArgs = ['pack', '--json', application.packageIdentifier];
600
- if (!allowScripts) {
601
- packArgs.push('--ignore-scripts');
602
- }
603
- else if (application.gitCredentialEnv) {
604
- application.logger.warn(`Deploying ${application.name} from a git reference with install scripts enabled: the repository's ` +
605
- `prepare/build scripts and its dependencies' install scripts run on this node during the clone and ` +
606
- `can read the git credential. Unset install_allow_scripts to keep the credential out of their reach.`);
2847
+ active++;
2848
+ try {
2849
+ await visit(next);
2850
+ }
2851
+ finally {
2852
+ active--;
2853
+ }
2854
+ }
2855
+ };
2856
+ await Promise.all(Array.from({ length: LINK_REPAIR_CONCURRENCY }, worker));
2857
+ }
2858
+ /** Windows junction targets come back with an extended-length `\\?\` prefix that plain paths never have. */
2859
+ function stripExtendedLengthPrefix(target) {
2860
+ return target.startsWith('\\\\?\\') ? target.slice(4) : target;
2861
+ }
2862
+ /** Remove a candidate's whole deployment directory, best-effort — it is never the last good copy. */
2863
+ async function discardCandidate(application, deploymentId) {
2864
+ const deploymentDirPath = candidateDeploymentDirPath(application.dirPath, deploymentId);
2865
+ await (0, promises_1.rm)(deploymentDirPath, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }).catch((error) => application.logger.warn(`Failed to remove the abandoned deploy candidate at ${deploymentDirPath}:`, error));
2866
+ // And the staging root itself once nothing is in it, so an idle install leaves the components root as
2867
+ // it found it. ENOTEMPTY just means a concurrent deploy still owns a candidate.
2868
+ await (0, promises_1.rmdir)((0, node_path_1.dirname)(deploymentDirPath)).catch(() => { });
2869
+ }
2870
+ /**
2871
+ * Build a deploy candidate at `.deploy-staging/<deploymentId>/<component>`, leaving the live tree
2872
+ * completely untouched — this is what lets the previous version keep serving through the clone, the
2873
+ * extraction and the dependency install.
2874
+ *
2875
+ * Failure needs no compensation, which is the whole point: nothing about the live component was modified,
2876
+ * so the abandoned candidate is simply removed and the error propagates.
2877
+ */
2878
+ async function buildCandidateApplication(application, deploymentId, options = {}) {
2879
+ const deploymentDirPath = candidateDeploymentDirPath(application.dirPath, deploymentId);
2880
+ const candidateDirPath = candidateApplicationPath(application.dirPath, deploymentId);
2881
+ await ensureSecureStagingDirectory((0, node_path_1.dirname)(deploymentDirPath));
2882
+ await claimDeploymentDirectory(deploymentDirPath, application.name);
2883
+ try {
2884
+ // Replaced, not extracted into: a prior attempt on this id may have left a partial tree.
2885
+ await (0, promises_1.rm)(candidateDirPath, { recursive: true, force: true });
2886
+ const resolved = await resolveApplicationTarball(application);
2887
+ if (resolved.kind === 'link' && options.rejectLinkSource) {
2888
+ // What the operator asked for, not a server fault: the same component deploys immediately.
2889
+ throw new hdbError_ts_1.ClientError(`Cannot stage ${application.name} from ${application.packageIdentifier}: a 'file:' directory is linked ` +
2890
+ `rather than copied, so the bytes activated later are not the bytes this build certified`);
2891
+ }
2892
+ if (resolved.kind === 'link') {
2893
+ // A `file:` directory becomes a symlink AT THE CANDIDATE PATH, so it is validated and swapped in
2894
+ // like any other candidate instead of appearing at the live path unvalidated.
2895
+ await (0, promises_1.symlink)(resolved.sourceDirPath, candidateDirPath, 'dir');
2896
+ }
2897
+ else {
2898
+ const { tarball, tarballPath, shouldDeleteTarball } = resolved;
2899
+ try {
2900
+ await extractTarballInto(tarball, candidateDirPath, deploymentDirPath);
2901
+ }
2902
+ finally {
2903
+ if (!tarball.destroyed)
2904
+ tarball.destroy();
2905
+ if (shouldDeleteTarball && tarballPath) {
2906
+ await (0, promises_1.rm)(tarballPath, { force: true }).catch((error) => application.logger.warn(`Failed to remove temporary package ${tarballPath}:`, error));
607
2907
  }
608
- tarballPath = await runNpmPack(application, packArgs, parentDirPath, application.gitCredentialEnv);
609
2908
  }
610
- shouldDeleteTarball = true;
611
- tarball = (0, node_fs_1.createReadStream)(tarballPath);
612
2909
  }
2910
+ // The credential socket only has to be up for extraction — that is where npm resolves and clones a
2911
+ // git-reference package. Closed BEFORE the install so the dependency tree's own install scripts,
2912
+ // which are arbitrary code from the registry running as this uid, cannot ask the helper for the
2913
+ // deployer's git token. `prepareApplication`'s finally still calls this; it is idempotent.
2914
+ await application.cleanupGitCredentialSession();
2915
+ await installApplication(application, candidateDirPath);
2916
+ return candidateDirPath;
613
2917
  }
614
- // Replace any existing component directory atomically instead of clearing it in
615
- // place. A previous version's worker can still be running and actively writing
616
- // into this directory — e.g. a live Next.js app writing into `.next/cache` — and
617
- // an in-place recursive rm races that writer: rm empties `.next`, then its leaf
618
- // `rmdir('.next')` fails with ENOTEMPTY because the worker just re-created a cache
619
- // entry. (`force: true` only suppresses ENOENT; ENOTEMPTY is not retried unless
620
- // `maxRetries` is set, and a continuously-writing app would outlast retries
621
- // anyway.) Renaming the old directory aside is atomic and immune to the race: the
622
- // still-running worker keeps writing into the renamed inode harmlessly until it's
623
- // replaced on restart, and the aside copy is removed best-effort below.
624
- //
625
- // The aside lives under a hidden, component-scoped staging directory inside the
626
- // components root: same filesystem as the source so the rename stays atomic, the
627
- // leading dot keeps loadComponentDirectories from picking it up as a phantom
628
- // component, and the per-component path means a sibling component never collides
629
- // with (or sweeps) another's aside.
630
- const asideStagingDir = (0, node_path_1.join)((0, node_path_1.dirname)(application.dirPath), exports.ASIDE_STAGING_DIR, (0, node_path_1.basename)(application.dirPath));
631
- let asidePath;
632
- try {
633
- await (0, promises_1.access)(application.dirPath, promises_1.constants.F_OK);
634
- await (0, promises_1.mkdir)(asideStagingDir, { recursive: true });
635
- const candidateAsidePath = (0, node_path_1.join)(asideStagingDir, `${process.pid}-${Date.now()}-${(0, node_crypto_1.randomUUID)()}`);
636
- await (0, promises_1.rename)(application.dirPath, candidateAsidePath);
637
- asidePath = candidateAsidePath;
2918
+ catch (error) {
2919
+ await discardCandidate(application, deploymentId);
2920
+ throw error;
638
2921
  }
639
- catch (err) {
640
- // Ignore does not exist error
641
- if (err.code !== 'ENOENT') {
642
- throw err;
2922
+ }
2923
+ async function recoverOrCleanupStaleExtractionPaths(application, asideStagingDir) {
2924
+ const entries = await (0, promises_1.readdir)(asideStagingDir, { withFileTypes: true });
2925
+ const entryNames = new Set(entries.map((entry) => entry.name));
2926
+ const paths = new Set(entries.map((entry) => (0, node_path_1.join)(asideStagingDir, entry.name)));
2927
+ const recoveryRecords = entries
2928
+ .filter((entry) => isExtractionRecoveryRecord(entry) &&
2929
+ entry.name.startsWith(IN_PROGRESS_ASIDE_PREFIX) &&
2930
+ !entryNames.has(`${RETIRED_ASIDE_PREFIX}${entry.name.slice(IN_PROGRESS_ASIDE_PREFIX.length)}`))
2931
+ .map((entry) => ({
2932
+ entry,
2933
+ priorStateAbsent: isPriorAbsentRecoveryRecord(entry),
2934
+ timestamp: extractionAsideTimestamp(entry.name),
2935
+ }))
2936
+ .filter(({ timestamp }) => Number.isFinite(timestamp))
2937
+ .sort((left, right) => right.timestamp - left.timestamp);
2938
+ const recoveryRecord = recoveryRecords.find(({ priorStateAbsent }) => !priorStateAbsent) ??
2939
+ recoveryRecords.find(({ priorStateAbsent }) => priorStateAbsent);
2940
+ if (recoveryRecord) {
2941
+ // A journal outranks the record. Without this the pass restores the tree a completed activation
2942
+ // displaced, back over the candidate it committed — the inversion the journal exists to prevent, and
2943
+ // reachable on any thread whose settlement did not run or did not succeed. Enforced HERE, at the one
2944
+ // place a tree is restored, so every entry point is covered by construction rather than by each
2945
+ // caller remembering to settle first — and so a component with nothing left to restore still loads.
2946
+ const journaled = await journaledDeploymentForComponent((0, node_path_1.dirname)(application.dirPath), application.name);
2947
+ if (journaled) {
2948
+ throw new Error(`Refusing to restore ${application.name} from ${recoveryRecord.entry.name}: the interrupted ` +
2949
+ `activation in ${journaled} is not settled, and its journal is the only record of which tree ` +
2950
+ `is current. If that journal names no component at all it cannot settle itself; remove that ` +
2951
+ `directory once you have determined which tree is current.`);
2952
+ }
2953
+ const recoveryPath = (0, node_path_1.join)(asideStagingDir, recoveryRecord.entry.name);
2954
+ // Retire the losing candidates durably; a cleanup that fails must not let a later
2955
+ // pass adopt one of them and restore an older tree over the one recovered here.
2956
+ for (const { entry } of recoveryRecords) {
2957
+ if (entry === recoveryRecord.entry)
2958
+ continue;
2959
+ paths.add(await retireExtractionAside((0, node_path_1.join)(asideStagingDir, entry.name)));
643
2960
  }
2961
+ await rollbackExtractedDirectory(application, asideStagingDir, recoveryRecord.priorStateAbsent ? undefined : recoveryPath, paths, false);
2962
+ application.logger.warn((recoveryRecord.priorStateAbsent
2963
+ ? `Removed the partial ${application.name} component directory after an interrupted first deploy`
2964
+ : `Recovered the previous ${application.name} component directory after an interrupted deploy`) +
2965
+ (recoveryRecords.length > 1 ? `; discarded ${recoveryRecords.length - 1} older recovery candidates` : ''));
2966
+ return;
644
2967
  }
645
- // A directory existed for this component name prior to this deploy, so this is a redeploy of
646
- // an already-active component rather than a first-time deploy. See `isNewComponent` above.
647
- if (asidePath)
648
- application.isNewComponent = false;
2968
+ await cleanupExtractionPaths(application, asideStagingDir, paths);
2969
+ }
2970
+ function isPriorAbsentRecoveryRecord(entry) {
2971
+ return entry.isFile() && entry.name.endsWith(PRIOR_ABSENT_RECORD_SUFFIX);
2972
+ }
2973
+ function isExtractionRecoveryRecord(entry) {
2974
+ return entry.isDirectory() || entry.isSymbolicLink() || isPriorAbsentRecoveryRecord(entry);
2975
+ }
2976
+ function extractionAsideTimestamp(name) {
2977
+ const timestampEnd = name.indexOf('-', IN_PROGRESS_ASIDE_PREFIX.length);
2978
+ if (timestampEnd < 0)
2979
+ return Number.NaN;
2980
+ return Number(name.slice(IN_PROGRESS_ASIDE_PREFIX.length, timestampEnd));
2981
+ }
2982
+ async function recoverInterruptedComponentExtractions(componentsRootDirPath) {
2983
+ const stagingRoot = (0, node_path_1.join)(componentsRootDirPath, exports.ASIDE_STAGING_DIR);
2984
+ let entries;
649
2985
  try {
650
- await (0, promises_1.mkdir)(application.dirPath, { recursive: true });
651
- await (0, promises_2.pipeline)(tarball, (0, gunzip_maybe_1.default)(), (0, tar_fs_1.extract)(application.dirPath));
652
- const extracted = await (0, promises_1.readdir)(application.dirPath, { withFileTypes: true });
653
- if (extracted.length === 1 && extracted[0].isDirectory()) {
654
- const topLevelDirPath = (0, node_path_1.join)(application.dirPath, extracted[0].name);
655
- await (0, promises_1.mkdir)(asideStagingDir, { recursive: true });
656
- const tempDirPath = await (0, promises_1.mkdtemp)((0, node_path_1.join)(asideStagingDir, '.normalize-'));
657
- await (0, promises_1.cp)(topLevelDirPath, tempDirPath, { recursive: true });
658
- await (0, promises_1.rm)(topLevelDirPath, { recursive: true, force: true });
659
- await (0, promises_1.cp)(tempDirPath, application.dirPath, { recursive: true });
660
- await (0, promises_1.rm)(tempDirPath, { recursive: true, force: true });
2986
+ const stagingStat = await (0, promises_1.lstat)(stagingRoot);
2987
+ if (!stagingStat.isDirectory() || stagingStat.isSymbolicLink()) {
2988
+ throw new Error(`Component deploy staging path is not a directory: ${stagingRoot}`);
661
2989
  }
2990
+ entries = await (0, promises_1.readdir)(stagingRoot, { withFileTypes: true });
662
2991
  }
663
2992
  catch (error) {
2993
+ if (error.code === 'ENOENT')
2994
+ return new Map();
2995
+ throw error;
2996
+ }
2997
+ const failedComponents = new Map();
2998
+ await Promise.all(entries
2999
+ .filter((entry) => entry.isDirectory())
3000
+ .map(async (entry) => {
664
3001
  try {
665
- await rollbackExtractedDirectory(application, asideStagingDir, asidePath);
3002
+ await recoverInterruptedComponentExtraction(componentsRootDirPath, entry.name, false);
666
3003
  }
667
- catch (rollbackError) {
668
- throw new AggregateError([error, rollbackError], `Failed to extract ${application.name} and restore its previous component directory`);
3004
+ catch (error) {
3005
+ const recoveryError = error instanceof Error ? error : new Error(String(error));
3006
+ failedComponents.set(entry.name, recoveryError);
3007
+ const deferred = recoveryError instanceof componentPreparationLock_ts_1.ComponentPreparationLockTimeoutError;
3008
+ harper_logger_ts_1.default[deferred ? 'warn' : 'error'](`${deferred ? 'Deferring' : 'Not loading'} ${entry.name} because its interrupted component deployment ` +
3009
+ `${deferred ? 'is still being prepared' : 'could not be recovered'}:`, (0, harper_logger_ts_1.errorForLog)(recoveryError));
3010
+ }
3011
+ }));
3012
+ return failedComponents;
3013
+ }
3014
+ async function recoverInterruptedComponentExtraction(componentsRootDirPath, componentName, waitForPreparation = true, waitTimeoutMs = COMPONENT_RECOVERY_WAIT_TIMEOUT_MS) {
3015
+ const componentDirPath = (0, node_path_1.join)(componentsRootDirPath, componentName);
3016
+ await (0, componentPreparationLock_ts_1.withComponentPreparationLock)(componentDirPath, async () => {
3017
+ const asideStagingDir = extractionStagingDirectory(componentDirPath);
3018
+ try {
3019
+ await (0, promises_1.lstat)(asideStagingDir);
3020
+ }
3021
+ catch (error) {
3022
+ if (error.code === 'ENOENT')
3023
+ return;
3024
+ throw error;
669
3025
  }
3026
+ await ensureExtractionStagingDirectory(asideStagingDir);
3027
+ await recoverOrCleanupStaleExtractionPaths({ name: componentName, dirPath: componentDirPath, logger: harper_logger_ts_1.default }, asideStagingDir);
3028
+ }, {
3029
+ timeoutMs: waitForPreparation ? waitTimeoutMs : COMPONENT_RECOVERY_TRY_TIMEOUT_MS,
3030
+ purpose: COMPONENT_RECOVERY_LOCK_PURPOSE,
3031
+ renewTimeoutWhileOwnerAlive: waitForPreparation,
3032
+ onWait: (owner) => {
3033
+ harper_logger_ts_1.default.info(`Waiting to settle component deployment state for ${componentName}` +
3034
+ (owner ? ` held by process ${owner.pid}, thread ${owner.threadId}` : ''));
3035
+ },
3036
+ isOwnerAlive: (owner) => owner.pid !== process.pid || (0, manageThreads_js_1.isThreadRunning)(owner.threadId),
3037
+ });
3038
+ }
3039
+ async function retireComponentExtractionStaging(componentDirPath, componentName = (0, node_path_1.basename)(componentDirPath), componentLogger = harper_logger_ts_1.default) {
3040
+ const asideStagingDir = extractionStagingDirectory(componentDirPath);
3041
+ let entries;
3042
+ try {
3043
+ await (0, promises_1.lstat)(asideStagingDir);
3044
+ await ensureExtractionStagingDirectory(asideStagingDir);
3045
+ entries = await (0, promises_1.readdir)(asideStagingDir, { withFileTypes: true });
3046
+ }
3047
+ catch (error) {
3048
+ if (error.code === 'ENOENT')
3049
+ return;
670
3050
  throw error;
671
3051
  }
672
- // Clean up the original tarball
673
- if (shouldDeleteTarball && tarballPath) {
674
- await (0, promises_1.rm)(tarballPath, { force: true }).catch((error) => application.logger.warn(`Failed to remove temporary package ${tarballPath}:`, error));
3052
+ const paths = new Set(entries.map((entry) => (0, node_path_1.join)(asideStagingDir, entry.name)));
3053
+ for (const entry of entries) {
3054
+ if (!isExtractionRecoveryRecord(entry) || !entry.name.startsWith(IN_PROGRESS_ASIDE_PREFIX))
3055
+ continue;
3056
+ const markerPath = retiredMarkerForAside((0, node_path_1.join)(asideStagingDir, entry.name));
3057
+ try {
3058
+ await (0, promises_1.writeFile)(markerPath, '', { flag: 'wx', mode: 0o600 });
3059
+ }
3060
+ catch (error) {
3061
+ if (error.code !== 'EEXIST')
3062
+ throw error;
3063
+ }
3064
+ paths.add(markerPath);
675
3065
  }
676
- // Remove this component's aside copies. The old worker may still hold files open
677
- // in the just-renamed copy (the live writer that motivated the rename), so this is
678
- // best-effort: removing the whole staging subdirectory also clears leftovers from
679
- // earlier deploys whose workers have since exited, and a copy that survives because
680
- // its worker is still live is swept by the next deploy. The failure is expected in
681
- // the live-worker case, so it's logged at trace rather than as a warning.
682
- let settled = false;
683
- const transaction = {
684
- async commit() {
685
- if (settled)
686
- return;
687
- settled = true;
688
- await cleanupExtractionStaging(application, asideStagingDir);
689
- },
690
- async rollback() {
691
- if (settled)
692
- return;
693
- settled = true;
694
- await rollbackExtractedDirectory(application, asideStagingDir, asidePath);
695
- },
696
- };
697
- if (deferCommit)
698
- return transaction;
699
- await transaction.commit();
3066
+ await cleanupExtractionPaths({ name: componentName, dirPath: componentDirPath, logger: componentLogger }, asideStagingDir, paths);
700
3067
  }
701
- async function cleanupExtractionStaging(application, asideStagingDir) {
3068
+ async function dropComponentDirectory(componentDirPath, componentName = (0, node_path_1.basename)(componentDirPath), componentLogger = harper_logger_ts_1.default) {
3069
+ await retireComponentExtractionStaging(componentDirPath, componentName, componentLogger);
3070
+ const asideStagingDir = extractionStagingDirectory(componentDirPath);
3071
+ await ensureExtractionStagingDirectory(asideStagingDir);
3072
+ const droppedPath = (0, node_path_1.join)(asideStagingDir, `.dropped-${process.pid}-${Date.now()}-${(0, node_crypto_1.randomUUID)()}`);
3073
+ try {
3074
+ await (0, promises_1.rename)(componentDirPath, droppedPath);
3075
+ }
3076
+ catch (error) {
3077
+ if (error.code !== 'ENOENT')
3078
+ throw error;
3079
+ }
3080
+ await cleanupExtractionPaths({ name: componentName, dirPath: componentDirPath, logger: componentLogger }, asideStagingDir, new Set([droppedPath]));
3081
+ // A dropped component has no next deploy to bound its dormant builds.
702
3082
  try {
703
- await (0, promises_1.rm)(asideStagingDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
3083
+ await pruneDormantBuilds(componentName, await dormantBuildsOf((0, node_path_1.dirname)(componentDirPath), componentName), 0);
704
3084
  }
705
3085
  catch (error) {
706
- harper_logger_ts_1.default.trace?.(`Cleanup of previous ${application.name} component directory deferred: ${error.message}`);
3086
+ componentLogger.warn(`Dropped ${componentName} but could not reclaim its dormant staged builds:`, (0, harper_logger_ts_1.errorForLog)(error));
707
3087
  }
708
3088
  }
709
- async function rollbackExtractedDirectory(application, asideStagingDir, asidePath) {
710
- await (0, promises_1.mkdir)(asideStagingDir, { recursive: true });
711
- const retryableRenameCodes = new Set(['EEXIST', 'ENOTEMPTY', 'EPERM', 'EACCES', 'EBUSY']);
712
- const displaceCurrentDirectory = async () => {
3089
+ async function cleanupExtractionPaths(application, asideStagingDir, paths) {
3090
+ const retiredMarkers = [];
3091
+ for (const path of paths) {
3092
+ if ((0, node_path_1.basename)(path).startsWith(RETIRED_ASIDE_PREFIX)) {
3093
+ retiredMarkers.push(path);
3094
+ continue;
3095
+ }
3096
+ try {
3097
+ await (0, promises_1.rm)(path, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
3098
+ }
3099
+ catch (error) {
3100
+ application.logger.trace?.(`Cleanup of previous ${application.name} component directory deferred: ${errorMessage(error)}`);
3101
+ }
3102
+ }
3103
+ for (const markerPath of retiredMarkers) {
3104
+ const asidePath = (0, node_path_1.join)(asideStagingDir, `${IN_PROGRESS_ASIDE_PREFIX}${(0, node_path_1.basename)(markerPath).slice(RETIRED_ASIDE_PREFIX.length)}`);
3105
+ try {
3106
+ await (0, promises_1.access)(asidePath, promises_1.constants.F_OK);
3107
+ continue;
3108
+ }
3109
+ catch (error) {
3110
+ if (error.code !== 'ENOENT')
3111
+ continue;
3112
+ }
3113
+ await (0, promises_1.rm)(markerPath, { force: true }).catch((error) => application.logger.trace?.(`Cleanup of previous ${application.name} component directory deferred: ${errorMessage(error)}`));
3114
+ }
3115
+ await (0, promises_1.rmdir)(asideStagingDir).catch((error) => {
3116
+ if (!['ENOENT', 'ENOTEMPTY'].includes(error.code ?? '')) {
3117
+ application.logger.trace?.(`Cleanup of ${application.name} deploy staging directory deferred: ${errorMessage(error)}`);
3118
+ }
3119
+ });
3120
+ }
3121
+ async function rollbackExtractedDirectory(application, asideStagingDir, asidePath, transactionPaths, retainReplacement) {
3122
+ await ensureExtractionStagingDirectory(asideStagingDir);
3123
+ const retryableRenameCodes = new Set(['EEXIST', 'ENOTEMPTY', 'ENOTDIR', 'EISDIR', 'EPERM', 'EACCES', 'EBUSY']);
3124
+ const displaceCurrentDirectorySync = () => {
713
3125
  const displacedPath = (0, node_path_1.join)(asideStagingDir, `.failed-${process.pid}-${Date.now()}-${(0, node_crypto_1.randomUUID)()}`);
3126
+ try {
3127
+ (0, node_fs_1.renameSync)(application.dirPath, displacedPath);
3128
+ transactionPaths.add(displacedPath);
3129
+ return displacedPath;
3130
+ }
3131
+ catch (error) {
3132
+ if (error.code === 'ENOENT')
3133
+ return undefined;
3134
+ throw error;
3135
+ }
3136
+ };
3137
+ const displaceCurrentDirectory = async () => {
3138
+ const retryDeadline = Date.now() + 5000;
714
3139
  let lastError;
715
- for (let attempt = 0; attempt < 100; attempt++) {
3140
+ do {
3141
+ const displacedPath = (0, node_path_1.join)(asideStagingDir, `.failed-${process.pid}-${Date.now()}-${(0, node_crypto_1.randomUUID)()}`);
716
3142
  try {
717
3143
  await (0, promises_1.rename)(application.dirPath, displacedPath);
718
- return;
3144
+ transactionPaths.add(displacedPath);
3145
+ return displacedPath;
719
3146
  }
720
3147
  catch (error) {
721
3148
  const code = error.code;
722
3149
  if (code === 'ENOENT')
723
- return;
3150
+ return undefined;
724
3151
  if (!retryableRenameCodes.has(code ?? ''))
725
3152
  throw error;
726
3153
  lastError = error;
727
3154
  await (0, promises_3.setTimeout)(10);
728
3155
  }
729
- }
3156
+ } while (Date.now() < retryDeadline);
730
3157
  throw lastError;
731
3158
  };
732
- await displaceCurrentDirectory();
733
3159
  if (asidePath) {
734
- let restored = false;
3160
+ const asideIsSymbolicLink = (await (0, promises_1.lstat)(asidePath)).isSymbolicLink();
735
3161
  let restoreError;
736
- for (let attempt = 0; attempt < 100; attempt++) {
3162
+ let restoreRetryDeadline;
3163
+ let fallbackDisplacedPath;
3164
+ let placeholderIdentity = await identifyRollbackPlaceholder(application.dirPath);
3165
+ const failRestore = async (error) => {
3166
+ try {
3167
+ await makeRollbackPlaceholderMovable(application.dirPath, placeholderIdentity);
3168
+ if (retainReplacement && fallbackDisplacedPath) {
3169
+ const fallbackRetryDeadline = Date.now() + 5000;
3170
+ let fallbackRestoreError;
3171
+ do {
3172
+ let writerDisplacedPath;
3173
+ try {
3174
+ writerDisplacedPath = displaceCurrentDirectorySync();
3175
+ placeholderIdentity = undefined;
3176
+ (0, node_fs_1.renameSync)(fallbackDisplacedPath, application.dirPath);
3177
+ fallbackRestoreError = undefined;
3178
+ }
3179
+ catch (restoreFallbackError) {
3180
+ fallbackRestoreError = restoreFallbackError;
3181
+ }
3182
+ if (writerDisplacedPath) {
3183
+ await (0, promises_1.rm)(writerDisplacedPath, {
3184
+ recursive: true,
3185
+ force: true,
3186
+ maxRetries: 3,
3187
+ retryDelay: 100,
3188
+ });
3189
+ transactionPaths.delete(writerDisplacedPath);
3190
+ }
3191
+ if (fallbackRestoreError &&
3192
+ !retryableRenameCodes.has(fallbackRestoreError.code ?? '')) {
3193
+ throw fallbackRestoreError;
3194
+ }
3195
+ if (fallbackRestoreError) {
3196
+ await (0, promises_3.setTimeout)(10);
3197
+ }
3198
+ else {
3199
+ break;
3200
+ }
3201
+ } while (Date.now() < fallbackRetryDeadline);
3202
+ if (fallbackRestoreError)
3203
+ throw fallbackRestoreError;
3204
+ transactionPaths.delete(fallbackDisplacedPath);
3205
+ transactionPaths.add(await retireExtractionAside(asidePath));
3206
+ }
3207
+ if (placeholderIdentity) {
3208
+ try {
3209
+ const current = await (0, promises_1.lstat)(application.dirPath, { bigint: true });
3210
+ if (current.dev === placeholderIdentity.dev && current.ino === placeholderIdentity.ino) {
3211
+ await (0, promises_1.rm)(application.dirPath, {
3212
+ recursive: true,
3213
+ force: true,
3214
+ maxRetries: 3,
3215
+ retryDelay: 100,
3216
+ });
3217
+ placeholderIdentity = undefined;
3218
+ }
3219
+ }
3220
+ catch (placeholderError) {
3221
+ if (placeholderError.code !== 'ENOENT')
3222
+ throw placeholderError;
3223
+ }
3224
+ }
3225
+ const disposablePaths = new Set(transactionPaths);
3226
+ disposablePaths.delete(asidePath);
3227
+ await cleanupExtractionPaths(application, asideStagingDir, disposablePaths);
3228
+ }
3229
+ catch (fallbackError) {
3230
+ throw new AggregateError([error, fallbackError], `Failed to restore either the previous or replacement ${application.name} component directory`);
3231
+ }
3232
+ throw new Error(`Failed to restore ${asidePath} to the live component directory ${application.dirPath}: ${errorMessage(error)}`, { cause: error });
3233
+ };
3234
+ do {
737
3235
  try {
738
- await (0, promises_1.rename)(asidePath, application.dirPath);
739
- restored = true;
740
- break;
3236
+ if (placeholderIdentity) {
3237
+ const current = (0, node_fs_1.lstatSync)(application.dirPath, { bigint: true });
3238
+ if (current.dev === placeholderIdentity.dev && current.ino === placeholderIdentity.ino) {
3239
+ (0, node_fs_1.chmodSync)(application.dirPath, 0o700);
3240
+ (0, node_fs_1.renameSync)(asidePath, application.dirPath);
3241
+ }
3242
+ else {
3243
+ placeholderIdentity = undefined;
3244
+ await (0, promises_1.rename)(asidePath, application.dirPath);
3245
+ }
3246
+ }
3247
+ else {
3248
+ await (0, promises_1.rename)(asidePath, application.dirPath);
3249
+ }
3250
+ transactionPaths.delete(asidePath);
3251
+ await cleanupExtractionPaths(application, asideStagingDir, transactionPaths);
3252
+ return;
741
3253
  }
742
3254
  catch (error) {
743
3255
  restoreError = error;
744
- if (!retryableRenameCodes.has(error.code ?? ''))
745
- break;
746
- await displaceCurrentDirectory();
3256
+ if (!retryableRenameCodes.has(error.code ?? '')) {
3257
+ return failRestore(error);
3258
+ }
3259
+ let displacedPath;
3260
+ const displacedPlaceholderIdentity = placeholderIdentity;
3261
+ try {
3262
+ await makeRollbackPlaceholderMovable(application.dirPath, placeholderIdentity);
3263
+ displacedPath = await displaceCurrentDirectory();
3264
+ placeholderIdentity = undefined;
3265
+ if (displacedPath && displacedPlaceholderIdentity) {
3266
+ try {
3267
+ const displaced = await (0, promises_1.lstat)(displacedPath, { bigint: true });
3268
+ if (displaced.dev === displacedPlaceholderIdentity.dev &&
3269
+ displaced.ino === displacedPlaceholderIdentity.ino) {
3270
+ const displacedPlaceholderPath = displacedPath;
3271
+ displacedPath = undefined;
3272
+ await (0, promises_1.rm)(displacedPlaceholderPath, {
3273
+ recursive: true,
3274
+ force: true,
3275
+ maxRetries: 3,
3276
+ retryDelay: 100,
3277
+ });
3278
+ transactionPaths.delete(displacedPlaceholderPath);
3279
+ }
3280
+ }
3281
+ catch (placeholderCleanupError) {
3282
+ application.logger.trace?.(`Cleanup of the ${application.name} rollback placeholder deferred: ${errorMessage(placeholderCleanupError)}`);
3283
+ }
3284
+ }
3285
+ }
3286
+ catch (displaceError) {
3287
+ return failRestore(new AggregateError([error, displaceError], `Failed to clear the live ${application.name} component directory for rollback`));
3288
+ }
3289
+ if (displacedPath) {
3290
+ if (fallbackDisplacedPath) {
3291
+ try {
3292
+ await (0, promises_1.rm)(displacedPath, {
3293
+ recursive: true,
3294
+ force: true,
3295
+ maxRetries: 3,
3296
+ retryDelay: 100,
3297
+ });
3298
+ transactionPaths.delete(displacedPath);
3299
+ }
3300
+ catch (cleanupError) {
3301
+ return failRestore(new AggregateError([error, cleanupError], `Failed to discard a displaced ${application.name} writer directory during rollback`));
3302
+ }
3303
+ }
3304
+ else {
3305
+ fallbackDisplacedPath = displacedPath;
3306
+ }
3307
+ }
3308
+ restoreRetryDeadline ??= Date.now() + 5000;
3309
+ if (process.platform !== 'win32' && process.getuid?.() !== 0) {
3310
+ const stagedPlaceholderPath = (0, node_path_1.join)(asideStagingDir, `.rollback-placeholder-${process.pid}-${Date.now()}-${(0, node_crypto_1.randomUUID)()}`);
3311
+ try {
3312
+ if (asideIsSymbolicLink) {
3313
+ await (0, promises_1.writeFile)(stagedPlaceholderPath, '', { flag: 'wx', mode: 0o000 });
3314
+ }
3315
+ else {
3316
+ await (0, promises_1.mkdir)(stagedPlaceholderPath, { mode: 0o300 });
3317
+ }
3318
+ transactionPaths.add(stagedPlaceholderPath);
3319
+ let placeholderPlacementError;
3320
+ do {
3321
+ let writerDisplacedPath;
3322
+ try {
3323
+ writerDisplacedPath = displaceCurrentDirectorySync();
3324
+ (0, node_fs_1.renameSync)(stagedPlaceholderPath, application.dirPath);
3325
+ if (!asideIsSymbolicLink) {
3326
+ try {
3327
+ (0, node_fs_1.chmodSync)(application.dirPath, 0o100);
3328
+ }
3329
+ catch (chmodError) {
3330
+ try {
3331
+ (0, node_fs_1.renameSync)(application.dirPath, stagedPlaceholderPath);
3332
+ }
3333
+ catch (compensationError) {
3334
+ throw new AggregateError([chmodError, compensationError], `Failed to restrict and then restore the ${application.name} rollback placeholder`);
3335
+ }
3336
+ throw chmodError;
3337
+ }
3338
+ }
3339
+ transactionPaths.delete(stagedPlaceholderPath);
3340
+ placeholderPlacementError = undefined;
3341
+ }
3342
+ catch (placeholderError) {
3343
+ placeholderPlacementError = placeholderError;
3344
+ }
3345
+ if (writerDisplacedPath) {
3346
+ await (0, promises_1.rm)(writerDisplacedPath, {
3347
+ recursive: true,
3348
+ force: true,
3349
+ maxRetries: 3,
3350
+ retryDelay: 100,
3351
+ });
3352
+ transactionPaths.delete(writerDisplacedPath);
3353
+ }
3354
+ if (placeholderPlacementError &&
3355
+ !retryableRenameCodes.has(placeholderPlacementError.code ?? '')) {
3356
+ throw placeholderPlacementError;
3357
+ }
3358
+ if (!placeholderPlacementError)
3359
+ break;
3360
+ await (0, promises_3.setTimeout)(10);
3361
+ } while (Date.now() < restoreRetryDeadline);
3362
+ if (transactionPaths.has(stagedPlaceholderPath)) {
3363
+ throw new Error(`Failed to place the ${application.name} rollback placeholder before the deadline: ${errorMessage(placeholderPlacementError)}`, { cause: placeholderPlacementError });
3364
+ }
3365
+ const placeholder = await (0, promises_1.lstat)(application.dirPath, { bigint: true });
3366
+ placeholderIdentity = { dev: placeholder.dev, ino: placeholder.ino };
3367
+ }
3368
+ catch (placeholderError) {
3369
+ return failRestore(new AggregateError([error, placeholderError], `Failed to block a live ${application.name} writer during rollback`));
3370
+ }
3371
+ }
747
3372
  await (0, promises_3.setTimeout)(10);
748
3373
  }
3374
+ } while (restoreRetryDeadline !== undefined && Date.now() < restoreRetryDeadline);
3375
+ return failRestore(restoreError);
3376
+ }
3377
+ try {
3378
+ await displaceCurrentDirectory();
3379
+ }
3380
+ catch (displaceError) {
3381
+ try {
3382
+ await (0, promises_1.rm)(application.dirPath, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
3383
+ await cleanupExtractionPaths(application, asideStagingDir, transactionPaths);
3384
+ return;
3385
+ }
3386
+ catch (removeError) {
3387
+ throw new AggregateError([displaceError, removeError], `Failed to remove the partial ${application.name} component directory after extraction failed`);
749
3388
  }
750
- if (!restored)
751
- throw restoreError;
752
3389
  }
753
- await cleanupExtractionStaging(application, asideStagingDir);
3390
+ await cleanupExtractionPaths(application, asideStagingDir, transactionPaths);
3391
+ }
3392
+ /**
3393
+ * The one definition of how Harper invokes a package manager to install dependencies; every npm
3394
+ * entry point composes its arguments here rather than assembling its own.
3395
+ */
3396
+ function packageManagerInstallArguments(packageManagerName, allowInstallScripts, force = false) {
3397
+ const args = ['install'];
3398
+ if (force)
3399
+ args.push('--force');
3400
+ if (packageManagerName === 'npm')
3401
+ args.push('--omit=dev', '--no-audit', '--no-fund');
3402
+ if (!allowInstallScripts)
3403
+ args.push('--ignore-scripts');
3404
+ return args;
754
3405
  }
755
3406
  /**
756
- * Install an application to its relative `application.dirPath` using either a
757
- * configured `application.install` command, a derived package manager from the
758
- * application's `package.json#devEngines`, or falling back to the default
759
- * package manager, `npm`.
3407
+ * Install a component's dependencies into `buildDirPath` — the live path, or a candidate under
3408
+ * `.deploy-staging`. Explicit rather than repointing `application.dirPath`, which is read after preparation
3409
+ * too and would name a vanished directory if any failure path skipped the restore.
760
3410
  *
761
- * Will return early if `node_modules` already exists within the `application.dirPath`
3411
+ * Uses a configured `application.install` command, a package manager derived from the application's
3412
+ * `package.json#devEngines`, or the default, `npm`. Returns early when `node_modules` already exists or
3413
+ * when the manifest has no automatic install work. An explicitly selected non-npm manager is always
3414
+ * allowed to inspect its own workspace configuration, even when the root manifest has no production
3415
+ * dependencies.
762
3416
  *
763
- * This method may be called from any Harper thread as part of a serialized preparation.
3417
+ * May be called from any Harper thread as part of a serialized preparation.
764
3418
  */
765
- async function installApplication(application) {
3419
+ async function installApplication(application, buildDirPath = application.dirPath) {
766
3420
  let packageJSON;
767
3421
  try {
768
- packageJSON = JSON.parse(await (0, promises_1.readFile)((0, node_path_1.join)(application.dirPath, 'package.json'), 'utf8'));
3422
+ packageJSON = JSON.parse(await (0, promises_1.readFile)((0, node_path_1.join)(buildDirPath, 'package.json'), 'utf8'));
769
3423
  }
770
3424
  catch (err) {
771
3425
  if (err.code !== 'ENOENT')
@@ -776,7 +3430,7 @@ async function installApplication(application) {
776
3430
  }
777
3431
  try {
778
3432
  // Does node_modules exist?
779
- await (0, promises_1.access)((0, node_path_1.join)(application.dirPath, 'node_modules'), promises_1.constants.F_OK);
3433
+ await (0, promises_1.access)((0, node_path_1.join)(buildDirPath, 'node_modules'), promises_1.constants.F_OK);
780
3434
  application.logger.info(`Application ${application.name} already has node_modules; skipping install and treating the runtime as opaque for redeploy comparison`);
781
3435
  application.installationIsOpaque = true;
782
3436
  return;
@@ -786,13 +3440,17 @@ async function installApplication(application) {
786
3440
  throw err;
787
3441
  // If node_modules doesn't exist, we need to install dependencies
788
3442
  }
3443
+ const allowInstallScripts = !!application.install?.allowInstallScripts;
789
3444
  // If custom install command is specified, run it
790
3445
  if (application.install?.command) {
3446
+ if (application.install.allowInstallScripts === undefined) {
3447
+ application.logger.warn(`Application ${application.name} uses install_command without install_allow_scripts; package lifecycle scripts are disabled by default for npm and tools that honor npm_config_ignore_scripts, including npm run pre/post hooks. Set install_allow_scripts (or install.allowInstallScripts in root config) to true to opt in`);
3448
+ }
791
3449
  const [command, ...args] = application.install.command.split(' ');
792
3450
  const customOnLine = application.onInstallLine
793
3451
  ? (stream, line) => application.onInstallLine(command, stream, line)
794
3452
  : undefined;
795
- const { stdout, stderr, code } = await nonInteractiveSpawn(application.name, command, args, application.dirPath, application.install?.timeout, customOnLine, application.npmUserconfigPath);
3453
+ const { stdout, stderr, code } = await nonInteractiveSpawn(application.name, command, args, buildDirPath, application.install?.timeout, customOnLine, application.npmUserconfigPath, undefined, !allowInstallScripts);
796
3454
  // if it succeeds, return
797
3455
  if (code === 0) {
798
3456
  application.installationIsOpaque = true;
@@ -807,8 +3465,16 @@ async function installApplication(application) {
807
3465
  // and throw a descriptive error
808
3466
  throw new Error(`Failed to install dependencies for ${application.name} using custom install command: ${application.install.command}. Exit code: ${code}`);
809
3467
  }
810
- // Next, try package.json devEngines field
811
3468
  const { packageManager } = packageJSON.devEngines || {};
3469
+ if (dependencyFieldHasWork(packageJSON, 'devDependencies')) {
3470
+ application.logger.warn(`Application ${application.name} declares devDependencies; automatic npm installation omits them, while explicitly selected non-npm package managers retain their own install defaults. Use install_command when deployment requires custom behavior`);
3471
+ }
3472
+ if (!packageHasAutomaticInstallWork(packageJSON) &&
3473
+ !(allowInstallScripts && packageHasAllowedInstallLifecycleWork(packageJSON))) {
3474
+ application.logger.info(`Application ${application.name} has no production package work; skipping install`);
3475
+ return;
3476
+ }
3477
+ // Next, try package.json devEngines field
812
3478
  // Custom package manager specified
813
3479
  if (packageManager) {
814
3480
  // On any given system we want to leverage the `name` to match the package manager executable
@@ -833,8 +3499,7 @@ async function installApplication(application) {
833
3499
  const pmOnLine = application.onInstallLine
834
3500
  ? (stream, line) => application.onInstallLine(packageManager.name, stream, line)
835
3501
  : undefined;
836
- const { stdout, stderr, code } = await nonInteractiveSpawn(application.name, (application.packageManagerPrefix ? application.packageManagerPrefix + ' ' : '') + packageManager.name, application.install?.allowInstallScripts ? ['install'] : ['install', '--ignore-scripts'], // All of `npm`, `yarn`, and `pnpm` support the `install` command. If we need to configure options here we may have to use some other defaults though
837
- application.dirPath, application.install?.timeout, pmOnLine, application.npmUserconfigPath);
3502
+ const { stdout, stderr, code } = await nonInteractiveSpawn(application.name, (application.packageManagerPrefix ? application.packageManagerPrefix + ' ' : '') + packageManager.name, packageManagerInstallArguments(packageManager.name, allowInstallScripts), buildDirPath, application.install?.timeout, pmOnLine, application.npmUserconfigPath);
838
3503
  // if it succeeds, return
839
3504
  if (code === 0) {
840
3505
  if (application.install?.allowInstallScripts)
@@ -866,13 +3531,18 @@ async function installApplication(application) {
866
3531
  // But then fall through to installing with npm
867
3532
  }
868
3533
  // Finally, default to running `npm install`
869
- const npmInstallArgs = application.install?.allowInstallScripts
870
- ? ['install', '--force']
871
- : ['install', '--force', '--ignore-scripts'];
3534
+ const npmInstallArgs = packageManagerInstallArguments('npm', allowInstallScripts, true);
3535
+ // A candidate build is installed at a staging path and then RENAMED to the live path, so nothing npm
3536
+ // writes may depend on the build location. npm links a `file:` dependency relatively on POSIX, which
3537
+ // survives the move — but as an absolute junction on Windows, which does not, so the dependency stops
3538
+ // resolving once the tree moves. `--install-links` copies instead of linking, leaving no path to break.
3539
+ // win32 and candidate builds only, since it does change how `file:` dependencies behave.
3540
+ if (process.platform === 'win32' && buildDirPath !== application.dirPath)
3541
+ npmInstallArgs.push('--install-links');
872
3542
  const npmOnLine = application.onInstallLine
873
3543
  ? (stream, line) => application.onInstallLine('npm', stream, line)
874
3544
  : undefined;
875
- const { stdout, stderr, code } = await nonInteractiveSpawn(application.name, (application.packageManagerPrefix ? application.packageManagerPrefix + ' ' : '') + 'npm', npmInstallArgs, application.dirPath, application.install?.timeout, npmOnLine, application.npmUserconfigPath);
3545
+ const { stdout, stderr, code } = await nonInteractiveSpawn(application.name, (application.packageManagerPrefix ? application.packageManagerPrefix + ' ' : '') + 'npm', npmInstallArgs, buildDirPath, application.install?.timeout, npmOnLine, application.npmUserconfigPath);
876
3546
  // if it succeeds, return
877
3547
  if (code === 0) {
878
3548
  if (application.install?.allowInstallScripts)
@@ -893,6 +3563,7 @@ class Application {
893
3563
  name;
894
3564
  payload;
895
3565
  packageIdentifier;
3566
+ packLocalDirectory;
896
3567
  install;
897
3568
  onInstallLine;
898
3569
  dirPath;
@@ -917,6 +3588,7 @@ class Application {
917
3588
  constructor({ name, payload, packageIdentifier, install, onInstallLine, credentials }) {
918
3589
  this.name = name;
919
3590
  this.payload = payload;
3591
+ this.packLocalDirectory = shouldPackLocalDirectory(packageIdentifier);
920
3592
  this.packageIdentifier = packageIdentifier && derivePackageIdentifier(packageIdentifier);
921
3593
  this.install = install;
922
3594
  this.onInstallLine = onInstallLine;
@@ -1033,7 +3705,12 @@ exports.Application = Application;
1033
3705
  * during the installation process in order to actually resolve what the user specifies for a
1034
3706
  * component matching some of npm's package resolution rules.
1035
3707
  */
3708
+ function isBareAbsolutePackagePath(packageIdentifier) {
3709
+ return (0, node_path_1.isAbsolute)(packageIdentifier) || node_path_1.win32.isAbsolute(packageIdentifier);
3710
+ }
1036
3711
  function derivePackageIdentifier(packageIdentifier) {
3712
+ if (isBareAbsolutePackagePath(packageIdentifier))
3713
+ return `file:${packageIdentifier}`;
1037
3714
  if (packageIdentifier.includes(':')) {
1038
3715
  return packageIdentifier;
1039
3716
  }
@@ -1045,59 +3722,108 @@ function derivePackageIdentifier(packageIdentifier) {
1045
3722
  }
1046
3723
  return `github:${packageIdentifier}`;
1047
3724
  }
1048
- /**
1049
- * Extract and install the specified application.
1050
- *
1051
- * This method may be called from any Harper thread. Same-component calls are serialized across
1052
- * threads by the preparation lock below.
1053
- *
1054
- * Bracketed with `deploy:start`/`deploy:end` lifecycle broadcasts so every
1055
- * Harper thread's file watchers can suppress restart-on-change events while
1056
- * the component directory is being rewritten — see harper#488 and
1057
- * `components/deployLifecycle.ts`. The broadcast is best-effort: if it fails
1058
- * (e.g. workers haven't started yet during initial install), the deploy still
1059
- * proceeds.
1060
- *
1061
- * @param application The application to prepare.
1062
- * @returns A promise that resolves when all preparation steps complete.
1063
- */
1064
- async function prepareApplication(application) {
1065
- const deploymentId = await (0, deployLifecycle_ts_1.broadcastDeployStart)(application.name);
3725
+ function shouldPackLocalDirectory(packageIdentifier, platform = process.platform) {
3726
+ return platform === 'win32' && !!packageIdentifier && isBareAbsolutePackagePath(packageIdentifier);
3727
+ }
3728
+ async function prepareApplication(application, options = {}) {
3729
+ const lifecycleToken = await (0, deployLifecycle_ts_1.broadcastDeployStart)(application.name);
3730
+ const mode = options.mode ?? 'deploy';
3731
+ const artifactId = options.artifactId ?? lifecycleToken;
1066
3732
  try {
1067
3733
  const commandTimeoutMs = application.install?.timeout ?? DEFAULT_COMMAND_TIMEOUT_MS;
1068
3734
  await (0, componentPreparationLock_ts_1.withComponentPreparationLock)(application.dirPath, async () => {
3735
+ await options.beforePrepare?.();
3736
+ const asideStagingDir = extractionStagingDirectory(application.dirPath);
3737
+ let recoveryPending = true;
3738
+ try {
3739
+ await (0, promises_1.lstat)(asideStagingDir);
3740
+ }
3741
+ catch (error) {
3742
+ if (error.code !== 'ENOENT')
3743
+ throw error;
3744
+ recoveryPending = false;
3745
+ }
3746
+ // BEFORE the legacy pass. That pass refuses to restore while a journal survives, so skipping
3747
+ // this would not lose data — it would just stall the deploy behind its own unsettled state.
3748
+ //
3749
+ // The id this request names is pinned against the retention this runs. An activation would
3750
+ // otherwise have its own artifact deleted by its own preamble; and a redelivered stage would
3751
+ // have the artifact evicted out from under the exclusive claim below, which would then rebuild
3752
+ // different bytes under an id that already named some.
3753
+ await settleStagingForComponent((0, node_path_1.dirname)(application.dirPath), application.name, artifactId);
3754
+ if (recoveryPending) {
3755
+ await ensureExtractionStagingDirectory(asideStagingDir);
3756
+ await recoverOrCleanupStaleExtractionPaths(application, asideStagingDir);
3757
+ }
1069
3758
  const previousPackageMetadata = await readInstalledPackageMetadata(application.dirPath);
1070
- let extraction;
3759
+ // Determined before the swap, because both trees exist then: the runtime comparison below
3760
+ // wants the live version and the candidate side by side.
3761
+ application.isNewComponent = !(await (0, promises_1.lstat)(application.dirPath).then(() => true, (error) => {
3762
+ if (error.code === 'ENOENT')
3763
+ return false;
3764
+ throw error;
3765
+ }));
3766
+ if (mode === 'activate') {
3767
+ await activateStagedArtifact(application, artifactId, previousPackageMetadata, options);
3768
+ return;
3769
+ }
1071
3770
  try {
1072
- // Materialize the per-deploy `.npmrc` before extraction so both `npm pack` (extract) and
1073
- // `npm install` authenticate against the private registry; always remove it afterward.
3771
+ // Materialize the per-deploy `.npmrc` before the build so both `npm pack` and `npm install`
3772
+ // authenticate against the private registry; always remove it afterward.
1074
3773
  await application.writeTransientNpmrc();
3774
+ let candidateDirPath;
1075
3775
  try {
1076
- // The git credential socket only has to be up for extraction — that is where npm resolves and
1077
- // clones a git-reference package. Closing it before installApplication means the credential is
1078
- // already gone by the time the component's dependency tree (and any install script it is
1079
- // allowed to run) executes.
3776
+ // Backstop only: the builder closes the session as soon as extraction is done, so the
3777
+ // credential is already gone before any install script runs. This finally covers the paths
3778
+ // that fail before it gets there.
1080
3779
  await application.startGitCredentialSession();
1081
- extraction = await extractApplication(application, true);
3780
+ candidateDirPath = await buildCandidateApplication(application, artifactId, {
3781
+ rejectLinkSource: mode === 'stage',
3782
+ });
1082
3783
  }
1083
3784
  finally {
1084
3785
  await application.cleanupGitCredentialSession();
1085
3786
  }
1086
- await installApplication(application);
1087
- if (!application.isNewComponent) {
1088
- const currentPackageMetadata = await readInstalledPackageMetadata(application.dirPath);
1089
- application.packageMetadataChanged = installedRuntimeChanged(previousPackageMetadata, currentPackageMetadata, application.installationIsOpaque);
1090
- }
1091
- await extraction?.commit();
1092
- }
1093
- catch (error) {
1094
3787
  try {
1095
- await extraction?.rollback();
3788
+ // Validated while the previous version is still the one serving, so a candidate that
3789
+ // installs cleanly but throws at load is rejected without ever having been live.
3790
+ await options.validateCandidate?.(candidateDirPath);
3791
+ if (!application.isNewComponent) {
3792
+ application.packageMetadataChanged = installedRuntimeChanged(previousPackageMetadata, await readInstalledPackageMetadata(candidateDirPath), application.installationIsOpaque);
3793
+ }
3794
+ if (mode === 'stage') {
3795
+ await assertOwnedArtifactTree(candidateDirPath, application.name);
3796
+ // The descriptor goes first so `.complete` vouches for it: after this pair the artifact
3797
+ // is dormant, and a delayed activation reads its build's decisions from here because
3798
+ // nothing on disk carries them otherwise.
3799
+ const declared = options.describeArtifact?.() ?? { rootConfig: null, isolated: false };
3800
+ await writeArtifactDescriptor(application.dirPath, artifactId, {
3801
+ v: ARTIFACT_DESCRIPTOR_VERSION,
3802
+ component: application.name,
3803
+ rootConfig: declared.rootConfig,
3804
+ installationIsOpaque: application.installationIsOpaque,
3805
+ isolated: declared.isolated,
3806
+ });
3807
+ await markCandidateComplete(application.dirPath, artifactId, application.name);
3808
+ await syncArtifactAncestors(candidateDeploymentDirPath(application.dirPath, artifactId));
3809
+ return;
3810
+ }
3811
+ await markCandidateComplete(application.dirPath, artifactId, application.name);
3812
+ await activateCandidateApplication(application, artifactId);
1096
3813
  }
1097
- catch (rollbackError) {
1098
- throw new AggregateError([error, rollbackError], `Failed to prepare ${application.name} and restore its previous component directory`);
3814
+ catch (error) {
3815
+ // The builder's own cleanup only covers a failed BUILD. A rejected validation, or an
3816
+ // activation that was cleanly compensated, would otherwise leave a whole installed
3817
+ // dependency tree under this deployment id — repeated rejections fill the volume.
3818
+ //
3819
+ // NOT when compensation itself failed. There the previous version is not back and the live
3820
+ // path may be absent, and the candidate plus its `.complete` marker and journal are exactly
3821
+ // what recovery needs to roll the validated deploy forward at the next start. Discarding
3822
+ // them there trades a bounded disk cost for a component with no version at all.
3823
+ if (!compensationIncomplete(error))
3824
+ await discardCandidate(application, artifactId);
3825
+ throw error;
1099
3826
  }
1100
- throw error;
1101
3827
  }
1102
3828
  finally {
1103
3829
  await application.cleanupTransientNpmrc();
@@ -1116,8 +3842,70 @@ async function prepareApplication(application) {
1116
3842
  });
1117
3843
  }
1118
3844
  finally {
1119
- (0, deployLifecycle_ts_1.broadcastDeployEnd)(application.name, deploymentId);
3845
+ (0, deployLifecycle_ts_1.broadcastDeployEnd)(application.name, lifecycleToken);
3846
+ }
3847
+ }
3848
+ /**
3849
+ * Swap an already-certified artifact into the live path. Called with the component's preparation lock held
3850
+ * and after the same recovery preamble every build runs, so the state read here is settled.
3851
+ *
3852
+ * Nothing is resolved, fetched or installed: the bytes were certified when they were staged, which is the
3853
+ * whole point of addressing one by id. Verification is therefore the only gate, and it is strict — this is
3854
+ * activation input for a build this process did not make and may not have made on this node.
3855
+ *
3856
+ * A rejection here must NOT discard: the artifact belongs to whoever staged it, a wrong-component request
3857
+ * must not delete another component's build, and a retry needs what a failed attempt left behind.
3858
+ */
3859
+ async function activateStagedArtifact(application, artifactId, previousPackageMetadata, options) {
3860
+ const deploymentDirPath = candidateDeploymentDirPath(application.dirPath, artifactId);
3861
+ const candidateDirPath = candidateApplicationPath(application.dirPath, artifactId);
3862
+ // 404 means only one thing — no artifact answers to this id here — so a caller can tell "never existed or
3863
+ // already used" from "present, but not something this can activate", which is every other refusal below
3864
+ // and a 409 like the rest of that family.
3865
+ const refuse = (why, statusCode) => new hdbError_ts_1.ClientError(`Cannot deploy ${application.name} from deployment ${artifactId}: ${why}`, statusCode);
3866
+ const missing = (why) => refuse(why, 404);
3867
+ const unusable = (why) => refuse(why, 409);
3868
+ const owner = await candidateComponentName(deploymentDirPath);
3869
+ if (owner === undefined)
3870
+ throw missing('there is no staged build with that id on this node');
3871
+ if (owner !== application.name)
3872
+ throw unusable(`that staged build belongs to '${owner}'`);
3873
+ if (!(await presentOrAbsent((0, node_path_1.join)(deploymentDirPath, CANDIDATE_COMPLETE_MARKER)))) {
3874
+ throw unusable('its build never completed');
3875
+ }
3876
+ if (await presentOrAbsent((0, node_path_1.join)(deploymentDirPath, UNSETTLED_MARKER))) {
3877
+ throw unusable('recovery could not settle it, so it is not safe to activate');
3878
+ }
3879
+ if (await presentOrAbsent((0, node_path_1.join)(deploymentDirPath, ACTIVATION_JOURNAL))) {
3880
+ throw unusable('an activation of it is unsettled');
3881
+ }
3882
+ const candidateStat = await presentOrAbsent(candidateDirPath);
3883
+ if (!candidateStat || !candidateStat.isDirectory()) {
3884
+ // Unlike an immediate deploy, a symlink is refused: a `file:` directory is linked rather than
3885
+ // copied, so what it points at now is not what was certified. Staging rejects the source for the
3886
+ // same reason; this is the other end of the same rule, for an artifact staged by an older build.
3887
+ throw unusable('its build tree is missing or is a link rather than a copy');
1120
3888
  }
3889
+ const descriptor = await readArtifactDescriptor(deploymentDirPath, application.name);
3890
+ if (!descriptor)
3891
+ throw unusable('it does not record what its build decided');
3892
+ await options.admitIsolation?.(descriptor);
3893
+ // `.complete` is a durability marker over the bytes, not a seal on them, and every check that made this
3894
+ // artifact safe ran at stage time. The link rule especially cannot be skipped:
3895
+ // `repairRelocatedDependencyLinks` runs past the commit point and can only warn, so a link planted while
3896
+ // the artifact sat dormant would otherwise go live with the operation reporting success.
3897
+ await assertOwnedArtifactTree(candidateDirPath, application.name, 'activate');
3898
+ // Also the activation's `prepare` phase end: the deploy path emits `prepare`/`start` for every mode but
3899
+ // only ever emitted its `done` from here.
3900
+ await options.validateCandidate?.(candidateDirPath);
3901
+ if (!application.isNewComponent) {
3902
+ application.packageMetadataChanged = installedRuntimeChanged(previousPackageMetadata, await readInstalledPackageMetadata(candidateDirPath), descriptor.installationIsOpaque);
3903
+ }
3904
+ await activateCandidateApplication(application, artifactId, {
3905
+ // Returns its own undo, which the swap runs inside its pre-commit boundary — see there for why it
3906
+ // cannot be run out here.
3907
+ afterJournal: descriptor.rootConfig ? () => options.publishRootConfig(descriptor.rootConfig) : undefined,
3908
+ });
1121
3909
  }
1122
3910
  /**
1123
3911
  * Install all applications specified in the root config.
@@ -1403,19 +4191,6 @@ function buildNpmrcContent(registryCredentials) {
1403
4191
  }
1404
4192
  return lines.join('\n') + '\n';
1405
4193
  }
1406
- /**
1407
- * Execute a command (using `spawn`) with stdin ignored.
1408
- *
1409
- * Stdout is logged chunk-by-chunk. Stderr is buffered and then logged line-by-line.
1410
- *
1411
- * Rejects with an error if the command fails or times out.
1412
- *
1413
- * @param command The command to run.
1414
- * @param args The arguments to pass to the command.
1415
- * @param cwd The working directory for the command.
1416
- * @param timeoutMs The timeout for the command in milliseconds. Defaults to 5 minutes.
1417
- * @returns A promise that resolves when the command completes.
1418
- */
1419
4194
  /**
1420
4195
  * Line-buffered split that emits complete `\n`-terminated lines as they
1421
4196
  * arrive, holding any partial trailing fragment until the next chunk or `flush()`.
@@ -1454,20 +4229,31 @@ function createLineSplitter(onLine) {
1454
4229
  };
1455
4230
  }
1456
4231
  /**
1457
- * Run a command with the deploy's SSH key material materialized only for the duration of the
1458
- * spawn. The keys are decrypted to a transient 0700 dir (see `materializeGitSSH`) and removed as
1459
- * soon as the process settles — on success, failure, and timeout alike.
4232
+ * Execute a command (using `spawn`) with stdin ignored, with the deploy's SSH key material
4233
+ * materialized only for the duration of the spawn. The keys are decrypted to a transient 0700 dir
4234
+ * (see `materializeGitSSH`) and removed as soon as the process settles — on success, failure, and
4235
+ * timeout alike.
4236
+ *
4237
+ * Stdout is logged chunk-by-chunk. Stderr is buffered and then logged line-by-line.
4238
+ *
4239
+ * Rejects with an error if the command fails or times out.
4240
+ *
4241
+ * @param command The command to run.
4242
+ * @param args The arguments to pass to the command.
4243
+ * @param cwd The working directory for the command.
4244
+ * @param timeoutMs The timeout for the command in milliseconds. Defaults to DEFAULT_COMMAND_TIMEOUT_MS.
4245
+ * @returns A promise that resolves when the command completes.
1460
4246
  */
1461
- async function nonInteractiveSpawn(applicationName, command, args, cwd, timeoutMs = DEFAULT_COMMAND_TIMEOUT_MS, onLine, npmUserconfigPath, gitCredentialEnv) {
4247
+ async function nonInteractiveSpawn(applicationName, command, args, cwd, timeoutMs = DEFAULT_COMMAND_TIMEOUT_MS, onLine, npmUserconfigPath, gitCredentialEnv, ignoreNpmScripts = false) {
1462
4248
  const gitSSH = await materializeGitSSH();
1463
4249
  try {
1464
- return await spawnWithEnv(applicationName, command, args, cwd, timeoutMs, onLine, npmUserconfigPath, gitSSH?.command, gitCredentialEnv);
4250
+ return await spawnWithEnv(applicationName, command, args, cwd, timeoutMs, onLine, npmUserconfigPath, gitSSH?.command, gitCredentialEnv, ignoreNpmScripts);
1465
4251
  }
1466
4252
  finally {
1467
4253
  await gitSSH?.cleanup();
1468
4254
  }
1469
4255
  }
1470
- function spawnWithEnv(applicationName, command, args, cwd, timeoutMs, onLine, npmUserconfigPath, gitSSHCommand, gitCredentialEnv) {
4256
+ function spawnWithEnv(applicationName, command, args, cwd, timeoutMs, onLine, npmUserconfigPath, gitSSHCommand, gitCredentialEnv, ignoreNpmScripts) {
1471
4257
  return new Promise((resolve, reject) => {
1472
4258
  harper_logger_ts_1.default
1473
4259
  .loggerWithTag(`${applicationName}:spawn:${command}`)
@@ -1500,9 +4286,17 @@ function spawnWithEnv(applicationName, command, args, cwd, timeoutMs, onLine, np
1500
4286
  }
1501
4287
  env.npm_config_userconfig = npmUserconfigPath;
1502
4288
  }
4289
+ if (ignoreNpmScripts) {
4290
+ for (const key of Object.keys(env)) {
4291
+ if (key.toLowerCase() === 'npm_config_ignore_scripts')
4292
+ delete env[key];
4293
+ }
4294
+ env.npm_config_ignore_scripts = 'true';
4295
+ }
1503
4296
  if (process.platform === 'win32' && command === 'npm') {
1504
4297
  command = 'npm.cmd';
1505
4298
  }
4299
+ const spawnLogger = harper_logger_ts_1.default.loggerWithTag(`${applicationName}:spawn:${command}`);
1506
4300
  const childProcess = (0, node_child_process_1.spawn)(command, args, {
1507
4301
  shell: true,
1508
4302
  cwd,
@@ -1591,7 +4385,19 @@ function spawnWithEnv(applicationName, command, args, cwd, timeoutMs, onLine, np
1591
4385
  reject(error);
1592
4386
  }
1593
4387
  });
1594
- childProcess.on('close', async (code) => {
4388
+ childProcess.on('exit', (code, signal) => {
4389
+ spawnLogger.debug?.(`Direct child exited with code ${code}, signal ${signal}; awaiting stdio close`);
4390
+ });
4391
+ childProcess.on('close', async (code, signal) => {
4392
+ if (didTimeout) {
4393
+ spawnLogger.debug?.(`Child stdio closed with code ${code}, signal ${signal}; timeout path owns process-tree confirmation`);
4394
+ }
4395
+ else if (trackedProcessId) {
4396
+ spawnLogger.debug?.(`Child stdio closed with code ${code}, signal ${signal}; confirming process-tree termination`);
4397
+ }
4398
+ else {
4399
+ spawnLogger.debug?.(`Child stdio closed with code ${code}, signal ${signal}; no process tree was tracked`);
4400
+ }
1595
4401
  resolveClose();
1596
4402
  clearTimeout(timeout);
1597
4403
  // A successful direct-child exit does not prove the process group is empty: a custom
@@ -1613,6 +4419,7 @@ function spawnWithEnv(applicationName, command, args, cwd, timeoutMs, onLine, np
1613
4419
  }
1614
4420
  return;
1615
4421
  }
4422
+ spawnLogger.debug?.(`Process tree termination confirmed after command close with code ${code}`);
1616
4423
  untrackProcessGroup();
1617
4424
  }
1618
4425
  // When didTimeout is true, the timeout path's own terminateProcessTree(...).then(...) owns
@@ -1624,7 +4431,6 @@ function spawnWithEnv(applicationName, command, args, cwd, timeoutMs, onLine, np
1624
4431
  if (stderr) {
1625
4432
  printStd(applicationName, command, stderr, 'stderr');
1626
4433
  }
1627
- harper_logger_ts_1.default.loggerWithTag(`${applicationName}:spawn:${command}`).debug?.(`Process exited with code ${code}`);
1628
4434
  if (didTimeout || didSettle)
1629
4435
  return;
1630
4436
  didSettle = true;
@@ -1647,13 +4453,7 @@ class CommandTimeoutError extends Error {
1647
4453
  }
1648
4454
  }
1649
4455
  function processGroupIsAlive(processGroupId) {
1650
- try {
1651
- process.kill(-processGroupId, 0);
1652
- return true;
1653
- }
1654
- catch (error) {
1655
- return error.code === 'EPERM';
1656
- }
4456
+ return (0, manageThreads_js_1.isProcessGroupAlive)(processGroupId);
1657
4457
  }
1658
4458
  async function waitForProcessGroupExit(processGroupId, timeoutMs) {
1659
4459
  const deadline = performance.now() + timeoutMs;