@cortex-agent/server 2026.9.15 → 2026.9.25

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 (297) hide show
  1. package/README.md +3 -2
  2. package/defaults/config/hooks/08-agents-md-injector-post-tool.json +10 -0
  3. package/defaults/config/hooks/{10-cortex-md-injector-session-start.json → 10-agents-md-injector-session-start.json} +3 -3
  4. package/defaults/config/hooks/{CORTEX.md → AGENTS.md} +2 -2
  5. package/defaults/config/thread-templates/agents/creative.json +17 -0
  6. package/defaults/hooks/{CORTEX.md → AGENTS.md} +1 -1
  7. package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  8. package/defaults/hooks/cortex-hook-api.mjs +2 -2
  9. package/defaults/hooks/new-session-hook.mjs +2 -2
  10. package/defaults/hooks/rules-loader.mjs +2 -2
  11. package/defaults/hooks/status-md-guard.mjs +8 -8
  12. package/defaults/hooks/task-status-check.mjs +18 -76
  13. package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
  14. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
  15. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
  16. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
  17. package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
  18. package/defaults/prompts/systemPrompts/creative.md +13 -0
  19. package/defaults/prompts/systemPrompts/direct.md +1 -1
  20. package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
  21. package/defaults/rules/decision-records.md +1 -1
  22. package/defaults/rules/meta-conventions.md +4 -4
  23. package/defaults/rules/mission-md.md +1 -1
  24. package/dist/agent-adapter/claude/adapter.d.ts +12 -0
  25. package/dist/agent-adapter/claude/adapter.js +19 -1
  26. package/dist/agent-adapter/claude/hooks-builder.js +2 -2
  27. package/dist/agent-adapter/claude/spawn-args.d.ts +7 -0
  28. package/dist/agent-adapter/claude/spawn-args.js +14 -0
  29. package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
  30. package/dist/agent-adapter/claude/turn-machine.js +46 -5
  31. package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
  32. package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
  33. package/dist/agent-adapter/pi/child-runner.d.ts +4 -2
  34. package/dist/agent-adapter/pi/child-runner.js +5 -1
  35. package/dist/agent-adapter/pi/event-parser.d.ts +3 -2
  36. package/dist/agent-adapter/pi/event-parser.js +46 -2
  37. package/dist/agent-adapter/pi/extensions.d.ts +7 -1
  38. package/dist/agent-adapter/pi/extensions.js +10 -3
  39. package/dist/agent-adapter/pi/mcp-bridge.js +8 -8
  40. package/dist/agent-adapter/pi/pi-session.js +5 -0
  41. package/dist/agent-adapter/pi/runtime.js +3 -0
  42. package/dist/agent-adapter/pi/session-options.js +5 -1
  43. package/dist/agent-adapter/pi/subagent.d.ts +15 -3
  44. package/dist/agent-adapter/pi/subagent.js +18 -0
  45. package/dist/agent-adapter/pi/tool-shims.d.ts +6 -1
  46. package/dist/agent-adapter/pi/tool-shims.js +34 -1
  47. package/dist/agent-adapter/types.d.ts +6 -0
  48. package/dist/core/agents/subagent/types.d.ts +3 -0
  49. package/dist/core/config-generator.js +17 -2
  50. package/dist/core/debug-mode.d.ts +11 -10
  51. package/dist/core/debug-mode.js +12 -18
  52. package/dist/core/exec-async.d.ts +26 -0
  53. package/dist/core/exec-async.js +47 -0
  54. package/dist/core/locales/en.d.ts +14 -1
  55. package/dist/core/locales/slices/commands.d.ts +12 -1
  56. package/dist/core/locales/slices/commands.js +24 -2
  57. package/dist/core/locales/slices/startup.d.ts +2 -0
  58. package/dist/core/locales/slices/startup.js +4 -0
  59. package/dist/core/mcp-tool-gate.js +1 -0
  60. package/dist/core/media-types.d.ts +10 -0
  61. package/dist/core/media-types.js +34 -0
  62. package/dist/core/platform-settings-spec.js +1 -1
  63. package/dist/core/rebuild-progress.d.ts +58 -0
  64. package/dist/core/rebuild-progress.js +103 -0
  65. package/dist/core/resilient-watch.js +5 -3
  66. package/dist/core/run-registry.d.ts +7 -0
  67. package/dist/core/run-registry.js +6 -0
  68. package/dist/core/settings-spec.d.ts +21 -0
  69. package/dist/core/settings-spec.js +28 -1
  70. package/dist/core/types/agent-types.d.ts +3 -1
  71. package/dist/core/types/thread-types.d.ts +23 -4
  72. package/dist/core/utils.d.ts +1 -1
  73. package/dist/core/utils.js +1 -1
  74. package/dist/domain/agents/agent-state.d.ts +7 -0
  75. package/dist/domain/agents/agent-state.js +9 -1
  76. package/dist/domain/agents/agent-switch.d.ts +38 -0
  77. package/dist/domain/agents/agent-switch.js +106 -0
  78. package/dist/domain/agents/config.d.ts +20 -2
  79. package/dist/domain/agents/config.js +58 -4
  80. package/dist/domain/agents/index.d.ts +1 -0
  81. package/dist/domain/agents/index.js +1 -0
  82. package/dist/domain/agents/profile-manager.d.ts +6 -0
  83. package/dist/domain/agents/profile-manager.js +14 -1
  84. package/dist/domain/executions/registry.d.ts +3 -2
  85. package/dist/domain/executions/registry.js +84 -10
  86. package/dist/domain/mcp/bundled-server.js +4 -3
  87. package/dist/domain/mcp/feishu/file.js +37 -18
  88. package/dist/domain/mcp/feishu/types.d.ts +3 -0
  89. package/dist/domain/mcp/feishu-server.js +1 -1
  90. package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
  91. package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
  92. package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
  93. package/dist/domain/mcp/tools/remote-file.js +44 -0
  94. package/dist/domain/mcp/tools/slack.d.ts +2 -0
  95. package/dist/domain/mcp/tools/slack.js +22 -7
  96. package/dist/domain/mcp/tools/task-ops.js +5 -13
  97. package/dist/domain/mcp/tools/ui-file.js +23 -10
  98. package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
  99. package/dist/domain/mcp/tools/waitpoint.js +122 -0
  100. package/dist/domain/memory/agents-md-injector.d.ts +24 -0
  101. package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
  102. package/dist/domain/plugins/runtime.js +1 -1
  103. package/dist/domain/plugins/skill-projection.d.ts +8 -2
  104. package/dist/domain/plugins/skill-projection.js +76 -19
  105. package/dist/domain/projects/project-store.d.ts +1 -1
  106. package/dist/domain/projects/project-store.js +3 -3
  107. package/dist/domain/remote/client-bootstrap.js +1 -1
  108. package/dist/domain/remote/client-hot-reload.d.ts +1 -1
  109. package/dist/domain/remote/client-hot-reload.js +30 -24
  110. package/dist/domain/remote/client-manager.js +39 -119
  111. package/dist/domain/remote/cortex-client-config.d.ts +1 -1
  112. package/dist/domain/remote/cortex-client-config.js +1 -1
  113. package/dist/domain/remote/device-file.d.ts +51 -0
  114. package/dist/domain/remote/device-file.js +193 -0
  115. package/dist/domain/remote/device-port.js +3 -0
  116. package/dist/domain/remote/reverse-stream.d.ts +18 -7
  117. package/dist/domain/remote/reverse-stream.js +19 -6
  118. package/dist/domain/runs/engine-spec.js +4 -0
  119. package/dist/domain/runs/request.d.ts +6 -0
  120. package/dist/domain/runs/run.js +1 -0
  121. package/dist/domain/runs/spec-loader.d.ts +4 -3
  122. package/dist/domain/runs/spec-loader.js +4 -3
  123. package/dist/domain/scheduling/jobs/sync-public.js +6 -6
  124. package/dist/domain/scheduling/scheduler.js +14 -12
  125. package/dist/domain/sessions/session-lifecycle.d.ts +5 -0
  126. package/dist/domain/sessions/session-lifecycle.js +13 -1
  127. package/dist/domain/system/rebuild-hold.d.ts +44 -0
  128. package/dist/domain/system/rebuild-hold.js +91 -0
  129. package/dist/domain/system/server-update-check.d.ts +2 -1
  130. package/dist/domain/system/server-update-check.js +15 -13
  131. package/dist/domain/tasks/archiver.js +21 -13
  132. package/dist/domain/tasks/claim-recovery.js +2 -2
  133. package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
  134. package/dist/domain/tasks/dispatch-utils.js +46 -1
  135. package/dist/domain/tasks/dispatcher.js +4 -5
  136. package/dist/domain/tasks/mutator.d.ts +2 -2
  137. package/dist/domain/tasks/mutator.js +62 -61
  138. package/dist/domain/tasks/system/task-cli.js +2 -2
  139. package/dist/domain/tasks/system/task-completion.d.ts +7 -2
  140. package/dist/domain/tasks/system/task-completion.js +69 -6
  141. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -1
  142. package/dist/domain/tasks/system/task-lifecycle-edit.js +21 -2
  143. package/dist/domain/tasks/system/task-lock.d.ts +23 -0
  144. package/dist/domain/tasks/system/task-lock.js +29 -1
  145. package/dist/domain/tasks/system/task-mutations.d.ts +14 -1
  146. package/dist/domain/tasks/system/task-mutations.js +25 -2
  147. package/dist/domain/tasks/system/task-state.d.ts +12 -1
  148. package/dist/domain/tasks/system/task-state.js +20 -3
  149. package/dist/domain/threads/prompt-builder.d.ts +9 -6
  150. package/dist/domain/threads/prompt-builder.js +28 -10
  151. package/dist/domain/threads/runner.js +10 -4
  152. package/dist/domain/threads/state-machine.js +15 -11
  153. package/dist/domain/threads/template-loader.js +6 -4
  154. package/dist/domain/threads/template-validate.d.ts +43 -6
  155. package/dist/domain/threads/template-validate.js +12 -0
  156. package/dist/domain/ui-service/app-router.d.ts +34 -3
  157. package/dist/domain/ui-service/app-router.js +9 -14
  158. package/dist/domain/ui-service/input-schemas.d.ts +28 -5
  159. package/dist/domain/ui-service/input-schemas.js +24 -9
  160. package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
  161. package/dist/domain/ui-service/mutate/sessions.d.ts +6 -1
  162. package/dist/domain/ui-service/mutate/sessions.js +54 -0
  163. package/dist/domain/ui-service/mutate/tasks.js +4 -3
  164. package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
  165. package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
  166. package/dist/domain/ui-service/platform-settings.js +1 -1
  167. package/dist/domain/ui-service/plugins-shared.js +1 -1
  168. package/dist/domain/ui-service/query/config.js +20 -2
  169. package/dist/domain/ui-service/query/executions.js +0 -2
  170. package/dist/domain/ui-service/query/machine-detail.js +3 -8
  171. package/dist/domain/ui-service/query/memory.js +29 -35
  172. package/dist/domain/ui-service/query/sessions.js +96 -12
  173. package/dist/domain/ui-service/query/system.js +19 -0
  174. package/dist/domain/ui-service/query/threads.js +1 -54
  175. package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
  176. package/dist/domain/ui-service/query/waitpoints.js +117 -0
  177. package/dist/domain/ui-service/query-input-schemas.d.ts +4 -0
  178. package/dist/domain/ui-service/query-input-schemas.js +5 -0
  179. package/dist/domain/ui-service/trpc.js +1 -1
  180. package/dist/domain/ui-service/types.d.ts +229 -51
  181. package/dist/domain/ui-service/types.js +1 -1
  182. package/dist/domain/ui-service/ui-service.js +8 -31
  183. package/dist/domain/waitpoints/notices.d.ts +21 -0
  184. package/dist/domain/waitpoints/notices.js +115 -0
  185. package/dist/domain/waitpoints/service.d.ts +91 -0
  186. package/dist/domain/waitpoints/service.js +243 -0
  187. package/dist/entry/app.js +52 -11
  188. package/dist/entry/auth-login-cli.js +1 -1
  189. package/dist/entry/auth-login-terminal.js +1 -1
  190. package/dist/entry/daemon-notice.d.ts +10 -1
  191. package/dist/entry/daemon-notice.js +16 -1
  192. package/dist/entry/daemon.d.ts +43 -2
  193. package/dist/entry/daemon.js +163 -9
  194. package/dist/entry/init-auth.js +1 -1
  195. package/dist/entry/init.js +6 -6
  196. package/dist/entry/signal-cli.d.ts +30 -0
  197. package/dist/entry/signal-cli.js +207 -0
  198. package/dist/entry/start-ui-http.d.ts +1 -1
  199. package/dist/entry/start-ui-http.js +2 -2
  200. package/dist/events/event-types.d.ts +0 -7
  201. package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  202. package/dist/hooks/cortex-hook-api.mjs +2 -2
  203. package/dist/hooks/new-session-hook.mjs +2 -2
  204. package/dist/hooks/rules-loader.mjs +2 -2
  205. package/dist/hooks/status-md-guard.mjs +8 -8
  206. package/dist/hooks/task-status-check.mjs +18 -76
  207. package/dist/hooks/tasks-yaml-guard.mjs +2 -2
  208. package/dist/orchestration/agent-file-send.d.ts +9 -0
  209. package/dist/orchestration/agent-file-send.js +21 -2
  210. package/dist/orchestration/agent-runner.d.ts +3 -2
  211. package/dist/orchestration/agent-runner.js +33 -12
  212. package/dist/orchestration/attachments-store.d.ts +31 -0
  213. package/dist/orchestration/attachments-store.js +184 -0
  214. package/dist/orchestration/conversation-request.d.ts +37 -0
  215. package/dist/orchestration/conversation-request.js +91 -22
  216. package/dist/orchestration/interactions/plan-approvals.js +1 -1
  217. package/dist/orchestration/mid-turn-inject.d.ts +3 -0
  218. package/dist/orchestration/mid-turn-inject.js +9 -4
  219. package/dist/orchestration/outputs-store.d.ts +11 -0
  220. package/dist/orchestration/outputs-store.js +32 -6
  221. package/dist/orchestration/resume-dispatcher.js +4 -2
  222. package/dist/orchestration/routing/commands/mode.js +114 -63
  223. package/dist/orchestration/routing/file-handler.d.ts +23 -2
  224. package/dist/orchestration/routing/file-handler.js +22 -5
  225. package/dist/orchestration/routing/webhook.js +193 -39
  226. package/dist/orchestration/session-gateway.d.ts +1 -1
  227. package/dist/orchestration/session-gateway.js +1 -0
  228. package/dist/orchestration/thread-executor.d.ts +2 -0
  229. package/dist/orchestration/thread-executor.js +24 -1
  230. package/dist/orchestration/thread-input.d.ts +3 -2
  231. package/dist/orchestration/thread-input.js +8 -9
  232. package/dist/orchestration/turn/turn-prep.d.ts +15 -1
  233. package/dist/orchestration/turn/turn-prep.js +19 -8
  234. package/dist/orchestration/turn/turn.js +1 -0
  235. package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
  236. package/dist/orchestration/waitpoint-ingress.js +172 -0
  237. package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
  238. package/dist/orchestration/waitpoint-notifier.js +119 -0
  239. package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
  240. package/dist/orchestration/waitpoint-remote-drain.js +147 -0
  241. package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
  242. package/dist/orchestration/waitpoint-sweep.js +87 -0
  243. package/dist/platform/adapters/feishu-image.d.ts +19 -0
  244. package/dist/platform/adapters/feishu-image.js +71 -0
  245. package/dist/platform/adapters/feishu.d.ts +2 -0
  246. package/dist/platform/adapters/feishu.js +26 -16
  247. package/dist/platform/ui-http/listening-ports.d.ts +1 -1
  248. package/dist/platform/ui-http/listening-ports.js +1 -1
  249. package/dist/platform/ui-http/ui-session.js +1 -1
  250. package/dist/store/conversation-display-projection.d.ts +9 -1
  251. package/dist/store/conversation-display-projection.js +13 -6
  252. package/dist/store/conversation-history-reader.d.ts +19 -0
  253. package/dist/store/conversation-history-reader.js +163 -44
  254. package/dist/store/conversation-history-repo.d.ts +37 -10
  255. package/dist/store/conversation-history-repo.js +161 -139
  256. package/dist/store/conversation-ledger-repo.js +1 -1
  257. package/dist/store/execution-repo.d.ts +1 -19
  258. package/dist/store/execution-repo.js +1 -18
  259. package/dist/store/project-notes-repo.js +11 -2
  260. package/dist/store/prompt-migration-replacements.js +1 -1
  261. package/dist/store/session-registry-import.js +1 -1
  262. package/dist/store/session-registry-journal.d.ts +4 -0
  263. package/dist/store/session-registry-journal.js +5 -1
  264. package/dist/store/session-registry-repo.d.ts +2 -1
  265. package/dist/store/session-registry-repo.js +3 -1
  266. package/dist/store/task-repo.d.ts +6 -3
  267. package/dist/store/task-repo.js +26 -10
  268. package/dist/store/version-migrations.d.ts +13 -3
  269. package/dist/store/version-migrations.js +254 -24
  270. package/dist/store/waitpoint-repo.d.ts +108 -0
  271. package/dist/store/waitpoint-repo.js +94 -0
  272. package/package.json +3 -2
  273. package/web/dist/AGENTS.md +10 -0
  274. package/web/dist/assets/index-B1dBi8Za.css +1 -0
  275. package/web/dist/assets/{index-CEZ0DSei.js → index-BAeLybF0.js} +1 -1
  276. package/web/dist/assets/index-BcQI8Fh5.js +445 -0
  277. package/web/dist/index.html +12 -4
  278. package/web/dist/theme.css +211 -40
  279. package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
  280. package/dist/domain/executions/log-tailer.d.ts +0 -71
  281. package/dist/domain/executions/log-tailer.js +0 -194
  282. package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
  283. package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
  284. package/dist/domain/memory/cortex-md-scanner.js +0 -66
  285. package/dist/domain/remote/cortex-client.d.ts +0 -1
  286. package/dist/domain/remote/cortex-client.js +0 -662
  287. package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
  288. package/dist/domain/tasks/system/cortex-run.js +0 -360
  289. package/web/dist/assets/index-CRDJo39X.css +0 -1
  290. package/web/dist/assets/index-DjuPJVZE.js +0 -444
  291. /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
  292. /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
  293. /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
  294. /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
  295. /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
  296. /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
  297. /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
