charness 3.11.0 → 3.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (390) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/DEVELOPMENT.md +3 -3
  3. package/README.md +1 -1
  4. package/SETUP.md +6 -5
  5. package/agent-plugin/README.md +15 -6
  6. package/agent-plugin/skills/charness-delegate-claude/SKILL.md +23 -13
  7. package/agent-plugin/skills/charness-delegate-opencode/SKILL.md +10 -6
  8. package/agent-plugin/skills/charness-delivery-loop/SKILL.md +92 -0
  9. package/agent-plugin/skills/charness-orchestration/SKILL.md +116 -0
  10. package/dist/adapters/openCodeAdapter.d.ts +15 -0
  11. package/dist/adapters/openCodeAdapter.d.ts.map +1 -1
  12. package/dist/adapters/openCodeAdapter.js +48 -4
  13. package/dist/adapters/openCodeAdapter.js.map +1 -1
  14. package/dist/agentLogin/agentLogin.d.ts +11 -0
  15. package/dist/agentLogin/agentLogin.d.ts.map +1 -1
  16. package/dist/agentLogin/agentLogin.js +18 -6
  17. package/dist/agentLogin/agentLogin.js.map +1 -1
  18. package/dist/apiErrorRetry.d.ts +5 -0
  19. package/dist/apiErrorRetry.d.ts.map +1 -1
  20. package/dist/apiErrorRetry.js +3 -3
  21. package/dist/apiErrorRetry.js.map +1 -1
  22. package/dist/bot.d.ts.map +1 -1
  23. package/dist/bot.js +158 -20
  24. package/dist/bot.js.map +1 -1
  25. package/dist/cli/claudeProfiles.d.ts +5 -2
  26. package/dist/cli/claudeProfiles.d.ts.map +1 -1
  27. package/dist/cli/claudeProfiles.js +43 -20
  28. package/dist/cli/claudeProfiles.js.map +1 -1
  29. package/dist/cli/claudeProfilesCredit.d.ts +49 -0
  30. package/dist/cli/claudeProfilesCredit.d.ts.map +1 -0
  31. package/dist/cli/claudeProfilesCredit.js +160 -0
  32. package/dist/cli/claudeProfilesCredit.js.map +1 -0
  33. package/dist/cli/flagValue.d.ts +10 -0
  34. package/dist/cli/flagValue.d.ts.map +1 -0
  35. package/dist/cli/flagValue.js +17 -0
  36. package/dist/cli/flagValue.js.map +1 -0
  37. package/dist/connectors/telegram/commands/botSkills.js +1 -1
  38. package/dist/connectors/telegram/commands/claudeAccounts.d.ts +6 -1
  39. package/dist/connectors/telegram/commands/claudeAccounts.d.ts.map +1 -1
  40. package/dist/connectors/telegram/commands/claudeAccounts.js +9 -6
  41. package/dist/connectors/telegram/commands/claudeAccounts.js.map +1 -1
  42. package/dist/connectors/telegram/commands/compaction.d.ts +11 -0
  43. package/dist/connectors/telegram/commands/compaction.d.ts.map +1 -1
  44. package/dist/connectors/telegram/commands/compaction.js +208 -22
  45. package/dist/connectors/telegram/commands/compaction.js.map +1 -1
  46. package/dist/connectors/telegram/commands/runners.d.ts +5 -1
  47. package/dist/connectors/telegram/commands/runners.d.ts.map +1 -1
  48. package/dist/connectors/telegram/commands/runners.js +146 -31
  49. package/dist/connectors/telegram/commands/runners.js.map +1 -1
  50. package/dist/connectors/telegram/runnerPairingMessages.d.ts +2 -7
  51. package/dist/connectors/telegram/runnerPairingMessages.d.ts.map +1 -1
  52. package/dist/connectors/telegram/runnerPairingMessages.js +5 -19
  53. package/dist/connectors/telegram/runnerPairingMessages.js.map +1 -1
  54. package/dist/i18n/de.d.ts.map +1 -1
  55. package/dist/i18n/de.js +52 -8
  56. package/dist/i18n/de.js.map +1 -1
  57. package/dist/i18n/en.d.ts.map +1 -1
  58. package/dist/i18n/en.js +52 -8
  59. package/dist/i18n/en.js.map +1 -1
  60. package/dist/i18n/es.d.ts.map +1 -1
  61. package/dist/i18n/es.js +52 -8
  62. package/dist/i18n/es.js.map +1 -1
  63. package/dist/i18n/fr.d.ts.map +1 -1
  64. package/dist/i18n/fr.js +52 -8
  65. package/dist/i18n/fr.js.map +1 -1
  66. package/dist/i18n/hi.d.ts.map +1 -1
  67. package/dist/i18n/hi.js +52 -8
  68. package/dist/i18n/hi.js.map +1 -1
  69. package/dist/i18n/ja.d.ts.map +1 -1
  70. package/dist/i18n/ja.js +52 -8
  71. package/dist/i18n/ja.js.map +1 -1
  72. package/dist/i18n/ka.d.ts.map +1 -1
  73. package/dist/i18n/ka.js +52 -8
  74. package/dist/i18n/ka.js.map +1 -1
  75. package/dist/i18n/pt.d.ts.map +1 -1
  76. package/dist/i18n/pt.js +52 -8
  77. package/dist/i18n/pt.js.map +1 -1
  78. package/dist/i18n/ru.d.ts.map +1 -1
  79. package/dist/i18n/ru.js +52 -8
  80. package/dist/i18n/ru.js.map +1 -1
  81. package/dist/i18n/uk.d.ts.map +1 -1
  82. package/dist/i18n/uk.js +52 -8
  83. package/dist/i18n/uk.js.map +1 -1
  84. package/dist/i18n/uz.d.ts.map +1 -1
  85. package/dist/i18n/uz.js +52 -8
  86. package/dist/i18n/uz.js.map +1 -1
  87. package/dist/i18n/zh.d.ts.map +1 -1
  88. package/dist/i18n/zh.js +52 -8
  89. package/dist/i18n/zh.js.map +1 -1
  90. package/dist/installManager.d.ts.map +1 -1
  91. package/dist/installManager.js +3 -0
  92. package/dist/installManager.js.map +1 -1
  93. package/dist/instanceLock.d.ts.map +1 -1
  94. package/dist/instanceLock.js +2 -1
  95. package/dist/instanceLock.js.map +1 -1
  96. package/dist/platform/outbound.d.ts +14 -1
  97. package/dist/platform/outbound.d.ts.map +1 -1
  98. package/dist/platform/outbound.js.map +1 -1
  99. package/dist/remoteRun/cleanReport.d.ts +45 -0
  100. package/dist/remoteRun/cleanReport.d.ts.map +1 -0
  101. package/dist/remoteRun/cleanReport.js +84 -0
  102. package/dist/remoteRun/cleanReport.js.map +1 -0
  103. package/dist/remoteRun/cliArgs.d.ts +18 -0
  104. package/dist/remoteRun/cliArgs.d.ts.map +1 -1
  105. package/dist/remoteRun/cliArgs.js +100 -4
  106. package/dist/remoteRun/cliArgs.js.map +1 -1
  107. package/dist/remoteRun/commands.d.ts +30 -1
  108. package/dist/remoteRun/commands.d.ts.map +1 -1
  109. package/dist/remoteRun/commands.js +84 -9
  110. package/dist/remoteRun/commands.js.map +1 -1
  111. package/dist/remoteRun/exitCodes.d.ts +5 -0
  112. package/dist/remoteRun/exitCodes.d.ts.map +1 -1
  113. package/dist/remoteRun/exitCodes.js +6 -1
  114. package/dist/remoteRun/exitCodes.js.map +1 -1
  115. package/dist/remoteRun/foreground.d.ts +6 -0
  116. package/dist/remoteRun/foreground.d.ts.map +1 -1
  117. package/dist/remoteRun/foreground.js +13 -1
  118. package/dist/remoteRun/foreground.js.map +1 -1
  119. package/dist/remoteRun/interrupts.d.ts.map +1 -1
  120. package/dist/remoteRun/interrupts.js +2 -2
  121. package/dist/remoteRun/interrupts.js.map +1 -1
  122. package/dist/remoteRun/jobFiles.d.ts +6 -1
  123. package/dist/remoteRun/jobFiles.d.ts.map +1 -1
  124. package/dist/remoteRun/jobFiles.js +14 -0
  125. package/dist/remoteRun/jobFiles.js.map +1 -1
  126. package/dist/remoteRun/jobId.d.ts +5 -0
  127. package/dist/remoteRun/jobId.d.ts.map +1 -1
  128. package/dist/remoteRun/jobId.js +10 -0
  129. package/dist/remoteRun/jobId.js.map +1 -1
  130. package/dist/remoteRun/jobState.d.ts.map +1 -1
  131. package/dist/remoteRun/jobState.js +3 -2
  132. package/dist/remoteRun/jobState.js.map +1 -1
  133. package/dist/remoteRun/pairedRunners.d.ts +1 -1
  134. package/dist/remoteRun/pairedRunners.d.ts.map +1 -1
  135. package/dist/remoteRun/pairedRunners.js +4 -0
  136. package/dist/remoteRun/pairedRunners.js.map +1 -1
  137. package/dist/remoteRun/pathPatterns.d.ts +1 -1
  138. package/dist/remoteRun/pathPatterns.js +1 -1
  139. package/dist/remoteRun/probe.d.ts +58 -5
  140. package/dist/remoteRun/probe.d.ts.map +1 -1
  141. package/dist/remoteRun/probe.js +107 -11
  142. package/dist/remoteRun/probe.js.map +1 -1
  143. package/dist/remoteRun/probeTiming.d.ts +15 -0
  144. package/dist/remoteRun/probeTiming.d.ts.map +1 -0
  145. package/dist/remoteRun/probeTiming.js +23 -0
  146. package/dist/remoteRun/probeTiming.js.map +1 -0
  147. package/dist/remoteRun/project.d.ts +5 -0
  148. package/dist/remoteRun/project.d.ts.map +1 -1
  149. package/dist/remoteRun/project.js +10 -0
  150. package/dist/remoteRun/project.js.map +1 -1
  151. package/dist/remoteRun/projectConfig.d.ts +8 -1
  152. package/dist/remoteRun/projectConfig.d.ts.map +1 -1
  153. package/dist/remoteRun/projectConfig.js +18 -5
  154. package/dist/remoteRun/projectConfig.js.map +1 -1
  155. package/dist/remoteRun/pruneReport.d.ts +48 -0
  156. package/dist/remoteRun/pruneReport.d.ts.map +1 -0
  157. package/dist/remoteRun/pruneReport.js +80 -0
  158. package/dist/remoteRun/pruneReport.js.map +1 -0
  159. package/dist/remoteRun/remoteRunCli.d.ts +1 -1
  160. package/dist/remoteRun/remoteRunCli.d.ts.map +1 -1
  161. package/dist/remoteRun/remoteRunCli.js +20 -0
  162. package/dist/remoteRun/remoteRunCli.js.map +1 -1
  163. package/dist/remoteRun/runnerClient.d.ts +10 -0
  164. package/dist/remoteRun/runnerClient.d.ts.map +1 -1
  165. package/dist/remoteRun/runnerClient.js +19 -5
  166. package/dist/remoteRun/runnerClient.js.map +1 -1
  167. package/dist/remoteRun/runnerWait.d.ts.map +1 -1
  168. package/dist/remoteRun/runnerWait.js +2 -1
  169. package/dist/remoteRun/runnerWait.js.map +1 -1
  170. package/dist/remoteRun/runners.d.ts +48 -7
  171. package/dist/remoteRun/runners.d.ts.map +1 -1
  172. package/dist/remoteRun/runners.js +105 -40
  173. package/dist/remoteRun/runners.js.map +1 -1
  174. package/dist/remoteRun/runnersConfig.d.ts +24 -0
  175. package/dist/remoteRun/runnersConfig.d.ts.map +1 -1
  176. package/dist/remoteRun/runnersConfig.js +29 -2
  177. package/dist/remoteRun/runnersConfig.js.map +1 -1
  178. package/dist/remoteRun/ssh.d.ts +3 -3
  179. package/dist/remoteRun/ssh.d.ts.map +1 -1
  180. package/dist/remoteRun/ssh.js +19 -5
  181. package/dist/remoteRun/ssh.js.map +1 -1
  182. package/dist/remoteRun/submit.d.ts +1 -1
  183. package/dist/remoteRun/submit.d.ts.map +1 -1
  184. package/dist/remoteRun/submit.js +30 -2
  185. package/dist/remoteRun/submit.js.map +1 -1
  186. package/dist/runnerUtility/adminService.d.ts.map +1 -1
  187. package/dist/runnerUtility/adminService.js +5 -5
  188. package/dist/runnerUtility/adminService.js.map +1 -1
  189. package/dist/runnerUtility/appInstall.d.ts +9 -0
  190. package/dist/runnerUtility/appInstall.d.ts.map +1 -1
  191. package/dist/runnerUtility/appInstall.js +12 -2
  192. package/dist/runnerUtility/appInstall.js.map +1 -1
  193. package/dist/runnerUtility/execEnv.d.ts +1 -1
  194. package/dist/runnerUtility/execEnv.d.ts.map +1 -1
  195. package/dist/runnerUtility/execEnv.js +23 -5
  196. package/dist/runnerUtility/execEnv.js.map +1 -1
  197. package/dist/runnerUtility/guiAgentHeal.d.ts +3 -3
  198. package/dist/runnerUtility/guiAgentHeal.d.ts.map +1 -1
  199. package/dist/runnerUtility/guiAgentHeal.js +4 -2
  200. package/dist/runnerUtility/guiAgentHeal.js.map +1 -1
  201. package/dist/runnerUtility/homeFolders.d.ts +1 -0
  202. package/dist/runnerUtility/homeFolders.d.ts.map +1 -1
  203. package/dist/runnerUtility/homeFolders.js +2 -1
  204. package/dist/runnerUtility/homeFolders.js.map +1 -1
  205. package/dist/runnerUtility/iosCheck.d.ts +2 -0
  206. package/dist/runnerUtility/iosCheck.d.ts.map +1 -1
  207. package/dist/runnerUtility/iosCheck.js +12 -3
  208. package/dist/runnerUtility/iosCheck.js.map +1 -1
  209. package/dist/runnerUtility/keepAwake.d.ts +47 -10
  210. package/dist/runnerUtility/keepAwake.d.ts.map +1 -1
  211. package/dist/runnerUtility/keepAwake.js +108 -31
  212. package/dist/runnerUtility/keepAwake.js.map +1 -1
  213. package/dist/runnerUtility/launcher.d.ts +4 -0
  214. package/dist/runnerUtility/launcher.d.ts.map +1 -1
  215. package/dist/runnerUtility/launcher.js +31 -13
  216. package/dist/runnerUtility/launcher.js.map +1 -1
  217. package/dist/runnerUtility/linkLoop.d.ts +4 -0
  218. package/dist/runnerUtility/linkLoop.d.ts.map +1 -1
  219. package/dist/runnerUtility/linkLoop.js +15 -6
  220. package/dist/runnerUtility/linkLoop.js.map +1 -1
  221. package/dist/runnerUtility/managedNode.d.ts +84 -0
  222. package/dist/runnerUtility/managedNode.d.ts.map +1 -0
  223. package/dist/runnerUtility/managedNode.js +165 -0
  224. package/dist/runnerUtility/managedNode.js.map +1 -0
  225. package/dist/runnerUtility/nodeOnPath.d.ts +10 -0
  226. package/dist/runnerUtility/nodeOnPath.d.ts.map +1 -0
  227. package/dist/runnerUtility/nodeOnPath.js +49 -0
  228. package/dist/runnerUtility/nodeOnPath.js.map +1 -0
  229. package/dist/runnerUtility/nodeUpkeep.d.ts +140 -0
  230. package/dist/runnerUtility/nodeUpkeep.d.ts.map +1 -0
  231. package/dist/runnerUtility/nodeUpkeep.js +348 -0
  232. package/dist/runnerUtility/nodeUpkeep.js.map +1 -0
  233. package/dist/runnerUtility/nodeUpkeepTiming.d.ts +14 -0
  234. package/dist/runnerUtility/nodeUpkeepTiming.d.ts.map +1 -0
  235. package/dist/runnerUtility/nodeUpkeepTiming.js +21 -0
  236. package/dist/runnerUtility/nodeUpkeepTiming.js.map +1 -0
  237. package/dist/runnerUtility/packageManagerShims.d.ts +10 -0
  238. package/dist/runnerUtility/packageManagerShims.d.ts.map +1 -1
  239. package/dist/runnerUtility/packageManagerShims.js +67 -3
  240. package/dist/runnerUtility/packageManagerShims.js.map +1 -1
  241. package/dist/runnerUtility/pueueDaemon.d.ts +73 -8
  242. package/dist/runnerUtility/pueueDaemon.d.ts.map +1 -1
  243. package/dist/runnerUtility/pueueDaemon.js +90 -15
  244. package/dist/runnerUtility/pueueDaemon.js.map +1 -1
  245. package/dist/runnerUtility/runnerCommands.d.ts +7 -1
  246. package/dist/runnerUtility/runnerCommands.d.ts.map +1 -1
  247. package/dist/runnerUtility/runnerCommands.js +119 -16
  248. package/dist/runnerUtility/runnerCommands.js.map +1 -1
  249. package/dist/runnerUtility/runnerHome.d.ts +34 -0
  250. package/dist/runnerUtility/runnerHome.d.ts.map +1 -1
  251. package/dist/runnerUtility/runnerHome.js +17 -3
  252. package/dist/runnerUtility/runnerHome.js.map +1 -1
  253. package/dist/runnerUtility/serviceCommon.d.ts +2 -0
  254. package/dist/runnerUtility/serviceCommon.d.ts.map +1 -1
  255. package/dist/runnerUtility/serviceCommon.js +3 -1
  256. package/dist/runnerUtility/serviceCommon.js.map +1 -1
  257. package/dist/runnerUtility/serviceManager.d.ts.map +1 -1
  258. package/dist/runnerUtility/serviceManager.js +7 -2
  259. package/dist/runnerUtility/serviceManager.js.map +1 -1
  260. package/dist/runnerUtility/simctlGuard.d.ts +38 -0
  261. package/dist/runnerUtility/simctlGuard.d.ts.map +1 -0
  262. package/dist/runnerUtility/simctlGuard.js +166 -0
  263. package/dist/runnerUtility/simctlGuard.js.map +1 -0
  264. package/dist/runners/bootstrapLine.d.ts +3 -4
  265. package/dist/runners/bootstrapLine.d.ts.map +1 -1
  266. package/dist/runners/bootstrapLine.js +108 -83
  267. package/dist/runners/bootstrapLine.js.map +1 -1
  268. package/dist/runners/hubPackage.d.ts +1 -1
  269. package/dist/runners/hubPackage.d.ts.map +1 -1
  270. package/dist/runners/hubPackage.js +5 -6
  271. package/dist/runners/hubPackage.js.map +1 -1
  272. package/dist/runners/hubPairing.d.ts +19 -0
  273. package/dist/runners/hubPairing.d.ts.map +1 -1
  274. package/dist/runners/hubPairing.js +38 -0
  275. package/dist/runners/hubPairing.js.map +1 -1
  276. package/dist/runners/hubRegistry.d.ts +8 -0
  277. package/dist/runners/hubRegistry.d.ts.map +1 -1
  278. package/dist/runners/hubRegistry.js +6 -0
  279. package/dist/runners/hubRegistry.js.map +1 -1
  280. package/dist/runners/pairCode.d.ts +34 -3
  281. package/dist/runners/pairCode.d.ts.map +1 -1
  282. package/dist/runners/pairCode.js +65 -13
  283. package/dist/runners/pairCode.js.map +1 -1
  284. package/dist/runners/runnerGroups.d.ts +22 -0
  285. package/dist/runners/runnerGroups.d.ts.map +1 -0
  286. package/dist/runners/runnerGroups.js +41 -0
  287. package/dist/runners/runnerGroups.js.map +1 -0
  288. package/dist/runners/runnersCli.d.ts +5 -2
  289. package/dist/runners/runnersCli.d.ts.map +1 -1
  290. package/dist/runners/runnersCli.js +59 -9
  291. package/dist/runners/runnersCli.js.map +1 -1
  292. package/dist/runners/runnersList.d.ts +1 -1
  293. package/dist/runners/runnersList.d.ts.map +1 -1
  294. package/dist/runners/runnersList.js +3 -1
  295. package/dist/runners/runnersList.js.map +1 -1
  296. package/dist/runners/runnersOverview.d.ts.map +1 -1
  297. package/dist/runners/runnersOverview.js +8 -4
  298. package/dist/runners/runnersOverview.js.map +1 -1
  299. package/dist/scheduler/checkStatus.d.ts +2 -0
  300. package/dist/scheduler/checkStatus.d.ts.map +1 -1
  301. package/dist/scheduler/checkStatus.js +5 -4
  302. package/dist/scheduler/checkStatus.js.map +1 -1
  303. package/dist/scheduler/delivery.d.ts +2 -1
  304. package/dist/scheduler/delivery.d.ts.map +1 -1
  305. package/dist/scheduler/delivery.js +5 -1
  306. package/dist/scheduler/delivery.js.map +1 -1
  307. package/dist/scheduler/mcpSurface.d.ts +7 -3
  308. package/dist/scheduler/mcpSurface.d.ts.map +1 -1
  309. package/dist/scheduler/mcpSurface.js +48 -22
  310. package/dist/scheduler/mcpSurface.js.map +1 -1
  311. package/dist/scheduler/workerWatch.d.ts +33 -10
  312. package/dist/scheduler/workerWatch.d.ts.map +1 -1
  313. package/dist/scheduler/workerWatch.js +37 -11
  314. package/dist/scheduler/workerWatch.js.map +1 -1
  315. package/dist/state.d.ts +95 -2
  316. package/dist/state.d.ts.map +1 -1
  317. package/dist/state.js +145 -7
  318. package/dist/state.js.map +1 -1
  319. package/dist/testTimings.d.ts +6 -2
  320. package/dist/testTimings.d.ts.map +1 -1
  321. package/dist/testTimings.js +12 -1
  322. package/dist/testTimings.js.map +1 -1
  323. package/dist/types.d.ts +2 -1
  324. package/dist/types.d.ts.map +1 -1
  325. package/dist/utils/agentPlugin.d.ts +2 -1
  326. package/dist/utils/agentPlugin.d.ts.map +1 -1
  327. package/dist/utils/agentPlugin.js +2 -1
  328. package/dist/utils/agentPlugin.js.map +1 -1
  329. package/dist/utils/botSkills.d.ts +1 -1
  330. package/dist/utils/claudeApiAgentStop.d.ts +64 -0
  331. package/dist/utils/claudeApiAgentStop.d.ts.map +1 -0
  332. package/dist/utils/claudeApiAgentStop.js +85 -0
  333. package/dist/utils/claudeApiAgentStop.js.map +1 -0
  334. package/dist/utils/claudeApiCredit.d.ts +168 -0
  335. package/dist/utils/claudeApiCredit.d.ts.map +1 -0
  336. package/dist/utils/claudeApiCredit.js +260 -0
  337. package/dist/utils/claudeApiCredit.js.map +1 -0
  338. package/dist/utils/claudeApiCreditRecheck.d.ts +120 -0
  339. package/dist/utils/claudeApiCreditRecheck.d.ts.map +1 -0
  340. package/dist/utils/claudeApiCreditRecheck.js +173 -0
  341. package/dist/utils/claudeApiCreditRecheck.js.map +1 -0
  342. package/dist/utils/claudeCompactHook.d.ts +18 -10
  343. package/dist/utils/claudeCompactHook.d.ts.map +1 -1
  344. package/dist/utils/claudeCompactHook.js +35 -14
  345. package/dist/utils/claudeCompactHook.js.map +1 -1
  346. package/dist/utils/claudeProfileUsageLines.d.ts +13 -1
  347. package/dist/utils/claudeProfileUsageLines.d.ts.map +1 -1
  348. package/dist/utils/claudeProfileUsageLines.js +75 -4
  349. package/dist/utils/claudeProfileUsageLines.js.map +1 -1
  350. package/dist/utils/claudeProfileUsageViews.d.ts +46 -0
  351. package/dist/utils/claudeProfileUsageViews.d.ts.map +1 -0
  352. package/dist/utils/claudeProfileUsageViews.js +114 -0
  353. package/dist/utils/claudeProfileUsageViews.js.map +1 -0
  354. package/dist/utils/claudeProfiles.d.ts +15 -0
  355. package/dist/utils/claudeProfiles.d.ts.map +1 -1
  356. package/dist/utils/claudeProfiles.js +54 -0
  357. package/dist/utils/claudeProfiles.js.map +1 -1
  358. package/dist/utils/claudeUsage.d.ts +94 -36
  359. package/dist/utils/claudeUsage.d.ts.map +1 -1
  360. package/dist/utils/claudeUsage.js +134 -60
  361. package/dist/utils/claudeUsage.js.map +1 -1
  362. package/dist/utils/compactOnIdle.d.ts +140 -15
  363. package/dist/utils/compactOnIdle.d.ts.map +1 -1
  364. package/dist/utils/compactOnIdle.js +209 -23
  365. package/dist/utils/compactOnIdle.js.map +1 -1
  366. package/dist/utils/compactSelfReviewFlags.d.ts +50 -0
  367. package/dist/utils/compactSelfReviewFlags.d.ts.map +1 -0
  368. package/dist/utils/compactSelfReviewFlags.js +120 -0
  369. package/dist/utils/compactSelfReviewFlags.js.map +1 -0
  370. package/dist/utils/fallbackChain.d.ts +18 -7
  371. package/dist/utils/fallbackChain.d.ts.map +1 -1
  372. package/dist/utils/fallbackChain.js +28 -12
  373. package/dist/utils/fallbackChain.js.map +1 -1
  374. package/dist/utils/openCodeCompactPlugin.d.ts +28 -7
  375. package/dist/utils/openCodeCompactPlugin.d.ts.map +1 -1
  376. package/dist/utils/openCodeCompactPlugin.js +80 -15
  377. package/dist/utils/openCodeCompactPlugin.js.map +1 -1
  378. package/dist/utils/runnersScreenPlan.d.ts +51 -20
  379. package/dist/utils/runnersScreenPlan.d.ts.map +1 -1
  380. package/dist/utils/runnersScreenPlan.js +143 -28
  381. package/dist/utils/runnersScreenPlan.js.map +1 -1
  382. package/dist/utils/streamedCompactionSummary.d.ts +65 -0
  383. package/dist/utils/streamedCompactionSummary.d.ts.map +1 -0
  384. package/dist/utils/streamedCompactionSummary.js +108 -0
  385. package/dist/utils/streamedCompactionSummary.js.map +1 -0
  386. package/package.json +2 -2
  387. package/remoteRun/ensureNode.sh +288 -0
  388. package/remoteRun/runner.sh +2252 -115
  389. package/agent-plugin/skills/charness-manager/SKILL.md +0 -157
  390. package/remoteRun/pickNode.sh +0 -65
@@ -9,7 +9,8 @@
9
9
  # files there and reports them — nothing else in this script knows about pairing. A hand-made runner has none of them:
10
10
  # <state>/paused exists → paused=yes (written by `charness-runner pause`; the main box never sends a job to a paused runner)
11
11
  # <state>/service one word: user-service | system-service (no file = run by hand: service=foreground)
12
- # <state>/ios-check.json the runner's iOS Simulator boot check (one JSON line): "status": "pass"|"fail"|"skipped" and "reason": "…"|null
12
+ # <state>/ios-check.json the runner's iOS Simulator boot check (one JSON line): "status": "pass"|"fail"|"skipped" and "reason": "…"|null; a pass also names the "deviceTypeId" and "runtimeId" it booted
13
+ # (what a job's own Simulator device is made of)
13
14
  # <state>/gui/ the login session's agent of an always-on Mac (service=system-service): agent.json is its heartbeat, requests/<id>/ the steps
