@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
@@ -0,0 +1,30 @@
1
+ export interface SignalCliResult {
2
+ exitCode: number;
3
+ stdout: string;
4
+ stderr: string;
5
+ }
6
+ interface ParsedArgs {
7
+ help: boolean;
8
+ id: string | null;
9
+ secret: string | null;
10
+ status: string | null;
11
+ message: string | null;
12
+ data: string | null;
13
+ member: string | null;
14
+ exitCode: string | null;
15
+ url: string | null;
16
+ noSpool: boolean;
17
+ }
18
+ export interface SignalCliOptions {
19
+ env?: NodeJS.ProcessEnv;
20
+ post?: (url: string, body: unknown) => Promise<{
21
+ status: number;
22
+ body: any;
23
+ }>;
24
+ spoolDir?: string;
25
+ writeSpool?: (dir: string, name: string, contents: string) => void;
26
+ }
27
+ export declare function parseSignalArgs(argv: string[]): ParsedArgs;
28
+ export declare function runSignalCli(argv: string[], options?: SignalCliOptions): Promise<SignalCliResult>;
29
+ export declare function main(argv?: string[]): Promise<void>;
30
+ export {};
@@ -0,0 +1,207 @@
1
+ #!/usr/bin/env node
2
+ // input: argv, CORTEX_SIGNAL_ID / CORTEX_SIGNAL_SECRET, WEBHOOK_PORT
3
+ // output: cortex-signal binary — resolve a waitpoint from outside Cortex
4
+ // pos: The emitter half of the waitpoint feature. Deliberately does not launch, supervise or
5
+ // adopt anything: the caller starts their own process however they like and appends one
6
+ // line. If the daemon cannot be reached the signal is spooled to disk instead of lost,
7
+ // which is the same file the daemon (or a device drain) picks up later.
8
+ import * as fs from 'node:fs';
9
+ import * as os from 'node:os';
10
+ import * as path from 'node:path';
11
+ import { formatError, formatHelp, cliError, readStdinSync } from '../core/cli-utils.js';
12
+ import { isMainModule } from '../core/utils.js';
13
+ const HELP = {
14
+ name: 'cortex-signal',
15
+ description: 'Tell Cortex that something it is waiting for has finished.',
16
+ usage: 'cortex-signal [--id wp_…] [--secret …] [--status ok|fail|progress] [--message TEXT] [--exit-code N]',
17
+ options: [
18
+ { flag: '--id <wp_…>', description: 'Waitpoint id', default: '$CORTEX_SIGNAL_ID' },
19
+ { flag: '--secret <hex>', description: 'Capability issued with the waitpoint', default: '$CORTEX_SIGNAL_SECRET' },
20
+ { flag: '--status <s>', description: 'ok | fail | progress', default: 'ok' },
21
+ { flag: '--exit-code <n>', description: 'Set status from a command exit code (0 = ok, else fail)' },
22
+ { flag: '--message <text>', description: 'One-line summary shown in the wake message' },
23
+ { flag: '--member <name>', description: 'Which member of a multi-job waitpoint this is' },
24
+ { flag: '--data <@file|->', description: 'Extra payload from a file or stdin (treated as data, not instructions)' },
25
+ { flag: '--url <url>', description: 'Daemon signal endpoint', default: 'http://127.0.0.1:$WEBHOOK_PORT/webhook/signal' },
26
+ { flag: '--no-spool', description: 'Fail instead of spooling to disk when the daemon is unreachable' },
27
+ { flag: '--help, -h', description: 'Show this help' },
28
+ ],
29
+ examples: [
30
+ { description: 'Report the exit code of the command that just ran', command: 'python train.py; cortex-signal --exit-code $?' },
31
+ { description: 'Report one arm of a multi-job waitpoint', command: 'cortex-signal --member arm2 --status ok --message "33,120 steps"' },
32
+ { description: 'Attach the tail of a log as data', command: 'tail -c 2000 train.log | cortex-signal --exit-code $? --data -' },
33
+ ],
34
+ };
35
+ const VALUE_FLAGS = {
36
+ '--id': 'id',
37
+ '--secret': 'secret',
38
+ '--status': 'status',
39
+ '--message': 'message',
40
+ '--member': 'member',
41
+ '--data': 'data',
42
+ '--exit-code': 'exitCode',
43
+ '--url': 'url',
44
+ };
45
+ const STATUSES = ['ok', 'fail', 'progress'];
46
+ export function parseSignalArgs(argv) {
47
+ const parsed = {
48
+ help: false, id: null, secret: null, status: null, message: null,
49
+ data: null, member: null, exitCode: null, url: null, noSpool: false,
50
+ };
51
+ for (let i = 0; i < argv.length; i += 1) {
52
+ const token = argv[i];
53
+ if (token === '--help' || token === '-h') {
54
+ parsed.help = true;
55
+ continue;
56
+ }
57
+ if (token === '--no-spool') {
58
+ parsed.noSpool = true;
59
+ continue;
60
+ }
61
+ const field = VALUE_FLAGS[token];
62
+ if (!field) {
63
+ throw cliError(formatError(`Unknown argument: '${token}'`, {
64
+ validValues: [...Object.keys(VALUE_FLAGS), '--no-spool', '--help'],
65
+ }));
66
+ }
67
+ const value = argv[i + 1];
68
+ if (value === undefined || (value.startsWith('--') && field !== 'message')) {
69
+ throw cliError(formatError(`${token} requires a value`));
70
+ }
71
+ parsed[field] = value;
72
+ i += 1;
73
+ }
74
+ return parsed;
75
+ }
76
+ /** `--exit-code` is the ergonomic form: one flag turns `$?` into both a status and a message. */
77
+ function resolveStatus(parsed) {
78
+ if (parsed.exitCode !== null) {
79
+ const code = Number.parseInt(parsed.exitCode, 10);
80
+ if (!Number.isFinite(code)) {
81
+ throw cliError(formatError(`--exit-code must be a number, got '${parsed.exitCode}'`));
82
+ }
83
+ const status = parsed.status ?? (code === 0 ? 'ok' : 'fail');
84
+ return { status, message: parsed.message ?? `exit=${code}` };
85
+ }
86
+ const status = parsed.status ?? 'ok';
87
+ if (!STATUSES.includes(status)) {
88
+ throw cliError(formatError(`Invalid --status '${status}'`, { validValues: STATUSES }));
89
+ }
90
+ return { status, message: parsed.message };
91
+ }
92
+ function readData(spec) {
93
+ if (spec === null)
94
+ return undefined;
95
+ if (spec === '-')
96
+ return readStdinSync();
97
+ if (spec.startsWith('@')) {
98
+ const file = spec.slice(1);
99
+ try {
100
+ return fs.readFileSync(file, 'utf8');
101
+ }
102
+ catch (error) {
103
+ throw cliError(formatError(`Cannot read --data file '${file}': ${error.message}`));
104
+ }
105
+ }
106
+ return spec;
107
+ }
108
+ async function httpPost(url, body) {
109
+ const response = await fetch(url, {
110
+ method: 'POST',
111
+ headers: { 'content-type': 'application/json' },
112
+ body: JSON.stringify(body),
113
+ });
114
+ const text = await response.text();
115
+ let parsed = text;
116
+ try {
117
+ parsed = JSON.parse(text);
118
+ }
119
+ catch { /* non-JSON bodies surface as text */ }
120
+ return { status: response.status, body: parsed };
121
+ }
122
+ function defaultSpoolDir(env) {
123
+ const home = env.CORTEX_HOME ? path.resolve(env.CORTEX_HOME) : path.join(os.homedir(), '.cortex');
124
+ return path.join(home, 'tmp', 'signals');
125
+ }
126
+ /** Write-then-rename: a same-directory rename is atomic, so a drain never sees a half file. */
127
+ function writeSpoolFile(dir, name, contents) {
128
+ fs.mkdirSync(dir, { recursive: true });
129
+ const tmp = path.join(dir, `${name}.tmp`);
130
+ fs.writeFileSync(tmp, contents);
131
+ fs.renameSync(tmp, path.join(dir, name));
132
+ }
133
+ export async function runSignalCli(argv, options = {}) {
134
+ const env = options.env ?? process.env;
135
+ try {
136
+ const parsed = parseSignalArgs(argv);
137
+ if (parsed.help || argv.length === 0) {
138
+ return { exitCode: 0, stdout: formatHelp(HELP), stderr: '' };
139
+ }
140
+ const id = parsed.id ?? env.CORTEX_SIGNAL_ID ?? null;
141
+ const secret = parsed.secret ?? env.CORTEX_SIGNAL_SECRET ?? null;
142
+ if (!id || !secret) {
143
+ return {
144
+ exitCode: 2,
145
+ stdout: '',
146
+ stderr: formatError('A waitpoint id and secret are required', {
147
+ hint: 'Pass --id/--secret, or export CORTEX_SIGNAL_ID and CORTEX_SIGNAL_SECRET (wait_create prints both).',
148
+ }),
149
+ };
150
+ }
151
+ const { status, message } = resolveStatus(parsed);
152
+ const payload = { id, secret, status };
153
+ if (message)
154
+ payload.message = message;
155
+ if (parsed.member)
156
+ payload.member = parsed.member;
157
+ const data = readData(parsed.data);
158
+ if (data !== undefined)
159
+ payload.data = data;
160
+ const port = env.WEBHOOK_PORT || '3001';
161
+ const url = parsed.url ?? `http://127.0.0.1:${port}/webhook/signal`;
162
+ const post = options.post ?? httpPost;
163
+ let response;
164
+ try {
165
+ response = await post(url, payload);
166
+ }
167
+ catch (error) {
168
+ // The daemon is down, or this machine has no route to it. Spooling is not a fallback for
169
+ // failure — it is the normal path on a remote device, where the daemon collects the file.
170
+ if (parsed.noSpool) {
171
+ return { exitCode: 1, stdout: '', stderr: formatError(`Cannot reach ${url}: ${error.message}`) };
172
+ }
173
+ const dir = options.spoolDir ?? defaultSpoolDir(env);
174
+ const name = `${Date.now()}-${process.pid}-${Math.random().toString(36).slice(2, 8)}.json`;
175
+ (options.writeSpool ?? writeSpoolFile)(dir, name, JSON.stringify(payload));
176
+ return { exitCode: 0, stdout: `spooled ${path.join(dir, name)}`, stderr: '' };
177
+ }
178
+ if (response.status === 202) {
179
+ const fired = response.body?.fired ? ' (waitpoint fired)' : '';
180
+ return { exitCode: 0, stdout: `accepted${fired}`, stderr: '' };
181
+ }
182
+ if (response.status === 410) {
183
+ // Not an error worth failing a build over: the waitpoint did its job already.
184
+ return { exitCode: 0, stdout: `already resolved (${response.body?.state ?? 'unknown'})`, stderr: '' };
185
+ }
186
+ const detail = typeof response.body === 'object' && response.body?.error ? response.body.error : String(response.body ?? '');
187
+ return { exitCode: 1, stdout: '', stderr: formatError(`Signal refused (HTTP ${response.status}): ${detail}`) };
188
+ }
189
+ catch (error) {
190
+ // cliError() tags usage problems with cliMessage; exit 2 is the usage code (CLI Rule ④).
191
+ const cliMessage = error.cliMessage;
192
+ if (cliMessage)
193
+ return { exitCode: 2, stdout: '', stderr: cliMessage };
194
+ return { exitCode: 1, stdout: '', stderr: error.message };
195
+ }
196
+ }
197
+ export async function main(argv = process.argv.slice(2)) {
198
+ const result = await runSignalCli(argv);
199
+ if (result.stdout)
200
+ process.stdout.write(`${result.stdout}\n`);
201
+ if (result.stderr)
202
+ process.stderr.write(`${result.stderr}\n`);
203
+ process.exitCode = result.exitCode;
204
+ }
205
+ if (isMainModule(import.meta.url)) {
206
+ void main();
207
+ }
@@ -25,7 +25,7 @@ export interface StartUiHttpOptions {
25
25
  verifyAccessJwt?: AccessJwtVerifier;
26
26
  /**
27
27
  * Explicit session store for the browser token-login path. Production builds one backed by
28
- * DATA_DIR/ui-sessions.json; tests inject a memory-only store so they never touch the real file.
28
+ * STORE_DIR/ui-sessions.json; tests inject a memory-only store so they never touch the real file.
29
29
  * Ignored when CORTEX_UI_TOKEN_LOGIN is switched off.
30
30
  */
31
31
  sessionStore?: UiSessionStore;
@@ -19,7 +19,7 @@ import { accessVerifierFromEnv } from '../platform/ui-http/access-jwt.js';
19
19
  import { getClientToken } from '../core/auth.js';
20
20
  import { createLogger } from '../core/log.js';
21
21
  import { getSettings } from '../core/settings.js';
22
- import { WORKSPACE_DIR, DATA_DIR, resolveWorkspaceRelPath } from '../core/paths.js';
22
+ import { WORKSPACE_DIR, STORE_DIR, resolveWorkspaceRelPath } from '../core/paths.js';
23
23
  import { projectStore } from '../domain/projects/project-store.js';
24
24
  import { resolveMemoryFilePath } from '../domain/ui-service/query/memory.js';
25
25
  const log = createLogger('ui-http');
@@ -31,7 +31,7 @@ function isEnabled(env) {
31
31
  return v === '1' || v === 'true' || v === 'on' || v === 'yes';
32
32
  }
33
33
  /** Where browser sessions survive a daemon restart. Written 0600 by the store. */
34
- const SESSIONS_FILE = path.join(DATA_DIR, 'ui-sessions.json');
34
+ const SESSIONS_FILE = path.join(STORE_DIR, 'ui-sessions.json');
35
35
  /**
36
36
  * Token login is ON unless explicitly switched off — a browser reaching this server can log in by
37
37
  * pasting the clientToken once. Opting out (`CORTEX_UI_TOKEN_LOGIN=0`) removes the login routes and
@@ -190,13 +190,6 @@ export type CortexEvent = {
190
190
  ts: string;
191
191
  executionId: string;
192
192
  reason: string;
193
- } | {
194
- type: 'execution.log';
195
- ts: string;
196
- executionId: string;
197
- seq: number;
198
- lines: string[];
199
- dropped?: number;
200
193
  } | {
201
194
  type: 'auth.required';
202
195
  ts: string;
@@ -1,33 +1,45 @@
1
1
  #!/usr/bin/env node
2
- // @cortex-hook-version 2026.8.7 ← set to the current release version (agent-server/package.json) whenever you change this hook; syncManagedHooks then refreshes deployed installs
2
+ // @cortex-hook-version 2026.9.15 ← set to the current release version (agent-server/package.json) whenever you change this hook; syncManagedHooks then refreshes deployed installs
3
3
  // input: stdin JSON — Claude Code hook event or PI hook-bridge payload; or runHook(payload, env)
4
4
  // output: { hookSpecificOutput: { hookEventName, additionalContext, matched } }
5
5
  // Exported `runHook` is the in-process entry point: the PI hook bridge calls it directly
6
6
  // instead of spawning this file, so every path here takes its scope from the `env`
7
7
  // argument rather than process.env (one daemon process serves many sessions).
8
- // pos: Inject CORTEX.md / CORTEX.local.md ancestor chain into agent context
8
+ // pos: Inject the AGENTS.md / AGENTS.local.md ancestor chain that THE BACKEND DOES NOT LOAD.
9
+ // Both backends load AGENTS.md natively now, so this hook only covers their blind spots
10
+ // (see backendLoadsNatively below for the measured matrix):
11
+ // · paths outside the session cwd tree — neither backend loads these
12
+ // · AGENTS.local.md, anywhere — neither backend has a `.local` name
13
+ // · descendants of cwd, on PI — PI walks cwd→root only, never downward
14
+ // Anything the backend already loaded is recorded in the dedup cache WITHOUT being
15
+ // injected, so the agent never receives the same rules twice.
9
16
  // 2-event dispatch:
10
17
  // PostToolUse (Read|Edit) — from tool_input.file_path/path
11
18
  // SessionStart (startup|resume|clear|compact) — from payload.cwd
12
19
  // Shared per-session cache with remote MCP injection under tmp/cortexmd-cache
13
20
  // — stable session + physical host + path + mtime dedup across tool families
14
21
  // — only files actually injected are marked seen; truncated files stay eligible
15
- // markOnlyPaths: exact CORTEX.md tool target → cache update only, no duplicate
22
+ // markOnlyPaths: exact AGENTS.md tool target → cache update only, no duplicate
16
23
  // Total length guard at 9,500 chars; files that overflow the budget are turned into an
17
24
  // explicit "Read EACH of these files now" instruction instead of a silent drop
18
- // >>> If I am updated, be sure to update my header comment and the CORTEX.md in the same folder <<<
25
+ // >>> If I am updated, be sure to update my header comment and the AGENTS.md in the same folder <<<
19
26
 
20
27
  import {
21
28
  closeSync, existsSync, mkdirSync, openSync, readFileSync,
22
29
  renameSync, rmSync, statSync, writeFileSync,
23
30
  } from 'fs';
24
- import { join, resolve, dirname, basename } from 'path';
31
+ import { join, resolve, dirname, basename, sep } from 'path';
25
32
  import { homedir, hostname } from 'os';
26
33
  import { fileURLToPath } from 'url';
27
34
 
28
35
  const HOSTNAME = hostname();
29
36
  const HOST_ID = HOSTNAME.toLowerCase();
30
- const CORTEX_MD_NAMES = ['CORTEX.md', 'CORTEX.local.md'];
37
+ const AGENTS_MD_NAMES = ['AGENTS.md', 'AGENTS.local.md'];
38
+ /** Names neither backend loads on its own — always ours to inject. */
39
+ const LOCAL_ONLY_NAMES = new Set(['AGENTS.local.md']);
40
+ /** Claude's AGENTS.md fallback is all-or-nothing: a single CLAUDE.md anywhere in the cwd
41
+ * ancestor chain makes it load THAT family and ignore every AGENTS.md. */
42
+ const CLAUDE_MD_NAMES = ['CLAUDE.md', 'CLAUDE.local.md', join('.claude', 'CLAUDE.md')];
31
43
  const MAX_FILE_SIZE = 200 * 1024;
32
44
  const MAX_DEPTH = 20;
33
45
  const MAX_CONTEXT_CHARS = 9500;
@@ -40,7 +52,7 @@ const SESSION_ID_RE = /^[A-Za-z0-9._-]+$/;
40
52
  function hookPaths(env) {
41
53
  const home = env.CORTEX_HOME ? resolve(env.CORTEX_HOME) : join(homedir(), '.cortex');
42
54
  return {
43
- homeFallback: join(home, 'CORTEX.md'),
55
+ homeFallback: join(home, 'AGENTS.md'),
44
56
  cacheDir: join(home, 'tmp', 'cortexmd-cache'),
45
57
  };
46
58
  }
@@ -59,32 +71,34 @@ function tryReadEntry(filePath) {
59
71
  }
60
72
  }