package/dist/entry/app.js CHANGED
@@ -21,7 +21,6 @@ import { recoverTuiOrphans } from '../agent-adapter/claude/adapter.js';
21
21
  import { startWebhookServer } from '../orchestration/routing/webhook.js';
22
22
  import * as pendingTaskTracker from '../domain/tasks/pending-tracker.js';
23
23
  import * as executionRegistry from '../domain/executions/registry.js';
24
- import { executionLogTailer } from '../domain/executions/log-tailer.js';
25
24
  import { initHookBridge, resolveRequest as resolveHookRequest, setOnStale } from '../orchestration/routing/hook-bridge.js';
26
25
  import { interactionRecords } from '../orchestration/interactions/interaction-records.js';
27
26
  import * as askUserQuestion from '../orchestration/interactions/ask-user-question.js';
@@ -32,6 +31,9 @@ import { taskStore } from '../domain/tasks/store.js';
32
31
  import { taskMutator } from '../domain/tasks/mutator.js';
33
32
  import { recoverOrphanedClaims } from '../domain/tasks/claim-recovery.js';
34
33
  import { projectDirRepo } from '../store/project-dir-repo.js';
34
+ import { waitpointRepo } from '../store/waitpoint-repo.js';
35
+ import { cancelWaitpoint } from '../domain/waitpoints/service.js';
36
+ import { recoverWaitpoints, startWaitpointSweep, stopWaitpointSweep } from '../orchestration/waitpoint-sweep.js';
35
37
  import { projectStore } from '../domain/projects/index.js';
