@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
@@ -62,6 +62,10 @@ function isChromeLine(line) {
62
62
  return line === '' || line === '# Notes' || line === FORMAT_MARKER || line === PRIVACY_MARKER
63
63
  || line === '## Active' || line === '## Completed';
64
64
  }
65
+ function excerpt(line) {
66
+ const text = line.trim();
67
+ return text.length > 60 ? `${text.slice(0, 60)}...` : text;
68
+ }
65
69
  export function parseNotesMarkdown(md) {
66
70
  if (!md.includes(FORMAT_MARKER))
67
71
  throw invalidFile('Unsupported NOTES.md format');
@@ -71,8 +75,13 @@ export function parseNotesMarkdown(md) {
71
75
  const line = lines[index];
72
76
  if (isChromeLine(line))
73
77
  continue;
74
- if (!line.startsWith(META_PREFIX))
75
- throw invalidFile(`Unexpected NOTES.md content at line ${index + 1}`);
78
+ // Strict on purpose: this file is machine-owned, and quietly skipping a line we do not
79
+ // understand would silently delete it on the next write. The excerpt is what makes the refusal
80
+ // actionable — hand-written prose appended below the notes is the one way this ever happens.
81
+ if (!line.startsWith(META_PREFIX)) {
82
+ throw invalidFile(`Unexpected NOTES.md content at line ${index + 1}: ${JSON.stringify(excerpt(line))}. `
83
+ + 'NOTES.md is written by the notes UI only — move hand-written text to another file.');
84
+ }
76
85
  notes.push(parseEntry(lines, index));
77
86
  index += 1;
78
87
  }
@@ -77,7 +77,7 @@ export const MANAGER_TASK_FILE_REPLACEMENTS = [
77
77
  export const STATUS_REGISTER_REPLACEMENTS = [
78
78
  [
79
79
  "Record findings, decisions, and artifacts in files as you go — not in a final summary. Update STATUS.md, the directory's CORTEX.md index, and the role's designated output artifact(s) before exiting.",
80
- "Record findings, decisions, and artifacts in files as you go — not in a final summary. Update the role's designated output artifact(s) and the directory's CORTEX.md index before exiting. Update STATUS.md only if your work changed the project's situation (unblocked something, introduced a blocker, changed the next step) — STATUS is a state register, not a changelog; one line + pointer per change (see rules/status-md.md).",
80
+ "Record findings, decisions, and artifacts in files as you go — not in a final summary. Update the role's designated output artifact(s) and the directory's AGENTS.md index before exiting. Update STATUS.md only if your work changed the project's situation (unblocked something, introduced a blocker, changed the next step) — STATUS is a state register, not a changelog; one line + pointer per change (see rules/status-md.md).",
81
81
  ],
82
82
  [
83
83
  "Prefer editing the existing project artifacts (STATUS.md, knowledge entries, the role's artifact file) over creating parallel new files.",
@@ -6,7 +6,7 @@
6
6
  // whitelist/replay contract stays the single source of truth for what a field means.
7
7
  // pos: Migration helper invoked as a step migration from store/version-migrations.ts (B.T4).
8
8
  // Idempotent via the rename: a second run finds no sources and is a no-op.
9
- // >>> Once I am updated, be sure to update my header comment and the parent folder CORTEX.md <<<
9
+ // >>> Once I am updated, be sure to update my header comment and the parent folder AGENTS.md <<<
10
10
  import * as fs from 'node:fs/promises';
11
11
  import * as path from 'node:path';
12
12
  import { createLogger } from '../core/log.js';
@@ -27,6 +27,10 @@ export interface SessionRecord {
27
27
  lastUsedAt: string;
28
28
  label: string | null;
29
29
  profileName: string | null;
30
+ /** The agent template this session runs as — its execution environment (prompt, tools, skills,
31
+ * rules), the twin of `profileName` on the model axis. Absent/null means the session follows its
32
+ * channel's selection, and beneath that the global default. */
33
+ agentName?: string | null;
30
34
  backendSessionId?: string | null;
31
35
  lastReadAt?: string | null;
32
36
  scheduleId?: string | null;
@@ -3,7 +3,7 @@
3
3
  // (records + channel bindings + per-CHANNEL conversation header & turn history;
4
4
  // events: put/patch/delete-*/bind/unbind/turn/conversation)
5
5
  // pos: Low-level journal I/O for session registry state — the single owner of session identity
6
- // >>> Once I am updated, be sure to update my header comment and the parent folder CORTEX.md <<<
6
+ // >>> Once I am updated, be sure to update my header comment and the parent folder AGENTS.md <<<
7
7
  import fs from 'node:fs';
8
8
  import fsp from 'node:fs/promises';
9
9
  import path from 'node:path';
@@ -214,6 +214,7 @@ function normalizeLegacyRecord(name, channelMap, raw) {
214
214
  lastUsedAt: toStringValue(raw.lastUsedAt),
215
215
  label,
216
216
  profileName: toNullableString(raw.profileName),
217
+ agentName: toOptionalNullableString(raw.agentName),
217
218
  backendSessionId: toOptionalNullableString(raw.backendSessionId),
218
219
  lastReadAt: toOptionalNullableString(raw.lastReadAt),
219
220
  scheduleId: toOptionalNullableString(raw.scheduleId),
@@ -356,6 +357,7 @@ function assertSessionRecord(raw, expectedId) {
356
357
  lastUsedAt: toStringValue(row?.lastUsedAt),
357
358
  label: toNullableString(row?.label),
358
359
  profileName: toNullableString(row?.profileName),
360
+ agentName: toOptionalNullableString(row?.agentName),
359
361
  backendSessionId: toOptionalNullableString(row?.backendSessionId),
360
362
  lastReadAt: toOptionalNullableString(row?.lastReadAt),
361
363
  scheduleId: toOptionalNullableString(row?.scheduleId),
@@ -383,6 +385,7 @@ function assertNewFormatRecord(raw, expectedId) {
383
385
  lastUsedAt: toStringValue(row?.lastUsedAt),
384
386
  label,
385
387
  profileName: toNullableString(row?.profileName),
388
+ agentName: toOptionalNullableString(row?.agentName),
386
389
  backendSessionId: toOptionalNullableString(row?.backendSessionId),
387
390
  lastReadAt: toOptionalNullableString(row?.lastReadAt),
388
391
  scheduleId: toOptionalNullableString(row?.scheduleId),
@@ -475,6 +478,7 @@ const PATCH_FIELD_READERS = {
475
478
  lastUsedAt: toStringValue,
476
479
  label: toNullableString,
477
480
  profileName: toNullableString,
481
+ agentName: toOptionalNullableString,
478
482
  backendSessionId: toOptionalNullableString,
479
483
  lastReadAt: toOptionalNullableString,
480
484
  scheduleId: toOptionalNullableString,
@@ -15,7 +15,7 @@ export interface PendingDeletion {
15
15
  }
16
16
  export type SessionRegistryData = Record<string, Session>;
17
17
  export type SessionRegistryRepoOptions = SessionRegistryJournalOptions;
18
- type UpdateFields = Partial<Pick<Session, 'lastUsedAt' | 'label' | 'profileName' | 'backendSessionId' | 'contextUsage' | 'browser'>> & {
18
+ type UpdateFields = Partial<Pick<Session, 'lastUsedAt' | 'label' | 'profileName' | 'agentName' | 'backendSessionId' | 'contextUsage' | 'browser'>> & {
19
19
  sessionId?: never;
20
20
  };
21
21
  export interface RegisterSessionOpts {
@@ -27,6 +27,7 @@ export interface RegisterSessionOpts {
27
27
  projectId?: string;
28
28
  label?: string | null;
29
29
  profileName?: string | null;
30
+ agentName?: string | null;
30
31
  backendSessionId?: string | null;
31
32
  scheduleId?: string | null;
32
33
  browser?: SessionBrowserOption | null;
@@ -2,7 +2,7 @@
2
2
  // output: SessionRegistryRepo JSONL-backed registry and admission APIs
3
3
  // (patch-delta updates, channel bindings + conduit resolvers, turn history, batch())
4
4
  // pos: Stable session identity store with delete-intent guards
5
- // >>> Once I am updated, be sure to update my header comment and the parent folder CORTEX.md <<<
5
+ // >>> Once I am updated, be sure to update my header comment and the parent folder AGENTS.md <<<
6
6
  import * as crypto from 'node:crypto';
7
7
  import * as path from 'node:path';
8
8
  import { isDeepStrictEqual } from 'node:util';
@@ -111,6 +111,7 @@ export class SessionRegistryRepo {
111
111
  lastUsedAt: now,
112
112
  label: trimLabel(opts.label),
113
113
  profileName: opts.profileName ?? null,
114
+ agentName: opts.agentName ?? null,
114
115
  backendSessionId: opts.backendSessionId ?? null,
115
116
  scheduleId: opts.scheduleId ?? null,
116
117
  browser: opts.browser ?? null,
@@ -143,6 +144,7 @@ export class SessionRegistryRepo {
143
144
  lastUsedAt: updates.lastUsedAt ?? current.lastUsedAt,
144
145
  label: updates.label !== undefined ? trimLabel(updates.label) : current.label,
145
146
  profileName: updates.profileName !== undefined ? updates.profileName : current.profileName,
147
+ agentName: updates.agentName !== undefined ? updates.agentName : current.agentName,
146
148
  backendSessionId: updates.backendSessionId !== undefined
147
149
  ? updates.backendSessionId
148
150
  : current.backendSessionId,
@@ -29,13 +29,16 @@ export declare class TaskRepo {
29
29
  * Wait for any in-flight `runExclusive` / mutation to drain.
30
30
  * Acquire-release the mutex; FIFO ordering guarantees all preceding
31
31
  * operations have completed when this resolves.
32
- * Git sync is synchronous so it's always done by the time mutex releases.
32
+ * Mutations await `commitAndPush` inside the mutex, so git sync is always done by the time
33
+ * the mutex releases.
33
34
  * Known limitation: asyncPush errors may be lost during SIGTERM drain —
34
35
  * matching current task-store.ts behavior.
35
36
  */
36
37
  flush(): Promise<void>;
37
- /** Commit TASKS.yaml changes and push to origin/main */
38
- commitAndPush(message: string): void;
38
+ /** Commit TASKS.yaml changes and push to origin/main.
39
+ * Async: git runs on the shared event loop, so the three commands are awaited instead of
40
+ * blocking every session/socket in the process (they used to run via execSync). */
41
+ commitAndPush(message: string): Promise<void>;
39
42
  private asyncPush;
40
43
  }
41
44
  export declare const taskStore: TaskRepo;
@@ -3,7 +3,8 @@
3
3
  // pos: Serialized coordination center for TASKS.yaml changes. Based on core/AsyncMutex + atomicWrite (Pattern B)
4
4
  // S4: mutation shim methods removed, now lives in domain/tasks/mutator.ts
5
5
  import * as path from 'path';
6
- import { execSync, execFileSync, spawn } from 'child_process';
6
+ import { spawn } from 'child_process';
7
+ import { runFile } from '../core/exec-async.js';
7
8
  import { PROJECTS_DIR, DATA_DIR } from '../core/utils.js';
8
9
  import { scanAllTasks, scanAvailableTasks, getTaskStatsFromTasks, } from '../core/task-parser.js';
9
10
  import { createLogger } from '../core/log.js';
@@ -87,7 +88,8 @@ export class TaskRepo {
87
88
  * Wait for any in-flight `runExclusive` / mutation to drain.
88
89
  * Acquire-release the mutex; FIFO ordering guarantees all preceding
89
90
  * operations have completed when this resolves.
90
- * Git sync is synchronous so it's always done by the time mutex releases.
91
+ * Mutations await `commitAndPush` inside the mutex, so git sync is always done by the time
92
+ * the mutex releases.
91
93
  * Known limitation: asyncPush errors may be lost during SIGTERM drain —
92
94
  * matching current task-store.ts behavior.
93
95
  */
@@ -95,19 +97,33 @@ export class TaskRepo {
95
97
  await this.taskMutex.run(async () => { });
96
98
  }
97
99
  // --- Git sync ---
98
- /** Commit TASKS.yaml changes and push to origin/main */
99
- commitAndPush(message) {
100
+ /** Commit TASKS.yaml changes and push to origin/main.
101
+ * Async: git runs on the shared event loop, so the three commands are awaited instead of
102
+ * blocking every session/socket in the process (they used to run via execSync). */
103
+ async commitAndPush(message) {
100
104
  if (this.skipGit)
101
105
  return;
102
106
  try {
103
107
  const rel = path.relative(DATA_DIR, PROJECTS_DIR);
104
108
  const glob = `${rel}/*/TASKS.yaml`;
105
- execSync(`git add "${glob}"`, { cwd: DATA_DIR, timeout: 10000 });
106
- const status = execSync(`git status --porcelain -- "${glob}"`, {
107
- cwd: DATA_DIR, encoding: 'utf8', timeout: 5000,
108
- }).trim();
109
- if (status) {
110
- execFileSync('git', ['commit', '-m', message], { cwd: DATA_DIR, timeout: 10000 });
109
+ const added = await runFile('git', ['add', glob], { cwd: DATA_DIR, timeoutMs: 10000 });
110
+ if (!added.ok) {
111
+ log.error(`Git add failed: ${(added.stderr || added.stdout || added.error || '').trim()}`);
112
+ return;
113
+ }
114
+ const status = await runFile('git', ['status', '--porcelain', '--', glob], {
115
+ cwd: DATA_DIR, timeoutMs: 5000,
116
+ });
117
+ if (!status.ok) {
118
+ log.error(`Git status failed: ${(status.stderr || status.error || '').trim()}`);
119
+ return;
120
+ }
121
+ if (status.stdout.trim()) {
122
+ const committed = await runFile('git', ['commit', '-m', message], { cwd: DATA_DIR, timeoutMs: 10000 });
123
+ if (!committed.ok) {
124
+ log.error(`Git commit failed: ${(committed.stderr || committed.stdout || '').trim()}`);
125
+ return;
126
+ }
111
127
  log.info(`Committed: ${message}`);
112
128
  this.asyncPush();
113
129
  }
@@ -42,6 +42,11 @@ export declare function upsertMarkerBlock(content: string, block: string): strin
42
42
  * customized away from the shipped wording simply won't match and is left untouched,
43
43
  * preserving their edits. */
44
44
  export declare function applyReplacements(content: string, pairs: ReadonlyArray<readonly [string, string]>): string;
45
+ export declare function renameMemoryFilesToAgentsMd(dataDir: string): Promise<number>;
46
+ /** Rename `rules/cortex-md.md` → `rules/agents-md.md` and repair references to it across `rules/`.
47
+ * Returns the number of rule files whose content changed. Never clobbers an existing
48
+ * `agents-md.md`; a no-op on a fresh install, where `init` seeded the new name already. */
49
+ export declare function renameIndexRuleFile(dataDir: string): Promise<number>;
45
50
  /** Exported for plugin-retirement.ts, which guards its own one-shot rewrite with a sentinel key
46
51
  * in the same versions.json. Keeping one reader means one definition of "corrupt → reset". */
47
52
  export declare function loadVersionsFrom(filePath: string): Promise<Record<string, string>>;
@@ -72,12 +77,17 @@ export declare function migrateAistatusConfigLocation(dataDir: string, dstPath?:
72
77
  /**
73
78
  * Delete hooks Cortex no longer ships from an existing install.
74
79
  *
75
- * All three current members were unreachable by construction rather than merely unused. The
80
+ * The first three members were unreachable by construction rather than merely unused. The
76
81
  * AskUserQuestion / ExitPlanMode bridge hooks matched native tools that headless `-p` strips from
77
82
  * the session whatever `--tools` lists (plan approval and questions now run through the
78
83
  * interaction-bridge MCP tools against the same webhook endpoints), and the PermissionRequest
79
84
  * auto-allow matched an event Claude never emits under the `bypassPermissions` mode every Cortex
80
- * spawn runs in. `syncManagedHooks` only adds and upgrades files, so without this the dead entries
81
- * would linger in every upgraded registry. Idempotent, and a no-op once the files are gone.
85
+ * spawn runs in. The last two are a rename: the CORTEX.md injector became the AGENTS.md injector
86
+ * under new filenames, and leaving the old pair deployed would double every injection.
87
+ * `syncManagedHooks` only adds and upgrades files, so without this the dead entries would linger
88
+ * in every upgraded registry. Idempotent, and a no-op once the files are gone.
89
+ *
90
+ * Entries go first and scripts second: two entries can share one script, so a script is only
91
+ * orphaned once every entry that ran it is gone.
82
92
  */
83
93
  export declare function removeRetiredDefaultHooks(dataDir: string): Promise<void>;
@@ -30,14 +30,14 @@ export function compareCalVer(a, b) {
30
30
  return aDay - bDay;
31
31
  }
32
32
  // ── Marker-block helpers (text migrations) ─────────────────────
33
- // Text migrations edit human-owned markdown (system prompts, CORTEX.md) without
33
+ // Text migrations edit human-owned markdown (system prompts, AGENTS.md) without
34
34
  // clobbering user customizations: a versioned, marker-delimited block is upserted
35
35
  // (replaced in place if present, appended otherwise). Bumping the block version token
36
36
  // makes a future migration replace an older block cleanly.
37
37
  const DOCS_BLOCK_VERSION = 'v1';
38
38
  const DOCS_MARKER_START = `<!-- cortex:docs ${DOCS_BLOCK_VERSION} -->`;
39
39
  const DOCS_MARKER_END = '<!-- /cortex:docs -->';
40
- /** The canonical Cortex-docs block inserted into system prompts and CORTEX.md. */
40
+ /** The canonical Cortex-docs block inserted into system prompts and AGENTS.md. */
41
41
  const DOCS_BLOCK = [
42
42
  DOCS_MARKER_START,
43
43
  '# Cortex documentation',
@@ -267,7 +267,7 @@ const migrations = [
267
267
  return out;
268
268
  },
269
269
  },
270
- // M4: Inject the Cortex usage-docs block into the user's system prompts and CORTEX.md.
270
+ // M4: Inject the Cortex usage-docs block into the user's system prompts and AGENTS.md.
271
271
  // These are user-owned copies seeded at `cortex init` with force=false, so editing the
272
272
  // shipped defaults only reaches new installs — existing installs need this migration to
273
273
  // pick up the docs URL. Uses upsertMarkerBlock (text format) so the block is inserted
@@ -275,7 +275,7 @@ const migrations = [
275
275
  // and fresh installs (whose seeded files already carry the block from defaults) match the
276
276
  // existing-block branch and are left unchanged. New files skip gracefully via ENOENT.
277
277
  ...[
278
- 'CORTEX.md',
278
+ 'AGENTS.md',
279
279
  'prompts/systemPrompts/direct.md',
280
280
  'prompts/systemPrompts/web.md',
281
281
  'prompts/systemPrompts/web-opus-4-6.md',
@@ -423,7 +423,213 @@ const stepMigrations = [
423
423
  version: '2026.9.14',
424
424
  run: async ({ storeDir }) => { await importLegacySessionStores(storeDir, { version: '2026.9.14' }); },
425
425
  },
426
+ // S2: relocate browser credentials without parsing or logging their contents.
427
+ // Never merge/overwrite a destination: it may already reflect revoked sessions.
428
+ {
429
+ key: 'data/ui-sessions.json',
430
+ version: '2026.9.15',
431
+ run: async ({ dataDir, storeDir }) => {
432
+ const source = path.join(dataDir, 'ui-sessions.json');
433
+ const destination = path.join(storeDir, 'ui-sessions.json');
434
+ try {
435
+ await fs.lstat(destination);
436
+ return; // Keep the legacy source on conflict (including dangling symlinks).
437
+ }
438
+ catch (error) {
439
+ if (error.code !== 'ENOENT')
440
+ throw error;
441
+ }
442
+ try {
443
+ await fs.chmod(source, 0o600);
444
+ }
445
+ catch (error) {
446
+ if (error.code === 'ENOENT')
447
+ return;
448
+ throw error;
449
+ }
450
+ await fs.mkdir(storeDir, { recursive: true });
451
+ try {
452
+ // COPYFILE_EXCL also protects a destination created after the check above.
453
+ // copyFile preserves the source mode, so credentials are never written world-readable.
454
+ await fs.copyFile(source, destination, fs.constants.COPYFILE_EXCL);
455
+ }
456
+ catch (error) {
457
+ if (error.code === 'EEXIST')
458
+ return;
459
+ throw error;
460
+ }
461
+ await fs.unlink(source);
462
+ },
463
+ },
464
+ // S3: rename every CORTEX.md / CORTEX.local.md in the data dir to AGENTS.md / AGENTS.local.md.
465
+ // Claude Code and PI both load AGENTS.md natively now, so the memory file adopts the name the
466
+ // backends already look for instead of one only Cortex knew about. Without this an upgraded
467
+ // install keeps a tree full of CORTEX.md that nothing reads.
468
+ //
469
+ // Skips `tmp/` (scratch workspaces and checked-out clones, not ours to rewrite) and
470
+ // `data/plugin-runtime/` (regenerated plugin snapshots). Never clobbers: where a destination
471
+ // already exists both files are left in place and the collision is logged, so a hand-made
472
+ // AGENTS.md always wins over the file we would have renamed onto it.
473
+ {
474
+ key: 'sentinel:agents-md-rename',
475
+ version: '2026.9.15',
476
+ run: async ({ dataDir }) => { await renameMemoryFilesToAgentsMd(dataDir); },
477
+ },
478
+ // S4: the same rename, for the rule file that describes the convention. `rules/` is seeded by
479
+ // `init` with copy-if-missing and never re-synced, so an upgraded install keeps `cortex-md.md`
480
+ // with its `context/**/CORTEX.md` glob — a glob that now matches nothing, leaving the index size
481
+ // limit silently unenforced — while `status-md-guard.mjs` points `ruleFile` at `rules/agents-md.md`,
482
+ // which does not exist. S3 cannot cover this: it renames files *named* CORTEX.md, and this one is
483
+ // not. Rule files are hand-edited, so the repair is a token substitution rather than a reinstall.
484
+ {
485
+ key: 'sentinel:agents-md-rules-rename',
486
+ version: '2026.9.15',
487
+ run: async ({ dataDir }) => { await renameIndexRuleFile(dataDir); },
488
+ },
489
+ ];
490
+ // ── AGENTS.md rename (S3) ──────────────────────────────────────
491
+ const MEMORY_FILE_RENAMES = [
492
+ ['CORTEX.md', 'AGENTS.md'],
493
+ ['CORTEX.local.md', 'AGENTS.local.md'],
426
494
  ];
495
+ /** Directory names never descended into during the rename walk. `tmp` holds scratch workspaces
496
+ * (including whole git clones with their own memory files) and `data/plugin-runtime` holds
497
+ * regenerated snapshots — rewriting either would be noise at best and destructive at worst. */
498
+ const RENAME_SKIP_DIRS = new Set(['tmp', 'node_modules', '.git', 'plugin-runtime']);
499
+ /** Remove a symlink whose target no longer exists, so it cannot block a rename onto its name.
500
+ * Older installs carry `AGENTS.md -> CLAUDE.md` symlinks left by a long-undone experiment. */
501
+ async function clearDanglingLink(candidate) {
502
+ try {
503
+ const link = await fs.lstat(candidate);
504
+ if (!link.isSymbolicLink())
505
+ return false;
506
+ try {
507
+ await fs.stat(candidate); // resolves → target exists → a real file, leave it
508
+ return false;
509
+ }
510
+ catch (error) {
511
+ if (error.code !== 'ENOENT')
512
+ return false;
513
+ await fs.unlink(candidate);
514
+ log.info(`Removed dangling memory-file symlink: ${candidate}`);
515
+ return true;
516
+ }
517
+ }
518
+ catch {
519
+ return false;
520
+ }
521
+ }
522
+ export async function renameMemoryFilesToAgentsMd(dataDir) {
523
+ let renamed = 0;
524
+ const walk = async (dir) => {
525
+ let dirents;
526
+ try {
527
+ dirents = await fs.readdir(dir, { withFileTypes: true });
528
+ }
529
+ catch {
530
+ return; // unreadable directory — nothing to migrate here
531
+ }
532
+ for (const [from, to] of MEMORY_FILE_RENAMES) {
533
+ if (!dirents.some((entry) => entry.name === from && entry.isFile()))
534
+ continue;
535
+ const source = path.join(dir, from);
536
+ const destination = path.join(dir, to);
537
+ await clearDanglingLink(destination);
538
+ try {
539
+ await fs.lstat(destination);
540
+ log.warn(`Both ${from} and ${to} exist in ${dir}; leaving both untouched`);
541
+ continue;
542
+ }
543
+ catch (error) {
544
+ if (error.code !== 'ENOENT')
545
+ continue;
546
+ }
547
+ try {
548
+ await fs.rename(source, destination);
549
+ renamed += 1;
550
+ }
551
+ catch (error) {
552
+ log.warn(`Could not rename ${source} → ${to}: ${error.message}`);
553
+ }
554
+ }
555
+ for (const entry of dirents) {
556
+ if (!entry.isDirectory() || entry.isSymbolicLink())
557
+ continue;
558
+ if (RENAME_SKIP_DIRS.has(entry.name))
559
+ continue;
560
+ await walk(path.join(dir, entry.name));
561
+ }
562
+ };
563
+ await walk(dataDir);
564
+ if (renamed > 0)
565
+ log.info(`Renamed ${renamed} memory file(s) to the AGENTS.md convention`);
566
+ return renamed;
567
+ }
568
+ // ── Index rule file rename (S4) ────────────────────────────────
569
+ const INDEX_RULE_FROM = 'cortex-md.md';
570
+ const INDEX_RULE_TO = 'agents-md.md';
571
+ /** Rewrite only the two filename tokens the AGENTS.md rename invalidated: `CORTEX.md`, which is the
572
+ * index rule's glob and prose subject, and `cortex-md.md`, which is how sibling rules cite it.
573
+ * Anything else in a hand-edited rule file is left exactly as the user wrote it. */
574
+ function retargetRuleText(text) {
575
+ return text.replaceAll('CORTEX.md', 'AGENTS.md').replaceAll(INDEX_RULE_FROM, INDEX_RULE_TO);
576
+ }
577
+ /** Rename `rules/cortex-md.md` → `rules/agents-md.md` and repair references to it across `rules/`.
578
+ * Returns the number of rule files whose content changed. Never clobbers an existing
579
+ * `agents-md.md`; a no-op on a fresh install, where `init` seeded the new name already. */
580
+ export async function renameIndexRuleFile(dataDir) {
581
+ const rulesDir = path.join(dataDir, 'rules');
582
+ const source = path.join(rulesDir, INDEX_RULE_FROM);
583
+ const destination = path.join(rulesDir, INDEX_RULE_TO);
584
+ try {
585
+ await fs.stat(source);
586
+ let occupied = true;
587
+ try {
588
+ await fs.lstat(destination);
589
+ }
590
+ catch (error) {
591
+ occupied = error.code !== 'ENOENT';
592
+ }
593
+ if (occupied) {
594
+ log.warn(`Both ${INDEX_RULE_FROM} and ${INDEX_RULE_TO} exist in ${rulesDir}; leaving both untouched`);
595
+ }
596
+ else {
597
+ await fs.rename(source, destination);
598
+ log.info(`Renamed ${source} → ${INDEX_RULE_TO}`);
599
+ }
600
+ }
601
+ catch {
602
+ // No old rule file: fresh install, or this step already ran.
603
+ }
604
+ let entries;
605
+ try {
606
+ entries = await fs.readdir(rulesDir);
607
+ }
608
+ catch {
609
+ return 0; // no rules dir — nothing to repair
610
+ }
611
+ let changed = 0;
612
+ for (const entry of entries) {
613
+ if (!entry.endsWith('.md'))
614
+ continue;
615
+ const file = path.join(rulesDir, entry);
616
+ let text;
617
+ try {
618
+ text = await fs.readFile(file, 'utf8');
619
+ }
620
+ catch {
621
+ continue; // unreadable or a directory — skip
622
+ }
623
+ const next = retargetRuleText(text);
624
+ if (next === text)
625
+ continue;
626
+ await atomicWrite(file, next);
627
+ changed += 1;
628
+ }
629
+ if (changed > 0)
630
+ log.info(`Retargeted ${changed} rule file(s) to the AGENTS.md convention`);
631
+ return changed;
632
+ }
427
633
  // ── Versions file I/O ──────────────────────────────────────────
428
634
  /** Exported for plugin-retirement.ts, which guards its own one-shot rewrite with a sentinel key
429
635
  * in the same versions.json. Keeping one reader means one definition of "corrupt → reset". */
@@ -831,17 +1037,17 @@ export async function migrateAistatusConfigLocation(dataDir, dstPath = path.join
831
1037
  log.error(`Failed to migrate aistatus config to ${dstPath}: ${err.message}`);
832
1038
  }
833
1039
  }
834
- // ── Retired shipped hooks ──────────────────────────────────────
835
- /** The managed assets of hooks Cortex used to ship and no longer does, as `config/hooks` entry
836
- * file → the `id` that entry must still carry to be considered ours. */
837
1040
  const RETIRED_HOOK_ENTRIES = [
838
- ['03-ask-user-question-hook.json', 'ask-user-question-hook'],
839
- ['04-exit-plan-mode-hook.json', 'exit-plan-mode-hook'],
840
- ['09-permission-request-auto-allow.json', 'permission-request-auto-allow'],
1041
+ { file: '03-ask-user-question-hook.json', id: 'ask-user-question-hook', script: 'ask-user-question-hook.mjs' },
1042
+ { file: '04-exit-plan-mode-hook.json', id: 'exit-plan-mode-hook', script: 'exit-plan-mode-hook.mjs' },
1043
+ // Ran an inline `run.command`, so there is no script to chase.
1044
+ { file: '09-permission-request-auto-allow.json', id: 'permission-request-auto-allow' },
1045
+ // Renamed, not deleted: the same hook now ships as `agents-md-injector` under 08/10. Sync only
1046
+ // ever adds and upgrades, so without these two rows an upgraded install would run the old
1047
+ // CORTEX.md-named copy alongside the new one and inject every rule file twice.
1048
+ { file: '08-cortex-md-injector-post-tool.json', id: 'cortex-md-injector-post-tool', script: 'cortex-md-injector.mjs' },
1049
+ { file: '10-cortex-md-injector-session-start.json', id: 'cortex-md-injector-session-start', script: 'cortex-md-injector.mjs' },
841
1050
  ];
842
- /** Scripts belonging to a retired entry, deleted alongside it. A retired entry that ran an inline
843
- * `run.command` (the permission auto-allow) has no script and is simply absent here. */
844
- const RETIRED_HOOK_SCRIPTS = ['ask-user-question-hook.mjs', 'exit-plan-mode-hook.mjs'];
845
1051
  async function removeIfPresent(filePath, label) {
846
1052
  try {
847
1053
  await fs.unlink(filePath);
@@ -867,27 +1073,51 @@ async function isShippedRetiredEntry(filePath, id) {
867
1073
  return false;
868
1074
  }
869
1075
  }
1076
+ /** True once every entry that ran `script` is gone from the registry. A surviving file under one
1077
+ * of those names means the user repurposed it, so the script may still be in use and stays. */
1078
+ async function isRetiredScriptOrphaned(registryDir, script) {
1079
+ for (const retired of RETIRED_HOOK_ENTRIES) {
1080
+ if (retired.script !== script)
1081
+ continue;
1082
+ try {
1083
+ await fs.stat(path.join(registryDir, retired.file));
1084
+ return false; // Some entry under that name is still there.
1085
+ }
1086
+ catch (error) {
1087
+ if (error.code !== 'ENOENT')
1088
+ return false;
1089
+ }
1090
+ }
1091
+ return true;
1092
+ }
870
1093
  /**
871
1094
  * Delete hooks Cortex no longer ships from an existing install.
872
1095
  *
873
- * All three current members were unreachable by construction rather than merely unused. The
1096
+ * The first three members were unreachable by construction rather than merely unused. The
874
1097
  * AskUserQuestion / ExitPlanMode bridge hooks matched native tools that headless `-p` strips from
875
1098
  * the session whatever `--tools` lists (plan approval and questions now run through the
876
1099
  * interaction-bridge MCP tools against the same webhook endpoints), and the PermissionRequest
877
1100
  * auto-allow matched an event Claude never emits under the `bypassPermissions` mode every Cortex
878
- * spawn runs in. `syncManagedHooks` only adds and upgrades files, so without this the dead entries
879
- * would linger in every upgraded registry. Idempotent, and a no-op once the files are gone.
1101
+ * spawn runs in. The last two are a rename: the CORTEX.md injector became the AGENTS.md injector
1102
+ * under new filenames, and leaving the old pair deployed would double every injection.
1103
+ * `syncManagedHooks` only adds and upgrades files, so without this the dead entries would linger
1104
+ * in every upgraded registry. Idempotent, and a no-op once the files are gone.
1105
+ *
1106
+ * Entries go first and scripts second: two entries can share one script, so a script is only
1107
+ * orphaned once every entry that ran it is gone.
880
1108
  */
881
1109
  export async function removeRetiredDefaultHooks(dataDir) {
882
1110
  const registryDir = path.join(dataDir, 'config', 'hooks');
883
- for (const [file, id] of RETIRED_HOOK_ENTRIES) {
884
- const entryPath = path.join(registryDir, file);
885
- if (!await isShippedRetiredEntry(entryPath, id))
1111
+ for (const retired of RETIRED_HOOK_ENTRIES) {
1112
+ const entryPath = path.join(registryDir, retired.file);
1113
+ if (!await isShippedRetiredEntry(entryPath, retired.id))
886
1114
  continue;
887
- if (await removeIfPresent(entryPath, 'hook entry')) {
888
- const script = RETIRED_HOOK_SCRIPTS.find((name) => id === name.replace(/\.mjs$/, ''));
889
- if (script)
890
- await removeIfPresent(path.join(dataDir, 'hooks', script), 'hook script');
891
- }
1115
+ await removeIfPresent(entryPath, 'hook entry');
1116
+ }
1117
+ const scripts = new Set(RETIRED_HOOK_ENTRIES.flatMap((r) => (r.script ? [r.script] : [])));
1118
+ for (const script of scripts) {
1119
+ if (!await isRetiredScriptOrphaned(registryDir, script))
1120
+ continue;
1121
+ await removeIfPresent(path.join(dataDir, 'hooks', script), 'hook script');
892
1122
  }
893
1123
  }