14
15
  # it runs for a job that needs iOS (`needs-ios` in the job folder) — see «the login session» below
15
16
  # <state> counts only when it holds config.json and keys/ (a work dir that merely is called «work» is not one).
@@ -18,8 +19,9 @@
18
19
  # `timeout(1)`, no `read -t` (its timeout status differs between 3.2 and 4+), no GNU-only flags. Time limits are done by background watchdogs.
19
20
  #
20
21
  # Subcommands (the contract is in src/remoteRun/README.md):
21
- # probe key=value lines: OS, CPU, RAM, disk, jobs, capabilities (paused / service / iOS boot check of a paired runner)
22
- # prepare layout for a job, Pueue daemon + groups, prune
22
+ # probe key=value lines: OS, CPU, RAM, disk, jobs, capabilities (paused / service / iOS boot check of a paired runner); `probe <work> prune`: a view of the runners that may start the background prune of a short disk
23
+ # prepare layout for a job, Pueue daemon + groups, prune (`prepare <work> <slug> <job> <groups> [<project-key> <install-key>]`: the repository and the install key of the job, so that the prune keeps the copy the job's first run is seeded from)
24
+ # apply-groups Pueue daemon + groups only (`apply-groups <work> <name=parallel,…>`): a changed «jobs at once» takes effect now, not at the next job's prepare
23
25
  # lease add the job to Pueue, stream its log, kill it when the caller's heartbeat stops (foreground run)
24
26
  # submit add the job to Pueue and return (--bg)
25
27
  # job the Pueue task itself: lock → apply the staged tree → deps → command → result files
@@ -33,7 +35,15 @@
33
35
  # workdir the work dir as an absolute path
34
36
  # pueue run Pueue itself with the configured binary and config
35
37
  # jobs the meta.json of every job of a project (or of all), as a JSON array
36
- # prune remove old jobs, stale stage dirs and unused project copies
38
+ # prune remove old jobs, stale stage dirs, project copies unused for days, and — while the disk is short of free space — the least recently used ones
39
+ # clean remove ONE project copy on request (`clean <work> <slug>`): refused while a job of it runs or waits, an exec runs in it, a job is being submitted, or a job ended lately whose results nobody fetched; says what it freed
40
+ # simctl-cleanup `xcrun simctl delete unavailable` on a Mac, bounded; started detached by the probe of a view of the runners at most once a day, never called by hand
41
+ # fetched mark a finished job's results as fetched (`fetched <work> - <job>`): `wait`, `fetch` and a foreground run say so once they have the files, and `clean` then does not keep the copy for them
42
+ # measure-copies write down how big each project copy is (p/<slug>/size-kb); the probe of a view of the runners starts it detached, and `prepare` when the disk is short; it is never called by hand
43
+ # ios-device `ios-device <work> <slug>`: a job's own Simulator device (create or reuse `charness-<slug>`, boot it); run BY the job as a step, never called by hand
44
+ # ios-device-shutdown `ios-device-shutdown <work> <slug> <udid>`: shut that device down (the step at the end of a job); never called by hand
45
+ # settle-queue `settle-queue <work>`: the scheduling safety net (`enqueue_idle_stashed`: end the jobs Pueue lost, enqueue a stashed job whose predecessor died); started detached by every `probe`, so that the probe's answer never waits for a scheduling lock or for Pueue; never called by hand
46
+ # sweep-tmpdirs the sweep of idle project copies: remove the files of their TMPDIRs (`<work>/t/<n>`) that were not modified for tmpdir_keep_days, and the Xcode build data (`ios/build`) of the copies nobody used for build_data_keep_hours; `prepare` starts it detached at most every tmpdir_sweep_interval_hours; never called by hand
37
47
  # sync-tree the apply step alone (tests)
38
48
 
39
49
  # The script's own tools (sort, sed, grep) run in the C locale: byte-wise and the same everywhere. The user's commands do NOT — see job_locale.
@@ -49,8 +59,50 @@ kill_settle_polls=10
49
59
  pueue_start_wait_sec=8
50
60
  default_timeout_sec=10800
51
61
  job_keep_days=3
52
- copy_keep_days=30
62
+ # A project copy nobody has used for this many days is removed (the runner's config can say another number: REMOTE_RUN_COPY_MAX_IDLE_DAYS).
63
+ copy_keep_days=3
53
64
  stage_keep_days=1
65
+ # The free space the work dir's disk should keep: the smaller of this many GiB and this percent of the disk (REMOTE_RUN_MIN_FREE_GB replaces both; 0 = no target).
66
+ min_free_cap_gb=60
67
+ min_free_percent=15
68
+ kib_per_gib=1048576
69
+ minutes_per_day=1440
70
+ # A job without an exit file and without a task is a submit that is still sending its files: its project copy is in use while its job folder or anything in its
71
+ # stage folder was touched this recently (a first upload of a big project goes quiet in the job folder for as long as it takes, but not in the stage folder).
72
+ pending_submit_grace_min=30
73
+ # The result files of a job that ended this recently are still on their way to whoever submitted it (`wait`, `fetch`): the copy that holds them is in use.
74
+ result_keep_min=60
75
+ # `prune` runs one at a time per work dir: the lock of the copy-removal step (tmp/prune.lock) is believed while its holder lives and the lock is younger than this.
76
+ prune_lock_max_age_min=120
77
+ # The age (minutes) after which `check_lock_is_stale` calls a lock stale although its holder lives (a pid can be given to anything); 0 = no limit, as for a project's lock, which a job of any length holds.
78
+ # The prune lock sets its own for the length of its calls.
79
+ lock_max_age_min=0
80
+ # A prune that finds another one at its copy-removal step waits for it this long, looking every prune_poll_sec (then goes on: it never hangs on one).
81
+ prune_wait_sec=600
82
+ prune_poll_sec=1
83
+ # A removal that freed less than this although the copy was measured bigger says the disk's free figure is not following (APFS snapshots, purgeable space): removing more copies would
84
+ # empty the runner for nothing, so the prune stops...
85
+ no_progress_freed_kb=1048576
86
+ # ...but only after this many such removals in a row did that (a copy too small to judge, or never measured, between them is not counted either way): a job writing to the same disk meanwhile can eat the space one removal freed.
87
+ no_progress_stop_after=2
88
+ # The refusal of a submit names this many of the biggest copies.
89
+ refusal_copy_count=3
90
+ # `prepare` ends with this exit code when the disk is still short of free space after the prune (28 is ENOSPC); src/remoteRun/pruneReport.ts has the same number.
91
+ low_disk_exit_code=28
92
+ # Set by the free-space prune (prune_copies_for_space) for the refusal that may follow it, and by the last removal for its report.
93
+ prune_stopped_without_gain=0
94
+ last_freed_kb=
95
+ # Set by probe_slow: 1 only when the probe has just said `cap_ios=yes` AND the simctl step answered. Nothing is deleted among the simulators otherwise — and never on an always-on Mac (see `start_simctl_cleanup_if_due`).
96
+ probe_may_clean_simulators=0
97
+ # `xcrun simctl delete unavailable` (the simulators of runtimes that are gone) is tried at most this often, and given this long; the look at the runtimes before it is given simctl_list_sec.
98
+ simctl_cleanup_interval_hours=24
99
+ simctl_cleanup_sec=120
100
+ simctl_list_sec=30
101
+ # 1 = the caller is a `clean`: a job that ended lately whose results were fetched (the `fetched` mark in its folder) does not keep the copy (the prune does not know that: it keeps it result_keep_min).
102
+ clean_ignores_fetched=0
103
+ # Set by check_copy_dir_is_busy when it says «in use»: why (lock | exec | running | queued | submitting | results) and which job (`-` when none).
104
+ copy_busy_kind=
105
+ copy_busy_job=-
54
106
  drain_interval_sec=0.2
55
107
  probe_step_sec=4
56
108
  exit_file_wait_sec=5
@@ -64,6 +116,52 @@ failed_step_error_lines=8
64
116
  gui_agent_stale_sec=20
65
117
  # What makes a line of a tool's output an error line.
66
118
  error_line_pattern='error|fatal|fail|exception|cannot|couldn|not found|no such|denied'
119
+ # Jobs of different projects run side by side, so what they would share without knowing is given out per PROJECT COPY: each copy gets, once, a number k from 0 to max_copy_indexes - 1 (`p/<slug>/index`) and from it
120
+ # a block of port_block_size ports from port_base_start + k * port_block_size (below Linux's ephemeral range, 32768+, and macOS's, 49152+), its own TMPDIR (`<work>/t/<k>`, short on purpose: macOS caps a
121
+ # unix-socket path at 104 bytes) and — for a job that needs iOS — its own Simulator device. The numbers are handed out under `tmp/index.lock` (a short hold; one that cannot be had in index_lock_wait_sec is
122
+ # said and the job runs without the three).
123
+ max_copy_indexes=100
124
+ # The system sweeps its own TMPDIR (macOS the files not touched for 3 days, a Linux tmpfs on reboot); the TMPDIR of a project copy it does not. Metro's and Jest's caches and every tool's leftovers land there, so the files of
125
+ # it that were not modified for tmpdir_keep_days go while no job of the copy runs (`sweep_idle_tmpdirs`), looked at every tmpdir_sweep_interval_hours at most.
126
+ tmpdir_keep_days=3
127
+ tmpdir_sweep_interval_hours=6
128
+ # A project copy nobody has used for this many hours loses the Xcode build data inside it (`trim_idle_build_data`; it rides the sweep above): the next iOS job of that copy builds from scratch instead of incrementally, and the disk is
129
+ # what an iOS build leaves — ~8.5 GB per app — back. The walk for it goes down to build_data_find_depth.
130
+ build_data_keep_hours=24
131
+ build_data_find_depth=5
132
+ # The folder of an `ios/build` that stays: the codegen pods' sources `pod install` writes there are part of the native project, not derived data (see `list_build_data_folders`).
133
+ build_data_kept_name=generated
134
+ # A prune on a short disk sweeps them at once, not more often than this (minutes): the walk finds nothing new a minute after the last one, and a Mac whose disk stays short for days must not pay it on every submit.
135
+ tmpdir_short_disk_sweep_interval_min=30
136
+ # A NEW project copy (its first job) is seeded from a sibling copy of the same project (`seed_new_copy`) instead of installing its dependencies from scratch. The folders to carry are looked for down to this depth below the copy's root
137
+ # (the root's `node_modules`, each workspace's, `ios/Pods`)...
138
+ seed_find_depth=5
139
+ # The Mac's own cp, by its path: the one that knows `-c` (clonefile).
140
+ darwin_cp=/bin/cp
141
+ # ...and inside a cloned `node_modules` the build output a package left in itself does not come along; it sits at most this deep (`@scope/pkg/android/build` is 4).
142
+ seed_clean_depth=4
143
+ port_base_start=20000
144
+ port_block_size=100
145
+ index_lock_wait_sec=30
146
+ index_lock_max_age_min=2
147
+ # Scheduling: a job whose project has another job under way is kept out of Pueue's queue (stashed) so that it takes no slot (see «adding the job to Pueue»). The per-project mutex `p/<slug>/sched.lock` is held for a few Pueue
148
+ # calls; one that cannot be had in sched_lock_wait_sec is believed stale after sched_lock_max_age_min.
149
+ sched_lock_wait_sec=30
150
+ sched_lock_max_age_min=2
151
+ # A caller that waits for a stashed job looks this often (seconds) whether its predecessor ended without enqueueing it (a job SIGKILLed with its own watchdog); see `wait_for_task`.
152
+ stash_recheck_sec=5
153
+ # The lease watcher's kill of a queued job that Pueue could not answer about is tried again this often (seconds) until Pueue answers; see `kill_job_until_answered`.
154
+ kill_retry_sec=5
155
+ # A job's own Simulator device is named for its project; its steps are each bounded (a watchdog: there is no `timeout(1)` on a Mac).
156
+ ios_device_prefix=charness-
157
+ ios_device_list_sec=30
158
+ ios_device_create_sec=60
159
+ ios_device_boot_sec=60
160
+ ios_device_bootstatus_sec=180
161
+ ios_device_delete_sec=60
162
+ ios_device_shutdown_sec=60
163
+ # A `kill` that has given a job its grace (kill_grace_sec) before it SIGKILLs the group waits on for a job that is shutting its Simulator device down: what that step is bounded by, and this much more for the login session's agent to pick it up.
164
+ simulator_shutdown_slack_sec=10
67
165
 
68
166
  # ─────────────────────────── helpers ───────────────────────────
69
167
 
@@ -163,6 +261,16 @@ keep_awake_while() {
163
261
  caffeinate -i -w "$1" > /dev/null 2>&1 < /dev/null &
164
262
  }
165
263
 
264
+ # End the background job $1 of this shell with SIGTERM ($2 names another signal) and say nothing about its death. A shell reports a job a signal ended on ITS OWN stderr — `line N: PID Killed: 9 ( sleep … )`, in a
265
+ # job's output, at the first command after the death — whatever redirections the job itself has. Measured: bash 3.2.57 (the Mac's) reports a job ended by SIGKILL and one ended by SIGTERM, bash 5.3 only one ended by
266
+ # SIGKILL. A `wait` with stderr thrown away would take the report, but it cannot be used for a job
267
+ # that is stopped by TERM: its trap runs only when the foreground command it sits in ends, and the caller would stand there for it. The job is `disown`ed first, so the shell has no job left to report (and no `wait`
268
+ # for it can follow). An already ended job, or a pid that is none of this shell's, is nothing to complain about.
269
+ stop_background_job() {
270
+ disown "$1" 2> /dev/null
271
+ kill "-${2:-TERM}" "$1" > /dev/null 2>&1
272
+ }
273
+
166
274
  # ─────────────────────────── the login session (always-on Mac) ───────────────────────────
167
275
 
168
276
  # A Mac runner kept running by LaunchDaemons has no login session of its own, and Xcode's nested builds crash in the System session the daemons
@@ -311,7 +419,8 @@ gui_run_step() {
311
419
  printf '%s' "$jd/log" > "$request/log"
312
420
  printf '%s' "$$" > "$request/owner"
313
421
  gui_process_start "$$" > "$request/owner-start"
314
- if [ -s "$jd/env" ]; then cp "$jd/env" "$request/env"; else : > "$request/env"; fi
422
+ # The agent applies the lines in order, a later one over an earlier (`parseJobEnvLines`): the runner's TMPDIR first (the job's own -e takes it back), the job's lines, then the runner's REMOTE_RUN_* (the job cannot).
423
+ { print_runner_env_lines tmpdir; print_job_env_lines; print_runner_env_lines vars; } > "$request/env"
315
424
  : > "$request/go"
316
425
  local looks=0
317
426
  while [ ! -f "$request/exit" ]; do
@@ -439,7 +548,7 @@ probe_jobs() {
439
548
  [ -f "$job_dir/task-id" ] || continue
440
549
  slug=$(basename "$(dirname "$(dirname "$job_dir")")")
441
550
  pid=$(read_file "$job_dir/pid")
442
- if [ -n "$pid" ] && kill -0 "$pid" 2> /dev/null; then
551
+ if [ -n "$pid" ] && check_runner_pid_alive "$pid"; then
443
552
  running=$((running + 1))
444
553
  elif [ -z "$pid" ]; then
445
554
  queued=$((queued + 1))
@@ -459,6 +568,50 @@ probe_jobs() {
459
568
  echo "jobs_projects=$project_count"
460
569
  }
461
570
 
571
+ # disk_total_mb and disk_min_free_mb (what the runner wants kept free; 0 = no target) from the disk step's "<total kb> <free kb>" ($1), and whether the disk is short of it
572
+ # (probe_disk_is_short, acted on by cmd_probe once the slow questions are over).
573
+ probe_disk_target() {
574
+ probe_disk_is_short=0
575
+ local total_kb=${1%% *} free_kb=${1##* } target_kb
576
+ case "$total_kb$free_kb" in
577
+ '' | *[!0-9]*) return 0 ;;
578
+ esac
579
+ target_kb=$(get_min_free_kb "$total_kb")
580
+ echo "disk_total_mb=$(kb_to_mb "$total_kb")"
581
+ echo "disk_min_free_mb=$(kb_to_mb "$target_kb")"
582
+ [ "$target_kb" -gt 0 ] && [ "$free_kb" -lt "$target_kb" ] && probe_disk_is_short=1
583
+ return 0
584
+ }
585
+
586
+ # copies_count= / copies_size_mb= / copies_unmeasured= : the project copies, their size from the figures `measure-copies` wrote down (an out-of-date one still counts; the number of copies
587
+ # with no figure, or used since their figure was written, is copies_unmeasured). Asking never waits for a `du`: a missing figure starts the measuring detached — for a VIEW of the runners only (`probe <work> prune`): the probe a
588
+ # run or an `exec` makes first comes right before its `prepare`, and a walk over the copy about to be built would compete with the build.
589
+ probe_copies() {
590
+ local count=0 total_kb=0 unmeasured=0 seed_groups= copy_group copy_dir size_file size_kb
591
+ for copy_dir in "$work"/p/*/; do
592
+ [ -d "$copy_dir" ] || continue
593
+ count=$((count + 1))
594
+ # `du` counts the blocks a clone shares with its source in full, so the total is more than the disk holds: the views say so when some copy is one (each copy's group is read once, counted after the loop).
595
+ copy_group=$(get_copy_seed_group "$work" "$(basename "$copy_dir")")
596
+ [ -z "$copy_group" ] || seed_groups="$seed_groups$copy_group"$'\n'
597
+ size_file="${copy_dir}size-kb"
598
+ size_kb=$(read_file "$size_file")
599
+ case $size_kb in
600
+ '' | *[!0-9]*) unmeasured=$((unmeasured + 1)) ;;
601
+ *)
602
+ total_kb=$((total_kb + size_kb))
603
+ [ "${copy_dir}used" -nt "$size_file" ] && unmeasured=$((unmeasured + 1))
604
+ ;;
605
+ esac
606
+ done
607
+ echo "copies_count=$count"
608
+ echo "copies_size_mb=$(kb_to_mb "$total_kb")"
609
+ echo "copies_unmeasured=$unmeasured"
610
+ echo "copies_cloned=$(count_copies_in_shared_groups "$seed_groups")"
611
+ [ "$unmeasured" -gt 0 ] && [ "$probe_may_prune" = prune ] && start_detached_run "$work" measure-copies
612
+ return 0
613
+ }
614
+
462
615
  # The probe's slow questions — Pueue, the disk, Xcode and its simulators, Docker — are asked at once, each bounded by probe_step_sec, so
463
616
  # a hung one costs that much in all, not that much each: the caller gives the whole probe 20 s, and a Mac with a slow simctl, a stalled
464
617
  # mount and a sleeping Docker would otherwise read as offline. One step: output in $probe_dir/<name>.out, its status in <name>.status
@@ -467,15 +620,7 @@ start_probe_step() {
467
620
  local name=$1
468
621
  local limit=$2
469
622
  shift 2
470
- (
471
- "$@" > "$probe_dir/$name.out" 2> /dev/null < /dev/null &
472
- local command_pid=$!
473
- ( sleep "$limit"; kill -9 "$command_pid" ) > /dev/null 2>&1 &
474
- local watchdog_pid=$!
475
- wait "$command_pid" 2> /dev/null
476
- echo "$?" > "$probe_dir/$name.status"
477
- kill "$watchdog_pid" > /dev/null 2>&1
478
- ) &
623
+ ( run_bounded "$limit" "$@" > "$probe_dir/$name.out" 2> /dev/null; echo "$?" > "$probe_dir/$name.status" ) &
479
624
  }
480
625
 
481
626
  probe_step_status() {
@@ -486,16 +631,55 @@ probe_step_output() {
486
631
  read_file "$probe_dir/$1.out"
487
632
  }
488
633
 
489
- # What a tool answered to `--version` (its first line, cut short): `none` when it is not on this PATH — a job that calls it ends with exit 127 —
490
- # and `unknown` when it is there but did not answer in time.
491
- probe_tool_version() {
492
- local name=$1
493
- command -v "$name" > /dev/null 2>&1 || { echo none; return 0; }
494
- if [ "$(probe_step_status "$name")" = 0 ]; then
495
- probe_step_output "$name" | head -n 1 | cut -c1-40
496
- else
497
- echo unknown
498
- fi
634
+ # What the tool of probe step $1 (the binary $2, asked for its `--version` by `probe_slow`) answered: its output as it was; `unknown` when the step was CUT OFF by probe_step_sec (137, the watchdog of
635
+ # run_bounded) — a loaded machine is slow at it, not without the tool, and a runner must not be refused for that; the word $3 (`none` / `missing`) when the binary is not on this PATH — a job that calls it
636
+ # ends with exit 127 — or is there and fails at once (a wrong-architecture binary, a missing library, a crash: a job that calls it fails too, and `unknown` would hide that). Each caller shapes the output of its tool.
637
+ probe_answered_version() {
638
+ local step=$1 binary=$2 absent_word=$3
639
+ command -v "$binary" > /dev/null 2>&1 || { echo "$absent_word"; return 0; }
640
+ case "$(probe_step_status "$step")" in
641
+ 0) probe_step_output "$step" ;;
642
+ 137) echo unknown ;;
643
+ *) echo "$absent_word" ;;
644
+ esac
645
+ }
646
+
647
+ # The simulators of OLDER runtimes than the newest of the same platform and major (`iOS 26.5` next to `iOS 27.1` is not older: another major; `iOS 26.4` next to `iOS 26.5` is), from the text of
648
+ # `xcrun simctl list devices available` on stdin: `iOS 26.4:11,watchOS 11.0:2` (runtime:devices), nothing when there are none. Only information: nothing here deletes anything.
649
+ list_older_simulator_runtimes() {
650
+ awk '
651
+ # The order of two versions of the SAME major (the major is the group, so it is not part of the rank).
652
+ function key(version, parts, count) {
653
+ count = split(version, parts, ".")
654
+ return (count > 1 ? parts[2] : 0) * 1000 + (count > 2 ? parts[3] : 0)
655
+ }
656
+ /^-- / {
657
+ runtime = ""
658
+ header = $0
659
+ sub(/^-- /, "", header)
660
+ sub(/ --$/, "", header)
661
+ if (match(header, /^[A-Za-z]+ [0-9]+(\.[0-9]+)*/)) {
662
+ runtime = substr(header, RSTART, RLENGTH)
663
+ split(runtime, words, " ")
664
+ split(words[2], numbers, ".")
665
+ group[runtime] = words[1] " " numbers[1]
666
+ rank[runtime] = key(words[2])
667
+ if (!(runtime in listed)) { listed[runtime] = 1; order[++count] = runtime }
668
+ if (!(group[runtime] in newest) || rank[runtime] > newest[group[runtime]]) newest[group[runtime]] = rank[runtime]
669
+ }
670
+ next
671
+ }
672
+ /^ +[^ ].*\([A-Za-z ]+\) *$/ { if (runtime != "") devices[runtime]++ }
673
+ END {
674
+ for (index_ = 1; index_ <= count; index_++) {
675
+ runtime = order[index_]
676
+ if (devices[runtime] > 0 && rank[runtime] < newest[group[runtime]]) {
677
+ output = output (output == "" ? "" : ",") runtime ":" devices[runtime]
678
+ }
679
+ }
680
+ if (output != "") print output
681
+ }
682
+ '
499
683
  }
500
684
 