36
38
  import { sendStartupDmIfConfigured } from './startup-notify.js';
37
39
  import { subscribeDaemonNotices } from './daemon-notice.js';
@@ -97,9 +99,10 @@ import { sessionStore } from '../store/session-registry-repo.js';
97
99
  import { retentionCandidateRepo } from '../store/retention-candidate-repo.js';
98
100
  import { createDirectSession, adoptScheduledSession } from '../domain/sessions/session-lifecycle.js';
99
101
  import { runSessionRetentionSweep } from '../domain/sessions/session-retention.js';
102
+ import { pruneInboundAttachments } from '../orchestration/attachments-store.js';
100
103
  import { syncClaudeUserCleanupPeriodDays } from '../domain/auth/claude-user-settings.js';
101
104
  import { setSessionAsync, getSessionAsync } from '../domain/sessions/session.js';
102
- import { applyChannelSelection, getChannelOverride, getSelectionDefault, resolveBackendForChannel, switchChannelProfile, } from '../domain/agents/index.js';
105
+ import { applyChannelSelection, clearChannelAgentSelection, getActiveProfile, getChannelOverride, getSelectionDefault, resolveBackendForChannel, switchChannelAgent, switchChannelProfile, } from '../domain/agents/index.js';
103
106
  import { isSessionCompactionSupported } from '../domain/runs/compact.js';
104
107
  import { initDiskMonitor, stopDiskMonitor } from '../domain/monitor/disk-monitor.js';
105
108
  import { startEventLoopMonitor, stopEventLoopMonitor } from '../domain/monitor/event-loop-monitor.js';
@@ -174,7 +177,10 @@ async function runRetentionSweep(retentionDays) {
174
177
  },
175
178
  syncClaudeUserCleanupPeriodDays,
176
179
  });
177
- log.info(`Retention sweep: registry=${result.registryCommitted} history=${result.historyOrphanDeleted} pi=${result.piOrphanDeleted} capture=${result.claudeCaptureDeleted} errors=${result.errors.length}`);
180
+ // Inbound platform attachments are read during the turn they arrive on; nothing links to them
181
+ // afterwards, and before this sweep existed they accumulated in the workspace forever.
182
+ const attachmentsPruned = await pruneInboundAttachments(retentionDays);
183
+ log.info(`Retention sweep: registry=${result.registryCommitted} history=${result.historyOrphanDeleted} pi=${result.piOrphanDeleted} capture=${result.claudeCaptureDeleted} attachments=${attachmentsPruned} errors=${result.errors.length}`);
178
184
  }