61
73
 
74
+ /** The directory an ancestor walk should start from: the path itself when it is a directory,
75
+ * otherwise its parent (also the right answer for a path that does not exist). */
76
+ function startDir(targetFilePath) {
77
+ const resolved = resolve(targetFilePath);
78
+ try {
79
+ const st = statSync(resolved, { throwIfNoEntry: false });
80
+ return (st && st.isDirectory()) ? resolved : dirname(resolved);
81
+ } catch {
82
+ return dirname(resolved);
83
+ }
84
+ }
85
+
62
86
  /** Walk from the directory containing `targetFilePath` up to the filesystem root,
63
- * collecting CORTEX.md and CORTEX.local.md at each level. Also appends the
64
- * home fallback at ~/.cortex/CORTEX.md if present. Returns leaf→root order.
65
- * If targetFilePath is a directory, scan that directory and its ancestors.
66
- * If it is a file (or does not exist), scan its parent directory and ancestors. */
87
+ * collecting AGENTS.md and AGENTS.local.md at each level. Also appends the
88
+ * home fallback at ~/.cortex/AGENTS.md if present. Returns leaf→root order. */
67
89
  function scanChain(targetFilePath, paths) {
68
90
  const entries = [];
69
91
  const seen = new Set();
70
92
 
71
- let resolved;
72
- try {
73
- resolved = resolve(targetFilePath);
74
- } catch {
75
- return entries;
76
- }
77
-
78
93
  let dir;
79
94
  try {
80
- const st = statSync(resolved, { throwIfNoEntry: false });
81
- dir = (st && st.isDirectory()) ? resolved : dirname(resolved);
95
+ dir = startDir(targetFilePath);
82
96
  } catch {
83
- dir = dirname(resolved);
97
+ return entries;
84
98
  }
85
99
 
86
100
  for (let depth = 0; depth < MAX_DEPTH; depth++) {
87
- for (const name of CORTEX_MD_NAMES) {
101
+ for (const name of AGENTS_MD_NAMES) {
88
102
  const p = join(dir, name);
89
103
  if (seen.has(p)) continue;
90
104
  seen.add(p);
@@ -106,6 +120,66 @@ function scanChain(targetFilePath, paths) {
106
120
  return entries;
107
121
  }
108
122
 
123
+ // ── backend coverage ──
124
+ //
125
+ // Measured against Claude Code 2.1.278 and pi (@earendil-works/pi-coding-agent):
126
+ //
127
+ // memory file location | Claude | PI | ours?
128
+ // --------------------------------+--------+-----+-------
129
+ // ancestor of cwd (incl. cwd) | yes | yes | no
130
+ // descendant of cwd, read by tool | yes | no | PI only
131
+ // outside the cwd tree | no | no | both
132
+ // *.local.md, anywhere | no | no | both
133
+ //
134
+ // Claude resolves its fallback through the `claude-md-or-agents-md` setting, whose default
135
+ // loads AGENTS.md ONLY when no CLAUDE.md exists in the chain — hence the guard below. PI
136
+ // reads ["AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"] per directory, cwd→root, and never
137
+ // descends, so on PI this hook is the only thing that delivers a project's own index file.
138
+
139
+ /** True when a CLAUDE.md-family file sits in the cwd ancestor chain, which switches Claude off
140
+ * the AGENTS.md fallback entirely. Cheap: same walk shape as scanChain, existence checks only. */
141
+ function claudeMdInChain(cwd) {
142
+ let dir;
143
+ try {
144
+ dir = startDir(cwd);
145
+ } catch {
146
+ return false;
147
+ }
148
+ for (let depth = 0; depth < MAX_DEPTH; depth++) {
149
+ for (const name of CLAUDE_MD_NAMES) {
150
+ try {
151
+ if (existsSync(join(dir, name))) return true;
152
+ } catch { /* unreadable — treat as absent */ }
153
+ }
154
+ const parent = dirname(dir);
155
+ if (parent === dir) break;
156
+ dir = parent;
157
+ }
158
+ return false;
159
+ }
160
+
161
+ function isAncestorOrSelf(dir, cwd) {
162
+ return dir === cwd || cwd.startsWith(dir.endsWith(sep) ? dir : dir + sep);
163
+ }
164
+
165
+ function isUnder(dir, cwd) {
166
+ return dir === cwd || dir.startsWith(cwd.endsWith(sep) ? cwd : cwd + sep);
167
+ }
168
+
169
+ /**
170
+ * Whether the backend has already put this entry in the agent's context on its own.
171
+ * Such entries are marked in the dedup cache but never injected — that is the whole point of
172
+ * this hook after both backends gained native AGENTS.md support.
173
+ */
174
+ function backendLoadsNatively(entry, cwd, backend, claudeUsesAgentsMd) {
175
+ if (LOCAL_ONLY_NAMES.has(basename(entry.path))) return false;
176
+ if (!cwd) return false;
177
+ const dir = dirname(entry.path);
178
+ if (backend === 'pi') return isAncestorOrSelf(dir, cwd);
179
+ if (!claudeUsesAgentsMd) return false;
180
+ return isAncestorOrSelf(dir, cwd) || isUnder(dir, cwd);
181
+ }
182
+
109
183
  // ── cache helpers ──
110
184
 
111
185
  function loadCache(sessionId, paths) {
@@ -186,7 +260,7 @@ function buildContext(entries) {
186
260
  // Walk entries in original order (leaf→root), inlining each as a block until the char
187
261
  // budget is exhausted. Once exhausted, the remaining entries are NOT inlined — instead
188
262
  // they are turned into an explicit read-instruction below, so their rules are never
189
- // silently dropped (e.g. a root-level CORTEX.local.md carrying dev/safety rules).
263
+ // silently dropped (e.g. a root-level AGENTS.local.md carrying dev/safety rules).
190
264
  const includedBlocks = [];
191
265
  const includedPaths = [];
192
266
  const truncated = [];
@@ -194,7 +268,7 @@ function buildContext(entries) {
194
268
  let budgetExhausted = false;
195
269
 
196
270
  for (const e of entries) {
197
- const block = `<system-reminder>\nAuto-loaded CORTEX.md from ${HOSTNAME}:${e.path} (ancestor of accessed path). These instructions apply to files under this directory.\n\n${e.content}\n</system-reminder>`;
271
+ const block = `<system-reminder>\nAuto-loaded AGENTS.md from ${HOSTNAME}:${e.path} (ancestor of accessed path, outside the session working directory). These instructions apply to files under this directory.\n\n${e.content}\n</system-reminder>`;
198
272
  if (budgetExhausted || totalLen + block.length > MAX_CONTEXT_CHARS) {
199
273
  budgetExhausted = true; // match prior behavior: stop inlining at the first overflow
200
274
  truncated.push(e);
@@ -212,7 +286,7 @@ function buildContext(entries) {
212
286
  if (truncated.length > 0) {
213
287
  const list = truncated.map(e => `- ${e.path}`).join('\n');
214
288
  parts.push(
215
- `<system-reminder>\n⚠️ ${truncated.length} CORTEX rule file(s) were too large to inline here. ` +
289
+ `<system-reminder>\n⚠️ ${truncated.length} AGENTS rule file(s) were too large to inline here. ` +
216
290
  `Read EACH of the following files now to load their rules before proceeding:\n${list}\n</system-reminder>`
217
291
  );
218
292
  }
@@ -227,6 +301,10 @@ function buildContext(entries) {
227
301
  * Run the hook against one payload and one session environment.
228
302
  * Returns the hook output object, or null when this event injects nothing.
229
303
  * Pure of process state apart from the filesystem, so the PI bridge can call it in-process.
304
+ *
305
+ * SessionStart is deliberately mark-only in the common case: the backend has just loaded the
306
+ * cwd ancestor chain itself, so recording those paths in the shared cache is what stops the
307
+ * first PostToolUse from injecting them a second time.
230
308
  */
231
309
  export function runHook(payload, env = process.env) {
232
310
  const paths = hookPaths(env);
@@ -236,6 +314,10 @@ export function runHook(payload, env = process.env) {
236
314
  const sessionId = stableSessionId && SESSION_ID_RE.test(stableSessionId)
237
315
  ? stableSessionId
238
316
  : payload.session_id;
317
+ // Default to PI, the backend with the SMALLER native coverage. Guessing "claude" for an
318
+ // undeclared spawn would make us skip descendants of cwd that PI never loads — a silent loss of
319
+ // rules. Guessing "pi" only risks injecting something Claude already had: wasteful, never wrong.
320
+ const backend = env.CORTEX_BACKEND?.trim() === 'claude' ? 'claude' : 'pi';
239
321
 
240
322
  let scanRoot = null;
241
323
  if (hookEventName === 'PostToolUse') {
@@ -250,13 +332,22 @@ export function runHook(payload, env = process.env) {
250
332
  const entries = scanChain(scanRoot, paths);
251
333
  if (entries.length === 0) return null;
252
334
 
335
+ const cwd = typeof payload.cwd === 'string' && payload.cwd ? resolve(payload.cwd) : null;
336
+ const claudeUsesAgentsMd = backend === 'claude' && cwd ? !claudeMdInChain(cwd) : false;
337
+
253
338
  const lock = acquireLock(sessionId, paths);
254
339
  try {
255
340
  const cache = loadCache(sessionId, paths);
341
+
342
+ // Paths whose mtime we record without injecting: the file the tool just returned in full,
343
+ // plus everything the backend loaded on its own.
256
344
  const markOnlyPaths = new Set();
257
345
  if (hookEventName === 'PostToolUse') {
258
346
  const targetPath = resolve(payload.tool_input?.file_path || payload.tool_input?.path || '');
259
- if (CORTEX_MD_NAMES.includes(basename(targetPath))) markOnlyPaths.add(targetPath);
347
+ if (AGENTS_MD_NAMES.includes(basename(targetPath))) markOnlyPaths.add(targetPath);
348
+ }
349
+ for (const entry of entries) {
350
+ if (backendLoadsNatively(entry, cwd, backend, claudeUsesAgentsMd)) markOnlyPaths.add(entry.path);
260
351
  }
261
352
 
262
353
  let changed = false;
@@ -1,7 +1,7 @@
1
1
  // input: node:http and Cortex hook environment
2
- // output: askUser helper @cortex-hook-version 2026.8.23
2
+ // output: askUser helper @cortex-hook-version 2026.9.15
3
3
  // pos: Hook script interaction client
4
- // >>> If updated, update this header and the folder CORTEX.md <<<
4
+ // >>> If updated, update this header and the folder AGENTS.md <<<
5
5
 
6
6
  import http from 'node:http';
7
7
 
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- // @cortex-hook-version 2026.6.22-2
2
+ // @cortex-hook-version 2026.9.15-2
3
3
  // input: stdin { channel, sessionId, sessionName, trigger, timestampIso } + env CORTEX_HOOK_*
4
4
  // output: stdout — prompt to inject into the closing session (empty stdout = skip)
5
5
  // pos: !new pre-close memory flush hook — recall valuable user and project info from the session, write to corresponding context files
6
- // >>> If I am updated, be sure to update my header comment and the CORTEX.md in the same folder <<<
6
+ // >>> If I am updated, be sure to update my header comment and the AGENTS.md in the same folder <<<
7
7
 
8
8
  import { execSync } from 'child_process';
9
9
 
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- // @cortex-hook-version 2026.6.22-2
2
+ // @cortex-hook-version 2026.9.15-2
3
3
  // input: stdin JSON — Claude Code PostToolUse event or PI hook-bridge payload
4
4
  // output: { matched: [...], hookSpecificOutput: { additionalContext: "..." } }
5
5
  // pos: Read/Grep hook — check if file path matches scoped rules in ~/.cortex/rules/
6
6
  // On match, return rule content for Claude (additionalContext) and PI (content mutation) injection
7
7
  // Session-level dedup: each rule injected at most once per session (on first match)
8
- // >>> If I am updated, be sure to update my header comment and the CORTEX.md in the same folder <<<
8
+ // >>> If I am updated, be sure to update my header comment and the AGENTS.md in the same folder <<<
9
9
 
10
10
  import { readFileSync, readdirSync, statSync, existsSync, mkdirSync, renameSync, writeFileSync } from 'fs';
11
11
  import { join, resolve, dirname } from 'path';
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
- // @cortex-hook-version 2026.8.2
2
+ // @cortex-hook-version 2026.9.15
3
3
  // input: stdin JSON — Claude Code PreToolUse event payload
4
4
  // output: stdout JSON — { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision, permissionDecisionReason }, systemMessage? }
5
5
  // pos: PreToolUse hook — intercepts Edit/Write on size-capped context files and
6
6
  // enforces their caps (limit table below; rules/status-md.md, rules/issues-md.md,
7
- // rules/cortex-md.md): deny writes whose result exceeds the caps, unless the
7
+ // rules/agents-md.md): deny writes whose result exceeds the caps, unless the
8
8
  // write shrinks an already-over-limit file (so cleanup stays possible); warn
9
9
  // when approaching the cap. Guarded files:
10
10
  // context/projects/<p>/STATUS.md — 80 lines / 6KB (state register)
11
11
  // context/projects/<p>/ISSUES.md — 80 lines / 6KB (friction log)
12
- // CORTEX.md anywhere under a context/ tree — 120 lines / 8KB (injected index)
13
- // >>> If I am updated, be sure to update my header comment and the CORTEX.md in the same folder <<<
12
+ // AGENTS.md anywhere under a context/ tree — 120 lines / 8KB (injected index)
13
+ // >>> If I am updated, be sure to update my header comment and the AGENTS.md in the same folder <<<
14
14
 
15
15
  import { readFileSync, existsSync } from 'fs';
16
16
  import { resolve, sep } from 'path';
@@ -61,16 +61,16 @@ const LIMIT_RULES = [
61
61
  ],
62
62
  },
63
63
  {
64
- name: 'CORTEX.md',
65
- ruleFile: 'rules/cortex-md.md',
66
- matches: (parts) => parts[parts.length - 1] === 'CORTEX.md' && parts.includes('context'),
64
+ name: 'AGENTS.md',
65
+ ruleFile: 'rules/agents-md.md',
66
+ matches: (parts) => parts[parts.length - 1] === 'AGENTS.md' && parts.includes('context'),
67
67
  maxLines: 120,
68
68
  maxBytes: 8 * 1024,
69
69
  warnLines: 90,
70
70
  warnBytes: 6656,
71
71
  capLabel: '120 lines AND 8KB',
72
72
  trimAdvice: [
73
- 'CORTEX.md is an injected index (truncated at 9500 chars): it answers "what is here, where to look", not the content itself. Trim before writing:',
73
+ 'AGENTS.md is a directory index loaded into every agent that works here: it answers "what is here, where to look", not the content itself. Trim before writing:',
74
74
  '- collapse atomic directories (experiments/ knowledge/ patterns/ decisions/) to one line each pointing at their index.md,',
75
75
  '- entry summaries already live in the atomic files and their auto-generated index.md — never duplicate them here,',
76
76
  '- keep each index line to one sentence + pointer (<=200 chars).',