501
685
  probe_slow() {
@@ -520,19 +704,17 @@ probe_slow() {
520
704
  wait
521
705
 
522
706
  echo "disk_free_mb=$(kb_to_mb "$(probe_step_output disk | awk 'NR == 2 { print $4 }')")"
523
- echo "job_node=$(probe_tool_version node)"
524
- echo "job_yarn=$(probe_tool_version yarn)"
525
- if [ "$(probe_step_status pueue)" = 0 ]; then
526
- echo "pueue=$(probe_step_output pueue | awk '{ print $NF }')"
527
- else
528
- echo "pueue=missing"
529
- fi
707
+ probe_disk_target "$(probe_step_output disk | awk 'NR == 2 { print $2, $4 }')"
708
+ echo "job_node=$(probe_answered_version node node none | head -n 1 | cut -c1-40)"
709
+ echo "job_yarn=$(probe_answered_version yarn yarn none | head -n 1 | cut -c1-40)"
710
+ echo "pueue=$(probe_answered_version pueue "${PUEUE_BIN:-pueue}" missing | awk '{ print $NF }')"
530
711
  if [ "$is_darwin" -eq 0 ]; then
531
712
  echo "cap_ios=no"
532
713
  echo "cap_ios_detail=$(uname -s)"
533
714
  elif [ "$(probe_step_status xcode)" = 0 ]; then
534
715
  local xcode_version
535
716
  xcode_version=$(probe_step_output xcode | head -n 1 | sed 's/^Xcode //')
717
+ local older_runtimes
536
718
  if gui_session_expected && ! gui_agent_alive; then
537
719
  # An always-on Mac runs its iOS work in the account's login session: with none, builds crash (Xcode's nested builds) and the Simulator will not boot.
538
720
  echo "cap_ios=no"
@@ -556,6 +738,10 @@ probe_slow() {
556
738
  echo "cap_ios=yes"
557
739
  if [ "$(probe_step_status simctl)" = 0 ]; then
558
740
  echo "cap_ios_detail=Xcode $xcode_version, $(probe_step_output simctl | grep -c '(Shutdown)\|(Booted)') simulators"
741
+ older_runtimes=$(probe_step_output simctl | list_older_simulator_runtimes)
742
+ [ -z "$older_runtimes" ] || echo "sim_older_runtimes=$older_runtimes"
743
+ # The only place the daily cleanup of the simulators is allowed from: iOS works here (not «no login session», not a failed or running Simulator check) and simctl answered.
744
+ probe_may_clean_simulators=1
559
745
  else
560
746
  # A slow simctl is no reason to say there is no Xcode, nor to invent a simulator count.
561
747
  echo "cap_ios_detail=Xcode $xcode_version"
@@ -583,11 +769,14 @@ probe_slow() {
583
769
  }
584
770
 
585
771
  # The state folder of the charness-runner this work dir belongs to (sets runner_state; empty for a hand-made runner), and what it says
586
- # about the machine: sets ios_boot_status (ok | failed | unchecked, empty off a Mac or without a check) and ios_boot_detail.
772
+ # about the machine: sets ios_boot_status (ok | failed | unchecked, empty off a Mac or without a check) and ios_boot_detail; for a check that
773
+ # passed also ios_device_type and ios_runtime (the device type and runtime it booted: what a job's own Simulator device is made of).
587
774
  read_runner_state() {
588
775
  runner_state=
589
776
  ios_boot_status=
590
777
  ios_boot_detail=
778
+ ios_device_type=
779
+ ios_runtime=
591
780
  local candidate
592
781
  candidate=$(dirname "$work")
593
782
  [ "$(basename "$work")" = work ] && [ -f "$candidate/config.json" ] && [ -d "$candidate/keys" ] || return 0
@@ -596,6 +785,8 @@ read_runner_state() {
596
785
  [ -f "$check" ] || return 0
597
786
  if grep -q '"status"[[:space:]]*:[[:space:]]*"pass"' "$check"; then
598
787
  ios_boot_status=ok
788
+ ios_device_type=$(sed -n 's/.*"deviceTypeId"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$check" | head -n 1)
789
+ ios_runtime=$(sed -n 's/.*"runtimeId"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$check" | head -n 1)
599
790
  elif grep -q '"status"[[:space:]]*:[[:space:]]*"fail"' "$check"; then
600
791
  ios_boot_status=failed
601
792
  else
@@ -652,7 +843,14 @@ probe_runner_state() {
652
843
 
653
844
  cmd_probe() {
654
845
  work=$1
846
+ # $2 = `prune`: the caller is a VIEW of the runners (`remote-run runners`, the bot's /runners) and may start the background prune on a short disk. The probe that picks a runner for a run or an `exec`
847
+ # never does: that prune has no copy to keep, and the project about to be used is typically the least recently used one — the very one it would take before the job's own `prepare` arrives.
848
+ probe_may_prune=${2:-}
655
849
  mkdir -p "$work" 2> /dev/null
850
+ # The scheduling safety net is NOT part of the answer: it waits for the project's scheduling mutex (up to sched_lock_wait_sec) and asks Pueue (no limit of its own), and a probe that did both while a job was
851
+ # being queued — on a Mac with load 129 — outlived the caller's 20 s and read as «offline» (measured: a starting job and a Pueue that takes 25 s to answer made the probe take 25.8 s, 0.4 s without the job).
852
+ # It runs detached, one at a time (see `start_detached_run`).
853
+ start_detached_run "$work" settle-queue
656
854
  read_runner_state
657
855
  echo "os=$(uname -s)"
658
856
  echo "arch=$(uname -m)"
@@ -661,7 +859,13 @@ cmd_probe() {
661
859
  Linux) probe_linux ;;
662
860
  Darwin) probe_darwin ;;
663
861
  esac
862
+ probe_may_clean_simulators=0
664
863
  probe_slow
864
+ # A Mac whose iOS works forgets the simulators of runtimes that are gone, when a view of the runners asks (a run or an `exec` never waits for it: it is started detached, and at most once in 24 hours).
865
+ [ "$probe_may_clean_simulators" -eq 1 ] && [ "$probe_may_prune" = prune ] && start_simctl_cleanup_if_due
866
+ # A disk short of free space frees itself, when a view of the runners asks for it: the prune runs detached (a probe must answer in seconds, removing a copy takes minutes).
867
+ [ "${probe_disk_is_short:-0}" -eq 1 ] && [ "$probe_may_prune" = prune ] && start_detached_run "$work" prune
868
+ probe_copies
665
869
  probe_jobs
666
870
  probe_android
667
871
  probe_playwright
@@ -684,22 +888,24 @@ ensure_pueued() {
684
888
  return 1
685
889
  }
686
890
 
687
- # groups = "name=parallel,name=parallel"
891
+ # groups = "name=parallel,name=parallel". Fails (after trying every pair) when Pueue refused a limit; `prepare` goes on regardless, `apply-groups` says so.
688
892
  apply_groups() {
689
- printf '%s\n' "$1" | tr ',' '\n' | while IFS= read -r pair; do
893
+ local pair name parallel failed=0
894
+ while IFS= read -r pair; do
690
895
  name=${pair%%=*}
691
896
  parallel=${pair#*=}
692
897
  [ -n "$name" ] || continue
693
898
  [ "$name" = default ] || pq group add "$name" > /dev/null 2>&1
694
- pq parallel -g "$name" "$parallel" > /dev/null 2>&1
695
- done
899
+ pq parallel -g "$name" "$parallel" > /dev/null 2>&1 || failed=1
900
+ done <<< "$(printf '%s\n' "$1" | tr ',' '\n')"
901
+ return "$failed"
696
902
  }
697
903
 
698
904
  # ─────────────────────────── prepare / prune ───────────────────────────
699
905
 
700
906
  cmd_prepare() {
701
907
  set_paths "$1" "$2" "$3"
702
- local groups=${4:-}
908
+ local groups=${4:-} project_key=${5:-} install_key=${6:-} seed_slug=
703
909
  # Ids are 30 random bits, made on the caller's side: a clash would make two jobs share one folder.
704
910
  if [ -e "$jd/meta.json" ] || [ -e "$jd/task-id" ]; then
705
911
  die "job id already in use: $job"
@@ -711,10 +917,33 @@ cmd_prepare() {
711
917
  die "Pueue daemon is not reachable and could not be started (check PUEUE_BIN / the pueue settings of this runner)"
712
918
  fi
713
919
  apply_groups "$groups"
714
- prune_work "$work" "$slug"
920
+ enqueue_idle_stashed "$work"
921
+ # The caller may hang up while this removes copies for minutes (its call has a time limit): writing a report line to a closed pipe is no reason to die half-way (SIGPIPE would end the removal after
922
+ # the copy it is at). Only here: elsewhere a closed pipe still ends a pipeline early, as it should.
923
+ trap '' PIPE
924
+ # A NEW copy is seeded from its best sibling by its first job (`seed_new_copy`): the prune of this submit must not take that copy first. The repository and the install key are the main box's words for what the job will say.
925
+ if [ ! -f "$proj/manifest" ]; then
926
+ seed_slug=$(list_seed_siblings "$slug" "$install_key" "$project_key")
927
+ seed_slug=${seed_slug%%$'\n'*}
928
+ fi
929
+ prune_work "$work" "$slug" wait "$seed_slug"
930
+ trap - PIPE
931
+ start_tmpdir_sweep_if_due "$work"
932
+ # A prune that ran at the same moment may have taken the folder this job was just given (its copy looked unused): say so, never answer with a folder that is gone.
933
+ [ -d "$jd" ] || die "the project copy was being removed while this job was prepared — submit again"
934
+ refuse_when_disk_is_short
715
935
  echo "work=$(cd "$work" && pwd -P)"
716
936
  }
717
937
 
938
+ # `apply-groups <work> <groups>`: the same Pueue steps as `prepare`, nothing else. Pueue's `parallel` is a gate for STARTS: a lowered limit never stops a task that runs, queued
939
+ # tasks start once fewer than the new limit run.
940
+ cmd_apply_groups() {
941
+ work=$1
942
+ mkdir -p "$work" 2> /dev/null
943
+ ensure_pueued || die "Pueue daemon is not reachable and could not be started (check PUEUE_BIN / the pueue settings of this runner)"
944
+ apply_groups "${2:-}" || die "Pueue refused a parallel limit (${2:-})"
945
+ }
946
+
718
947
  # Has the job in folder $1 ended? It wrote its exit file; or it never got a Pueue task (its submit failed half-way); or its process is
719
948
  # gone (a runner script of an earlier version SIGKILLed it without recording that). One that waits in the queue, or runs, has not.
720
949
  check_job_dir_ended() {
@@ -722,20 +951,44 @@ check_job_dir_ended() {
722
951
  [ -f "$1/task-id" ] || return 0
723
952
  local recorded_pid
724
953
  recorded_pid=$(read_file "$1/pid")
725
- [ -n "$recorded_pid" ] && ! kill -0 "$recorded_pid" 2> /dev/null
954
+ [ -n "$recorded_pid" ] && ! check_runner_pid_alive "$recorded_pid"
955
+ }
956
+
957
+ # Ask Pueue about the task $1 of job $2: sets job_task_state to `present` (it holds a task with that number and the job's label), `done` (that task has finished) or `absent`. Fails - and sets nothing - when Pueue does not answer
958
+ # or answers with something that is not its task list: only an ANSWER may say that a task is gone.
959
+ read_job_task_state() {
960
+ local reply
961
+ job_task_state=
962
+ reply=$(pq status --json "label=rr-$2" < /dev/null 2> /dev/null) || return 1
963
+ case $reply in
964
+ *'"tasks"'*) ;;
965
+ *) return 1 ;;
966
+ esac
967
+ if ! printf '%s\n' "$reply" | grep -Eq "\"$1\": ?\{ ?\"id\": ?$1[,}]"; then
968
+ job_task_state=absent
969
+ elif printf '%s\n' "$reply" | grep -Eq '"status": ?\{ ?"Done"'; then
970
+ job_task_state=done
971
+ else
972
+ job_task_state=present
973
+ fi
974
+ return 0
726
975
  }
727
976
 
728
977
  # Is Pueue's task number $1 the task of job $2? Pueue hands a number it has freed (a task that was removed, or cleaned) to the next task
729
- # added, and `pueue wait` / `pueue remove` of a number act on whoever holds it — so a job's recorded number is only good while the task
730
- # under it carries the job's own label. The label filter is Pueue's (`status --json label=…`: an exact match), the answer the task's id.
978
+ # added - after a `reset` it counts from 0 again - and `pueue wait` / `pueue remove` / `pueue kill` of a number act on whoever holds it: so a job's recorded number is only good while the task
979
+ # under it carries the job's own label. The label filter is Pueue's (`status --json label=…`: an exact match), the answer the task's id. A Pueue that does not answer confirms nothing.
731
980
  check_task_belongs_to_job() {
732
- pq status --json "label=rr-$2" 2> /dev/null | grep -Eq "\"$1\": ?\{ ?\"id\": ?$1[,}]"
981
+ read_job_task_state "$1" "$2" && [ "$job_task_state" != absent ]
733
982
  }
734
983
 
735
- # Remove: jobs older than the keep time (and their Pueue tasks), leftover stage dirs, project copies unused for long.
984
+ # Remove: jobs older than the keep time (and their Pueue tasks), leftover stage dirs, project copies unused for long. $4 = the copy a new copy's first job is going to be seeded from: removed last. $3 = `skip`: when another prune is at the copy-removal step,
985
+ # leave that step to it (the probe's detached prune); otherwise wait for it, bounded (a submit's: it needs the disk's free figure AFTER the other one is done).
736
986
  prune_work() {
737
987
  local work_dir=$1
738
988
  local keep_slug=${2:-}
989
+ local when_busy=${3:-wait}
990
+ local seed_slug=${4:-}
991
+ remove_finished_tmpdir_removals "$work_dir"
739
992
  [ -d "$work_dir/p" ] || return 0
740
993
  find "$work_dir/p" -mindepth 3 -maxdepth 3 -path '*/jobs/*' -type d -mtime +"$job_keep_days" 2> /dev/null | while IFS= read -r old_job; do
741
994
  check_job_dir_ended "$old_job" || continue
@@ -754,37 +1007,1001 @@ prune_work() {
754
1007
  find "$work_dir/tmp" -mindepth 1 -maxdepth 1 -mtime +"$stage_keep_days" 2> /dev/null | while IFS= read -r old_lease; do
755
1008
  rm -rf "$old_lease"
756
1009
  done
757
- find "$work_dir/p" -mindepth 2 -maxdepth 2 -name used -type f -mtime +"$copy_keep_days" 2> /dev/null | while IFS= read -r used_file; do
758
- old_copy=$(dirname "$used_file")
759
- [ "$(basename "$old_copy")" = "$keep_slug" ] && continue
760
- [ -e "$old_copy/lock" ] && continue
761
- rm -rf "$old_copy"
1010
+ begin_copy_removal "$work_dir" "$when_busy" || return 0
1011
+ remove_leftover_trash "$work_dir"
1012
+ prune_idle_copies "$work_dir" "$keep_slug" "$seed_slug"
1013
+ # A short disk gives up the stale files of the TMPDIRs, and the Xcode build data of the copies idle for a day, before it gives up a copy (at most every tmpdir_short_disk_sweep_interval_min minutes: see there).
1014
+ check_disk_is_short "$work_dir" && take_tmpdir_sweep_turn "$work_dir" "$tmpdir_short_disk_sweep_interval_min" && sweep_idle_copies "$work_dir"
1015
+ prune_copies_for_space "$work_dir" "$keep_slug" "$seed_slug"
1016
+ end_copy_removal "$work_dir"
1017
+ }
1018
+
1019
+ cmd_prune() {
1020
+ prune_work "$1" "" skip
1021
+ }
1022
+
1023
+ # ─────────────────────────── project copies: age, free space, size ───────────────────────────
1024
+
1025
+ # The settings a runner's config can replace arrive in the environment of every call (the main box sets them from runners.json / the registry); a
1026
+ # value that is not a plain number is the same as none.
1027
+ get_copy_keep_days() {
1028
+ case ${REMOTE_RUN_COPY_MAX_IDLE_DAYS:-} in
1029
+ '' | *[!0-9]*) ;;
1030
+ *) [ "$((10#$REMOTE_RUN_COPY_MAX_IDLE_DAYS))" -gt 0 ] && { printf '%s\n' "$((10#$REMOTE_RUN_COPY_MAX_IDLE_DAYS))"; return 0; } ;;
1031
+ esac
1032
+ printf '%s\n' "$copy_keep_days"
1033
+ }
1034
+
1035
+ # disk_total_kb and disk_free_kb of the disk under directory $1 (`df -Pk`: 1024-byte blocks, the same layout on Linux and macOS); both empty when df says nothing usable.
1036
+ read_disk_kb() {
1037
+ local line
1038
+ line=$(df -Pk "$1" 2> /dev/null | awk 'NR == 2 { print $2, $4 }')
1039
+ disk_total_kb=${line%% *}
1040
+ disk_free_kb=${line##* }
1041
+ case "$disk_total_kb$disk_free_kb" in
1042
+ '' | *[!0-9]*) disk_total_kb=; disk_free_kb= ;;
1043
+ esac
1044
+ }
1045
+
1046
+ # The free space (KiB) the disk should keep, given its total size $1; 0 = no target.
1047
+ get_min_free_kb() {
1048
+ case ${REMOTE_RUN_MIN_FREE_GB:-} in
1049
+ '' | *[!0-9]*) ;;
1050
+ *) printf '%s\n' "$((10#$REMOTE_RUN_MIN_FREE_GB * kib_per_gib))"; return 0 ;;
1051
+ esac
1052
+ local cap_kb=$((min_free_cap_gb * kib_per_gib))
1053
+ local share_kb=$(($1 * min_free_percent / 100))
1054
+ if [ "$share_kb" -lt "$cap_kb" ]; then printf '%s\n' "$share_kb"; else printf '%s\n' "$cap_kb"; fi
1055
+ }
1056
+
1057
+ # Is the disk under directory $1 short of its free-space target? Sets disk_total_kb, disk_free_kb and min_free_kb; false when the target is off or the disk unreadable.
1058
+ check_disk_is_short() {
1059
+ read_disk_kb "$1"
1060
+ [ -n "$disk_free_kb" ] || return 1
1061
+ min_free_kb=$(get_min_free_kb "$disk_total_kb")
1062
+ [ "$min_free_kb" -gt 0 ] && [ "$disk_free_kb" -lt "$min_free_kb" ]
1063
+ }
1064
+
1065
+ # Is process $1 alive AND one of this script's own (`bash …/runner-<hash>.sh …`, or `…/runner.sh` run from a checkout)? A pid written into a job folder, a lock, a marker, a trash name or a pid file outlives its
1066
+ # process, and after a crash or a reboot the number may belong to a daemon: `kill -0` alone would keep a copy "in use" for good, a project's queue stuck behind a lock no job holds, and a `kill` would signal a
1067
+ # stranger. The name is matched as the script's exact file name — `runner-<8 hex>.sh` (what `runnerClient.ts` uploads; any version counts) or `runner.sh` — as the LAST path component: a `case` pattern's `*` also
1068
+ # crosses `/`, so a looser `*/runner-*.sh` would take `…/runner-01/runsvc.sh` (a self-hosted GitHub runner's service, long-lived on a build Mac) for ours. `ps -ww` asks for the whole command line: procps cuts
1069
+ # the column to an exported `$COLUMNS` even into a pipe, and a cut line would read a LIVE job, lock holder or exec as a stranger. A `ps` that cannot answer (not there, or a BusyBox one that rejects `-ww`, `-p` or
1070
+ # `-o command=`) says nothing about the process that `kill -0` just saw alive: it counts as alive.
1071
+ check_runner_pid_alive() {
1072
+ case $1 in '' | *[!0-9]*) return 1 ;; esac
1073
+ kill -0 "$1" 2> /dev/null || return 1
1074
+ command -v ps > /dev/null 2>&1 || return 0
1075
+ local command_line
1076
+ command_line=$(ps -ww -p "$1" -o command= 2> /dev/null) || return 0
1077
+ [ -n "$command_line" ] || return 0
1078
+ case $command_line in
1079
+ */runner-[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f].sh | */runner-[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f].sh[\ \;]* | */runner.sh | */runner.sh[\ \;]*) return 0 ;;
1080
+ esac
1081
+ return 1
1082
+ }
1083
+
1084
+ # Is an `exec` running in the copy in folder $1? `exec` takes no lock and leaves no job folder: its marker is `exec.<pid>`, written by `cmd_exec`. The marker of a pid that is gone, or that a reboot gave to a process that is not
1085
+ # the script's, is cleared.
1086
+ check_copy_has_live_exec() {
1087
+ local marker marker_pid
1088
+ for marker in "$1"/exec.*; do
1089
+ [ -e "$marker" ] || continue
1090
+ marker_pid=${marker##*/exec.}
1091
+ case $marker_pid in '' | *[!0-9]*) continue ;; esac
1092
+ check_runner_pid_alive "$marker_pid" && return 0
1093
+ rm -f "$marker"
1094
+ done
1095
+ return 1
1096
+ }
1097
+
1098
+ # Is the project copy in folder $1 in use — never to be removed? Its lock is held by a live job; or an `exec` runs in it (`exec.<pid>`: exec takes no lock and leaves no job folder, so it writes this
1099
+ # marker, and a marker of a process that is gone is cleared); or a job of it waits or runs; or a job ended less than result_keep_min ago (its result files are about to be fetched); or a job of
1100
+ # it is being submitted (no task yet, no exit, and its job folder or its stage folder touched less than pending_submit_grace_min ago: a long upload only moves files in the stage folder).
1101
+ # When it is, copy_busy_kind (exec | running | queued | submitting | results | lock — the most telling first) and copy_busy_job (the job id, or `-`) say why: `clean` tells its caller.
1102
+ check_copy_dir_is_busy() {
1103
+ local copy_dir=$1
1104
+ copy_busy_kind=
1105
+ copy_busy_job=-
1106
+ if check_copy_has_live_exec "$copy_dir"; then
1107
+ copy_busy_kind=exec
1108
+ return 0
1109
+ fi
1110
+ local job_dir job_name
1111
+ for job_dir in "$copy_dir"/jobs/*/; do
1112
+ [ -d "$job_dir" ] || continue
1113
+ job_name=$(basename "$job_dir")
1114
+ if [ -f "$job_dir/exit" ]; then
1115
+ # A job that ended lately has its result files and log here until whoever submitted it has fetched them: `wait`, `fetch` and a foreground run leave the `fetched` mark when they have. A `clean` believes the mark
1116
+ # (it was asked for this copy), the prune does not look for it (it only guesses).
1117
+ if [ -n "$(find "$job_dir/exit" -maxdepth 0 -mmin -"$result_keep_min" 2> /dev/null)" ] && ! { [ "$clean_ignores_fetched" -eq 1 ] && [ -f "$job_dir/fetched" ]; }; then
1118
+ copy_busy_kind=results
1119
+ copy_busy_job=$job_name
1120
+ return 0
1121
+ fi
1122
+ continue
1123
+ fi
1124
+ if ! check_job_dir_ended "$job_dir"; then
1125
+ copy_busy_kind=queued
1126
+ [ -n "$(read_file "$job_dir/pid")" ] && copy_busy_kind=running
1127
+ copy_busy_job=$job_name
1128
+ return 0
1129
+ fi
1130
+ # No task yet, no exit: a submit that is still sending its files looks like this; a job nobody touched for a while is one that failed half-way.
1131
+ if [ -n "$(find "$job_dir" -maxdepth 0 -mmin -"$pending_submit_grace_min" 2> /dev/null)" ] ||
1132
+ [ -n "$(find "$copy_dir/stage/$job_name" -cmin -"$pending_submit_grace_min" 2> /dev/null | head -n 1)" ]; then
1133
+ copy_busy_kind=submitting
1134
+ copy_busy_job=$job_name
1135
+ return 0
1136
+ fi
1137
+ done
1138
+ # The lock is looked at LAST: a job that runs holds it, and «job X is running» says more than «its lock is held by X». What is left is a lock whose holder shows in no job folder.
1139
+ if [ -e "$copy_dir/lock" ] && ! ( lock="$copy_dir/lock"; jobs_dir="$copy_dir/jobs"; check_lock_is_stale ); then
1140
+ local holder_pid holder_job
1141
+ read_lock_holder "$copy_dir/lock"
1142
+ copy_busy_kind=lock
1143
+ copy_busy_job=${holder_job:--}
1144
+ return 0
1145
+ fi
1146
+ return 1
1147
+ }
1148
+
1149
+ # The same for slug $2 under work dir $1. A name that is not a plain slug is not ours to judge: it counts as in use.
1150
+ check_copy_is_busy() {
1151
+ case $2 in
1152
+ '' | *[!A-Za-z0-9._-]* | .*) copy_busy_kind=name; copy_busy_job=-; return 0 ;;
1153
+ esac
1154
+ check_copy_dir_is_busy "$1/p/$2"
1155
+ }
1156
+
1157
+ # The copy-removal step is one at a time per work dir: of copies being removed by a prune that is still at it, a second prune would remove more than needed (the disk's free figure moves only when the
1158
+ # first one's `rm` ends) and `rm` the same folders. Its lock is `tmp/prune.lock`, made and broken by the project lock's own helpers (`create_lock_file`: the exclusive create, so the creator wins whatever the
1159
+ # clocks say; `check_lock_is_stale`; `break_stale_lock`: the generation-numbered right to break) — here with no job (`job` empty), `lock_max_age_min` set so a holder that has been at it for hours does not count
1160
+ # (a pid can be given to anything), and the pid test being `check_runner_pid_alive`. Fails when the lock is held, or when another process is breaking a stale one (it looks again soon). The project lock's
1161
+ # proof of the break (a named holder is gone for good) covers a holder that is gone; a lock broken for its AGE has a live holder, so there a holder that ends at that very moment can have its lock replaced by a
1162
+ # new one that is then removed: two prunes at once for a few milliseconds after a two-hour hold, which `remove_and_report_copy` tolerates (a copy that is already gone is code 2).
1163
+ acquire_prune_lock() {
1164
+ try_take_lock "$1/tmp/prune.lock" "" "$prune_lock_max_age_min"
1165
+ }
1166
+
1167
+ # Take the lock file $1 once, never waiting: made with the project lock's own helpers — the exclusive create, a stale holder's lock (`check_lock_is_stale`, over its job folders $2 and the age limit $3 in minutes, 0 = none) broken by the
1168
+ # generation-numbered right to break it, then the create again. Succeeds when this process holds the lock; fails when a holder lives or another process is breaking a stale one (it looks again soon). The prune lock and the lock of a copy
1169
+ # that a seed reads from (`seed_new_copy`) are taken this way.
1170
+ try_take_lock() {
1171
+ local lock=$1 jobs_dir=$2 lock_max_age_min=$3 job=
1172
+ while ! create_lock_file "$lock"; do
1173
+ check_lock_is_stale && break_stale_lock && continue
1174
+ return 1
1175
+ done
1176
+ # The rights to break the lock name holders that are gone and can never hold it again: nothing needs them any more.
1177
+ rm -f "$lock".breaking.* 2> /dev/null
1178
+ return 0
1179
+ }
1180
+
1181
+ # Give the lock file $1 back — only if it is still this process's own (a lock that was broken as stale and taken by another is not ours to remove).
1182
+ release_own_lock() {
1183
+ local holder_pid holder_job
1184
+ read_lock_holder "$1"
1185
+ [ "$holder_pid" = "$$" ] && rm -f "$1"
1186
+ return 0
1187
+ }
1188
+
1189
+ # Take the copy-removal step. A prune that finds another at it leaves the step (and says so by failing) when $2 is `skip`, or when it is `wait` and its own disk is not short (what the other one does is
1190
+ # what the idle copies need); else (`wait` on a short disk, and `always`: a `clean`, which was asked for this very copy and has no disk to judge by) it waits for it, up to prune_wait_sec, and then goes on
1191
+ # without the lock: it never hangs on one.
1192
+ begin_copy_removal() {
1193
+ local work_dir=$1 when_busy=$2
1194
+ mkdir -p "$work_dir/tmp" 2> /dev/null
1195
+ local waited_since=$SECONDS
1196
+ until acquire_prune_lock "$work_dir"; do
1197
+ if [ "$when_busy" = skip ]; then return 1; fi
1198
+ if [ "$when_busy" = wait ] && ! check_disk_is_short "$work_dir"; then return 1; fi
1199
+ [ $((SECONDS - waited_since)) -ge "$prune_wait_sec" ] && return 0
1200
+ ( trap '' TERM; exec sleep "$prune_poll_sec" )
1201
+ done
1202
+ return 0
1203
+ }
1204
+
1205
+ # Give the lock back — only if it is still this process's own (a prune that went on after its wait never had it).
1206
+ end_copy_removal() {
1207
+ release_own_lock "$1/tmp/prune.lock"
1208
+ }
1209
+
1210
+ # A removal that was cut off (ssh dropped, the machine slept) leaves its folder under a `.trash-<slug>-<pid>` name: the next prune finishes it — unless the pid of the one that made it still lives
1211
+ # (it is at it), or the folder holds something in use (a copy that got busy as it was moved aside and could not be put back).
1212
+ remove_leftover_trash() {
1213
+ local leftover
1214
+ for leftover in "$1"/p/.trash-*; do
1215
+ [ -e "$leftover" ] || continue
1216
+ finish_trash_removal "$leftover"
1217
+ done
1218
+ return 0
1219
+ }
1220
+
1221
+ # Finish the removal of the moved-aside folder $1 (`p/.trash-<slug>-<pid>`). Returns 0 gone · 1 its remover still lives (it is at it) · 2 something in it is in use (left as it is; copy_busy_kind says what) · 3 it would not go.
1222
+ finish_trash_removal() {
1223
+ local leftover=$1
1224
+ check_runner_pid_alive "${leftover##*-}" && return 1
1225
+ check_copy_dir_is_busy "$leftover" && return 2
1226
+ # The remover that was cut off may not have got to retire the copy's Simulator device. Its TMPDIR is not touched here: its number may be another copy's by now (that copy starts with an empty one).
1227
+ retire_copy_simulator "$(dirname "$(dirname "$leftover")")" "$leftover"
1228
+ remove_path_even_if_read_only "$leftover" || return 3
1229
+ }
1230
+
1231
+ # Is $1 the moved-aside folder of project copy $2 — `p/.trash-<slug>-<pid>` with a number for the pid (another slug that starts with this one's name is not)?
1232
+ check_is_trash_of_slug() {
1233
+ case ${1##*/} in
1234
+ .trash-"$2"-*) ;;
1235
+ *) return 1 ;;
1236
+ esac
1237
+ case ${1##*/.trash-"$2"-} in
1238
+ '' | *[!0-9]*) return 1 ;;
1239
+ esac
1240
+ }
1241
+
1242
+ # Remove the path $1 (a folder, a file, a link) however read-only it is. A link goes as the link, never followed. The folders CocoaPods' xcframeworks leave read-only stop `rm`, so a tree is made writable first, and a
1243
+ # read-only parent is the last resort. Succeeds when nothing is left there.
1244
+ remove_path_even_if_read_only() {
1245
+ local target=$1
1246
+ [ -L "$target" ] || chmod -R u+rwX "$target" 2> /dev/null
1247
+ rm -rf "$target" 2> /dev/null
1248
+ if [ -e "$target" ] || [ -L "$target" ]; then
1249
+ chmod u+w "$(dirname "$target")" 2> /dev/null
1250
+ rm -rf "$target" 2> /dev/null
1251
+ fi
1252
+ [ ! -e "$target" ] && [ ! -L "$target" ]
1253
+ }
1254
+
1255
+ # Remove project copy $2 (a slug) under work dir $1. Moved aside by one rename first: a submit that meets the name afterwards makes a copy of its own, and a removal that is cut off is finished by the
1256
+ # next prune. The busy check that chose the copy and the rename are two steps, and a job can be prepared between them — so it is asked AGAIN of the moved folder, and a copy that turned out in use is put back.
1257
+ # Returns: 0 removed · 1 would not go · 2 gone already (another prune took it) · 3 in use after all (put back when its name is still free; else left under its trash name, which is never removed while it is in use).
1258
+ remove_project_copy() {
1259
+ local source="$1/p/$2" trash="$1/p/.trash-$2-$$"
1260
+ [ -e "$trash" ] && return 1
1261
+ # The index lock is held from the rename of the copy to the rename of its TMPDIR - an instant, not the removal: the copy's number is free the moment it leaves p/<slug>, and a copy that is given it must not meet the old
1262
+ # TMPDIR. The TMPDIR is removed after the lock is given back. A lock that cannot be had leaves the TMPDIR to the next copy that gets the number (it starts with an empty one); the Simulator device is retired either way.
1263
+ local is_index_lock_held=0
1264
+ acquire_index_lock "$1" && is_index_lock_held=1
1265
+ if ! mv "$source" "$trash" 2> /dev/null; then
1266
+ [ "$is_index_lock_held" -eq 1 ] && release_index_lock "$1"
1267
+ [ -e "$source" ] && return 1
1268
+ return 2
1269
+ fi
1270
+ if check_copy_dir_is_busy "$trash"; then
1271
+ if [ ! -e "$source" ]; then
1272
+ mv "$trash" "$source" 2> /dev/null
1273
+ # A `prepare` can make the folder between the test and the `mv`, which then moves the copy INTO it: out again, to where the next prune looks for trash (and where its markers are seen).
1274
+ [ -e "$source/${trash##*/}" ] && mv "$source/${trash##*/}" "$trash" 2> /dev/null
1275
+ fi
1276
+ [ "$is_index_lock_held" -eq 1 ] && release_index_lock "$1"
1277
+ return 3
1278
+ fi
1279
+ local set_aside=
1280
+ if [ "$is_index_lock_held" -eq 1 ]; then
1281
+ retire_copy_simulator "$1" "$trash" held
1282
+ set_aside_copy_tmpdir "$1" "$trash"
1283
+ set_aside=$tmpdir_set_aside
1284
+ release_index_lock "$1"
1285
+ else
1286
+ retire_copy_simulator "$1" "$trash" unlocked
1287
+ fi
1288
+ [ -z "$set_aside" ] || remove_path_even_if_read_only "$set_aside"
1289
+ remove_path_even_if_read_only "$trash" || return 1
1290
+ }
1291
+
1292
+ # Set the TMPDIR of the copy moved aside to folder $2 aside, by the number it held (`set_aside_tmpdir`: sets tmpdir_set_aside). The index lock of work dir $1 must be held.
1293
+ set_aside_copy_tmpdir() {
1294
+ local recorded
1295
+ tmpdir_set_aside=
1296
+ recorded=$(read_file "$2/index")
1297
+ case $recorded in
1298
+ '' | *[!0-9]*) return 0 ;;
1299
+ esac
1300
+ set_aside_tmpdir "$1" "$((10#$recorded))"
1301
+ }
1302
+
1303
+ # last_freed_kb = how much the disk under $1 has gained since it had $2 KiB free (0 when it did not grow; empty when df said nothing).
1304
+ set_freed_kb_since() {
1305
+ local work_dir=$1 before_kb=$2
1306
+ last_freed_kb=
1307
+ read_disk_kb "$work_dir"
1308
+ if [ -n "$before_kb" ] && [ -n "$disk_free_kb" ]; then
1309
+ last_freed_kb=$((disk_free_kb - before_kb))
1310
+ [ "$last_freed_kb" -ge 0 ] || last_freed_kb=0
1311
+ fi
1312
+ }
1313
+
1314
+ # Print the report of a removal of project copy $2 (under work dir $1) that freed space since $3 KiB were free there: `removed=<slug> freed_kb=<n> why=<reason $4>`.
1315
+ report_removed_since() {
1316
+ set_freed_kb_since "$1" "$3"
1317
+ printf 'removed=%s freed_kb=%s why=%s\n' "$2" "$last_freed_kb" "$4"
1318
+ }
1319
+
1320
+ # Remove copy $2 for reason $3 (idle | space | clean) and say so on stdout, one line the submit shows: `removed=<slug> freed_kb=<n> why=<reason>`; a copy that would not go: `stuck=<slug>`; one that
1321
+ # an earlier prune took, or that turned out in use, is not said anything of. freed_kb is the change of the disk's free space across the removal (empty when df said nothing).
1322
+ # Sets last_freed_kb. Returns remove_project_copy's code.
1323
+ remove_and_report_copy() {
1324
+ local work_dir=$1 copy_slug=$2 reason=$3
1325
+ local before_kb removal_code
1326
+ read_disk_kb "$work_dir"
1327
+ before_kb=$disk_free_kb
1328
+ remove_project_copy "$work_dir" "$copy_slug"
1329
+ removal_code=$?
1330
+ case $removal_code in
1331
+ 0) report_removed_since "$work_dir" "$copy_slug" "$before_kb" "$reason" ;;
1332
+ 1) printf 'stuck=%s\n' "$copy_slug" ;;
1333
+ esac
1334
+ return "$removal_code"
1335
+ }
1336
+
1337
+ # Project copies unused for copy_keep_days (the runner's setting, else the default) are removed, unless in use or the copy of the job being submitted.
1338
+ prune_idle_copies() {
1339
+ local work_dir=$1 keep_slug=$2 seed_slug=${3:-}
1340
+ local idle_minutes=$(($(get_copy_keep_days) * minutes_per_day))
1341
+ local used_file idle_slug
1342
+ while IFS= read -r used_file; do
1343
+ idle_slug=$(basename "$(dirname "$used_file")")
1344
+ [ "$idle_slug" = "$keep_slug" ] && continue
1345
+ # The copy a new copy's first job is about to be seeded from is kept for this submit: the next `prepare` removes it by age if nobody has used it since (what the clone holds then is shared with it: little is given back).
1346
+ [ -n "$seed_slug" ] && [ "$idle_slug" = "$seed_slug" ] && continue
1347
+ check_copy_is_busy "$work_dir" "$idle_slug" && continue
1348
+ remove_and_report_copy "$work_dir" "$idle_slug" idle || true
1349
+ done < <(find "$work_dir/p" -mindepth 2 -maxdepth 2 -name used -type f -mmin +"$idle_minutes" 2> /dev/null)
1350
+ }
1351
+
1352
+ # While the disk is short of free space, remove the project copies that were used longest ago, one by one, until it is not — except copies in use and the copy of the job being submitted.
1353
+ # Stops, with a `stopped=` line, after no_progress_stop_after removals in a row that each freed next to nothing from a copy measured bigger: the disk's free figure is not following the removals
1354
+ # (a Mac's APFS keeps the space of deleted files while Time Machine local snapshots hold it), and going on would remove every copy and refuse anyway; one such removal is not enough to say so
1355
+ # (a job writing to the same disk meanwhile can eat the space it freed). «In a row» counts only the removals that can say anything: a copy measured at most no_progress_freed_kb, or not measured, between two
1356
+ # of them neither counts nor resets the count; a removal that freed what it should does reset it. Sets prune_stopped_without_gain for the submit's refusal.
1357
+ prune_copies_for_space() {
1358
+ local work_dir=$1 keep_slug=$2 seed_slug=${3:-}
1359
+ local used_file lru_slug size_kb removal_code no_gain_removals=0 is_shared=0 is_seed_source_left=0
1360
+ prune_stopped_without_gain=0
1361
+ while IFS= read -r used_file; do
1362
+ check_disk_is_short "$work_dir" || break
1363
+ lru_slug=$(basename "$(dirname "$used_file")")
1364
+ [ "$lru_slug" = "$keep_slug" ] && continue
1365
+ # The copy the submitted job's first run is seeded from goes last, if the others are not enough: a new copy that is cloned from it costs next to nothing, one that installs from scratch costs all of it again.
1366
+ if [ -n "$seed_slug" ] && [ "$lru_slug" = "$seed_slug" ]; then
1367
+ is_seed_source_left=1
1368
+ continue
1369
+ fi
1370
+ check_copy_is_busy "$work_dir" "$lru_slug" && continue
1371
+ size_kb=$(read_file "$work_dir/p/$lru_slug/size-kb")
1372
+ # Asked BEFORE the removal: the marks go with the copy.
1373
+ is_shared=0
1374
+ check_copy_shares_blocks "$work_dir" "$lru_slug" && is_shared=1
1375
+ remove_and_report_copy "$work_dir" "$lru_slug" space
1376
+ removal_code=$?
1377
+ [ "$removal_code" -eq 0 ] || continue
1378
+ # A copy that shares its blocks with a clone frees only what is its alone while `du` counts them all: what it gave back says nothing about whether the disk follows — like a copy that was never measured, it neither counts nor resets.
1379
+ [ "$is_shared" -eq 0 ] || continue
1380
+ # Only a copy measured bigger than the threshold says anything about whether the disk follows: one too small or never measured leaves the count as it is (an LRU order of big, small, big, small
1381
+ # must not hide a disk that keeps every big copy's space); a removal that freed what it should resets it.
1382
+ case "$size_kb:$last_freed_kb" in
1383
+ *[!0-9:]* | : | :* | *:) continue ;;
1384
+ esac
1385
+ [ "$size_kb" -gt "$no_progress_freed_kb" ] || continue
1386
+ if [ "$last_freed_kb" -ge "$no_progress_freed_kb" ]; then
1387
+ no_gain_removals=0
1388
+ continue
1389
+ fi
1390
+ no_gain_removals=$((no_gain_removals + 1))
1391
+ if [ "$no_gain_removals" -ge "$no_progress_stop_after" ]; then
1392
+ printf 'stopped=%s freed_kb=%s size_kb=%s\n' "$lru_slug" "$last_freed_kb" "$size_kb"
1393
+ prune_stopped_without_gain=1
1394
+ break
1395
+ fi
1396
+ done < <(ls -1tr "$work_dir"/p/*/used 2> /dev/null)
1397
+ if [ "$is_seed_source_left" -eq 1 ] && [ "$prune_stopped_without_gain" -eq 0 ] && check_disk_is_short "$work_dir" && ! check_copy_is_busy "$work_dir" "$seed_slug"; then
1398
+ remove_and_report_copy "$work_dir" "$seed_slug" space || true
1399
+ fi
1400
+ }
1401
+
1402
+ # KiB project copy $2 (a slug, under work dir $1) takes, per mode $3: `written` = the figure `measure-copies` wrote into the copy (size-kb), whatever its age, and failure when there is none (never a `du`);
1403
+ # `current` = that figure unless the copy was used after it was written (then, and when there is none, measured now with `du -sk` and written down — a copy is measured again only when it was used,
1404
+ # not by the clock: a `du` over millions of files is not something to repeat hourly for copies nobody touched). Fails when the copy cannot be measured.
1405
+ read_copy_size_kb() {
1406
+ local size_file="$1/p/$2/size-kb" size_kb=
1407
+ if [ -f "$size_file" ] && { [ "$3" = written ] || ! [ "$1/p/$2/used" -nt "$size_file" ]; }; then
1408
+ size_kb=$(read_file "$size_file")
1409
+ fi
1410
+ case $size_kb in
1411
+ '' | *[!0-9]*)
1412
+ [ "$3" = written ] && return 1
1413
+ size_kb=$(du -sk "$1/p/$2" 2> /dev/null | awk '{ print $1 }')
1414
+ case $size_kb in '' | *[!0-9]*) return 1 ;; esac
1415
+ # The copy's TMPDIR (`t/<n>`, outside the copy's folder) belongs to its figure: it is removed with the copy, and it is where a copy in daily use piles up caches.
1416
+ local tmp_number tmp_kb
1417
+ tmp_number=$(read_file "$1/p/$2/index")
1418
+ case $tmp_number in
1419
+ '' | *[!0-9]*) ;;
1420
+ *)
1421
+ tmp_kb=$(du -sk "$1/t/$((10#$tmp_number))" 2> /dev/null | awk '{ print $1 }')
1422
+ case $tmp_kb in '' | *[!0-9]*) ;; *) size_kb=$((size_kb + tmp_kb)) ;; esac
1423
+ ;;
1424
+ esac
1425
+ write_copy_size_kb "$size_file" "$size_kb"
1426
+ ;;
1427
+ esac
1428
+ printf '%s\n' "$size_kb"
1429
+ }
1430
+
1431
+ # `5 GB` / `41 GB` / `0.4 GB` for KiB $1 (the words `formatGigabytes` in probe.ts uses).
1432
+ format_kb_as_gb() {
1433
+ awk -v kb="$1" 'BEGIN { g = kb / 1048576; if (g >= 10) printf "%d GB", g + 0.5; else printf "%g GB", int(g * 10 + 0.5) / 10 }'
1434
+ }
1435
+
1436
+ # The submit's refusal when the disk is still short after the prune: free, needed, the biggest copies, the way out. One line on stderr, exit low_disk_exit_code. It never measures anything (a `du` of
1437
+ # copies of tens of GB would make the refusal that is meant to come at once take minutes): it names the copies whose size was written down and counts the others.
1438
+ refuse_when_disk_is_short() {
1439
+ check_disk_is_short "$work" || return 0
1440
+ # This submit goes no further: take back what `prepare` made for it (a project that has nothing else in it, its first submit, goes away with it).
1441
+ rm -rf "$jd" "$stage"
1442
+ rmdir "$proj/stage" "$jobs_dir" "$tree" 2> /dev/null
1443
+ [ -z "$(ls -A "$proj" 2> /dev/null | grep -v -x -e used -e size-kb)" ] && rm -rf "$proj"
1444
+ # Only a refusal needs fresh sizes (it names the biggest copies; the walk is detached, so that the next submit has them): a submit that goes on does not start a walk over its neighbours' trees. Started only now, with this submit's copy
1445
+ # taken back: the walk outlives this call and writes `size-kb` into every copy it finds — into the folder this refusal was removing, it would leave a copy that nothing knows (no `used`: no prune ever takes it) behind.
1446
+ start_detached_run "$work" measure-copies
1447
+ local copy_dir copy_slug size_kb sizes= listing= copies=0 unmeasured=0 seed_groups= copy_group is_listing_cloned=0
1448
+ for copy_dir in "$work"/p/*/; do
1449
+ [ -d "$copy_dir" ] || continue
1450
+ copies=$((copies + 1))
1451
+ copy_slug=$(basename "$copy_dir")
1452
+ copy_group=$(get_copy_seed_group "$work" "$copy_slug")
1453
+ [ -z "$copy_group" ] || seed_groups="$seed_groups$copy_group"$'\n'
1454
+ if size_kb=$(read_copy_size_kb "$work" "$copy_slug" written); then
1455
+ sizes="$sizes$size_kb $copy_slug"$'\n'
1456
+ else
1457
+ unmeasured=$((unmeasured + 1))
1458
+ fi
1459
+ done
1460
+ while read -r size_kb copy_slug; do
1461
+ listing="${listing:+$listing, }$copy_slug $(format_kb_as_gb "$size_kb")"
1462
+ # A clone's figure counts the blocks it shares with its source in full (`du` cannot see them shared): removing one gives back less than it says. Only the copies the line NAMES are asked.
1463
+ copy_group=$(get_copy_seed_group "$work" "$copy_slug")
1464
+ [ -n "$copy_group" ] && check_group_is_shared "$seed_groups" "$copy_group" && is_listing_cloned=1
1465
+ done < <(printf '%s' "$sizes" | sort -rn | head -n "$refusal_copy_count")
1466
+ local advice="there is no project copy here to free: the disk is full of other files"
1467
+ if [ "$copies" -gt 0 ]; then
1468
+ advice="free space with \`charness remote-run clean <slug>\` on the copies of project folders whose last task is closed (\`charness remote-run runners\` shows what they take)"
1469
+ local listing_notes=
1470
+ [ "$unmeasured" -gt 0 ] && listing_notes="and $unmeasured not measured yet"
1471
+ [ "$is_listing_cloned" -eq 1 ] && listing_notes="${listing_notes:+$listing_notes; }clones counted in full"
1472
+ [ -n "$listing_notes" ] && listing_notes=" ($listing_notes)"
1473
+ [ -n "$listing" ] && advice="biggest project copies: $listing$listing_notes; $advice"
1474
+ [ -z "$listing" ] && advice="$copies project copies, their sizes are still being measured; $advice"
1475
+ [ "$prune_stopped_without_gain" -eq 1 ] && advice="$advice. Removing copies did not give their space back (on a Mac: APFS local snapshots or purgeable space; anywhere: jobs writing meanwhile, see docs/remote-run.md)"
1476
+ fi
1477
+ printf 'remote-run-runner: only %s free on the work disk, the runner needs %s; %s\n' "$(format_kb_as_gb "$disk_free_kb")" "$(format_kb_as_gb "$min_free_kb")" "$advice" >&2
1478
+ exit "$low_disk_exit_code"
1479
+ }
1480
+
1481
+ get_script_path() {
1482
+ printf '%s\n' "$(cd "$(dirname "$0")" && pwd)/$(basename "$0")"
1483
+ }
1484
+
1485
+ # Run subcommand $2 of this script on work dir $1 detached (output and input away, so an ssh call that started it returns), unless a run of it is still going.
1486
+ start_detached_run() {
1487
+ local work_dir=$1 subcommand=$2
1488
+ local pid_file="$work_dir/tmp/$subcommand.pid" running_pid
1489
+ mkdir -p "$work_dir/tmp" 2> /dev/null
1490
+ running_pid=$(read_file "$pid_file")
1491
+ check_runner_pid_alive "$running_pid" && return 0
1492
+ ( nice -n 19 bash "$(get_script_path)" "$subcommand" "$work_dir" > /dev/null 2>&1 < /dev/null & echo "$!" > "$pid_file" )
1493
+ }
1494
+
1495
+ # The scheduling safety net, run detached by a probe (`start_detached_run`): see `enqueue_idle_stashed`.
1496
+ cmd_settle_queue() {
1497
+ enqueue_idle_stashed "$1"
1498
+ }
1499
+
1500
+ # Write down the size of every project copy whose figure is missing, or was written before the copy was last used (`du` of a copy of tens of GB takes long: this runs detached).
1501
+ cmd_measure_copies() {
1502
+ local work_dir=$1 copy_dir copy_slug
1503
+ for copy_dir in "$work_dir"/p/*/; do
1504
+ [ -d "$copy_dir" ] || continue
1505
+ copy_slug=$(basename "$copy_dir")
1506
+ # A copy in use is measured after its job ends: its figure would be wrong as soon as the build writes, and the walk would compete with the build for the disk. Unless it has no figure at all: a refusal on a short disk
1507
+ # names the copies it can by their figures, and the copies left then are the ones in use — one walk each, ever, keeps that promise.
1508
+ if check_copy_is_busy "$work_dir" "$copy_slug" && read_copy_size_kb "$work_dir" "$copy_slug" written > /dev/null; then
1509
+ continue
1510
+ fi
1511
+ read_copy_size_kb "$work_dir" "$copy_slug" current > /dev/null
1512
+ done
1513
+ }
1514
+
1515
+ # A probe of a VIEW of the runners on a Mac whose iOS works starts `simctl-cleanup` detached, unless it ran in the last simctl_cleanup_interval_hours (the stamp `$work/simctl-cleanup.at`). The stamp is touched HERE, before the start,
1516
+ # so two views a second apart (the CLI and the bot's /runners) cannot both pass the check; the run touches it again when it starts, and a run that hangs or dies is not started again at every probe.
1517
+ start_simctl_cleanup_if_due() {
1518
+ # An always-on Mac does all its iOS work in the login session's agent, and the cleanup would run in the service's own session — whose CoreSimulator is not known to see the same devices and runtimes. Not there until it goes
1519
+ # through the agent.
1520
+ gui_session_expected && return 0
1521
+ local stamp="$work/simctl-cleanup.at"
1522
+ if [ -f "$stamp" ] && [ -z "$(find "$stamp" -maxdepth 0 -mmin +"$((simctl_cleanup_interval_hours * 60))" 2> /dev/null)" ]; then
1523
+ return 0
1524
+ fi
1525
+ touch "$stamp"
1526
+ start_detached_run "$work" simctl-cleanup
1527
+ }
1528
+
1529
+ # Run "$@" with at most $1 seconds to finish (a watchdog: there is no `timeout(1)` on a Mac), its stdin from /dev/null; its stdout and stderr are the call's own (redirect the call). Returns its exit code (137 when the
1530
+ # watchdog killed it). The probe's steps and the simulator cleanup are both bounded by it.
1531
+ run_bounded() {
1532
+ local limit_sec=$1
1533
+ shift
1534
+ "$@" < /dev/null &
1535
+ local command_pid=$!
1536
+ ( sleep "$limit_sec"; kill -9 "$command_pid" ) > /dev/null 2>&1 &
1537
+ local watchdog_pid=$!
1538
+ local command_code
1539
+ wait "$command_pid" 2> /dev/null
1540
+ command_code=$?
1541
+ # KILL, not TERM: a caller that ignores TERM (the Simulator shutdown step does, `cmd_ios_device_shutdown`) hands that to the watchdog, whose subshell would then sleep out the whole limit - holding the caller's pipes, and
1542
+ # firing a `kill -9` at a pid that may be another process's by then. Quietly: the shell would report the killed watchdog («Killed: 9») in the output of whoever called this.
1543
+ stop_background_job "$watchdog_pid" KILL
1544
+ return "$command_code"
1545
+ }
1546
+
1547
+ # `xcrun simctl delete unavailable`: the simulators whose runtime is gone (an Xcode that was updated or an old runtime that was removed leave them behind: 17 MB each, but their apps' data is 2-10 GB). Nothing else is deleted — no
1548
+ # erase, no device of an installed runtime, no runtime. It is asked ONLY when `simctl list runtimes available` shows at least one runtime in this very session: a CoreSimulator that sees no runtime (the System session of a
1549
+ # LaunchDaemon, a half-started service) calls EVERY device «unavailable», and the call would delete them all with their app data. Both calls are bounded (a watchdog); what they said is in `$work/simctl-cleanup.log`.
1550
+ # Sets simctl_runtime_list_code (the exit code of `xcrun simctl list runtimes available`, bounded) and simctl_runtime_count (the runtimes it lists); what simctl said is appended to file $2 when given. A CoreSimulator that sees
1551
+ # no runtime (the System session of a LaunchDaemon, a service that has only just started, an Xcode or a runtime being installed) calls EVERY device «unavailable»: nothing may be judged gone, deleted or made on its word.
1552
+ count_visible_simulator_runtimes() {
1553
+ local work_dir=$1 log=${2:-}
1554
+ local runtimes_file="$work_dir/tmp/simctl-runtimes.$$"
1555
+ mkdir -p "$work_dir/tmp"
1556
+ : > "$runtimes_file"
1557
+ run_bounded "$simctl_list_sec" xcrun simctl list runtimes available >> "$runtimes_file" 2>&1
1558
+ simctl_runtime_list_code=$?
1559
+ [ -z "$log" ] || cat "$runtimes_file" >> "$log"
1560
+ simctl_runtime_count=$(grep -c '^[A-Za-z][A-Za-z]* [0-9]' "$runtimes_file")
1561
+ rm -f "$runtimes_file"
1562
+ }
1563
+
1564
+ cmd_simctl_cleanup() {
1565
+ local work_dir=$1
1566
+ local log="$work_dir/simctl-cleanup.log"
1567
+ touch "$work_dir/simctl-cleanup.at"
1568
+ command -v xcrun > /dev/null 2>&1 || return 0
1569
+ echo "$(date '+%Y-%m-%d %H:%M:%S') xcrun simctl list runtimes available" > "$log"
1570
+ count_visible_simulator_runtimes "$work_dir" "$log"
1571
+ if [ "$simctl_runtime_list_code" -ne 0 ] || [ "${simctl_runtime_count:-0}" -eq 0 ]; then
1572
+ echo "refused: this session sees no Simulator runtime (simctl exit $simctl_runtime_list_code), so every device would read «unavailable» — nothing was deleted" >> "$log"
1573
+ return 0
1574
+ fi
1575
+ echo "$(date '+%Y-%m-%d %H:%M:%S') xcrun simctl delete unavailable" >> "$log"
1576
+ run_bounded "$simctl_cleanup_sec" xcrun simctl delete unavailable >> "$log" 2>&1
1577
+ echo "exit $?" >> "$log"
1578
+ return 0
1579
+ }
1580
+
1581
+ # ─────────────────────────── a job's own Simulator device ───────────────────────────
1582
+
1583
+ # Is $1 the shape of a Simulator device's UDID (8-4-4-4-12 hex digits)? Whatever comes from a file or from simctl is checked before it names a device.
1584
+ check_is_udid() {
1585
+ case $1 in
1586
+ [0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]-[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]-[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]-[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]-[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]) return 0 ;;
1587
+ esac
1588
+ return 1
1589
+ }
1590
+
1591
+ # The Simulator device of the project copy in folder $2 goes onto the retired list of work dir $1 when the copy goes (`<work>/ios-devices-retired`, one UDID per line, no UDID twice). The device itself is deleted
1592
+ # by the next `ios-device` step, which runs in the session that can see it: an always-on Mac's daemon is not that session.
1593
+ retire_copy_simulator() {
1594
+ local retired_file="$1/ios-devices-retired" udid mode=${3:-take} is_taken=0
1595
+ udid=$(read_file "$2/ios-simulator")
1596
+ check_is_udid "$udid" || return 0
1597
+ # The list is rewritten under the index lock (`delete_retired_simulators`), so it is appended to under it too: a line added between that rewrite's read and its `mv` would be lost, and the device with its app data never deleted.
1598
+ # $3: `take` (the default: take the lock for the append), `held` (the caller holds it), `unlocked` (the caller could not get it: appended without — rare, and a lost line costs a device left behind, not a failure).
1599
+ [ "$mode" = take ] && acquire_index_lock "$1" && is_taken=1
1600
+ grep -qxF "$udid" "$retired_file" 2> /dev/null || printf '%s\n' "$udid" >> "$retired_file"
1601
+ [ "$is_taken" -eq 1 ] && release_index_lock "$1"
1602
+ return 0
1603
+ }
1604
+
1605
+ # Delete the devices of the retired list ($1 = work dir) that this runner made: the device must be listed, and its name must start with ios_device_prefix — a device of the operator's is never touched, whatever the
1606
+ # list says. A line whose device is gone, or is not ours, is dropped; one whose deletion failed stays for the next time. Silent when simctl cannot list devices (the list stays as it is).
1607
+ delete_retired_simulators() {
1608
+ local work_dir=$1
1609
+ local retired_file="$work_dir/ios-devices-retired"
1610
+ [ -s "$retired_file" ] || return 0
1611
+ local all_file="$work_dir/tmp/ios-devices-all.$$" done_file="$work_dir/tmp/ios-devices-done.$$"
1612
+ mkdir -p "$work_dir/tmp" 2> /dev/null
1613
+ : > "$done_file"
1614
+ if ! run_bounded "$ios_device_list_sec" xcrun simctl list devices > "$all_file" 2>&1; then
1615
+ rm -f "$all_file" "$done_file"
1616
+ return 0
1617
+ fi
1618
+ local udid device_name
1619
+ while IFS= read -r udid || [ -n "$udid" ]; do
1620
+ if ! check_is_udid "$udid"; then
1621
+ printf '%s\n' "$udid" >> "$done_file"
1622
+ continue
1623
+ fi
1624
+ device_name=$(sed -n "s/^[[:space:]]*\(.*\) ($udid).*/\1/p" "$all_file" | head -n 1)
1625
+ case $device_name in
1626
+ '') printf '%s\n' "$udid" >> "$done_file" ;;
1627
+ "$ios_device_prefix"*)
1628
+ if run_bounded "$ios_device_delete_sec" xcrun simctl delete "$udid" > /dev/null 2>&1; then
1629
+ say "deleted the simulator $device_name ($udid) of a project copy that was removed"
1630
+ printf '%s\n' "$udid" >> "$done_file"
1631
+ else
1632
+ say "the simulator $device_name ($udid) of a removed project copy could not be deleted now; it is tried again at the next job that needs iOS"
1633
+ fi
1634
+ ;;
1635
+ *) printf '%s\n' "$udid" >> "$done_file" ;;
1636
+ esac
1637
+ done < "$retired_file"
1638
+ # The list is rewritten under the index lock, from what it holds NOW: a copy removed meanwhile appends to it under the same lock.
1639
+ if [ -s "$done_file" ] && acquire_index_lock "$work_dir"; then
1640
+ { grep -vxF -f "$done_file" "$retired_file" || true; } > "$retired_file.tmp.$$"
1641
+ mv "$retired_file.tmp.$$" "$retired_file"
1642
+ release_index_lock "$work_dir"
1643
+ fi
1644
+ rm -f "$all_file" "$done_file" "$retired_file.tmp.$$"
1645
+ return 0
1646
+ }
1647
+
1648
+ # The last line of file $1 that is a UDID, or nothing.
1649
+ read_last_udid_line() {
1650
+ local line found=
1651
+ while IFS= read -r line || [ -n "$line" ]; do
1652
+ check_is_udid "$line" && found=$line
1653
+ done < "$1"
1654
+ printf '%s' "$found"
1655
+ }
1656
+
1657
+ # `ios-device <work> <slug>`: the project copy's own Simulator device, ready — run BY the job as a step before its command (so on an always-on Mac in the login session, like every iOS step). The retired devices go first;
1658
+ # then the device recorded in `p/<slug>/ios-simulator` is kept if `simctl list devices available` still has it, else (never made, or its runtime is gone) a new `charness-<slug>` is made of the device type and runtime the
1659
+ # runner's last passing iOS check used, and recorded; it is booted and waited for. Exit 0: the recorded device is booted. Anything else says why on stdout (the job's log) and exits 1: the job then runs without
1660
+ # REMOTE_RUN_IOS_SIMULATOR_UDID — a booted device nobody names is no harm, and the `xcrun` guard still protects the others.
1661
+ cmd_ios_device() {
1662
+ set_paths "$1" "$2" ""
1663
+ read_runner_state
1664
+ if [ "$ios_boot_status" != ok ] || [ -z "$ios_device_type" ]; then
1665
+ say "no simulator of its own: the runner's iOS check has not passed with a device type"
1666
+ return 1
1667
+ fi
1668
+ if ! command -v xcrun > /dev/null 2>&1; then
1669
+ say "no simulator of its own: xcrun is not on the PATH of this step"
1670
+ return 1
1671
+ fi
1672
+ mkdir -p "$work/tmp" 2> /dev/null
1673
+ delete_retired_simulators "$work"
1674
+ local device_name="$ios_device_prefix$slug" udid available_file="$work/tmp/ios-available.$$" output_file="$work/tmp/ios-step.$$"
1675
+ udid=$(read_file "$proj/ios-simulator")
1676
+ if ! run_bounded "$ios_device_list_sec" xcrun simctl list devices available > "$available_file" 2>&1; then
1677
+ say "no simulator of its own: simctl cannot list the simulators ($(tail -n 1 "$available_file" | cut -c1-200))"
1678
+ rm -f "$available_file"
1679
+ return 1
1680
+ fi
1681
+ if check_is_udid "$udid" && grep -qF "($udid)" "$available_file"; then
1682
+ say "using the simulator $device_name ($udid) of this project's copy"
1683
+ else
1684
+ # The device is not listed as available - or there is none yet. A session that sees no runtime lists nothing as available: that is no word for a device being gone, and none for making one.
1685
+ count_visible_simulator_runtimes "$work"
1686
+ if [ "$simctl_runtime_list_code" -ne 0 ] || [ "${simctl_runtime_count:-0}" -eq 0 ]; then
1687
+ say "no simulator of its own: this session sees no Simulator runtime, so no device can be told gone or made (CoreSimulator may still be starting)"
1688
+ rm -f "$available_file"
1689
+ return 1
1690
+ fi
1691
+ if [ -n "$udid" ]; then
1692
+ say "the simulator of this project's copy ($udid) is gone or unavailable: making a new one"
1693
+ retire_copy_simulator "$work" "$proj"
1694
+ rm -f "$proj/ios-simulator"
1695
+ fi
1696
+ if ! run_bounded "$ios_device_create_sec" xcrun simctl create "$device_name" "$ios_device_type" ${ios_runtime:+"$ios_runtime"} > "$output_file" 2>&1; then
1697
+ say "no simulator of its own: simctl create $device_name failed ($(tail -n 1 "$output_file" | cut -c1-200))"
1698
+ rm -f "$available_file" "$output_file"
1699
+ return 1
1700
+ fi
1701
+ udid=$(read_last_udid_line "$output_file")
1702
+ if [ -z "$udid" ]; then
1703
+ say "no simulator of its own: simctl create $device_name answered with no device id"
1704
+ rm -f "$available_file" "$output_file"
1705
+ return 1
1706
+ fi
1707
+ if ! { printf '%s\n' "$udid" > "$proj/ios-simulator.tmp.$$" && mv "$proj/ios-simulator.tmp.$$" "$proj/ios-simulator"; } 2> /dev/null; then
1708
+ say "no simulator of its own: the device $udid could not be written down"
1709
+ rm -f "$available_file" "$output_file" "$proj/ios-simulator.tmp.$$"
1710
+ return 1
1711
+ fi
1712
+ say "made the simulator $device_name ($udid) for this project's copy"
1713
+ fi
1714
+ # Booting a device that is booted already is an error of simctl's, and no failure here.
1715
+ if ! run_bounded "$ios_device_boot_sec" xcrun simctl boot "$udid" > "$output_file" 2>&1 && ! grep -q 'current state: Booted' "$output_file"; then
1716
+ say "no simulator of its own: simctl boot $udid failed ($(tail -n 1 "$output_file" | cut -c1-200))"
1717
+ rm -f "$available_file" "$output_file"
1718
+ return 1
1719
+ fi
1720
+ if ! run_bounded "$ios_device_bootstatus_sec" xcrun simctl bootstatus "$udid" > "$output_file" 2>&1; then
1721
+ say "no simulator of its own: $udid did not finish booting in ${ios_device_bootstatus_sec}s"
1722
+ rm -f "$available_file" "$output_file"
1723
+ return 1
1724
+ fi
1725
+ rm -f "$available_file" "$output_file"
1726
+ say "the simulator $device_name ($udid) is booted"
1727
+ }
1728
+
1729
+ # `ios-device-shutdown <work> <slug> <udid>`: shut that device down — the step at the end of a job (frees its memory for the next one; never `erase`: the app installed on it is what the next job reuses). Bounded.
1730
+ # A device that is shut down already is no failure.
1731
+ cmd_ios_device_shutdown() {
1732
+ # Deaf to TERM, INT and HUP: this step is what a kill waits for (the device must be shut down after a kill), and a kill that reads the job's phase and sends TERM to the group is check-then-act - the job can enter this phase
1733
+ # in between, and a second kill (the lease watcher's, an agent's retry) arrives while it runs. `run_bounded` still SIGKILLs a `simctl` that hangs; an ignored signal stays ignored in what is exec'd from here.
1734
+ trap '' TERM INT HUP
1735
+ set_paths "$1" "$2" ""
1736
+ local udid=${3:-}
1737
+ if ! check_is_udid "$udid"; then
1738
+ say "not shutting a simulator down: $udid is no device id"
1739
+ return 1
1740
+ fi
1741
+ mkdir -p "$work/tmp" 2> /dev/null
1742
+ local output_file="$work/tmp/ios-shutdown.$$"
1743
+ if run_bounded "$ios_device_shutdown_sec" xcrun simctl shutdown "$udid" > "$output_file" 2>&1 || grep -q 'current state: Shutdown' "$output_file"; then
1744
+ say "shut the simulator $udid down"
1745
+ rm -f "$output_file"
1746
+ return 0
1747
+ fi
1748
+ say "the simulator $udid could not be shut down ($(tail -n 1 "$output_file" | cut -c1-200))"
1749
+ rm -f "$output_file"
1750
+ return 1
1751
+ }
1752
+
1753
+ # The moved-aside folders of project copy $2 under work dir $1 (`p/.trash-<slug>-<pid>`), one per line.
1754
+ list_trash_of_slug() {
1755
+ local leftover
1756
+ for leftover in "$1"/p/.trash-"$2"-*; do
1757
+ [ -e "$leftover" ] && check_is_trash_of_slug "$leftover" "$2" && printf '%s\n' "$leftover"
1758
+ done
1759
+ }
1760
+
1761
+ # `clean <work> <slug>`: remove ONE project copy because its owner is done with it (the last task of its project folder was closed), with the removal machinery of the prune — the copy-removal lock, the busy check (asked
1762
+ # again of the moved-aside folder), the rename + `chmod` + `rm`. What differs from the prune: the copy is named, not guessed; and a job that ENDED lately keeps the copy only while nobody has fetched its results (the
1763
+ # `fetched` mark of `wait` / `fetch` / a foreground run): the prune keeps it for result_keep_min whatever. A job that runs or waits, an `exec`, a job still being submitted and a held project lock refuse it — then nothing
1764
+ # is removed. A folder an earlier removal left (`p/.trash-<slug>-<pid>`: cut off, or past its caller's time limit) is finished first, so «clean again» sees it through (when no copy is left and every leftover is being removed by a live process, the answer is `removing=` AT ONCE: that remover holds the copy-removal lock to the end of its `rm`, and waiting for it would only keep the caller silent). The answer is some lines on stdout (the exit status
1765
+ # is 0 whenever the script could answer): `removed=<slug> freed_kb=<n> why=clean` (the copy, the leftover, or both: one line each) · `absent=<slug>` (no such copy, or a prune took it first) · `removing=<slug>` (a leftover
1766
+ # whose remover still lives) · `busy=<slug> kind=<kind> job=<id|->` · `stuck=<slug>` (it would not go). Its jobs' logs and result files go with it.
1767
+ cmd_clean() {
1768
+ local work_dir=$1 clean_slug=${2:-}
1769
+ check_name "$clean_slug"
1770
+ # The caller may hang up while this removes tens of GB (its call has a time limit); the removal goes on to its end.
1771
+ trap '' PIPE
1772
+ local clean_ignores_fetched=1
1773
+ local leftover is_trash_left=0 is_a_remover_gone=0
1774
+ while IFS= read -r leftover; do
1775
+ is_trash_left=1
1776
+ check_runner_pid_alive "${leftover##*-}" || is_a_remover_gone=1
1777
+ done < <(list_trash_of_slug "$work_dir" "$clean_slug")
1778
+ if [ ! -d "$work_dir/p/$clean_slug" ] && [ "$is_trash_left" -eq 0 ]; then
1779
+ printf 'absent=%s\n' "$clean_slug"
1780
+ return 0
1781
+ fi
1782
+ # No copy, and every leftover is being removed right now: nothing for this call to do, and nothing to wait for. The remover HOLDS the copy-removal lock until its `rm` ends, so waiting for the lock
1783
+ # would keep the caller silent for minutes to hear the same thing (or, once the remover is done, to find nothing at all).
1784
+ if [ ! -d "$work_dir/p/$clean_slug" ] && [ "$is_a_remover_gone" -eq 0 ]; then
1785
+ printf 'removing=%s\n' "$clean_slug"
1786
+ return 0
1787
+ fi
1788
+ begin_copy_removal "$work_dir" always
1789
+ local before_kb trash_code is_answered=0
1790
+ while IFS= read -r leftover; do
1791
+ read_disk_kb "$work_dir"
1792
+ before_kb=$disk_free_kb
1793
+ finish_trash_removal "$leftover"
1794
+ trash_code=$?
1795
+ is_answered=1
1796
+ case $trash_code in
1797
+ 0) report_removed_since "$work_dir" "$clean_slug" "$before_kb" clean ;;
1798
+ 1) printf 'removing=%s\n' "$clean_slug" ;;
1799
+ 2) printf 'busy=%s kind=%s job=%s\n' "$clean_slug" "$copy_busy_kind" "$copy_busy_job" ;;
1800
+ 3) printf 'stuck=%s\n' "$clean_slug" ;;
1801
+ esac
1802
+ done < <(list_trash_of_slug "$work_dir" "$clean_slug")
1803
+ local removal_code=0
1804
+ if [ ! -d "$work_dir/p/$clean_slug" ]; then
1805
+ removal_code=-1
1806
+ elif check_copy_is_busy "$work_dir" "$clean_slug"; then
1807
+ removal_code=3
1808
+ else
1809
+ remove_and_report_copy "$work_dir" "$clean_slug" clean
1810
+ removal_code=$?
1811
+ fi
1812
+ end_copy_removal "$work_dir"
1813
+ case $removal_code in
1814
+ 2) printf 'absent=%s\n' "$clean_slug" ;;
1815
+ 3) printf 'busy=%s kind=%s job=%s\n' "$clean_slug" "$copy_busy_kind" "$copy_busy_job" ;;
1816
+ # Everything that was there went while this call waited for the lock (another remover finished it): said as «nothing there», never as an empty answer.
1817
+ -1) [ "$is_answered" -eq 1 ] || printf 'absent=%s\n' "$clean_slug" ;;
1818
+ esac
1819
+ return 0
1820
+ }
1821
+
1822
+ # `fetched <work> - <job>`: leave the mark that the results of finished job $3 are with whoever submitted it (`wait`, `fetch` and a foreground run call this once they have the files): `clean` then does not keep the copy for them.
1823
+ cmd_fetched() {
1824
+ set_paths "$1" "$2" "$3"
1825
+ [ -d "$jd" ] || die "no such job: $job"
1826
+ touch "$jd/fetched"
1827
+ }
1828
+
1829
+ # ─────────────────────────── adding the job to Pueue ───────────────────────────
1830
+
1831
+ # Quote one word for a shell (single quotes).
1832
+ quote_word() {
1833
+ printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"
1834
+ }
1835
+
1836
+ # The scheduling mutex of the project copy in folder $1: `<copy>/sched.lock`, made and broken by the project lock's helpers like the index lock (no job, a short age limit), waited for sched_lock_wait_sec at most. Fails when it
1837
+ # could not be had: a caller then goes on without the scheduling it was to do (a job is queued the old way; an enqueue is left to the next `prepare` or `probe`).
1838
+ acquire_sched_lock() {
1839
+ local lock="$1/sched.lock" jobs_dir= job= lock_max_age_min=$sched_lock_max_age_min
1840
+ local waited_since=$SECONDS
1841
+ while ! create_lock_file "$lock"; do
1842
+ check_lock_is_stale && break_stale_lock && continue
1843
+ [ $((SECONDS - waited_since)) -ge "$sched_lock_wait_sec" ] && return 1
1844
+ nap 0.2
1845
+ done
1846
+ rm -f "$lock".breaking.* 2> /dev/null
1847
+ return 0
1848
+ }
1849
+
1850
+ release_sched_lock() {
1851
+ local holder_pid holder_job
1852
+ read_lock_holder "$1/sched.lock"
1853
+ [ "$holder_pid" = "$$" ] && rm -f "$1/sched.lock"
1854
+ return 0
1855
+ }
1856
+
1857
+ # Is any job of the project copy in folder $1 under way - it has a Pueue task, no result, and no process that has died? `active` counts only the jobs Pueue may run (not the stashed ones: those wait for the others), `any` all.
1858
+ # A job that succeeded and is removing paths from the copy (phase `cleaning`, process alive) has its result already but still holds the project lock: it counts too, or a job submitted meanwhile would take a slot to sit in
1859
+ # the lock wait. One whose process died in that phase does not (it would stall the project for ever).
1860
+ check_project_has_unended_job() {
1861
+ local job_dir
1862
+ for job_dir in "$1"/jobs/*/; do
1863
+ [ -d "$job_dir" ] || continue
1864
+ if [ "$(read_file "$job_dir/phase")" = cleaning ] && check_runner_pid_alive "$(read_file "$job_dir/pid")"; then
1865
+ return 0
1866
+ fi
1867
+ check_job_dir_ended "$job_dir" && continue
1868
+ [ "$2" = active ] && [ -f "$job_dir/stashed" ] && continue
1869
+ return 0
1870
+ done
1871
+ return 1
1872
+ }
1873
+
1874
+ # End the job in folder $2 of project copy $1 as one that never ran: its Pueue task is gone (the queue was reset by a hub removal or an unpair, a state file was lost). It reads as killed (137) with a line in its log, and its
1875
+ # stash mark goes, so that it stops counting as under way and no later job of the project waits for it for ever.
1876
+ end_lost_job() {
1877
+ printf 'remote-run: the Pueue task of this job is gone (the queue was reset, or Pueue lost it), so it did not run\n' >> "$2/log"
1878
+ touch "$2/task-removed"
1879
+ [ -f "$2/timeout" ] || touch "$2/killed"
1880
+ ( jd=$2; proj=$1; stage="$1/stage/$(basename "$2")"; finish_killed_job )
1881
+ }
1882
+
1883
+ # End every job of the project copy in folder $1 that waits for a Pueue task Pueue does not have: a job with a task number, no result and no process (it never started) whose task is absent from Pueue's answer, or is
1884
+ # done there. A Pueue that does not answer ends nothing, and the answer is 1 (a caller then judges nothing either). Pueue is asked once per such job and not at all when the project has none. The scheduling mutex must be held.
1885
+ end_lost_jobs_of_project() {
1886
+ local job_dir task
1887
+ for job_dir in "$1"/jobs/*/; do
1888
+ [ -d "$job_dir" ] || continue
1889
+ job_dir=${job_dir%/}
1890
+ check_job_dir_ended "$job_dir" && continue
1891
+ [ -f "$job_dir/pid" ] && continue
1892
+ task=$(read_file "$job_dir/task-id")
1893
+ case $task in '' | *[!0-9]*) continue ;; esac
1894
+ read_job_task_state "$task" "$(basename "$job_dir")" || return 1
1895
+ case $job_task_state in
1896
+ absent | done) end_lost_job "$1" "$job_dir" ;;
1897
+ esac
1898
+ done
1899
+ return 0
1900
+ }
1901
+
1902
+ # Settle the waiting jobs of the project copy in folder $1: end the ones whose Pueue task is gone (`end_lost_jobs_of_project`), then enqueue (`pueue enqueue`) the oldest stashed job - if no other job of the copy is under
1903
+ # way: its predecessor ended (`finish_job`), or died before it could say so (the next `prepare` or `probe`, `enqueue_idle_stashed`; a `wait` on the stashed job, `kill_job`). A stashed job that has a result already (it was
1904
+ # killed) only loses its mark. Under the scheduling mutex, so that a job being added at the same moment is either seen here (stashed before this looks) or sees its predecessor ended (and is queued as usual): none is left
1905
+ # stashed with nobody to enqueue it. Pueue is asked only when a job waits for a task (a stashed one always does), and a Pueue that does not answer judges nothing: marks stay.
1906
+ enqueue_idle_stashed_of_project() {
1907
+ local project_dir=$1 marker job_dir task stashed_marks
1908
+ acquire_sched_lock "$project_dir" || return 0
1909
+ if end_lost_jobs_of_project "$project_dir"; then
1910
+ stashed_marks=$(ls -1tr "$project_dir"/jobs/*/stashed 2> /dev/null)
1911
+ if [ -n "$stashed_marks" ] && ! check_project_has_unended_job "$project_dir" active; then
1912
+ while IFS= read -r marker; do
1913
+ [ -f "$marker" ] || continue
1914
+ job_dir=$(dirname "$marker")
1915
+ task=$(read_file "$job_dir/task-id")
1916
+ case $task in '' | *[!0-9]*) rm -f "$marker"; continue ;; esac
1917
+ if [ -f "$job_dir/exit" ]; then
1918
+ rm -f "$marker"
1919
+ continue
1920
+ fi
1921
+ read_job_task_state "$task" "$(basename "$job_dir")" || break
1922
+ if [ "$job_task_state" != present ]; then
1923
+ rm -f "$marker"
1924
+ continue
1925
+ fi
1926
+ pq enqueue "$task" < /dev/null > /dev/null 2>&1 && rm -f "$marker"
1927
+ break
1928
+ done <<< "$stashed_marks"
1929
+ fi
1930
+ fi
1931
+ release_sched_lock "$project_dir"
1932
+ return 0
1933
+ }
1934
+
1935
+ # The safety net of the scheduling: every project copy of work dir $1 that has a stashed job, or a job waiting for a Pueue task (no process, no result: queued, or lost), gets `enqueue_idle_stashed_of_project` - a job that was
1936
+ # SIGKILLed never ran its `finish_job`, so its successor would wait for ever; a job whose task Pueue lost (a reset) would be under way for ever, in `ls`, in the queued count, and in the way of the copy's removal.
1937
+ # Run by `prepare` (inline: a job is starting) and by `probe` (detached, `settle-queue`: the answer never waits for it); both are asked often; costs a look at the job folders when nothing waits.
1938
+ enqueue_idle_stashed() {
1939
+ local job_dir project_dir seen=" "
1940
+ for job_dir in "$1"/p/*/jobs/*/; do
1941
+ [ -d "$job_dir" ] || continue
1942
+ if [ ! -f "$job_dir/stashed" ]; then
1943
+ [ -f "$job_dir/task-id" ] && [ ! -f "$job_dir/exit" ] && [ ! -f "$job_dir/pid" ] || continue
1944
+ fi
1945
+ project_dir=${job_dir%/jobs/*}
1946
+ case $seen in *" $project_dir "*) continue ;; esac
1947
+ seen="$seen$project_dir "
1948
+ enqueue_idle_stashed_of_project "$project_dir"
762
1949
  done
1950
+ return 0
763
1951
  }
764
1952
 
765
- cmd_prune() {
766
- prune_work "$1" ""
1953
+ # Is the job of `$jd` waiting for a Pueue task that Pueue does not have (the queue was reset, a state file was lost)? It has a task number, no process and no result, and Pueue's answer holds no task of that number with
1954
+ # the job's label, or one that is done. A Pueue that does not answer says nothing: the job is not judged lost.
1955
+ check_own_job_is_lost() {
1956
+ local task
1957
+ [ -f "$jd/exit" ] && return 1
1958
+ [ -f "$jd/pid" ] && return 1
1959
+ task=$(read_file "$jd/task-id")
1960
+ case $task in '' | *[!0-9]*) return 1 ;; esac
1961
+ read_job_task_state "$task" "$job" || return 1
1962
+ [ "$job_task_state" != present ]
767
1963
  }
768
1964
 
769
- # ─────────────────────────── adding the job to Pueue ───────────────────────────
770
-
771
- # Quote one word for a shell (single quotes).
772
- quote_word() {
773
- printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"
1965
+ # A caller that looks at the job of `$jd` (a `wait`, a `follow`, a lease, a `result`) ends it when Pueue has lost its task - a `pueue wait` on the number would return at once, or follow the stranger that holds the number
1966
+ # now for hours, and `result` would show it as queued for ever - and lets the stashed jobs behind a job that never ran go (a job killed in the queue, or ended just now as lost). Cheap: one question to Pueue, for a job that
1967
+ # has no process and no result yet.
1968
+ end_own_job_if_lost() {
1969
+ check_own_job_is_lost && end_lost_job "$proj" "$jd"
1970
+ if [ -f "$jd/task-removed" ] && [ ! -f "$jd/pid" ]; then enqueue_idle_stashed_of_project "$proj"; fi
1971
+ return 0
774
1972
  }
775
1973
 
1974
+ # Add the job to Pueue. A job whose project copy has another job under way is added STASHED (`$jd/stashed`): Pueue starts tasks in order of their numbers, and a second job of a project that is started because a slot
1975
+ # is free would sit in `waiting-lock` holding that slot, while a job of another project waits for it - a limit of 2 would often be 1. A stashed job takes no slot and is enqueued when its predecessor ends (`finish_job`),
1976
+ # at the latest by the next `prepare` / `probe`. Not `pueue add --after`: a task runs only if what it follows ended well, and a red test must not fail the project's next job. The project lock stays what keeps two jobs of a copy
1977
+ # apart; this only decides who may take a slot. Without the scheduling mutex the job is queued as before.
776
1978
  add_job() {
777
1979
  local group=$1
778
1980
  local script_path
779
- script_path=$(cd "$(dirname "$0")" && pwd)/$(basename "$0")
1981
+ script_path=$(get_script_path)
780
1982
  local command_line
781
1983
  command_line="exec bash $(quote_word "$script_path") job $(quote_word "$work") $(quote_word "$slug") $(quote_word "$job")"
782
- local task
1984
+ local task stash_option= is_stashed=0 holds_sched_lock=0
783
1985
  # The job's time limit counts from here (a foreground run's own timer does too): a job that waited its whole limit in the queue is
784
1986
  # over when it starts (cmd_job), not given the limit again.
785
1987
  date +%s > "$jd/queued-at"
786
- task=$(pq add --print-task-id -g "$group" -l "rr-$job" -w "$proj" -- "$command_line") || return 1
1988
+ acquire_sched_lock "$proj" && holds_sched_lock=1
1989
+ if [ "$holds_sched_lock" -eq 1 ] && check_project_has_unended_job "$proj" any; then
1990
+ # A job Pueue has lost (its queue was reset) is over, not under way: ended first, or this job would wait for it for ever.
1991
+ pq status < /dev/null > /dev/null 2>&1 && end_lost_jobs_of_project "$proj"
1992
+ if check_project_has_unended_job "$proj" any; then
1993
+ is_stashed=1
1994
+ stash_option=--stashed
1995
+ fi
1996
+ fi
1997
+ if ! task=$(pq add --print-task-id $stash_option -g "$group" -l "rr-$job" -w "$proj" -- "$command_line"); then
1998
+ [ "$holds_sched_lock" -eq 1 ] && release_sched_lock "$proj"
1999
+ return 1
2000
+ fi
787
2001
  printf '%s\n' "$task" > "$jd/task-id"
2002
+ [ "$is_stashed" -eq 1 ] && : > "$jd/stashed"
2003
+ [ "$holds_sched_lock" -eq 1 ] && release_sched_lock "$proj"
2004
+ return 0
788
2005
  }
789
2006
 
790
2007
  cmd_submit() {
@@ -804,43 +2021,92 @@ cmd_submit() {
804
2021
  signal_job_group() {
805
2022
  local job_pid group_id
806
2023
  job_pid=$(read_file "$jd/pid")
807
- [ -n "$job_pid" ] && kill -0 "$job_pid" 2> /dev/null || return 1
2024
+ [ -n "$job_pid" ] && check_runner_pid_alive "$job_pid" || return 1
808
2025
  group_id=$(ps -o pgid= -p "$job_pid" 2> /dev/null | tr -d ' ')
809
2026
  [ -n "$group_id" ] && [ "$group_id" = "$job_pid" ] || return 1
810
2027
  kill "-$1" -- "-$group_id" 2> /dev/null
811
2028
  }
812
2029
 
2030
+ # Pueue's own kill of the task `$1` of this job - only while the task under that number carries the job's label. Pueue hands a number it has freed to the next task it adds (after a `reset` it counts from 0 again), so a
2031
+ # number written down long ago may be another project's running job: acting on one that was not confirmed would kill a stranger. A Pueue that does not answer confirms nothing.
2032
+ kill_pueue_task_of_job() {
2033
+ check_task_belongs_to_job "$1" "$job" || return 1
2034
+ pq kill "$1" > /dev/null 2>&1
2035
+ }
2036
+
813
2037
  # Stop a job: a queued one is removed, a running one gets SIGTERM (its whole group) and, after the grace time, Pueue's own kill of the
814
2038
  # whole task tree. $1 says why: `timeout` when the caller's own time limit ran out (recorded like the job's own watchdog does it — 124,
815
- # "timed out" — whichever of the two gets there first), anything else is a kill (137).
2039
+ # "timed out" — whichever of the two gets there first), anything else is a kill (137). A job with no process yet is looked up in Pueue by its LABEL first
2040
+ # (`read_job_task_state`): its recorded number is acted on only when it is the job's own (`remove`), and a job Pueue has lost (a reset) is ended as one that never ran without a call on the number. The answer is 1 for a job
2041
+ # that has no task, 2 when Pueue did not answer (nothing is done then: a number that was not confirmed is never acted on).
816
2042
  kill_job() {
817
2043
  local task
818
2044
  task=$(read_file "$jd/task-id")
819
2045
  [ -n "$task" ] || return 1
820
2046
  [ -f "$jd/exit" ] && return 0
2047
+ local has_process=1
2048
+ if [ ! -f "$jd/pid" ]; then
2049
+ has_process=0
2050
+ read_job_task_state "$task" "$job" || return 2
2051
+ fi
821
2052
  if [ "${1:-}" = timeout ]; then
822
2053
  touch "$jd/timeout"
823
2054
  else
824
2055
  touch "$jd/killed"
825
2056
  fi
826
- if [ ! -f "$jd/pid" ] && pq remove "$task" > /dev/null 2>&1; then
827
- # Pueue gives a number it has freed to the next task it is asked to add: from here on `task-id` is a number that may belong to another
828
- # job, so nothing may act on it any more (`prune_work` skips such a job's task; waiting is decided by the exit file below).
829
- touch "$jd/task-removed"
830
- finish_killed_job
831
- return 0
2057
+ if [ "$has_process" -eq 0 ]; then
2058
+ if [ "$job_task_state" != present ]; then
2059
+ end_lost_job "$proj" "$jd"
2060
+ enqueue_idle_stashed_of_project "$proj"
2061
+ return 0
2062
+ fi
2063
+ if pq remove "$task" > /dev/null 2>&1; then
2064
+ # Pueue gives a number it has freed to the next task it is asked to add: from here on `task-id` is a number that may belong to another
2065
+ # job, so nothing may act on it any more (`prune_work` skips such a job's task; waiting is decided by the exit file below).
2066
+ touch "$jd/task-removed"
2067
+ finish_killed_job
2068
+ # A job of the same project that waits stashed behind this one may go now (it is a no-op while another job of the project is under way).
2069
+ enqueue_idle_stashed_of_project "$proj"
2070
+ return 0
2071
+ fi
832
2072
  fi
833
- signal_job_group TERM || pq kill "$task" > /dev/null 2>&1
834
- local started=$SECONDS
835
- while [ $((SECONDS - started)) -lt "$kill_grace_sec" ]; do
2073
+ # A job that is already shutting its Simulator device down is past its command: there is nothing left to stop, and a TERM to its group would reach the shutdown step (a second kill - the lease watcher's after the caller's,
2074
+ # an agent's retry - must not leave the device booted). The step itself ignores TERM as well (`shutdown_job_simulator`): this read is only the quick way out, and the phase may change right after it.
2075
+ if [ "$(read_file "$jd/phase")" != simulator-off ]; then
2076
+ signal_job_group TERM || kill_pueue_task_of_job "$task"
2077
+ fi
2078
+ local started=$SECONDS grace_sec=$kill_grace_sec
2079
+ while :; do
836
2080
  check_job_ended && return 0
2081
+ # A job that is shutting its Simulator device down is given what that step is bounded by (and the agent's pick-up of it) before the group is SIGKILLed, which would leave the device booted. The hub's kill call
2082
+ # waits for the same number (`simulatorShutdownGraceSeconds` in exitCodes.ts).
2083
+ [ "$(read_file "$jd/phase")" = simulator-off ] && grace_sec=$((kill_grace_sec + ios_device_shutdown_sec + simulator_shutdown_slack_sec))
2084
+ [ $((SECONDS - started)) -ge "$grace_sec" ] && break
837
2085
  sleep 0.2
838
2086
  done
839
2087
  hard_kill_job "$task"
840
2088
  sleep 1
2089
+ # Its own `finish_job` did not run: the next stashed job of the project is enqueued here (the job's own watchdog, which is killed with it, leaves it to the next `prepare` / `probe`).
2090
+ enqueue_idle_stashed_of_project "$proj"
841
2091
  return 0
842
2092
  }
843
2093
 
2094
+ # The lease watcher's kill (the caller is gone): a kill Pueue could not answer (`kill_job` returns 2: nothing was done) is tried again every kill_retry_sec until it answers or the job has its result - a queued job
2095
+ # whose only kill was dropped would start when Pueue is back and run its whole limit with nobody watching. `$jd/kill-pending` is there meanwhile (`cmd_lease` lets the watcher finish).
2096
+ kill_job_until_answered() {
2097
+ local kill_code
2098
+ while :; do
2099
+ kill_job "$@"
2100
+ kill_code=$?
2101
+ [ "$kill_code" -eq 2 ] || break
2102
+ : > "$jd/kill-pending"
2103
+ [ -f "$jd/exit" ] && break
2104
+ nap "$kill_retry_sec"
2105
+ done
2106
+ rm -f "$jd/kill-pending"
2107
+ return "$kill_code"
2108
+ }
2109
+
844
2110
  # SIGKILL of the whole group; Pueue's own kill follows only so that its task list agrees. Without a verifiable group, Pueue's kill
845
2111
  # is all there is. A job that is SIGKILLed cannot write its own result, so the result is recorded FIRST: when the caller is the job's own
846
2112
  # watchdog the group-wide SIGKILL takes the watchdog down with the job.
@@ -852,8 +2118,8 @@ kill_job() {
852
2118
  hard_kill_job() {
853
2119
  trap '' TERM HUP
854
2120
  finish_killed_job
855
- signal_job_group KILL || pq kill "$1" > /dev/null 2>&1
856
- pq kill "$1" > /dev/null 2>&1
2121
+ signal_job_group KILL || kill_pueue_task_of_job "$1"
2122
+ kill_pueue_task_of_job "$1"
857
2123
  return 0
858
2124
  }
859
2125
 
@@ -862,11 +2128,13 @@ hard_kill_job() {
862
2128
  # of the project takes over its lock at once, and prune removes it after 3 days like any other.
863
2129
  finish_killed_job() {
864
2130
  [ -f "$jd/exit" ] && return 0
2131
+ rm -f "$jd/stashed"
865
2132
  local code=137
866
2133
  [ -f "$jd/timeout" ] && code=124
867
2134
  rm -rf "$stage"
868
2135
  printf '%s\n' done > "$jd/phase"
869
2136
  date +%s > "$jd/finished-at"
2137
+ touch "$proj/used"
870
2138
  printf '%s\n' "$code" > "$jd/exit.tmp" && mv "$jd/exit.tmp" "$jd/exit"
871
2139
  }
872
2140
 
@@ -875,7 +2143,7 @@ check_job_ended() {
875
2143
  [ -f "$jd/exit" ] && return 0
876
2144
  local pid
877
2145
  pid=$(read_file "$jd/pid")
878
- [ -n "$pid" ] && ! kill -0 "$pid" 2> /dev/null && return 0
2146
+ [ -n "$pid" ] && ! check_runner_pid_alive "$pid" && return 0
879
2147
  return 1
880
2148
  }
881
2149
 
@@ -887,7 +2155,10 @@ cmd_kill() {
887
2155
  echo "already-ended $(read_file "$jd/exit")"
888
2156
  return 0
889
2157
  fi
890
- kill_job "${4:-}" || die "no such job: $job"
2158
+ kill_job "${4:-}" || case $? in
2159
+ 2) die "Pueue did not answer, so the task of job $job could not be told from another job's: nothing was killed" ;;
2160
+ *) die "no such job: $job" ;;
2161
+ esac
891
2162
  echo killed
892
2163
  }
893
2164
 
@@ -927,21 +2198,38 @@ stream_log() {
927
2198
  wait_for_task() {
928
2199
  [ -f "$jd/exit" ] && return 0
929
2200
  set -m
930
- pq wait "$1" < /dev/null > /dev/null 2>&1 &
2201
+ wait_for_own_task "$1" < /dev/null > /dev/null 2>&1 &
931
2202
  local waiter_pid=$!
932
2203
  set +m
2204
+ local looks=0
933
2205
  while kill -0 "$waiter_pid" 2> /dev/null; do
934
2206
  if [ -f "$jd/exit" ]; then
935
2207
  # The group, or the process alone when it did not get a group of its own: a group id that is not a live group is harmless.
936
2208
  kill -- "-$waiter_pid" > /dev/null 2>&1 || kill "$waiter_pid" > /dev/null 2>&1
937
2209
  break
938
2210
  fi
2211
+ # A job that waits stashed is enqueued by the job before it when that one ends; one SIGKILLed together with its own watchdog never does, and nobody else may look (the safety net of `prepare` / `probe` needs a caller).
2212
+ # Whoever waits for the stashed job looks itself: cheap (a listing; Pueue is asked only when a mark is there).
2213
+ looks=$((looks + 1))
2214
+ if [ -f "$jd/stashed" ] && [ $((looks % (stash_recheck_sec * 5))) -eq 0 ]; then enqueue_idle_stashed_of_project "$proj"; fi
939
2215
  sleep 0.2
940
2216
  done
941
2217
  { wait "$waiter_pid"; } 2> /dev/null
2218
+ # Pueue forgot the task while this waited (a reset ends its wait without a result), or the waiter ended a lost job: say so now, and let the jobs stashed behind it go.
2219
+ end_own_job_if_lost
942
2220
  return 0
943
2221
  }
944
2222
 
2223
+ # What the waiter of `wait_for_task` runs, in its process group (so the exit file can cut it, however long a question to Pueue or its wait takes): a job Pueue has lost is ended instead of waited for - a `pueue wait`
2224
+ # on its number would follow whoever holds the number now - else Pueue's wait.
2225
+ wait_for_own_task() {
2226
+ if check_own_job_is_lost; then
2227
+ end_lost_job "$proj" "$jd"
2228
+ return 0
2229
+ fi
2230
+ pq wait "$1"
2231
+ }
2232
+
945
2233
  # Stream the log of the task until Pueue reports it done.
946
2234
  follow_until_done() {
947
2235
  rm -f "$jd/drain-stop"
@@ -1015,6 +2303,7 @@ print_job_facts() {
1015
2303
  cmd_result() {
1016
2304
  set_paths "$1" "$2" "$3"
1017
2305
  [ -d "$jd" ] || die "no such job: $job"
2306
+ end_own_job_if_lost
1018
2307
  print_job_facts
1019
2308
  }
1020
2309
 
@@ -1085,7 +2374,7 @@ write_lease_beat() {
1085
2374
  }
1086
2375
 
1087
2376
  end_lease_watch() {
1088
- [ -n "${lease_reader_pid:-}" ] && kill "$lease_reader_pid" > /dev/null 2>&1
2377
+ [ -n "${lease_reader_pid:-}" ] && stop_background_job "$lease_reader_pid"
1089
2378
  [ -n "${lease_state_dir:-}" ] && rm -rf "$lease_state_dir"
1090
2379
  }
1091
2380
 
@@ -1106,13 +2395,18 @@ cmd_lease() {
1106
2395
  stream_log 0 &
1107
2396
  local streamer_pid=$!
1108
2397
  (
1109
- watch_lease "$lease_sec" || kill_job
2398
+ watch_lease "$lease_sec" || kill_job_until_answered
1110
2399
  ) &
1111
2400
  local watcher_pid=$!
1112
2401
  local task
1113
2402
  task=$(read_file "$jd/task-id")
1114
2403
  wait_for_task "$task"
1115
- kill "$watcher_pid" > /dev/null 2>&1
2404
+ # The watcher goes with the job - except one that is still retrying a kill Pueue could not answer: it is let finish, or the queued job it is about to stop would start when Pueue is back and run unwatched.
2405
+ if [ -f "$jd/kill-pending" ]; then
2406
+ wait "$watcher_pid" 2> /dev/null
2407
+ else
2408
+ stop_background_job "$watcher_pid"
2409
+ fi
1116
2410
  wait_for_exit_file
1117
2411
  touch "$jd/drain-stop"
1118
2412
  wait "$streamer_pid" 2> /dev/null
@@ -1121,6 +2415,14 @@ cmd_lease() {
1121
2415
  # ─────────────────────────── the job (the Pueue task) ───────────────────────────
1122
2416
 
1123
2417
  lock_held=0
2418
+ # The copy's number (empty: none was given) and its Simulator device (empty: none), set by cmd_job; `$jd/runner-env` is written from them.
2419
+ copy_index=
2420
+ ios_udid=
2421
+ tmpdir_set_aside=
2422
+ # 1 once the job has started the step that makes its Simulator device: whatever state that step left it in, the job shuts the device down at its end.
2423
+ ios_device_step_started=0
2424
+ # 1 once a TERM, INT or HUP has reached the job (its trap in `cmd_job` sets it): `run_step` starts no step after that. Set here so that a step run outside `cmd_job` reads it too.
2425
+ killed=0
1124
2426
 
1125
2427
  # The project lock is a FILE made with the shell's own exclusive create (`set -C`, noclobber: open(O_EXCL)) — never with `mkdir`. The uutils
1126
2428
  # coreutils that current Ubuntu ships as /usr/bin/mkdir let several simultaneous `mkdir` of one path ALL succeed (measured here: 265 races
@@ -1138,15 +2440,19 @@ read_lock_holder() {
1138
2440
  return 0
1139
2441
  }
1140
2442
 
1141
- # Is the lock held by nobody any more? Its holder's process is gone, or its job has an exit record, or no holder was ever written and it
1142
- # is over a minute old (its creator died between creating the file and writing it).
2443
+ # Is the lock held by nobody any more? Its holder's process is gone (or a stranger's now: check_runner_pid_alive), or its job has an exit record, or it is over lock_max_age_min old (when that is set), or no
2444
+ # holder was ever written and it is over a minute old (its creator died between creating the file and writing it).
1143
2445
  check_lock_is_stale() {
1144
2446
  local holder_pid holder_job
1145
2447
  read_lock_holder "$lock"
1146
- if [ -n "$holder_pid" ] && ! kill -0 "$holder_pid" 2> /dev/null; then
2448
+ if [ -n "$holder_pid" ] && ! check_runner_pid_alive "$holder_pid"; then
1147
2449
  return 0
1148
2450
  fi
1149
- if [ -n "$holder_job" ] && [ -f "$jobs_dir/$holder_job/exit" ]; then
2451
+ # The holder's job has ended — except while it removes paths from the copy after a job that worked (`finish_job` writes the result BEFORE that and keeps the lock to the end of the removal; a holder that dies meanwhile is caught by the pid test above).
2452
+ if [ -n "$holder_job" ] && [ -f "$jobs_dir/$holder_job/exit" ] && [ "$(read_file "$jobs_dir/$holder_job/phase")" != cleaning ]; then
2453
+ return 0
2454
+ fi
2455
+ if [ "$lock_max_age_min" -gt 0 ] && [ -n "$(find "$lock" -maxdepth 0 -mmin +"$lock_max_age_min" 2> /dev/null)" ]; then
1150
2456
  return 0
1151
2457
  fi
1152
2458
  [ -z "$holder_pid" ] && [ -n "$(find "$lock" -maxdepth 0 -mmin +1 2> /dev/null)" ]
@@ -1201,7 +2507,7 @@ check_breaker_is_alive() {
1201
2507
  return 1
1202
2508
  fi
1203
2509
  if [ -n "$holder_pid" ]; then
1204
- kill -0 "$holder_pid" 2> /dev/null
2510
+ check_runner_pid_alive "$holder_pid"
1205
2511
  return
1206
2512
  fi
1207
2513
  [ -z "$(find "$1" -maxdepth 0 -mmin +1 2> /dev/null)" ]
@@ -1305,11 +2611,637 @@ describe_failed_step() {
1305
2611
  done
1306
2612
  }
1307
2613
 
2614
+ # ─────────────────────────── seeding a new copy from a sibling ───────────────────────────
2615
+
2616
+ # A copy's dependencies are most of its size (a React Native monorepo: ~13 GB of `node_modules` and `Pods`), and every new copy of a project installed them from scratch. A NEW copy (the first job of it: no manifest yet) is seeded from a
2617
+ # sibling instead: a copy of the same REPOSITORY — the job's `project-key` (the main box's hash of the user and the repository's root commit: the same in every clone and worktree whatever the folder is called, and different for
2618
+ # another project or another user whose folder shares a name), kept in the copy as `p/<slug>/project-key`; a copy or a job without one is never a source or seeded — whose dependencies step finished (`deps.hash` is there): the one with this
2619
+ # job's own install key first, then the most recently used. The folders are CLONES, copy-on-write, so nothing is ever shared for writing (one copy's build cannot touch the other's files): on a Mac `/bin/cp -cR` (clonefile(2); the system's own
2620
+ # cp, not whatever comes first on a PATH that has GNU coreutils), elsewhere `cp --reflink=always`, and where the filesystem cannot clone nothing is seeded at all — a plain copy would take MORE disk than the install it replaces when the
2621
+ # project's package manager links files into a store (hard links are only kept inside the copied set). Carried: every top-level `node_modules` (the root's and each workspace's, never one inside another) and, for every `<app>/ios/Pods`,
2622
+ # the whole `<app>/ios` when the new tree has the app folder but no `ios` (an Expo prebuild app keeps its `ios` out of git: the native project, its prebuild marker and its Pods come along; cloned entry by entry, `build` skipped) or just the `Pods` when it has an
2623
+ # `ios` of its own — each with `ios/build/generated`, the codegen pods' sources `pod install` writes (a build with its `pod install` skipped needs them); never the build output (`ios/build` but for `generated`, `android/build`, `.cxx`, `.gradle`: absolute
2624
+ # paths of the sibling are in them), and nothing whose parent folder the new tree lacks. `deps.hash` is written only when the sibling's key equals this job's —
2625
+ # then the dependencies step is skipped; a different key still runs it, on top of what is there.
2626
+ # The sibling is taken under its project lock, tried once and never waited for (a job that holds it may be in its dependencies step or a build): a busy sibling is passed over for the next. Seeding never fails the job: whatever goes wrong
2627
+ # removes the partial seed, says one line and leaves the install to run from scratch. The folders are cloned into `seed.tmp` of the new copy and only then moved into place, so a job cut off half-way leaves no half-made `node_modules`.
2628
+ # What was cloned shares its disk blocks with its source until a file is written: the new copy's `seeded-from` names the copy the blocks first came from (the source's own `seeded-from`, else the source), the source gets a `seed-shared`
2629
+ # mark, and the free-space prune does not read a removal of a copy that still shares as «the disk is not following» (`check_copy_shares_blocks`). The prune of a submit of a new copy leaves the sibling it would be seeded from to the last.
2630
+
2631
+ # Is the filesystem of work dir $1 one that clones files — can the seed clone at all? A Mac's `cp -c` replaces itself by a plain copy where it cannot, which the APFS volume a runner lives on never needs; elsewhere a file of 64 KiB is cloned
2632
+ # with `--reflink=always`, which fails where the filesystem has no reflink (ext4), and the seed is then not made.
2633
+ check_filesystem_clones_files() {
2634
+ [ "$(uname -s)" = Darwin ] && return 0
2635
+ local probe_dir="$1/tmp/clone-probe.$$" is_cloned=1
2636
+ mkdir -p "$probe_dir" 2> /dev/null || return 1
2637
+ head -c 65536 /dev/zero > "$probe_dir/source" 2> /dev/null && cp --reflink=always "$probe_dir/source" "$probe_dir/clone" 2> /dev/null && is_cloned=0
2638
+ rm -rf "$probe_dir"
2639
+ return "$is_cloned"
2640
+ }
2641
+
2642
+ # Clone folder $1 to the path $2 (its parent exists, $2 does not): copy-on-write, or it fails. The Mac's own `cp` is asked for by its path (darwin_cp): a GNU `cp` earlier on the PATH (Homebrew coreutils) reads `-c` as
2643
+ # `--preserve=context`.
2644
+ clone_folder() {
2645
+ if [ "$(uname -s)" = Darwin ]; then
2646
+ "$darwin_cp" -cR "$1" "$2"
2647
+ else
2648
+ cp -a --reflink=always "$1" "$2"
2649
+ fi
2650
+ }
2651
+
2652
+ # The slugs of the copies a new copy (slug $1, install key $2, repository $3) may be seeded from, one per line, best first: copies of the same repository (their `project-key`) whose dependencies step finished, those with the same install
2653
+ # key before the others, each group the most recently used first. None for a job that has no repository key.
2654
+ list_seed_siblings() {
2655
+ local own_slug=$1 install_key=$2 project_key=$3 used_file sibling_slug sibling_key same_key= other_key=
2656
+ [ -n "$project_key" ] || return 0
2657
+ while IFS= read -r used_file; do
2658
+ sibling_slug=${used_file%/used}
2659
+ sibling_slug=${sibling_slug##*/}
2660
+ [ "$sibling_slug" != "$own_slug" ] || continue
2661
+ [ "$(read_file "$work/p/$sibling_slug/project-key")" = "$project_key" ] || continue
2662
+ [ -d "$work/p/$sibling_slug/tree" ] || continue
2663
+ sibling_key=$(read_file "$work/p/$sibling_slug/deps.hash")
2664
+ [ -n "$sibling_key" ] || continue
2665
+ if [ "$sibling_key" = "$install_key" ]; then
2666
+ same_key="$same_key$sibling_slug"$'\n'
2667
+ else
2668
+ other_key="$other_key$sibling_slug"$'\n'
2669
+ fi
2670
+ done < <(ls -1t "$work"/p/*/used 2> /dev/null)
2671
+ printf '%s%s' "$same_key" "$other_key"
2672
+ }
2673
+
2674
+ # The copy remembers which repository it is of — the job's `project-key` — for the copies that are seeded from it and for its own seed. A job that has none (a repository with no commit yet) leaves the copy with none.
2675
+ persist_project_key() {
2676
+ local key
2677
+ key=$(read_file "$jd/project-key")
2678
+ case $key in
2679
+ '' | *[!0-9a-f]*) rm -f "$proj/project-key"; return 0 ;;
2680
+ esac
2681
+ printf '%s\n' "$key" > "$proj/project-key"
2682
+ }
2683
+
2684
+ # The folders of the copy tree $1 a seed looks at, relative to it (`./node_modules`, `./projects/app/ios/Pods`), one per line: the dependencies down to seed_find_depth, the build output folders and `.git` pruned from the walk.
2685
+ list_seed_folders() {
2686
+ (cd "$1" && find . -maxdepth "$seed_find_depth" \( -name .git -o -name .gradle -o -name .cxx -o -path '*/ios/build' -o -path '*/android/build' \) -prune -o \( -name node_modules -o -path '*/ios/Pods' \) -type d -print -prune 2> /dev/null)
2687
+ }
2688
+
2689
+ # In the cloned dependencies folder $1: the build output a package left in itself (Gradle's and CMake's folders hold the sibling's absolute paths) does not come along. Failing to remove one is no reason to give up the seed.
2690
+ remove_seeded_build_output() {
2691
+ find "$1" -maxdepth "$seed_clean_depth" \( -path '*/android/build' -o -path '*/android/.cxx' -o -path '*/ios/build' -o -name .gradle \) -type d -prune -exec rm -rf {} + 2> /dev/null
2692
+ return 0
2693
+ }
2694
+
2695
+ # What a seed carries for the sibling's folder $1 (relative): the folder itself — except that a `<app>/ios/Pods` is carried as the whole `<app>/ios` when the new tree has the app folder and no `ios` (an app whose `ios` git ignores).
2696
+ # Sets seed_carried (the relative path to clone).
2697
+ get_seed_carried_path() {
2698
+ seed_carried=$1
2699
+ case $1 in
2700
+ */ios/Pods | ios/Pods)
2701
+ local ios_dir=${1%/Pods}
2702
+ [ ! -e "$tree/$ios_dir" ] && [ ! -L "$tree/$ios_dir" ] && [ -d "$tree/$(dirname "$ios_dir")" ] && seed_carried=$ios_dir
2703
+ ;;
2704
+ esac
2705
+ return 0
2706
+ }
2707
+
2708
+ # Clone the `ios` folder $1 of an app as $2 WITHOUT its derived data: every entry of it but `build` one by one — never `build` as a whole, which holds ~8.5 GB of derived data and would be cloned and removed again under the sibling's lock (a job of
2709
+ # the sibling waits for it) — and then `build/generated` (`build_data_kept_name`), the codegen pods' sources, as the one thing of `build` that belongs to the native project. Fails when a clone fails (`seed_failure` says why when it is a stop).
2710
+ clone_ios_folder() {
2711
+ local entry name
2712
+ mkdir -p "$2" || return 1
2713
+ for entry in "$1"/* "$1"/.[!.]* "$1"/..?*; do
2714
+ [ -e "$entry" ] || [ -L "$entry" ] || continue
2715
+ name=${entry##*/}
2716
+ [ "$name" != build ] || continue
2717
+ if [ "$killed" -eq 1 ]; then
2718
+ seed_failure="the job was stopped"
2719
+ return 1
2720
+ fi
2721
+ clone_folder "$entry" "$2/$name" || return 1
2722
+ done
2723
+ clone_generated_folder "$1" "$2"
2724
+ }
2725
+
2726
+ # Clone the `build/generated` folder of the `ios` folder $1 into the `ios` folder $2 (made if need be), when there is one and it is a real folder.
2727
+ clone_generated_folder() {
2728
+ [ -d "$1/build/$build_data_kept_name" ] && [ ! -L "$1/build/$build_data_kept_name" ] || return 0
2729
+ mkdir -p "$2/build" && clone_folder "$1/build/$build_data_kept_name" "$2/build/$build_data_kept_name"
2730
+ }
2731
+
2732
+ # Clone the folders of sibling $1 into $2 (the new copy's `seed.tmp`), the sibling's lock held by the caller. Sets seed_folders (the relative paths cloned, one per line) and, on a failure, seed_failure. Fails when nothing was
2733
+ # carried (with seed_failure empty: the sibling has nothing the new copy can take) or a clone failed.
2734
+ clone_sibling_folders() {
2735
+ local sibling_tree="$work/p/$1/tree" seed_dir=$2 relative parent listed_path generated_path
2736
+ seed_folders=
2737
+ seed_failure=
2738
+ if ! mkdir -p "$seed_dir"; then
2739
+ seed_failure="cannot make $seed_dir"
2740
+ return 1
2741
+ fi
2742
+ while IFS= read -r relative; do
2743
+ relative=${relative#./}
2744
+ [ -n "$relative" ] && check_relative_path "$relative" || continue
2745
+ listed_path=$relative
2746
+ get_seed_carried_path "$relative"
2747
+ relative=$seed_carried
2748
+ parent=$(dirname "$relative")
2749
+ # Not into a workspace the new revision no longer has, and never over what the new copy already holds.
2750
+ [ -d "$tree/$parent" ] && [ ! -e "$tree/$relative" ] && [ ! -L "$tree/$relative" ] || continue
2751
+ if [ "$killed" -eq 1 ]; then
2752
+ seed_failure="the job was stopped"
2753
+ return 1
2754
+ fi
2755
+ if [ "${relative##*/}" = ios ]; then
2756
+ # The whole native project of an app whose `ios` git ignores: entry by entry, its derived data left behind.
2757
+ if ! mkdir -p "$seed_dir/$parent" || ! clone_ios_folder "$sibling_tree/$relative" "$seed_dir/$relative"; then
2758
+ [ -n "$seed_failure" ] || seed_failure="cloning $relative failed"
2759
+ return 1
2760
+ fi
2761
+ elif ! mkdir -p "$seed_dir/$parent" || ! clone_folder "$sibling_tree/$relative" "$seed_dir/$relative"; then
2762
+ seed_failure="cloning $relative failed"
2763
+ return 1
2764
+ fi
2765
+ [ "${relative##*/}" != node_modules ] || remove_seeded_build_output "$seed_dir/$relative"
2766
+ seed_folders="$seed_folders$relative"$'\n'
2767
+ # `Pods` carried into an `ios` the new tree already has: the codegen pods' sources the Pods project refers to come with it, when the new tree has none.
2768
+ if [ "$relative" = "$listed_path" ] && [ "${relative##*/}" = Pods ]; then
2769
+ generated_path="$(dirname "$relative")/build/$build_data_kept_name"
2770
+ if [ -d "$sibling_tree/$generated_path" ] && [ ! -L "$sibling_tree/$generated_path" ] && [ ! -e "$tree/$generated_path" ] && [ ! -L "$tree/$generated_path" ]; then
2771
+ if ! mkdir -p "$seed_dir/$(dirname "$generated_path")" || ! clone_folder "$sibling_tree/$generated_path" "$seed_dir/$generated_path"; then
2772
+ seed_failure="cloning $generated_path failed"
2773
+ return 1
2774
+ fi
2775
+ seed_folders="$seed_folders$generated_path"$'\n'
2776
+ fi
2777
+ fi
2778
+ done <<< "$(list_seed_folders "$sibling_tree")"
2779
+ [ -n "$seed_folders" ]
2780
+ }
2781
+
2782
+ # Seed the new copy of this job from a sibling (see the section's comment); $1 = the job's install key. Always returns 0 — the job goes on, with what the seed gave it or without.
2783
+ seed_new_copy() {
2784
+ local install_key=$1 seed_dir="$proj/seed.tmp" sibling_slug sibling_dir sibling_key seed_code relative moved= tried=0 saw_sibling=0 project_key siblings
2785
+ seed_folders=
2786
+ seed_failure=
2787
+ project_key=$(read_file "$proj/project-key")
2788
+ siblings=$(list_seed_siblings "$slug" "$install_key" "$project_key")
2789
+ [ -n "$siblings" ] || return 0
2790
+ if ! check_filesystem_clones_files "$work"; then
2791
+ say "not seeded from another copy of this project: this runner's disk cannot clone files (copy-on-write), and a plain copy would take more space than installing"
2792
+ return 0
2793
+ fi
2794
+ while IFS= read -r sibling_slug; do
2795
+ [ -n "$sibling_slug" ] || continue
2796
+ [ "$killed" -eq 1 ] && return 0
2797
+ saw_sibling=1
2798
+ sibling_dir="$work/p/$sibling_slug"
2799
+ check_copy_has_live_exec "$sibling_dir" && continue
2800
+ try_take_lock "$sibling_dir/lock" "$sibling_dir/jobs" 0 || continue
2801
+ tried=1
2802
+ # The lock is the sibling's guarantee that its dependencies step is not running; its key is read again under it (a step that failed meanwhile removed it).
2803
+ sibling_key=$(read_file "$sibling_dir/deps.hash")
2804
+ if [ -n "$sibling_key" ]; then
2805
+ clone_sibling_folders "$sibling_slug" "$seed_dir"
2806
+ seed_code=$?
2807
+ else
2808
+ seed_code=1
2809
+ fi
2810
+ release_own_lock "$sibling_dir/lock"
2811
+ break
2812
+ done <<< "$siblings"
2813
+ if [ "$tried" -eq 0 ]; then
2814
+ [ "$saw_sibling" -eq 0 ] || say "not seeded from another copy of this project: they are all busy right now"
2815
+ return 0
2816
+ fi
2817
+ if [ "$seed_code" -eq 0 ]; then
2818
+ while IFS= read -r relative; do
2819
+ [ -n "$relative" ] || continue
2820
+ if ! mkdir -p "$(dirname "$tree/$relative")" || ! mv "$seed_dir/$relative" "$tree/$relative"; then
2821
+ seed_failure="moving $relative into place failed"
2822
+ seed_code=1
2823
+ break
2824
+ fi
2825
+ moved="$moved$relative"$'\n'
2826
+ done <<< "$seed_folders"
2827
+ fi
2828
+ if [ "$seed_code" -ne 0 ]; then
2829
+ while IFS= read -r relative; do
2830
+ [ -n "$relative" ] && remove_path_even_if_read_only "$tree/$relative"
2831
+ done <<< "$moved"
2832
+ remove_path_even_if_read_only "$seed_dir"
2833
+ [ -n "$seed_failure" ] && say "could not seed this copy from the copy $sibling_slug ($seed_failure): the dependencies are installed from scratch"
2834
+ return 0
2835
+ fi
2836
+ remove_path_even_if_read_only "$seed_dir"
2837
+ # The blocks of what was cloned are the source's too from now on: the prune must know (`check_copy_shares_blocks`).
2838
+ local origin
2839
+ origin=$(read_file "$sibling_dir/seeded-from")
2840
+ printf '%s\n' "${origin:-$sibling_slug}" > "$proj/seeded-from"
2841
+ : > "$sibling_dir/seed-shared" 2> /dev/null
2842
+ local folder_count
2843
+ folder_count=$(printf '%s' "$seed_folders" | grep -c '')
2844
+ if [ "$sibling_key" = "$install_key" ]; then
2845
+ printf '%s\n' "$install_key" > "$proj/deps.hash"
2846
+ say "seeded from the copy $sibling_slug of this project: $folder_count folder$([ "$folder_count" -eq 1 ] || echo s) cloned; its dependencies are the same, so the dependencies step is skipped"
2847
+ else
2848
+ say "seeded from the copy $sibling_slug of this project: $folder_count folder$([ "$folder_count" -eq 1 ] || echo s) cloned; its dependencies differ, so the dependencies step still runs on top"
2849
+ fi
2850
+ return 0
2851
+ }
2852
+
2853
+ # The group of copies whose disk blocks come from one clone: the copy the blocks first came from. A seeded copy names it (`seeded-from`); the copy it came from has `seed-shared` and is the group's own name. Nothing for a copy that took
2854
+ # part in no seed. $1 = work dir, $2 = slug.
2855
+ get_copy_seed_group() {
2856
+ local origin
2857
+ origin=$(read_file "$1/p/$2/seeded-from")
2858
+ if [ -n "$origin" ]; then
2859
+ printf '%s\n' "$origin"
2860
+ elif [ -f "$1/p/$2/seed-shared" ]; then
2861
+ printf '%s\n' "$2"
2862
+ fi
2863
+ }
2864
+
2865
+ # Does copy $2 (under work dir $1) share disk blocks with another copy that is still there — a clone of it, the one it was cloned from, or another clone of that? Removing such a copy frees only the blocks it holds alone, while `du` counts all of them,
2866
+ # so the free-space prune does not take a removal that gave little back as a sign that the disk is not following.
2867
+ check_copy_shares_blocks() {
2868
+ local group copy_dir other_slug
2869
+ group=$(get_copy_seed_group "$1" "$2")
2870
+ [ -n "$group" ] || return 1
2871
+ for copy_dir in "$1"/p/*/; do
2872
+ [ -d "$copy_dir" ] || continue
2873
+ other_slug=$(basename "$copy_dir")
2874
+ [ "$other_slug" != "$2" ] || continue
2875
+ [ "$(get_copy_seed_group "$1" "$other_slug")" = "$group" ] && return 0
2876
+ done
2877
+ return 1
2878
+ }
2879
+
2880
+ # How many copies of a list of seed groups (one per line, the group of each copy that has one: `get_copy_seed_group`) share disk blocks with another: those whose group has two members or more. One pass over a list that the caller built while it was
2881
+ # reading the copies anyway — `check_copy_shares_blocks` per copy would walk every copy for each (a probe of 30 clones: ~2,700 forks, on the path of every run).
2882
+ count_copies_in_shared_groups() {
2883
+ printf '%s' "$1" | sort | uniq -c | awk '$1 >= 2 { total += $1 } END { print total + 0 }'
2884
+ }
2885
+
2886
+ # Is seed group $2 held by two copies or more in the list $1 (one group per line)?
2887
+ check_group_is_shared() {
2888
+ [ "$(printf '%s' "$1" | grep -Fxc -- "$2")" -ge 2 ]
2889
+ }
2890
+
2891
+ # ─────────────────────────── what a copy is given: a number, a port block, a TMPDIR, a Simulator ───────────────────────────
2892
+
2893
+ # The index lock: `tmp/index.lock`, made and broken by the project lock's helpers like the prune lock (`acquire_prune_lock`) — here with no job, a short age limit (it is held for a moment: a holder that has been
2894
+ # at it for minutes is gone whatever its pid says), and a wait of index_lock_wait_sec at most. Fails when it could not be had.
2895
+ acquire_index_lock() {
2896
+ local lock="$1/tmp/index.lock" jobs_dir= job= lock_max_age_min=$index_lock_max_age_min
2897
+ local waited_since=$SECONDS
2898
+ mkdir -p "$1/tmp" 2> /dev/null
2899
+ while ! create_lock_file "$lock"; do
2900
+ check_lock_is_stale && break_stale_lock && continue
2901
+ [ $((SECONDS - waited_since)) -ge "$index_lock_wait_sec" ] && return 1
2902
+ nap 0.2
2903
+ done
2904
+ rm -f "$lock".breaking.* 2> /dev/null
2905
+ return 0
2906
+ }
2907
+
2908
+ # Give the index lock back — only if it is still this process's own.
2909
+ release_index_lock() {
2910
+ local holder_pid holder_job
2911
+ read_lock_holder "$1/tmp/index.lock"
2912
+ [ "$holder_pid" = "$$" ] && rm -f "$1/tmp/index.lock"
2913
+ return 0
2914
+ }
2915
+
2916
+ # Sets copy_index: the number of this job's project copy (`p/<slug>/index`), given once — the lowest below max_copy_indexes that no other copy under p/ holds (a copy moved aside to `p/.trash-*` is not under p/*:
2917
+ # its number is free) — and kept as long as the copy lives, so the port block, the TMPDIR and the Simulator device are the same for every job of the copy (an app built for a Metro port stays installed). A new copy
2918
+ # starts with an empty TMPDIR. Empty when none could be given (every number taken, or the lock not had): said, and the job runs without a port block and a TMPDIR of its own. The caller holds the project lock.
2919
+ ensure_copy_index() {
2920
+ copy_index=
2921
+ local recorded
2922
+ recorded=$(read_file "$proj/index")
2923
+ case $recorded in
2924
+ '' | *[!0-9]*) ;;
2925
+ *)
2926
+ if [ "$((10#$recorded))" -lt "$max_copy_indexes" ]; then
2927
+ copy_index=$((10#$recorded))
2928
+ return 0
2929
+ fi
2930
+ ;;
2931
+ esac
2932
+ if ! acquire_index_lock "$work"; then
2933
+ say "no port block and no TMPDIR of its own for this job: the number of this project's copy could not be given (the lock is held)"
2934
+ return 0
2935
+ fi
2936
+ local taken=" " index_file other_index candidate=0
2937
+ for index_file in "$work"/p/*/index; do
2938
+ [ -f "$index_file" ] || continue
2939
+ other_index=$(read_file "$index_file")
2940
+ case $other_index in '' | *[!0-9]*) continue ;; esac
2941
+ taken="$taken$((10#$other_index)) "
2942
+ done
2943
+ while [ "$candidate" -lt "$max_copy_indexes" ]; do
2944
+ case $taken in
2945
+ *" $candidate "*) candidate=$((candidate + 1)) ;;
2946
+ *) break ;;
2947
+ esac
2948
+ done
2949
+ if [ "$candidate" -ge "$max_copy_indexes" ]; then
2950
+ release_index_lock "$work"
2951
+ say "no port block and no TMPDIR of its own for this job: all $max_copy_indexes numbers of project copies are taken"
2952
+ return 0
2953
+ fi
2954
+ # What an earlier copy of this number left in its TMPDIR is set aside (an instant rename) under the lock and removed after it: a TMPDIR can hold hundreds of thousands of files, and a lock held for their removal would keep every
2955
+ # other copy from being given a number meanwhile.
2956
+ set_aside_tmpdir "$work" "$candidate"
2957
+ local aside_dir=$tmpdir_set_aside
2958
+ if ! { printf '%s\n' "$candidate" > "$proj/index.tmp.$$" && mv "$proj/index.tmp.$$" "$proj/index"; } 2> /dev/null; then
2959
+ rm -f "$proj/index.tmp.$$"
2960
+ release_index_lock "$work"
2961
+ [ -z "$aside_dir" ] || remove_path_even_if_read_only "$aside_dir"
2962
+ say "no port block and no TMPDIR of its own for this job: the number of this project's copy could not be written down"
2963
+ return 0
2964
+ fi
2965
+ release_index_lock "$work"
2966
+ [ -z "$aside_dir" ] || remove_path_even_if_read_only "$aside_dir"
2967
+ copy_index=$candidate
2968
+ }
2969
+
2970
+ # Set the TMPDIR `<work>/t/$2` aside by one rename, to `t/.gone-<pid>-<number>-<random>`; sets tmpdir_set_aside to the new path (empty when there was none, or the rename failed — then the next copy of the number wipes it).
2971
+ # The caller removes the folder AFTER it has given the index lock back; a caller that is cut off leaves it for the prune (`remove_finished_tmpdir_removals`). The index lock of work dir $1 must be held.
2972
+ set_aside_tmpdir() {
2973
+ tmpdir_set_aside=
2974
+ [ -d "$1/t/$2" ] || return 0
2975
+ local aside_dir="$1/t/.gone-$$-$2-$RANDOM"
2976
+ mv "$1/t/$2" "$aside_dir" 2> /dev/null && tmpdir_set_aside=$aside_dir
2977
+ return 0
2978
+ }
2979
+
2980
+ # Remove the TMPDIRs that a removal set aside and was cut off before it had removed (`t/.gone-<pid>-…`): those whose process is gone. One whose process lives is being removed by it.
2981
+ remove_finished_tmpdir_removals() {
2982
+ local gone_dir rest
2983
+ for gone_dir in "$1"/t/.gone-*; do
2984
+ [ -e "$gone_dir" ] || continue
2985
+ rest=${gone_dir##*/.gone-}
2986
+ check_runner_pid_alive "${rest%%-*}" && continue
2987
+ remove_path_even_if_read_only "$gone_dir"
2988
+ done
2989
+ return 0
2990
+ }
2991
+
2992
+ # The slug of the project copy that holds number $2 (`p/<slug>/index`) under work dir $1; nothing when no copy does.
2993
+ read_slug_of_copy_index() {
2994
+ local index_file recorded owner
2995
+ for index_file in "$1"/p/*/index; do
2996
+ [ -f "$index_file" ] || continue
2997
+ recorded=$(read_file "$index_file")
2998
+ case $recorded in '' | *[!0-9]*) continue ;; esac
2999
+ [ "$((10#$recorded))" -eq "$((10#$2))" ] || continue
3000
+ owner=${index_file%/index}
3001
+ printf '%s\n' "${owner##*/}"
3002
+ return 0
3003
+ done
3004
+ return 0
3005
+ }
3006
+
3007
+ # Remove, from the TMPDIR of every project copy of work dir $1, the files and links not modified for tmpdir_keep_days, then the empty folders of that age (a chain of them goes a level per run). A copy that is busy (a job
3008
+ # runs or waits, results not fetched, ...) is not touched. Going by age keeps a fresh file even if a job is given the copy at that very moment. A TMPDIR no copy holds the number of (its copy was removed) is swept too.
3009
+ sweep_idle_tmpdirs() {
3010
+ local work_dir=$1 tmp_dir tmp_number owner_slug
3011
+ for tmp_dir in "$work_dir"/t/*/; do
3012
+ [ -d "$tmp_dir" ] || continue
3013
+ tmp_dir=${tmp_dir%/}
3014
+ tmp_number=${tmp_dir##*/}
3015
+ case $tmp_number in '' | *[!0-9]*) continue ;; esac
3016
+ owner_slug=$(read_slug_of_copy_index "$work_dir" "$tmp_number")
3017
+ if [ -n "$owner_slug" ] && check_copy_is_busy "$work_dir" "$owner_slug"; then
3018
+ continue
3019
+ fi
3020
+ # A killed `pod install`, or any extractor of a read-only archive, leaves read-only folders (CocoaPods' xcframeworks): their files could not be removed. `chmod` leaves the times alone, so the ages hold.
3021
+ find "$tmp_dir" -mindepth 1 -type d -mtime +"$tmpdir_keep_days" ! -perm -u+w -exec chmod u+w {} + 2> /dev/null
3022
+ find "$tmp_dir" -mindepth 1 \( -type f -o -type l \) -mtime +"$tmpdir_keep_days" -exec rm -f {} + 2> /dev/null
3023
+ find "$tmp_dir" -mindepth 1 -depth -type d -empty -mtime +"$tmpdir_keep_days" -exec rmdir {} + 2> /dev/null
3024
+ done
3025
+ return 0
3026
+ }
3027
+
3028
+ # What an iOS job builds INTO a copy, relative paths under the tree $1, one per line: Xcode's derived data — the `ios/build` that `-derivedDataPath ios/build` (the way the projects build) and `expo run:ios` write, and an `ios/DerivedData`.
3029
+ # Of any app folder of a monorepo; the walk never enters `.git`, `node_modules` or `Pods`. NOT all of `ios/build` is derived data: its `generated` folder (`build_data_kept_name`) is where `pod install` writes the sources of the codegen
3030
+ # pods (React Native 0.74+ podspecs point at `build/generated/ios/…`), part of the native project that `Pods.xcodeproj` refers to — a build with a copy's `pod install` skipped (a prebuild marker that still matches) fails without it.
3031
+ list_build_data_folders() {
3032
+ (cd "$1" && find . -maxdepth "$build_data_find_depth" \( -name .git -o -name node_modules -o -name Pods \) -prune -o \( -path '*/ios/build' -o -path '*/ios/DerivedData' \) -type d -print -prune 2> /dev/null)
3033
+ }
3034
+
3035
+ # Does the copy $1's manifest — every file the main box sent, tracked or not ignored — list the path $2 (relative), or a file inside it? Then it is, or holds, sources: never build data. A copy with no manifest has had no stage applied: nothing is known of it.
3036
+ check_manifest_lists_files_in() {
3037
+ [ -f "$1/manifest" ] || return 0
3038
+ awk -v path="$2" -v prefix="$2/" '$0 == path || index($0, prefix) == 1 { found = 1; exit } END { if (found) exit 0; exit 1 }' "$1/manifest"
3039
+ }
3040
+
3041
+ # The entries of the real folder $1 (an `ios/build`) that are derived data, one name per line: everything in it but `generated` (`build_data_kept_name`) and links (never followed).
3042
+ list_derived_data_entries() {
3043
+ local entry name
3044
+ for entry in "$1"/* "$1"/.[!.]* "$1"/..?*; do
3045
+ [ -e "$entry" ] && [ ! -L "$entry" ] || continue
3046
+ name=${entry##*/}
3047
+ [ "$name" = "$build_data_kept_name" ] || printf '%s\n' "$name"
3048
+ done
3049
+ }
3050
+
3051
+ # Write the measured size of a copy into its figure file $1 (KiB $2), atomically: the one write both `measure-copies` and a trim make.
3052
+ write_copy_size_kb() {
3053
+ { printf '%s\n' "$2" > "$1.tmp.$$" && mv "$1.tmp.$$" "$1"; } 2> /dev/null
3054
+ }
3055
+
3056
+ # The figure of copy folder $1 (`size-kb`) goes down by $2 KiB (not below 0) — what a trim took out of it. A copy with no figure, or with a damaged one, is left as it is: a missing figure stays missing (a short-disk prune reads it as
3057
+ # «cannot tell», and an invented one would let it judge). The figure matters to the free-space prune's no-progress guard (it needs the copies' sizes), and to the biggest copies a refusal names.
3058
+ lower_copy_size_kb() {
3059
+ local size_file="$1/size-kb" size_kb
3060
+ [ -f "$size_file" ] || return 0
3061
+ size_kb=$(read_file "$size_file")
3062
+ case $size_kb in '' | *[!0-9]*) return 0 ;; esac
3063
+ if [ "$size_kb" -gt "$2" ]; then size_kb=$((size_kb - $2)); else size_kb=0; fi
3064
+ write_copy_size_kb "$size_file" "$size_kb"
3065
+ }
3066
+
3067
+ # Rename folder $1 to path $2, a name that does not exist yet, on the same filesystem: instant, whatever the folder holds. A folder without write permission cannot move to another parent (the rename rewrites its `..`) and a read-only
3068
+ # parent cannot give it up: they are made writable first, as every removal here does.
3069
+ move_folder_aside() {
3070
+ chmod u+w "$1" 2> /dev/null
3071
+ mv "$1" "$2" 2> /dev/null && return 0
3072
+ chmod u+w "$(dirname "$1")" 2> /dev/null
3073
+ mv "$1" "$2" 2> /dev/null
3074
+ }
3075
+
3076
+ # Remove the Xcode build data from the tree of the copy in folder $1 — it is idle (the caller looked), and not busy. A folder with a file the manifest lists in it is left whole. Under the copy's project lock, tried once, nothing is done
3077
+ # but RENAMES: the lock is what a seed from this copy (`seed_new_copy`), a job of it and a `clean` ask for, and a removal of tens of GB takes minutes; an `exec` takes no lock, and must not meet a folder that is being deleted. So the idle test
3078
+ # is made again under the lock (a `prepare` touches `used` before its job asks for it), each build folder is renamed out of the tree — to `build-trash.<pid>` in the copy's own folder, NOT in `tree/`: a seed carries whole `ios` folders and walks the
3079
+ # tree — the note for the next job's log (`build-data-trimmed`) and the lowered figure (`size-kb`) are written, and only then the lock is given back and the trash removed. The sizes are read before the lock: they are a walk of the same folders.
3080
+ # A trash a sweep left (`build-trash.<pid>` of a process that is gone) is removed by the next one (`remove_leftover_build_trash`).
3081
+ trim_copy_build_data() {
3082
+ local copy_dir=$1 folders relative unit entries entry is_split candidates= candidate folder_kb removed_kb=0 trimmed= trash_dir="$1/build-trash.$$" trash_count=0
3083
+ [ -d "$copy_dir/tree" ] || return 0
3084
+ folders=$(list_build_data_folders "$copy_dir/tree")
3085
+ [ -n "$folders" ] || return 0
3086
+ while IFS= read -r relative; do
3087
+ relative=${relative#./}
3088
+ [ -n "$relative" ] && check_relative_path "$relative" || continue
3089
+ [ -d "$copy_dir/tree/$relative" ] && [ ! -L "$copy_dir/tree/$relative" ] || continue
3090
+ # What goes is a UNIT: an `ios/DerivedData` whole, but of an `ios/build` every entry except `generated` — each looked at by itself (a sent file in one keeps that one), each sized by itself.
3091
+ is_split=0
3092
+ entries=
3093
+ case $relative in
3094
+ */ios/build | ios/build)
3095
+ is_split=1
3096
+ entries=$(list_derived_data_entries "$copy_dir/tree/$relative")
3097
+ [ -n "$entries" ] || continue
3098
+ ;;
3099
+ esac
3100
+ while IFS= read -r entry; do
3101
+ if [ "$is_split" -eq 1 ]; then unit="$relative/$entry"; else unit=$relative; fi
3102
+ check_manifest_lists_files_in "$copy_dir" "$unit" && continue
3103
+ folder_kb=$(du -sk "$copy_dir/tree/$unit" 2> /dev/null | awk '{ print $1 }')
3104
+ case $folder_kb in '' | *[!0-9]*) folder_kb=0 ;; esac
3105
+ candidates="$candidates$folder_kb"$'\t'"$relative"$'\t'"$unit"$'\n'
3106
+ done <<< "$entries"
3107
+ done <<< "$folders"
3108
+ [ -n "$candidates" ] || return 0
3109
+ try_take_lock "$copy_dir/lock" "$copy_dir/jobs" 0 || return 0
3110
+ if [ -z "$(find "$copy_dir/used" -maxdepth 0 -mmin +"$((build_data_keep_hours * 60))" 2> /dev/null)" ] || check_copy_has_live_exec "$copy_dir" || ! mkdir -p "$trash_dir" 2> /dev/null; then
3111
+ release_own_lock "$copy_dir/lock"
3112
+ return 0
3113
+ fi
3114
+ while IFS=$'\t' read -r folder_kb relative unit; do
3115
+ [ -n "$unit" ] || continue
3116
+ if move_folder_aside "$copy_dir/tree/$unit" "$trash_dir/$trash_count"; then
3117
+ trash_count=$((trash_count + 1))
3118
+ removed_kb=$((removed_kb + folder_kb))
3119
+ # The note names the folder, once, whatever number of its entries went.
3120
+ case ", $trimmed, " in
3121
+ *", $relative, "*) ;;
3122
+ *) trimmed="$trimmed${trimmed:+, }$relative" ;;
3123
+ esac
3124
+ fi
3125
+ done <<< "$candidates"
3126
+ if [ -n "$trimmed" ]; then
3127
+ printf '%s\n' "$trimmed" > "$copy_dir/build-data-trimmed"
3128
+ lower_copy_size_kb "$copy_dir" "$removed_kb"
3129
+ fi
3130
+ release_own_lock "$copy_dir/lock"
3131
+ remove_path_even_if_read_only "$trash_dir"
3132
+ }
3133
+
3134
+ # Remove the trash of build data (`p/<slug>/build-trash.<pid>`) that a trim was cut off in the middle of removing: those whose process is gone. One whose process lives is being removed by it.
3135
+ remove_leftover_build_trash() {
3136
+ local trash_dir trash_pid
3137
+ for trash_dir in "$1"/p/*/build-trash.*; do
3138
+ [ -e "$trash_dir" ] || continue
3139
+ trash_pid=${trash_dir##*.}
3140
+ case $trash_pid in '' | *[!0-9]*) continue ;; esac
3141
+ check_runner_pid_alive "$trash_pid" && continue
3142
+ remove_path_even_if_read_only "$trash_dir"
3143
+ done
3144
+ return 0
3145
+ }
3146
+
3147
+ # The Xcode build data of every copy that nobody used for build_data_keep_hours and that is not in use (`check_copy_is_busy`: a lock, an exec, a job that waits or runs or just ended or is being submitted).
3148
+ trim_idle_build_data() {
3149
+ local work_dir=$1 used_file copy_slug
3150
+ while IFS= read -r used_file; do
3151
+ copy_slug=$(basename "$(dirname "$used_file")")
3152
+ check_copy_is_busy "$work_dir" "$copy_slug" && continue
3153
+ trim_copy_build_data "$work_dir/p/$copy_slug"
3154
+ done < <(find "$work_dir/p" -mindepth 2 -maxdepth 2 -name used -type f -mmin +"$((build_data_keep_hours * 60))" 2> /dev/null)
3155
+ return 0
3156
+ }
3157
+
3158
+ # What the sweep of idle copies does: the stale files of their TMPDIRs, and the Xcode build data of the copies that nobody used for a day.
3159
+ sweep_idle_copies() {
3160
+ sweep_idle_tmpdirs "$1"
3161
+ remove_leftover_build_trash "$1"
3162
+ trim_idle_build_data "$1"
3163
+ }
3164
+
3165
+ cmd_sweep_tmpdirs() {
3166
+ sweep_idle_copies "$1"
3167
+ }
3168
+
3169
+ # Is it time to sweep the TMPDIRs of work dir $1 - the stamp `$1/tmpdir-sweep.at` is missing, or older than $2 minutes? When it is, the stamp is touched BEFORE the sweep starts, so that two callers at once start one.
3170
+ take_tmpdir_sweep_turn() {
3171
+ local stamp="$1/tmpdir-sweep.at"
3172
+ if [ -f "$stamp" ] && [ -z "$(find "$stamp" -maxdepth 0 -mmin +"$2" 2> /dev/null)" ]; then
3173
+ return 1
3174
+ fi
3175
+ touch "$stamp"
3176
+ }
3177
+
3178
+ # `prepare` sweeps the TMPDIRs of idle copies detached, unless it ran in the last tmpdir_sweep_interval_hours: a walk over a TMPDIR of hundreds of thousands of files is not something a submit waits for.
3179
+ start_tmpdir_sweep_if_due() {
3180
+ [ -d "$1/t" ] || return 0
3181
+ take_tmpdir_sweep_turn "$1" "$((tmpdir_sweep_interval_hours * 60))" || return 0
3182
+ start_detached_run "$1" sweep-tmpdirs
3183
+ }
3184
+
3185
+ # `$jd/runner-env`: the variables the runner gives every step of this job, one `NAME=VALUE` per line — TMPDIR (made here), REMOTE_RUN_PORT_BASE (the job owns this port and the 99 after it) and, once the job's own Simulator
3186
+ # device is booted, REMOTE_RUN_IOS_SIMULATOR_UDID. Without a number for the copy there are no TMPDIR and no port block (a TMPDIR that cannot be made leaves only the port block), but the device's id is still given. `exec` gets none of them: it takes no lock and may run beside a job of its own copy.
3187
+ write_runner_env() {
3188
+ : > "$jd/runner-env"
3189
+ local tmp_dir=
3190
+ if [ -n "$copy_index" ]; then
3191
+ tmp_dir="$work/t/$copy_index"
3192
+ if ! mkdir -p "$tmp_dir" 2> /dev/null; then
3193
+ say "no TMPDIR of its own for this job: $tmp_dir cannot be made"
3194
+ tmp_dir=
3195
+ fi
3196
+ fi
3197
+ {
3198
+ [ -z "$tmp_dir" ] || printf 'TMPDIR=%s\n' "$tmp_dir"
3199
+ # The port block does not depend on the folder: a full disk (where `mkdir` fails) is no reason for two jobs to fall back to the same default ports.
3200
+ [ -z "$copy_index" ] || printf 'REMOTE_RUN_PORT_BASE=%s\n' "$((port_base_start + port_block_size * copy_index))"
3201
+ # The device does not depend on the copy's number: a job that was given none (the index lock was not had, all numbers are taken) still knows its own device, or the guard and the tests would fall back to whichever is booted.
3202
+ [ -z "$ios_udid" ] || printf 'REMOTE_RUN_IOS_SIMULATOR_UDID=%s\n' "$ios_udid"
3203
+ } > "$jd/runner-env"
3204
+ }
3205
+
3206
+ # The job's own -e lines, one per line (also a last line without a newline).
3207
+ print_job_env_lines() {
3208
+ local env_line
3209
+ [ -s "$jd/env" ] || return 0
3210
+ while IFS= read -r env_line || [ -n "$env_line" ]; do printf '%s\n' "$env_line"; done < "$jd/env"
3211
+ }
3212
+
3213
+ # The lines of `$jd/runner-env` of one kind: `tmpdir` (TMPDIR, which the job's own -e may take back: it comes BEFORE them) or `vars` (REMOTE_RUN_*, which it may not: AFTER them).
3214
+ print_runner_env_lines() {
3215
+ local env_line
3216
+ [ -s "$jd/runner-env" ] || return 0
3217
+ while IFS= read -r env_line || [ -n "$env_line" ]; do
3218
+ case $env_line in
3219
+ TMPDIR=*) [ "$1" = tmpdir ] && printf '%s\n' "$env_line" ;;
3220
+ REMOTE_RUN_*) [ "$1" = vars ] && printf '%s\n' "$env_line" ;;
3221
+ esac
3222
+ done < "$jd/runner-env"
3223
+ return 0
3224
+ }
3225
+
3226
+ # Export the runner's lines of one kind (see print_runner_env_lines) in the step that is being set up.
3227
+ export_runner_env_lines() {
3228
+ local env_line
3229
+ while IFS= read -r env_line; do export "$env_line"; done < <(print_runner_env_lines "$1")
3230
+ }
3231
+
1308
3232
  # bash -c <command> in <directory>, with the job's -e variables, output into the log; sets step_code. Runs as a child so a
1309
3233
  # SIGTERM to the job (the `killed` flag) does not abandon it half-way.
1310
3234
  run_step() {
1311
3235
  local directory=$1
1312
3236
  local command_text=$2
3237
+ # A TERM that reached the job before this point (it sets `killed`) went to the job alone: a step that is forked now was not in the group yet, so it would run its whole course - to the watchdog's SIGKILL after its grace, with
3238
+ # the job's Simulator device still booted. Measured in a unit case on a loaded box: this fork came up to ~1.5 s after the TERM. The step is not started then; its code is that of a TERM. (A TERM in the microseconds between
3239
+ # this check and the fork can still miss the step - the same loss as before, a window that small.) The same on the login-session path: a request that is written with `go` starts the agent's command, and the `kill` the loop
3240
+ # writes comes a poll later.
3241
+ if [ "$killed" -eq 1 ]; then
3242
+ step_code=143
3243
+ return 0
3244
+ fi
1313
3245
  if gui_step_uses_agent; then
1314
3246
  gui_run_step "$directory" "$command_text"
1315
3247
  return 0
@@ -1318,9 +3250,11 @@ run_step() {
1318
3250
  cd "$directory" || exit 126
1319
3251
  LC_ALL=$job_locale
1320
3252
  export LC_ALL
3253
+ export_runner_env_lines tmpdir
1321
3254
  if [ -s "$jd/env" ]; then
1322
3255
  while IFS= read -r env_line; do export "$env_line"; done < "$jd/env"
1323
3256
  fi
3257
+ export_runner_env_lines vars
1324
3258
  exec bash -c "$command_text"
1325
3259
  ) < /dev/null &
1326
3260
  local step_pid=$!
@@ -1355,7 +3289,7 @@ start_watchdog() {
1355
3289
  done
1356
3290
  [ -f "$jd/watchdog-cancel" ] && exit 0
1357
3291
  touch "$jd/timeout"
1358
- signal_job_group TERM || pq kill "$task" > /dev/null 2>&1
3292
+ signal_job_group TERM || kill_pueue_task_of_job "$task"
1359
3293
  local grace_started=$SECONDS
1360
3294
  while [ $((SECONDS - grace_started)) -lt "$kill_grace_sec" ]; do
1361
3295
  [ -f "$jd/watchdog-cancel" ] && exit 0
@@ -1380,44 +3314,190 @@ check_has_no_symlink() {
1380
3314
  [ "$physical" = "$(cd "$tree" && pwd -P)/$parent" ]
1381
3315
  }
1382
3316
 
1383
- # Files the command created or changed that match pull.ere (one extended regular expression per line), kept per job. Only the folders in
1384
- # pull.roots are walked (the fixed prefixes of the patterns, `e2e/artifacts`): the copy also holds node_modules and every build folder,
1385
- # which a Gradle or Metro build fills with hundreds of thousands of files. `.` there (a pattern that starts with a wildcard) or no
1386
- # pull.roots at all (an older main box) walks the whole copy.
1387
- collect_artifacts() {
1388
- [ -s "$jd/pull.ere" ] || return 0
1389
- [ -f "$jd/start-marker" ] || return 0
1390
- local roots=()
1391
- local root
1392
- if [ -s "$jd/pull.roots" ]; then
3317
+ # The patterns of a job's pattern file $1 (`pull.ere`, `clean-after-success.ere`: one extended regular expression per line) and the folders to walk for them, from $2 (the matching `.roots`: the fixed prefixes of the patterns).
3318
+ # Sets the arrays job_patterns and job_roots. Fails when there is nothing to do: no pattern, or no root that exists in the copy with no symlink on its way. `.` among the roots (a pattern that starts with a wildcard),
3319
+ # or no roots file at all (an older main box) walks the whole copy.
3320
+ read_job_patterns() {
3321
+ job_patterns=()
3322
+ job_roots=()
3323
+ local pattern root
3324
+ while IFS= read -r pattern; do
3325
+ [ -n "$pattern" ] && job_patterns+=("$pattern")
3326
+ done < "$1"
3327
+ [ "${#job_patterns[@]}" -gt 0 ] || return 1
3328
+ if [ -s "$2" ]; then
1393
3329
  while IFS= read -r root; do
1394
3330
  [ -n "$root" ] || continue
1395
3331
  if [ "$root" = . ]; then
1396
- roots=(.)
3332
+ job_roots=(.)
1397
3333
  break
1398
3334
  fi
1399
- check_relative_path "$root" && [ -e "$tree/$root" ] && check_has_no_symlink "$root" && roots+=("$root")
1400
- done < "$jd/pull.roots"
1401
- [ "${#roots[@]}" -gt 0 ] || return 0
3335
+ check_relative_path "$root" && [ -e "$tree/$root" ] && check_has_no_symlink "$root" && job_roots+=("$root")
3336
+ done < "$2"
3337
+ [ "${#job_roots[@]}" -gt 0 ] || return 1
1402
3338
  else
1403
- roots=(.)
3339
+ job_roots=(.)
1404
3340
  fi
1405
- local patterns=()
1406
- local pattern
1407
- while IFS= read -r pattern; do
1408
- [ -n "$pattern" ] && patterns+=("$pattern")
1409
- done < "$jd/pull.ere"
1410
- [ "${#patterns[@]}" -gt 0 ] || return 0
1411
- local candidate relative
3341
+ }
3342
+
3343
+ # Files the command created or changed that match pull.ere, kept per job. Only the folders in pull.roots are walked (the fixed prefixes of the patterns, `e2e/artifacts`): the copy also holds node_modules and every
3344
+ # build folder, which a Gradle or Metro build fills with hundreds of thousands of files.
3345
+ collect_artifacts() {
3346
+ [ -s "$jd/pull.ere" ] || return 0
3347
+ [ -f "$jd/start-marker" ] || return 0
3348
+ read_job_patterns "$jd/pull.ere" "$jd/pull.roots" || return 0
3349
+ local pattern candidate relative
1412
3350
  while IFS= read -r -d '' candidate; do
1413
3351
  relative=${candidate#./}
1414
- for pattern in "${patterns[@]}"; do
3352
+ for pattern in "${job_patterns[@]}"; do
1415
3353
  if [[ $relative =~ $pattern ]]; then
1416
3354
  mkdir -p "$jd/artifacts/$(dirname "$relative")" && cp -p "$tree/$relative" "$jd/artifacts/$relative"
1417
3355
  break
1418
3356
  fi
1419
3357
  done
1420
- done < <(cd "$tree" && find "${roots[@]}" -name .git -prune -o -type f -newer "$jd/start-marker" -print0 2> /dev/null)
3358
+ done < <(cd "$tree" && find "${job_roots[@]}" -name .git -prune -o -type f -newer "$jd/start-marker" -print0 2> /dev/null)
3359
+ }
3360
+
3361
+ # A path with a `.git` component (the copy's repository) or a `node_modules` or `Pods` one (the dependencies: their step runs on the lockfile's key, not on their folder, so what is removed from there is never put back): never cleaned.
3362
+ check_is_protected_path() {
3363
+ case "/$1/" in
3364
+ */.git/* | */node_modules/* | */Pods/*) return 0 ;;
3365
+ esac
3366
+ return 1
3367
+ }
3368
+
3369
+ # Does folder $1 hold a `node_modules` or a `Pods` anywhere below it — the dependencies, which their step (keyed on the lockfile, not on the folder) would not put back? 0 = it does · 1 = it does not · 2 = `find` could not tell
3370
+ # (an error, a `find` without `-quit`): the caller treats that as «holds», so a doubt keeps the folder. A `.git` is not asked about: the copy holds none below a walk root except what a build tool checked out (Xcode's Swift
3371
+ # packages), which the next build fetches again.
3372
+ check_folder_holds_dependencies() {
3373
+ local found
3374
+ found=$(find "$1" \( -name node_modules -o -name Pods \) -print -quit 2> /dev/null) || return 2
3375
+ [ -n "$found" ]
3376
+ }
3377
+
3378
+ # Does pattern $1 name a folder that was kept (the array `kept_folders` of the caller) and holds path $2? A pattern that names a folder names everything below it too, so for $2 it is «kept with it»; any other pattern still applies.
3379
+ check_pattern_names_kept_folder_above() {
3380
+ local kept_folder
3381
+ [ "${#kept_folders[@]}" -gt 0 ] || return 1
3382
+ for kept_folder in "${kept_folders[@]}"; do
3383
+ if [[ $2 == "$kept_folder"/* ]] && [[ $kept_folder =~ $1 ]]; then
3384
+ return 0
3385
+ fi
3386
+ done
3387
+ return 1
3388
+ }
3389
+
3390
+ # The walk and the removals of `clean_after_success`; adds the paths it removed to its caller's `removed`.
3391
+ remove_paths_named_by_clean_after_success() {
3392
+ read_job_patterns "$jd/clean-after-success.ere" "$jd/clean-after-success.roots" || return 0
3393
+ local walk_roots=() kept_folders=() root pattern candidate relative holds_code
3394
+ for root in "${job_roots[@]}"; do
3395
+ check_is_protected_path "$root" || walk_roots+=("$root")
3396
+ done
3397
+ [ "${#walk_roots[@]}" -gt 0 ] || return 0
3398
+ # The matches are listed first and removed after: a folder removed while `find` is still walking it would only make `find` complain.
3399
+ local listing="$jd/clean-after-success.list"
3400
+ (cd "$tree" && find "${walk_roots[@]}" \( -name .git -o -name node_modules -o -name Pods \) -prune -o -print0 2> /dev/null) > "$listing"
3401
+ while IFS= read -r -d '' candidate; do
3402
+ relative=${candidate#./}
3403
+ # Gone already: below a folder that was just removed (the listing has its contents too — a pattern names a folder with everything below it).
3404
+ [ -e "$tree/$relative" ] || [ -L "$tree/$relative" ] || continue
3405
+ [ "$relative" != . ] && check_relative_path "$relative" || continue
3406
+ for pattern in "${job_patterns[@]}"; do
3407
+ [[ $relative =~ $pattern ]] || continue
3408
+ check_pattern_names_kept_folder_above "$pattern" "$relative" && continue
3409
+ holds_code=1
3410
+ if [ -d "$tree/$relative" ] && [ ! -L "$tree/$relative" ]; then
3411
+ check_folder_holds_dependencies "$tree/$relative"
3412
+ holds_code=$?
3413
+ fi
3414
+ if [ "$holds_code" -eq 1 ]; then
3415
+ if remove_path_even_if_read_only "$tree/$relative"; then
3416
+ removed=$((removed + 1))
3417
+ else
3418
+ say "clean-after-success: could not remove $relative"
3419
+ fi
3420
+ else
3421
+ kept_folders+=("$relative")
3422
+ if [ "$holds_code" -eq 0 ]; then
3423
+ say "clean-after-success: kept $relative (it holds a node_modules or Pods below it, which are never removed)"
3424
+ else
3425
+ say "clean-after-success: kept $relative (it could not be searched for a node_modules or Pods below it)"
3426
+ fi
3427
+ fi
3428
+ break
3429
+ done
3430
+ done < "$listing"
3431
+ rm -f "$listing"
3432
+ }
3433
+
3434
+ # After a job that SUCCEEDED: remove from the copy what the project's `clean-after-success:` names (a build's intermediates, tens of GB on a Mac, which the next job rebuilds anyway). Off unless the project says
3435
+ # so. A pattern names a file or a folder (a folder goes whole — unless it HOLDS a `node_modules` or `Pods` anywhere below it, like `ios` over `ios/Pods`: then it is kept whole, the other patterns still apply inside it, and the log
3436
+ # says so), inside the copy only: the walk starts from the patterns' fixed prefixes, a root with a symlink on its way is skipped, a root inside `.git`, `node_modules` or `Pods` is dropped and those folders are pruned from the
3437
+ # walk, the walk is NUL-separated (a name with a newline in it is one name, never two lines) and a path is removed only if `find` listed it, and a symlink goes as the link. Read-only folders are handled like the prune does.
3438
+ # The lock is still held, so no other job of the project sees the tree half-cleaned. Always says in the job's log how many paths went (0 included), and which were kept or would not go.
3439
+ clean_after_success() {
3440
+ [ -s "$jd/clean-after-success.ere" ] || return 0
3441
+ local removed=0
3442
+ remove_paths_named_by_clean_after_success
3443
+ say "clean-after-success: removed $removed path$([ "$removed" -eq 1 ] || echo s) of the copy"
3444
+ return 0
3445
+ }
3446
+
3447
+ # The job's own Simulator device (`needs-ios` jobs only): made or reused and booted by a step (`cmd_ios_device`), its UDID handed on as REMOTE_RUN_IOS_SIMULATOR_UDID through `runner-env`. Sets ios_udid; empty when the job
3448
+ # has none — a runner without a passing iOS check that names a device type (a hand-made one, a Mac whose check failed), or a step that failed: said in the log, and the job runs on, without the variable.
3449
+ prepare_job_simulator() {
3450
+ ios_udid=
3451
+ [ -f "$jd/needs-ios" ] || return 0
3452
+ read_runner_state
3453
+ if [ -z "$runner_state" ] || [ "$ios_boot_status" != ok ] || [ -z "$ios_device_type" ]; then
3454
+ say "no simulator of its own for this job: this runner has no passing iOS check that names a device type, so REMOTE_RUN_IOS_SIMULATOR_UDID is not set and the job shares the simulators that are there"
3455
+ return 0
3456
+ fi
3457
+ set_phase simulator
3458
+ say "preparing the simulator of this project's copy ($ios_device_prefix$slug)"
3459
+ ios_device_step_started=1
3460
+ run_step "$tree" "bash $(quote_word "$(get_script_path)") ios-device $(quote_word "$work") $(quote_word "$slug")"
3461
+ if [ "$step_code" -ne 0 ]; then
3462
+ say "the simulator of this project's copy could not be prepared (exit $step_code, see above): REMOTE_RUN_IOS_SIMULATOR_UDID is not set for this job"
3463
+ return 0
3464
+ fi
3465
+ ios_udid=$(read_file "$proj/ios-simulator")
3466
+ if ! check_is_udid "$ios_udid"; then
3467
+ ios_udid=
3468
+ say "the simulator step left no usable device id: REMOTE_RUN_IOS_SIMULATOR_UDID is not set for this job"
3469
+ fi
3470
+ }
3471
+
3472
+ # At the end of the job, before its lock goes (also after a kill or a timeout): the job's Simulator device is shut down, as a step, bounded — it frees the memory the next job needs. It is the first thing `finish_job` does after
3473
+ # the watchdog is stopped, so a kill finds the job here soonest, and `kill_job` gives a job in this phase the time the step is bounded by before it SIGKILLs the group. A command that ignores the TERM for the whole grace is
3474
+ # SIGKILLed before the job gets here, and its device stays booted. `killed` is clear for the step: a job that was killed still shuts its device down.
3475
+ shutdown_job_simulator() {
3476
+ [ "$ios_device_step_started" -eq 1 ] || return 0
3477
+ ios_device_step_started=0
3478
+ local udid was_killed=$killed
3479
+ udid=$(read_file "$proj/ios-simulator")
3480
+ check_is_udid "$udid" || return 0
3481
+ # The phase tells a `kill` that is about to SIGKILL the group that this step is under way (`kill_job` waits for it).
3482
+ set_phase simulator-off
3483
+ # A TERM that reaches the job from here on must neither set `killed` (the gui path would write `kill` to the agent, which stops the step) nor end the step's process (the daemon path: the step inherits the ignored signals).
3484
+ # The signals are ignored FIRST and `killed` cleared after: a TERM between the two lines would set it, and `run_step` starts no step once it is set - the device would stay booted.
3485
+ trap '' TERM INT HUP
3486
+ killed=0
3487
+ run_step "$tree" "bash $(quote_word "$(get_script_path)") ios-device-shutdown $(quote_word "$work") $(quote_word "$slug") $(quote_word "$udid")"
3488
+ trap 'killed=1' TERM INT HUP
3489
+ killed=$was_killed
3490
+ }
3491
+
3492
+ # The job's result, final: its stage goes, the phase it leaves is $2, its finish time and its exit code $1 are written (the exit file last: it is what `wait`, `status` and `kill` read as «over»).
3493
+ record_job_end() {
3494
+ rm -rf "$stage"
3495
+ # The phase BEFORE the exit file: a reader that finds the result must find `cleaning` with it (`check_lock_is_stale` takes an `exit` for «the holder is gone» only when the phase is not `cleaning`).
3496
+ set_phase "$2"
3497
+ date +%s > "$jd/finished-at"
3498
+ # The copy's mark of use means its last ACTIVITY: a job that queued and ran for hours must not leave its copy looking as old as its submit (the first one a short disk would remove, results and all).
3499
+ touch "$proj/used"
3500
+ printf '%s\n' "$1" > "$jd/exit.tmp" && mv "$jd/exit.tmp" "$jd/exit"
1421
3501
  }
1422
3502
 
1423
3503
  finish_job() {
@@ -1430,13 +3510,26 @@ finish_job() {
1430
3510
  say "job killed"
1431
3511
  fi
1432
3512
  stop_watchdog
3513
+ shutdown_job_simulator
1433
3514
  set_phase collecting
1434
3515
  collect_artifacts
1435
- release_lock
1436
- rm -rf "$stage"
1437
- set_phase done
1438
- date +%s > "$jd/finished-at"
1439
- printf '%s\n' "$code" > "$jd/exit.tmp" && mv "$jd/exit.tmp" "$jd/exit"
3516
+ if [ "$code" -eq 0 ] && [ -s "$jd/clean-after-success.ere" ]; then
3517
+ # Only a job that succeeded (its final code, after a timeout or a kill have had their say), and only after its results are collected: nothing a `pull:` names is lost to this. Its result is final already, so it is written
3518
+ # BEFORE the removal (minutes, for tens of GB): a `kill`, a lost lease or the hub's cut meanwhile finds the job ended and cannot turn one that worked into 137, and a caller waiting for the result does not wait for the removal.
3519
+ # The project lock stays held until the removal is over, so no other job of the project (and no `clean`) sees the tree half-cleaned.
3520
+ # Said BEFORE the result is written, so a foreground run (which streams the log until the result appears) shows it; the count that follows the removal is in the job's log on the runner.
3521
+ say "clean-after-success: removing what the project names from the copy now (the result is final; the count follows in the job's log)"
3522
+ record_job_end "$code" cleaning
3523
+ clean_after_success
3524
+ touch "$proj/used"
3525
+ release_lock
3526
+ set_phase done
3527
+ else
3528
+ release_lock
3529
+ record_job_end "$code" done
3530
+ fi
3531
+ # Its result is written and its lock is given back: the next job of the project may take a slot now. Last, so that a job added at this moment either was stashed before this looks or finds this one ended.
3532
+ enqueue_idle_stashed_of_project "$proj"
1440
3533
  exit "$code"
1441
3534
  }
1442
3535
 
@@ -1477,9 +3570,21 @@ cmd_job() {
1477
3570
 
1478
3571
  set_phase waiting-lock
1479
3572
  acquire_lock || finish_job 137
3573
+ if [ -f "$proj/build-data-trimmed" ]; then
3574
+ say "the Xcode build data of this copy ($(read_file "$proj/build-data-trimmed")) was removed after it had been idle for $build_data_keep_hours hours: an iOS build here starts from scratch"
3575
+ rm -f "$proj/build-data-trimmed"
3576
+ fi
3577
+ # This job alone is working in the copy now: a seed that an earlier job was cut off in the middle of is not wanted. A copy no job has applied a stage to yet is new (the manifest is the stage's last step).
3578
+ remove_path_even_if_read_only "$proj/seed.tmp"
3579
+ local is_new_copy=0
3580
+ [ -f "$proj/manifest" ] || is_new_copy=1
3581
+
3582
+ ensure_copy_index
3583
+ write_runner_env
1480
3584
 
1481
3585
  set_phase syncing
1482
3586
  sync_tree || { say "applying the files failed"; finish_job 125; }
3587
+ persist_project_key
1483
3588
 
1484
3589
  local subfolder
1485
3590
  subfolder=$(read_file "$jd/subfolder")
@@ -1489,6 +3594,12 @@ cmd_job() {
1489
3594
  local install_command install_key
1490
3595
  install_command=$(read_file "$jd/install-command")
1491
3596
  install_key=$(read_file "$jd/install-key")
3597
+ if [ "$is_new_copy" -eq 1 ] && [ -n "$install_command" ]; then
3598
+ set_phase seeding
3599
+ seed_new_copy "$install_key"
3600
+ set_phase syncing
3601
+ [ "$killed" -eq 1 ] && finish_job 137
3602
+ fi
1492
3603
  if [ -n "$install_command" ] && [ "$(read_file "$proj/deps.hash")" != "$install_key" ]; then
1493
3604
  set_phase deps
1494
3605
  say "installing dependencies: $install_command"
@@ -1506,6 +3617,11 @@ cmd_job() {
1506
3617
  fi
1507
3618
  [ "$killed" -eq 1 ] && finish_job 137
1508
3619
 
3620
+ # The Simulator device comes after the dependencies (the project's own install may use the system's), and its UDID is the one variable written after them.
3621
+ prepare_job_simulator
3622
+ write_runner_env
3623
+ [ "$killed" -eq 1 ] && finish_job 137
3624
+
1509
3625
  touch "$jd/start-marker"
1510
3626
  set_phase running
1511
3627
  run_step "$tree/$subfolder" "$(read_file "$jd/cmd")"
@@ -1514,6 +3630,12 @@ cmd_job() {
1514
3630
 
1515
3631
  # ─────────────────────────── exec ───────────────────────────
1516
3632
 
3633
+ # The exit hook of `exec`: its marker goes, and the copy's mark of use is fresh (the command may have run for hours; the copy is not the least recently used one for that).
3634
+ end_exec_use() {
3635
+ rm -f "$exec_marker"
3636
+ touch "$proj/used" 2> /dev/null
3637
+ }
3638
+
1517
3639
  cmd_exec() {
1518
3640
  set_paths "$1" "$2" ""
1519
3641
  local subfolder=$3
@@ -1521,7 +3643,13 @@ cmd_exec() {
1521
3643
  lease_sec=$(ms_to_sec "$4")
1522
3644
  shift 4
1523
3645
  check_relative_path "$subfolder" || die "bad subfolder"
3646
+ # `exec` takes no lock and leaves no job folder, so this marker is what tells a prune the copy is in use for as long as the command runs (it is written BEFORE the copy is looked at: a
3647
+ # prune that moves the copy aside after that finds the marker, and one that did so before leaves no folder to write it in). The exit hook removes it and counts the end as use.
3648
+ exec_marker="$proj/exec.$$"
3649
+ { printf '%s\n' "$$" > "$exec_marker"; } 2> /dev/null || die "the runner has no copy of this project yet (run a command first)"
3650
+ trap 'end_exec_use' EXIT
1524
3651
  [ -d "$tree/$subfolder" ] || die "the runner has no copy of this project yet (run a command first)"
3652
+ touch "$proj/used"
1525
3653
  exec 3<&0
1526
3654
  # Own process group, so the lease can stop the command and everything it started.
1527
3655
  set -m
@@ -1542,7 +3670,7 @@ cmd_exec() {
1542
3670
  local watcher_pid=$!
1543
3671
  wait "$exec_pid"
1544
3672
  local exec_code=$?
1545
- kill "$watcher_pid" > /dev/null 2>&1
3673
+ stop_background_job "$watcher_pid"
1546
3674
  # The command's own code, said out loud: ssh reports 255 for ITS failures, and a command that really exits 255 (ssh and adb do) would
1547
3675
  # look like a lost connection. The marker (RS, the name, the code, a newline) is the last thing on stderr; the CLI takes it out of what it
1548
3676
  # shows. A session that dies before it has none, which is how a lost connection is told from a command that exited 255.
@@ -1590,6 +3718,7 @@ main() {
1590
3718
  case $subcommand in
1591
3719
  probe) cmd_probe "$@" ;;
1592
3720
  prepare) cmd_prepare "$@" ;;
3721
+ apply-groups) cmd_apply_groups "$@" ;;
1593
3722
  lease) cmd_lease "$@" ;;
1594
3723
  submit) cmd_submit "$@" ;;
1595
3724
  job) cmd_job "$@" ;;
@@ -1604,6 +3733,14 @@ main() {
1604
3733
  workdir) cmd_workdir "$@" ;;
1605
3734
  jobs) cmd_jobs "$@" ;;
1606
3735
  prune) cmd_prune "$@" ;;
3736
+ measure-copies) cmd_measure_copies "$@" ;;
3737
+ settle-queue) cmd_settle_queue "$@" ;;
3738
+ sweep-tmpdirs) cmd_sweep_tmpdirs "$@" ;;
3739
+ clean) cmd_clean "$@" ;;
3740
+ simctl-cleanup) cmd_simctl_cleanup "$@" ;;
3741
+ fetched) cmd_fetched "$@" ;;
3742
+ ios-device) cmd_ios_device "$@" ;;
3743
+ ios-device-shutdown) cmd_ios_device_shutdown "$@" ;;
1607
3744
  sync-tree) cmd_sync_tree "$@" ;;
1608
3745
  *) die "unknown subcommand: $subcommand" ;;
1609
3746
  esac