179
185
  const retentionController = createSessionRetentionController({
180
186
  getRetentionDays: () => getSettings().sessionRetentionDays,
@@ -299,7 +305,6 @@ bus.subscribe('session.status', (e) => sessionHolds.onSessionStatus(e));
299
305
  planApprovals.setBus(bus); // S6-A: wire plan.approved events
300
306
  busyTracker.setBus(bus); // S6-C: wire busy/idle IPC through event bus
301
307
  taskMutator.setBus(bus); // c39d: wire task lifecycle events
302
- executionLogTailer.setBus(bus); // 342f: wire execution.log live log-tail stream
303
308
  initInteractionHandlers(bus); // BLK-1: wire ask-user.answered publisher
304
309
  const TEMP_DIR = WORKSPACE_DIR;
305
310
  mkdirSync(TEMP_DIR, { recursive: true });
@@ -434,13 +439,14 @@ process.on('SIGTERM', async () => {
434
439
  // Stop scheduler timers BEFORE draining repo writes — otherwise a late-firing
435
440
  // timer can enqueue a mutate() after scheduleRepo.flush() resolves, losing that write.
436
441
  scheduler.stop();
442
+ stopWaitpointSweep();
437
443
  // Stop outbound queue drain loop (pending WAL entries survive on disk for next startup).
438
444
  await oq.stop();
439
445
  // Drain in-flight atomic writes before exiting. Without this, SIGTERM landing between
440
446
  // `writeFile(tmp)` and `rename(tmp, target)` in atomic-write.ts leaves orphan .tmp.* siblings.
441
447
  // Daemon gives 5s before SIGKILL — well over the time needed to flush a few MB of JSON.
442
448
  try {
443
- await Promise.allSettled([bus.close(), oq.flush(), threadStore.flush(), conversationLedger.flush(), conversationHistory.flush(), pendingInjectionRepo.flush(), taskStore.flush(), executionRepo.flush(), projectDirRepo.flush(), scheduleRepo.flush(), providerStateRepo.flush(), costRepo.flush(), profileRepo.flush(), sessionStore.flush()]);
449
+ await Promise.allSettled([bus.close(), oq.flush(), threadStore.flush(), conversationLedger.flush(), conversationHistory.flush(), pendingInjectionRepo.flush(), taskStore.flush(), executionRepo.flush(), projectDirRepo.flush(), waitpointRepo.flush(), scheduleRepo.flush(), providerStateRepo.flush(), costRepo.flush(), profileRepo.flush(), sessionStore.flush()]);
444
450
  }
445
451
  catch { }
446
452
  await stopGateway();
@@ -500,6 +506,13 @@ process.on('SIGTERM', async () => {
500
506
  });
501
507
  if (recoveredPending > 0)
502
508
  log.info(`Recovered ${recoveredPending} pending injected message(s)`);
509
+ // A waitpoint that fired moments before shutdown has its wake still pending on disk, and the
510
+ // signal spool may hold files written while the daemon was down. Reconcile both before anything
511
+ // else can observe a session, on the same reasoning as the injection recovery above.
512
+ const recoveredWaitpoints = await recoverWaitpoints();
513
+ if (recoveredWaitpoints.delivered > 0 || recoveredWaitpoints.spooled > 0) {
514
+ log.info(`Recovered ${recoveredWaitpoints.delivered} waitpoint wake(s), ${recoveredWaitpoints.spooled} spooled signal(s)`);
515
+ }
503
516
  // ── Wire UI service into the TUI gateway ────────────────────────────────
504
517
  //
505
518
  // UI service (M3) provides store-backed query/mutate/subscribe capabilities
@@ -534,7 +547,13 @@ process.on('SIGTERM', async () => {
534
547
  update: (id, patch) => scheduler.update(id, patch),
535
548
  },
536
549
  executionRegistry,
537
- executionLogTailer,
550
+ // Waitpoints (SessionInfo.waitingOn + the waitpoints.* ops). Injected here, at the entry layer,
551
+ // so the ui-service domain never reaches into the waitpoint store. Only armed records are ever
552
+ // listed: a settled waitpoint has already announced itself in the session transcript.
553
+ waitpointRegistry: {
554
+ listArmed: () => waitpointRepo.listArmed(),
555
+ cancel: (id) => cancelWaitpoint(id),
556
+ },
538
557
  approvalsPath: path.join(CONTEXT_DIR, 'PENDING_APPROVALS.md'),
539
558
  runningExecutions: sessionStates,
540
559
  costSummary: getCostSummary,
@@ -582,6 +601,21 @@ process.on('SIGTERM', async () => {
582
601
  // Web profile switch: apply the shared per-channel profile-switch rule (same one the Slack/Feishu
583
602
  // `!profile` command uses). Wired here so the ui-service domain never imports domain/agents.
584
603
  switchSessionProfile: (opts) => switchChannelProfile(opts),
604
+ // Web agent picker: the same per-channel agent-switch rule the `!agent` command applies. A null
605
+ // name is the "follow the global default" row, which clears the channel's selection instead.
606
+ switchSessionAgent: async ({ channel, name }) => {
607
+ if (name === null) {
608
+ await clearChannelAgentSelection(channel);
609
+ return { ok: true, agentName: null, effectiveProfile: getActiveProfile(channel) ?? '', backendChanged: false };
610
+ }
611
+ const res = await switchChannelAgent({ channel, name });
612
+ return res.ok === true
613
+ ? { ok: true, agentName: res.agentName, effectiveProfile: res.effectiveProfile, backendChanged: res.backendChanged }
614
+ : {
615
+ ok: false, agentName: null, effectiveProfile: '', backendChanged: false,
616
+ reason: res.reason, currentBackend: res.currentBackend, targetBackend: res.targetBackend,
617
+ };
618
+ },
585
619
  // Web model picker: the composer's profile / model / provider / thinking choice, applied under
586
620
  // the one domain rule. Wired here for the same reason as the profile switch above.
587
621
  applySessionSelection: (opts) => applyChannelSelection(opts),
@@ -701,8 +735,8 @@ process.on('SIGTERM', async () => {
701
735
  // Crash-orphan claim recovery: a dispatch claim whose owner died with the server keeps the
702
736
  // task invisible to the dispatcher forever (claimed → not actionable → never re-dispatched),
703
737
  // stranding it and any manager suspended on it. Runs after markRunningAsFailedOnStartup so
704
- // surviving waiting/rate_limited threads still protect their claims; remote cortex-run tasks
705
- // (status pending / pending-tracker) and manual claims are respected. Before scheduler.start
738
+ // surviving waiting/rate_limited threads still protect their claims; tasks waiting on outside
739
+ // work (status pending / pending-tracker) and manual claims are respected. Before scheduler.start
706
740
  // so recovered tasks are back in the queue for the first dispatch cycle.
707
741
  await recoverOrphanedClaims().catch((e) => log.error(`recoverOrphanedClaims failed: ${e.message}`));
708
742
  // --- Rate-limit recovery (ordered; must run after threadStore.load) ---
@@ -759,8 +793,10 @@ process.on('SIGTERM', async () => {
759
793
  prewarmPiBackend();
760
794
  startClientManager(parseInt(process.env.CORTEX_CLIENT_PORT || '3002', 10));
761
795
  startClientHotReloadJob(getSettings().clientHotReloadEnabled, () => initClientHotReload((text) => { void emitSystemNotice(adapter, { text }); }), startAllRemoteClients);
762
- // DR-0013: server auto-update — first check after 60s, then every 24h
763
- setTimeout(async () => {
796
+ // DR-0013: server auto-update — first check after 60s, then every 24h.
797
+ // Both timers are unref'd so they never hold the process open, and the default latest-version
798
+ // probe is async (runFile), so neither blocks the event loop.
799
+ const bootUpdateCheck = setTimeout(async () => {
764
800
  try {
765
801
  await checkServerUpdate({ prompt: updatePrompt });
766
802
  }
@@ -768,7 +804,8 @@ process.on('SIGTERM', async () => {
768
804
  log.error(`Server auto-update check failed: ${e.message}`);
769
805
  }
770
806
  }, 60_000);
771
- setInterval(async () => {
807
+ bootUpdateCheck.unref?.();
808
+ const dailyUpdateCheck = setInterval(async () => {
772
809
  try {
773
810
  await checkServerUpdate({ prompt: updatePrompt });
774
811
  }
@@ -776,6 +813,7 @@ process.on('SIGTERM', async () => {
776
813
  log.error(`Server auto-update check failed: ${e.message}`);
777
814
  }
778
815
  }, 24 * 60 * 60 * 1000);
816
+ dailyUpdateCheck.unref?.();
779
817
  await scheduler.start();
780
818
  // One-time migration: resume tasks left paused by the old scheduler-based rate-limit mechanism.
781
819
  // The new provider-aware rate-limit-throttle no longer pauses tasks via the scheduler guard.
@@ -820,6 +858,9 @@ process.on('SIGTERM', async () => {
820
858
  // Periodic disk-driven backstop: recover any manager left suspended on a child task that is
821
859
  // already terminal on disk but whose event/settle delivery was lost to a race (2026-06-29).
822
860
  startWaitingManagerSweep();
861
+ // Same shape, for waitpoints: drains the signal spool, ages out expired waitpoints and retries
862
+ // any wake whose delivery failed. Every in-memory fast path dies with the process; this does not.
863
+ startWaitpointSweep();
823
864
  startBuiltinJobs(adapter);
824
865
  void emitCortexEvent('cortex:server.start', {
825
866
  version: CORTEX_VERSION,
@@ -1,7 +1,7 @@
1
1
  // input: auth status, shared login service, terminal interaction
2
2
  // output: localized runAuthLoginCli with abortable secret prompts and safe results
3
3
  // pos: TTY provider login without a running daemon
4
- // >>> Once I am updated, be sure to update my header comment and the parent folder CORTEX.md <<<
4
+ // >>> Once I am updated, be sure to update my header comment and the parent folder AGENTS.md <<<
5
5
  import { randomUUID } from 'node:crypto';
6
6
  import { formatHelp } from '../core/cli-utils.js';
7
7
  import { t } from '../core/i18n.js';
@@ -1,7 +1,7 @@
1
1
  // input: clack prompts, fixed Claude installer, login notices
2
2
  // output: localized, secret-safe terminal UI and confirmed Claude installation
3
3
  // pos: Terminal adapter for provider onboarding
4
- // >>> Once I am updated, be sure to update my header comment and the parent folder CORTEX.md <<<
4
+ // >>> Once I am updated, be sure to update my header comment and the parent folder AGENTS.md <<<
5
5
  import * as clack from '@clack/prompts';
6
6
  import { t } from '../core/i18n.js';
7
7
  import { execSync } from 'node:child_process';
@@ -4,6 +4,12 @@ import type { PlatformAdapter } from '../platform/index.js';
4
4
  export interface DaemonMessage {
5
5
  type?: string;
6
6
  text?: string;
7
+ /** 'rebuild-hold': whether new turns must be refused. */
8
+ hold?: boolean;
9
+ /** 'rebuild-hold': the pipeline step in flight, when the supervisor named one. */
10
+ phase?: string | null;
11
+ /** 'rebuild-hold': what triggered the rebuild. */
12
+ reason?: string | null;
7
13
  }
8
14
  /** Broadcast a supervisor-side notice to the admin channel and the Web toaster.
9
15
  *
@@ -13,5 +19,8 @@ export interface DaemonMessage {
13
19
  * change is invisible until someone notices. Logging alone made that failure silent. */
14
20
  export declare function handleDaemonMessage(msg: DaemonMessage | undefined | null, adapter: PlatformAdapter): Promise<boolean>;
15
21
  /** Wire the fork IPC channel to the notice broadcast. No-op when the process was not forked by
16
- * the daemon (standalone `cortex serve`, tests), where `process.send` is undefined. */
22
+ * the daemon (standalone `cortex serve`, tests), where `process.send` is undefined.
23
+ *
24
+ * `disconnect` lifts any hold: the supervisor that asked for it is gone, so nothing is going to
25
+ * restart this process and refusing work would only strand the operator. */
17
26
  export declare function subscribeDaemonNotices(adapter: PlatformAdapter): void;
@@ -1,4 +1,5 @@
1
1
  import { emitSystemNotice } from '../domain/system/system-notice.js';
2
+ import { holdNewTurns, releaseNewTurnHold } from '../domain/system/rebuild-hold.js';
2
3
  /** Broadcast a supervisor-side notice to the admin channel and the Web toaster.
3
4
  *
4
5
  * Returns whether a notice was emitted, so an unrelated IPC message is distinguishable from a
@@ -6,17 +7,31 @@ import { emitSystemNotice } from '../domain/system/system-notice.js';
6
7
  * install+restart, so the process stays on the previously installed build and every later code
7
8
  * change is invisible until someone notices. Logging alone made that failure silent. */
8
9
  export async function handleDaemonMessage(msg, adapter) {
10
+ // Admission control. Silent on purpose: the operator hears about a rebuild through the daemon page
11
+ // and through the abort notice, and a toast per phase would be noise. Handled without a notice, so
12
+ // it returns before the notice branch below.
13
+ if (msg?.type === 'rebuild-hold') {
14
+ if (msg.hold)
15
+ holdNewTurns({ phase: msg.phase ?? null, reason: msg.reason ?? null });
16
+ else
17
+ releaseNewTurnHold();
18
+ return true;
19
+ }
9
20
  if (msg?.type !== 'rebuild-aborted' || !msg.text)
10
21
  return false;
11
22
  await emitSystemNotice(adapter, { level: 'error', title: 'Rebuild', text: msg.text });
12
23
  return true;
13
24
  }
14
25
  /** Wire the fork IPC channel to the notice broadcast. No-op when the process was not forked by
15
- * the daemon (standalone `cortex serve`, tests), where `process.send` is undefined. */
26
+ * the daemon (standalone `cortex serve`, tests), where `process.send` is undefined.
27
+ *
28
+ * `disconnect` lifts any hold: the supervisor that asked for it is gone, so nothing is going to
29
+ * restart this process and refusing work would only strand the operator. */
16
30
  export function subscribeDaemonNotices(adapter) {
17
31
  if (!process.send)
18
32
  return;
19
33
  process.on('message', (msg) => {
20
34
  void handleDaemonMessage(msg, adapter).catch(() => { });
21
35
  });
36
+ process.on('disconnect', () => { releaseNewTurnHold(); });
22
37
  }
@@ -9,6 +9,18 @@
9
9
  * { type: 'rebuild-aborted', text } — pipeline stopped early; app.ts broadcasts it as an
10
10
  * error-level system notice. The daemon has no platform adapter, so this is its only
11
11
  * way to reach the operator.
12
+ * { type: 'rebuild-hold', hold, phase, reason } — admission control for the last seconds before
13
+ * this process is replaced: while `hold` is true the app refuses to START new turns, because a
14
+ * turn spawned now is orphaned by the SIGTERM. Scope is deliberately narrow — the install and
15
+ * restart steps and a queued restart, never the build (see `rebuildHoldsTurns`). Re-sent on every
16
+ * phase change: the app's hold expires on its own, so a daemon that dies mid-pipeline fails open
17
+ * instead of muting the app forever.
18
+ *
19
+ * Rebuild progress:
20
+ * The pipeline publishes its plan and each step transition to STORE_DIR/daemon-rebuild.json
21
+ * (core/rebuild-progress.ts), which `system.daemonStatus` reads for the daemon page. It is a file
22
+ * and not in-app state on purpose: the pipeline's last act replaces the process that would have
23
+ * held it, so only a file can tell the new app what the rebuild it was born from did.
12
24
  *
13
25
  * Restart serialization:
14
26
  * Only ONE restart cycle (stop → start) runs at a time. Concurrent requests
@@ -31,9 +43,21 @@
31
43
  * types and web typechecks against ui-contract's built dist, so skipping the middle package
32
44
  * makes web fail on every newly added server DTO.
33
45
  *
46
+ * Every step is paid on every rebuild, including a web build that a server-only edit almost
47
+ * never changes, so the cost of each is kept down at the package level rather than by skipping
48
+ * steps here: both tsconfigs carry an incremental cache, and web's `build` runs its typecheck
49
+ * and its bundle concurrently. The server's cache lives inside dist/ on purpose — tsc trusts
50
+ * its buildinfo over the filesystem, so a cache that outlived its output would let a deleted
51
+ * dist file stay deleted.
52
+ *
34
53
  * Any step failing → log + notify the operator + skip (no restart), so an abort never looks
35
- * like a no-op restart. busy/idle gating is reused: a rebuild during an in-flight Slack
36
- * request defers the final restart() step until the child reports idle.
54
+ * like a no-op restart.
55
+ *
56
+ * busy/idle gating is checked twice, because only the tail of the pipeline is dangerous to a live
57
+ * turn. Once before the build, and again after it: the build takes minutes, so a turn can have
58
+ * started meanwhile, and everything past that point replaces the files app.js is running from and
59
+ * then kills it. A busy child there parks the reason in `pendingRebuild` and the whole pipeline
60
+ * runs again on the idle transition — waiting for real work to finish, rather than refusing it.
37
61
  *
38
62
  * Manual upgrade workflow (still supported):
39
63
  * npm run build && npm pack && npm install -g ./cortex-agent-server-X.Y.Z.tgz (package: @cortex-agent/server)
@@ -41,6 +65,7 @@
41
65
  * watcher below picks up. In dev mode (CORTEX_REPO set) this triggers the full
42
66
  * rebuild pipeline; in production mode it just respawns app.js.
43
67
  */
68
+ import { type RebuildProgress, type RebuildStepName } from '../core/rebuild-progress.js';
44
69
  declare function buildChildProcessConfig(restartReason?: string | null): {
45
70
  cwd: string;
46
71
  stdio: ("pipe" | "ignore" | "ipc")[];
@@ -72,5 +97,21 @@ export declare function buildRebuildAbortNotice(p: {
72
97
  detail: string;
73
98
  reason: string;
74
99
  }): string;
100
+ /** Which published states close the child's turn gate.
101
+ *
102
+ * Only the two steps that touch the running process: `install` overwrites the files app.js loaded,
103
+ * `restart` kills it. The build steps before them read the repo and write `dist/` — a turn running
104
+ * during those is in no danger, and refusing it would be worse than useless: a refused waitpoint
105
+ * wake or background-agent result is dropped work, not delayed work (2026-09-21). Those two steps
106
+ * are only entered when app.ts is idle anyway, so the gate exists for the tick-level race — a
107
+ * message landing between the idle check and the SIGTERM.
108
+ *
109
+ * A queued restart (`pendingRestart`) holds regardless of the record: the build is over, but the
110
+ * process a turn would run in is still going to be replaced. */
111
+ export declare function rebuildHoldsTurns(progress: Pick<RebuildProgress, 'status' | 'current'> | null, queuedRestart: boolean): boolean;
112
+ /** The steps a checkout will actually run, in order. Derived from `planRebuildSteps` so the build
113
+ * half cannot drift — a package that is absent is never published as pending — plus the two phases
114
+ * the build planner does not own. */
115
+ export declare function planRebuildStepNames(dirs: Parameters<typeof planRebuildSteps>[0]): RebuildStepName[];
75
116
  declare function main(): void;
76
117
  export { main, buildChildProcessConfig };
@@ -9,6 +9,18 @@
9
9
  * { type: 'rebuild-aborted', text } — pipeline stopped early; app.ts broadcasts it as an
10
10
  * error-level system notice. The daemon has no platform adapter, so this is its only
11
11
  * way to reach the operator.
12
+ * { type: 'rebuild-hold', hold, phase, reason } — admission control for the last seconds before
13
+ * this process is replaced: while `hold` is true the app refuses to START new turns, because a
14
+ * turn spawned now is orphaned by the SIGTERM. Scope is deliberately narrow — the install and
15
+ * restart steps and a queued restart, never the build (see `rebuildHoldsTurns`). Re-sent on every
16
+ * phase change: the app's hold expires on its own, so a daemon that dies mid-pipeline fails open
17
+ * instead of muting the app forever.
18
+ *
19
+ * Rebuild progress:
20
+ * The pipeline publishes its plan and each step transition to STORE_DIR/daemon-rebuild.json
21
+ * (core/rebuild-progress.ts), which `system.daemonStatus` reads for the daemon page. It is a file
22
+ * and not in-app state on purpose: the pipeline's last act replaces the process that would have
23
+ * held it, so only a file can tell the new app what the rebuild it was born from did.
12
24
  *
13
25
  * Restart serialization:
14
26
  * Only ONE restart cycle (stop → start) runs at a time. Concurrent requests
@@ -31,9 +43,21 @@
31
43
  * types and web typechecks against ui-contract's built dist, so skipping the middle package
32
44
  * makes web fail on every newly added server DTO.
33
45
  *
46
+ * Every step is paid on every rebuild, including a web build that a server-only edit almost
47
+ * never changes, so the cost of each is kept down at the package level rather than by skipping
48
+ * steps here: both tsconfigs carry an incremental cache, and web's `build` runs its typecheck
49
+ * and its bundle concurrently. The server's cache lives inside dist/ on purpose — tsc trusts
50
+ * its buildinfo over the filesystem, so a cache that outlived its output would let a deleted
51
+ * dist file stay deleted.
52
+ *
34
53
  * Any step failing → log + notify the operator + skip (no restart), so an abort never looks
35
- * like a no-op restart. busy/idle gating is reused: a rebuild during an in-flight Slack
36
- * request defers the final restart() step until the child reports idle.
54
+ * like a no-op restart.
55
+ *
56
+ * busy/idle gating is checked twice, because only the tail of the pipeline is dangerous to a live
57
+ * turn. Once before the build, and again after it: the build takes minutes, so a turn can have
58
+ * started meanwhile, and everything past that point replaces the files app.js is running from and
59
+ * then kills it. A busy child there parks the reason in `pendingRebuild` and the whole pipeline
60
+ * runs again on the idle transition — waiting for real work to finish, rather than refusing it.
37
61
  *
38
62
  * Manual upgrade workflow (still supported):
39
63
  * npm run build && npm pack && npm install -g ./cortex-agent-server-X.Y.Z.tgz (package: @cortex-agent/server)
@@ -50,6 +74,7 @@ import { createResilientWatchMonitor } from '../core/resilient-watch.js';
50
74
  import { isMainModule, moduleDir, DATA_DIR, CONFIG_DIR, STORE_DIR, INSTALL_ROOT } from '../core/utils.js';
51
75
  import { planFastInstall, applyFastInstall } from './fast-install.js';
52
76
  import { tryAcquireSingletonLock, releaseSingletonLock as releaseLock } from '../core/singleton-lock.js';
77
+ import { finishRebuildStep, planRebuildProgress, settleRebuildProgress, startRebuildStep, writeRebuildProgress, } from '../core/rebuild-progress.js';
53
78
  // Load .env BEFORE reading any CORTEX_* env vars below. Mirrors app.ts §61 — the
54
79
  // daemon needs CORTEX_REPO (and potentially other vars) from .env, not just from
55
80
  // the OS shell env. Must be sync and before the `CORTEX_REPO` constant below.
@@ -98,6 +123,7 @@ let restarting = false; // true while restart() stop→start cycle is in progres
98
123
  let rebuilding = false; // true while runRebuildPipeline() is running
99
124
  let nextRestartReason = null; // forwarded to next child via CORTEX_RESTART_REASON
100
125
  let watchMonitors = [];
126
+ let rebuildProgress = null; // published pipeline state (file + child IPC)
101
127
  // Daemon logs are written by the centralized logger (src/core/log.ts)
102
128
  // — console + daily-rotating file output in DATA_DIR/logs/.
103
129
  // --- Cancel all pending restart timers ---
@@ -239,23 +265,39 @@ function stopChild() {
239
265
  c.kill('SIGTERM');
240
266
  });
241
267
  }
268
+ /**
269
+ * Stop the child and start a fresh one. Resolves once the replacement has been forked.
270
+ *
271
+ * Returns 'deferred' when the cycle did not run: the child was mid-request, or another cycle owns
272
+ * the stop→start, and `pendingRestart` now carries the reason to the next idle transition. Callers
273
+ * that report progress need that distinction — a deferred restart leaves the OLD process serving.
274
+ *
275
+ * The child is told to hold new turns before anything else happens, including on the deferred
276
+ * paths: a restart that is waiting for idle wants the child to drain, not to take more work.
277
+ */
242
278
  async function restart(reason) {
243
279
  // Defer if child is busy processing a request
244
280
  if (childBusy) {
245
281
  log.info(`Restart deferred (app.ts is busy): ${reason}`);
246
282
  pendingRestart = reason;
247
- return;
283
+ holdChildTurns(true, 'restart', reason);
284
+ return 'deferred';
248
285
  }
249
286
  // Serialize: only one stop→start cycle at a time
250
287
  if (restarting) {
251
288
  log.info(`Restart deferred (already restarting): ${reason}`);
252
289
  pendingRestart = reason;
253
- return;
290
+ holdChildTurns(true, 'restart', reason);
291
+ return 'deferred';
254
292
  }
255
293
  cancelPendingTimers();
256
294
  log.info(`Restarting: ${reason}`);
257
295
  backoff = BACKOFF_INITIAL;
258
296
  restarting = true;
297
+ // The window this closes is the one that orphaned a turn on 2026-09-21: app.ts reported idle, the
298
+ // daemon began the stop, and a message landing in the same tick spawned a CLI whose stdout owner
299
+ // died a moment later. Between this line and SIGTERM the child admits nothing new.
300
+ holdChildTurns(true, 'restart', reason);
259
301
  await stopChild();
260
302
  restarting = false;
261
303
  // Absorb any restarts requested during the stop phase —
@@ -266,6 +308,7 @@ async function restart(reason) {
266
308
  }
267
309
  nextRestartReason = reason;
268
310
  startChild();
311
+ return 'restarted';
269
312
  }
270
313
  // --- File Watching ---
271
314
  function closeWatchers(watchers) {
@@ -496,10 +539,84 @@ function notifyChild(msg) {
496
539
  }
497
540
  catch { /* child went away — the log line still records it */ }
498
541
  }
499
- /** Single exit point for every pipeline abort: log it AND tell the operator. */
542
+ /** Tell the child to stop admitting new turns (or to resume). Sent on every phase change so the
543
+ * child's hold, which expires on its own, keeps being renewed for as long as the pipeline runs.
544
+ * A turn admitted after this point would be spawned into a process that is about to be SIGTERMed:
545
+ * its CLI child outlives the app that owns its stdout, so the answer is written to a pipe nobody
546
+ * is reading and the turn never completes. */
547
+ function holdChildTurns(hold, phase, reason) {
548
+ notifyChild({ type: 'rebuild-hold', hold, phase, reason });
549
+ }
550
+ /** Which published states close the child's turn gate.
551
+ *
552
+ * Only the two steps that touch the running process: `install` overwrites the files app.js loaded,
553
+ * `restart` kills it. The build steps before them read the repo and write `dist/` — a turn running
554
+ * during those is in no danger, and refusing it would be worse than useless: a refused waitpoint
555
+ * wake or background-agent result is dropped work, not delayed work (2026-09-21). Those two steps
556
+ * are only entered when app.ts is idle anyway, so the gate exists for the tick-level race — a
557
+ * message landing between the idle check and the SIGTERM.
558
+ *
559
+ * A queued restart (`pendingRestart`) holds regardless of the record: the build is over, but the
560
+ * process a turn would run in is still going to be replaced. */
561
+ export function rebuildHoldsTurns(progress, queuedRestart) {
562
+ if (queuedRestart)
563
+ return true;
564
+ if (!progress || progress.status !== 'running')
565
+ return false;
566
+ return progress.current === 'install' || progress.current === 'restart';
567
+ }
568
+ /** Publish pipeline state: keep it in memory, on disk for `system.daemonStatus`, and in the child's
569
+ * turn gate. One function so a phase can never reach one reader and not the others. */
570
+ function setRebuildProgress(next) {
571
+ rebuildProgress = next;
572
+ writeRebuildProgress(next);
573
+ const queuedRestart = pendingRestart !== null;
574
+ holdChildTurns(rebuildHoldsTurns(next, queuedRestart), next.current ?? (queuedRestart ? 'restart' : null), next.reason);
575
+ }
576
+ /** The steps a checkout will actually run, in order. Derived from `planRebuildSteps` so the build
577
+ * half cannot drift — a package that is absent is never published as pending — plus the two phases
578
+ * the build planner does not own. */
579
+ export function planRebuildStepNames(dirs) {
580
+ const names = planRebuildSteps(dirs).map((step) => step.label);
581
+ return [...names, 'install', 'restart'];
582
+ }
583
+ /** `planRebuildStepNames` for this process's checkout. */
584
+ function plannedProgressSteps() {
585
+ return planRebuildStepNames({
586
+ repoDir: CORTEX_REPO,
587
+ uiContractDir: UI_CONTRACT_DIR && existsSync(UI_CONTRACT_DIR) ? UI_CONTRACT_DIR : null,
588
+ webDir: WEB_DIR && existsSync(WEB_DIR) ? WEB_DIR : null,
589
+ });
590
+ }
591
+ /** The pipeline's last step, with the progress record closed out according to what restart() did. */
592
+ async function restartForRebuild(reason) {
593
+ updateRebuildProgress((progress) => startRebuildStep(progress, 'restart'));
594
+ const outcome = await restart(`src rebuild: ${reason}`);
595
+ updateRebuildProgress((progress) => (outcome === 'restarted'
596
+ ? settleRebuildProgress(finishRebuildStep(progress, 'restart', 'done'), 'succeeded')
597
+ : settleRebuildProgress(finishRebuildStep(progress, 'restart', 'skipped', 'app.ts busy'), 'deferred', 'Build and install succeeded; the restart is queued until app.ts goes idle.')));
598
+ }
599
+ /** Advance the published progress, if a pipeline is being tracked at all. */
600
+ function updateRebuildProgress(patch) {
601
+ if (!rebuildProgress)
602
+ return;
603
+ setRebuildProgress(patch(rebuildProgress));
604
+ }
605
+ /** Map an abort's step label onto the published step vocabulary. `tgz cleanup` and `pack` are
606
+ * phases of the same install step from the reader's point of view. */
607
+ function progressStepFor(label) {
608
+ if (label === 'server' || label === 'ui-contract' || label === 'web' || label === 'install')
609
+ return label;
610
+ if (label === 'pack' || label === 'tgz cleanup')
611
+ return 'install';
612
+ return null;
613
+ }
614
+ /** Single exit point for every pipeline abort: log it, mark the step failed, tell the operator. */
500
615
  function abortRebuild(step, detail, reason) {
501
616
  const text = buildRebuildAbortNotice({ step, detail, reason });
502
617
  log.error(text);
618
+ const failed = progressStepFor(step);
619
+ updateRebuildProgress((progress) => settleRebuildProgress(failed ? finishRebuildStep(progress, failed, 'failed', detail) : progress, 'aborted', text));
503
620
  notifyChild({ type: 'rebuild-aborted', text });
504
621
  }
505
622
  /** Run the ordered build steps. Returns false once any step fails (already reported). */
@@ -513,11 +630,16 @@ async function runBuildSteps(reason) {
513
630
  log.warn('WEB_DIR not found — skipping web build, pack will use stale web/dist if present');
514
631
  }
515
632
  for (const step of steps) {
633
+ const tracked = progressStepFor(step.label);
634
+ if (tracked)
635
+ updateRebuildProgress((progress) => startRebuildStep(progress, tracked));
516
636
  const code = await spawnAsync(step.cmd, step.args, { cwd: step.cwd });
517
637
  if (code !== 0) {
518
638
  abortRebuild(step.label, `exit ${code}`, reason);
519
639
  return false;
520
640
  }
641
+ if (tracked)
642
+ updateRebuildProgress((progress) => finishRebuildStep(progress, tracked, 'done'));
521
643
  }
522
644
  return true;
523
645
  }
@@ -601,19 +723,42 @@ async function runRebuildPipeline(reason) {
601
723
  return;
602
724
  }
603
725
  rebuilding = true;
726
+ let awaitingIdle = false;
604
727
  try {
605
728
  log.info(`Rebuild pipeline starting: ${reason}`);
729
+ // Publishing the plan before the first step is what makes the progress honest: the reader gets
730
+ // the total up front, including the steps that have not started.
731
+ setRebuildProgress(planRebuildProgress({
732
+ reason,
733
+ names: plannedProgressSteps(),
734
+ daemonPid: process.pid,
735
+ }));
606
736
  // Step 1: build the workspace packages in dependency order (server → ui-contract → web).
607
737
  if (!await runBuildSteps(reason))
608
738
  return;
739
+ // Second busy gate. The build above is minutes long and touches nothing the running child
740
+ // reads, so a turn can legitimately have started during it — and everything below does touch
741
+ // it: the install overwrites the files app.js loaded, the restart kills it. Rather than refuse
742
+ // that turn (a refused waitpoint wake or background-agent result is dropped work, not delayed
743
+ // work), abandon the install and let the idle transition run the whole pipeline again. The
744
+ // build outputs stay on disk, so the retry is the incremental cost of a second `npm run build`.
745
+ if (childBusy) {
746
+ log.info(`Rebuild install deferred (app.ts busy): ${reason} — retrying when app.ts goes idle`);
747
+ pendingRebuild = reason;
748
+ awaitingIdle = true;
749
+ updateRebuildProgress((progress) => settleRebuildProgress(progress, 'deferred', 'Build finished; install and restart wait for app.ts to go idle.'));
750
+ return;
751
+ }
609
752
  // Step 2: fast install. A src edit changes only the compiled output, so copying it into the
610
753
  // install root is equivalent to reinstalling — and skips rewriting the ~40k-file vendored
611
754
  // closure that `npm install -g` rm -rf's and re-extracts on every rebuild.
612
755
  const started = Date.now();
756
+ updateRebuildProgress((progress) => startRebuildStep(progress, 'install'));
613
757
  const synced = tryFastInstall();
614
758
  if (synced) {
615
759
  log.info(`Fast install: ${synced.join(', ')} in ${Date.now() - started}ms — restarting app.ts`);
616
- restart(`src rebuild: ${reason}`);
760
+ updateRebuildProgress((progress) => finishRebuildStep(progress, 'install', 'done', 'fast'));
761
+ await restartForRebuild(reason);
617
762
  return;
618
763
  }
619
764
  // Step 3: pack (clean old tgz first, otherwise readdir picks up a stale one)
@@ -628,17 +773,26 @@ async function runRebuildPipeline(reason) {
628
773
  abortRebuild('install', `exit ${installCode}`, reason);
629
774
  return;
630
775
  }
776
+ updateRebuildProgress((progress) => finishRebuildStep(progress, 'install', 'done', 'pack + install -g'));
631
777
  // Step 5: restart app.ts. This reuses the busy/idle gate inside restart() —
632
778
  // if a request snuck in between the busy-check above and now, restart() will
633
779
  // re-defer to pendingRestart. Either way, the new app.js boots from the freshly
634
780
  // installed dist/.
635
781
  log.info(`Rebuild succeeded — restarting app.ts`);
636
- restart(`src rebuild: ${reason}`);
782
+ await restartForRebuild(reason);
637
783
  }
638
784
  finally {
785
+ // An aborted pipeline already settled its own record; a run that reached here still `running`
786
+ // never restarted the child either, so releasing the hold is the honest close.
787
+ if (rebuildProgress?.status === 'running') {
788
+ setRebuildProgress(settleRebuildProgress(rebuildProgress, 'aborted', 'pipeline ended without restarting app.ts'));
789
+ }
790
+ rebuildProgress = null;
639
791
  rebuilding = false;
640
- // If src changed again while we were rebuilding, pick that up now.
641
- if (pendingRebuild) {
792
+ // If src changed again while we were rebuilding, pick that up now. A pipeline that deferred its
793
+ // own install is the one exception: its reason stays queued for the idle transition, because
794
+ // re-triggering here would rebuild every couple of seconds for as long as the turn lasts.
795
+ if (pendingRebuild && !awaitingIdle) {
642
796
  const next = pendingRebuild;
643
797
  pendingRebuild = null;
644
798
  log.info(`Consuming queued rebuild: ${next}`);
@@ -1,7 +1,7 @@
1
1
  // input: auth snapshots, login CLI and terminal choices
2
2
  // output: localized init authentication choices, usable backends and cancellation
3
3
  // pos: Small shared init provider onboarding coordinator
4
- // >>> Once I am updated, be sure to update my header comment and the parent folder CORTEX.md <<<
4
+ // >>> Once I am updated, be sure to update my header comment and the parent folder AGENTS.md <<<
5
5
  import { defaultLoginDeps, LoginCliError, runAuthLoginCli } from './auth-login-cli.js';
6
6
  import { t } from '../core/i18n.js';
7
7
  export function usableBackends(snapshot) {
@@ -1166,15 +1166,15 @@ function safeCopyDir(srcDir, dstDir, force) {
1166
1166
  // ─── Config copy & generation ──────────────────────────────────
1167
1167
  function copyDefaults(paths, force) {
1168
1168
  // Scaffold files — never overwrite (user-customized content)
1169
- safeCopy(path.join(DEFAULTS_DIR, 'CORTEX.md'), path.join(paths.DATA_DIR, 'CORTEX.md'), false, 'CORTEX.md');
1169
+ safeCopy(path.join(DEFAULTS_DIR, 'AGENTS.md'), path.join(paths.DATA_DIR, 'AGENTS.md'), false, 'AGENTS.md');
1170
1170
  safeCopy(path.join(DEFAULTS_DIR, 'gitignore'), path.join(paths.DATA_DIR, '.gitignore'), false, '.gitignore');
1171
1171
  safeCopy(path.join(DEFAULTS_DIR, '.claude', 'settings.json'), path.join(paths.DATA_DIR, '.claude', 'settings.json'), false, '.claude/settings.json');
1172
1172
  // Context scaffold files — never overwrite
1173
- safeCopy(path.join(DEFAULTS_DIR, 'context', 'CORTEX.md'), path.join(paths.CONTEXT_DIR, 'CORTEX.md'), false, 'context/CORTEX.md');
1174
- safeCopy(path.join(DEFAULTS_DIR, 'context', 'projects', 'CORTEX.md'), path.join(paths.PROJECTS_DIR, 'CORTEX.md'), false, 'context/projects/CORTEX.md');
1175
- safeCopy(path.join(DEFAULTS_DIR, 'context', 'scans', 'CORTEX.md'), path.join(paths.CONTEXT_DIR, 'scans', 'CORTEX.md'), false, 'context/scans/CORTEX.md');
1176
- safeCopy(path.join(DEFAULTS_DIR, 'context', 'ideas', 'CORTEX.md'), path.join(paths.CONTEXT_DIR, 'ideas', 'CORTEX.md'), false, 'context/ideas/CORTEX.md');
1177
- safeCopy(path.join(DEFAULTS_DIR, 'context', 'user', 'CORTEX.md'), path.join(paths.CONTEXT_DIR, 'user', 'CORTEX.md'), false, 'context/user/CORTEX.md');
1173
+ safeCopy(path.join(DEFAULTS_DIR, 'context', 'AGENTS.md'), path.join(paths.CONTEXT_DIR, 'AGENTS.md'), false, 'context/AGENTS.md');
1174
+ safeCopy(path.join(DEFAULTS_DIR, 'context', 'projects', 'AGENTS.md'), path.join(paths.PROJECTS_DIR, 'AGENTS.md'), false, 'context/projects/AGENTS.md');
1175
+ safeCopy(path.join(DEFAULTS_DIR, 'context', 'scans', 'AGENTS.md'), path.join(paths.CONTEXT_DIR, 'scans', 'AGENTS.md'), false, 'context/scans/AGENTS.md');
1176
+ safeCopy(path.join(DEFAULTS_DIR, 'context', 'ideas', 'AGENTS.md'), path.join(paths.CONTEXT_DIR, 'ideas', 'AGENTS.md'), false, 'context/ideas/AGENTS.md');
1177
+ safeCopy(path.join(DEFAULTS_DIR, 'context', 'user', 'AGENTS.md'), path.join(paths.CONTEXT_DIR, 'user', 'AGENTS.md'), false, 'context/user/AGENTS.md');
1178
1178
  // Config defaults — budget overwrites only with --force;
1179
1179
  // thread-templates are merged per-file (new agents/templates/shells added, existing preserved)
1180
1180
  safeCopy(path.join(DEFAULTS_DIR, 'config', 'budget.json'), path.join(paths.CONFIG_DIR, 'budget.json'), force, 'budget.json');