@cortex-agent/server 2026.9.15 → 2026.9.21

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 (192) 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/hooks/{CORTEX.md → AGENTS.md} +1 -1
  6. package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  7. package/defaults/hooks/cortex-hook-api.mjs +2 -2
  8. package/defaults/hooks/new-session-hook.mjs +2 -2
  9. package/defaults/hooks/rules-loader.mjs +2 -2
  10. package/defaults/hooks/status-md-guard.mjs +8 -8
  11. package/defaults/hooks/task-status-check.mjs +18 -76
  12. package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
  13. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
  14. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
  15. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
  16. package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
  17. package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
  18. package/defaults/rules/decision-records.md +1 -1
  19. package/defaults/rules/meta-conventions.md +4 -4
  20. package/defaults/rules/mission-md.md +1 -1
  21. package/dist/agent-adapter/claude/hooks-builder.js +2 -2
  22. package/dist/agent-adapter/claude/spawn-args.js +4 -0
  23. package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
  24. package/dist/agent-adapter/claude/turn-machine.js +46 -5
  25. package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
  26. package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
  27. package/dist/agent-adapter/types.d.ts +1 -0
  28. package/dist/core/mcp-tool-gate.js +1 -0
  29. package/dist/core/media-types.d.ts +10 -0
  30. package/dist/core/media-types.js +34 -0
  31. package/dist/core/platform-settings-spec.js +1 -1
  32. package/dist/core/settings-spec.d.ts +21 -0
  33. package/dist/core/settings-spec.js +28 -1
  34. package/dist/core/types/agent-types.d.ts +3 -1
  35. package/dist/core/utils.d.ts +1 -1
  36. package/dist/core/utils.js +1 -1
  37. package/dist/domain/executions/registry.d.ts +1 -2
  38. package/dist/domain/executions/registry.js +0 -3
  39. package/dist/domain/mcp/bundled-server.js +4 -3
  40. package/dist/domain/mcp/feishu/file.js +37 -18
  41. package/dist/domain/mcp/feishu/types.d.ts +3 -0
  42. package/dist/domain/mcp/feishu-server.js +1 -1
  43. package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
  44. package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
  45. package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
  46. package/dist/domain/mcp/tools/remote-file.js +44 -0
  47. package/dist/domain/mcp/tools/slack.d.ts +2 -0
  48. package/dist/domain/mcp/tools/slack.js +22 -7
  49. package/dist/domain/mcp/tools/task-ops.js +5 -13
  50. package/dist/domain/mcp/tools/ui-file.js +23 -10
  51. package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
  52. package/dist/domain/mcp/tools/waitpoint.js +122 -0
  53. package/dist/domain/memory/agents-md-injector.d.ts +24 -0
  54. package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
  55. package/dist/domain/projects/project-store.d.ts +1 -1
  56. package/dist/domain/projects/project-store.js +3 -3
  57. package/dist/domain/remote/client-hot-reload.js +3 -1
  58. package/dist/domain/remote/client-manager.js +39 -119
  59. package/dist/domain/remote/cortex-client-config.d.ts +1 -1
  60. package/dist/domain/remote/cortex-client-config.js +1 -1
  61. package/dist/domain/remote/device-file.d.ts +51 -0
  62. package/dist/domain/remote/device-file.js +193 -0
  63. package/dist/domain/remote/device-port.js +3 -0
  64. package/dist/domain/remote/reverse-stream.d.ts +18 -7
  65. package/dist/domain/remote/reverse-stream.js +19 -6
  66. package/dist/domain/tasks/claim-recovery.js +2 -2
  67. package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
  68. package/dist/domain/tasks/dispatch-utils.js +46 -1
  69. package/dist/domain/tasks/dispatcher.js +4 -5
  70. package/dist/domain/tasks/mutator.d.ts +2 -2
  71. package/dist/domain/tasks/mutator.js +2 -2
  72. package/dist/domain/tasks/system/task-cli.js +2 -2
  73. package/dist/domain/tasks/system/task-state.js +1 -1
  74. package/dist/domain/threads/runner.js +3 -1
  75. package/dist/domain/ui-service/app-router.d.ts +24 -3
  76. package/dist/domain/ui-service/app-router.js +8 -14
  77. package/dist/domain/ui-service/input-schemas.d.ts +17 -5
  78. package/dist/domain/ui-service/input-schemas.js +13 -9
  79. package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
  80. package/dist/domain/ui-service/mutate/sessions.d.ts +5 -1
  81. package/dist/domain/ui-service/mutate/sessions.js +14 -0
  82. package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
  83. package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
  84. package/dist/domain/ui-service/platform-settings.js +1 -1
  85. package/dist/domain/ui-service/plugins-shared.js +1 -1
  86. package/dist/domain/ui-service/query/config.js +1 -1
  87. package/dist/domain/ui-service/query/executions.js +0 -2
  88. package/dist/domain/ui-service/query/machine-detail.js +3 -8
  89. package/dist/domain/ui-service/query/memory.js +1 -1
  90. package/dist/domain/ui-service/query/sessions.js +7 -0
  91. package/dist/domain/ui-service/query/threads.js +1 -54
  92. package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
  93. package/dist/domain/ui-service/query/waitpoints.js +117 -0
  94. package/dist/domain/ui-service/query-input-schemas.d.ts +3 -0
  95. package/dist/domain/ui-service/query-input-schemas.js +3 -0
  96. package/dist/domain/ui-service/trpc.js +1 -1
  97. package/dist/domain/ui-service/types.d.ts +133 -49
  98. package/dist/domain/ui-service/types.js +1 -1
  99. package/dist/domain/ui-service/ui-service.js +7 -31
  100. package/dist/domain/waitpoints/notices.d.ts +21 -0
  101. package/dist/domain/waitpoints/notices.js +115 -0
  102. package/dist/domain/waitpoints/service.d.ts +91 -0
  103. package/dist/domain/waitpoints/service.js +243 -0
  104. package/dist/entry/app.js +29 -7
  105. package/dist/entry/auth-login-cli.js +1 -1
  106. package/dist/entry/auth-login-terminal.js +1 -1
  107. package/dist/entry/init-auth.js +1 -1
  108. package/dist/entry/init.js +6 -6
  109. package/dist/entry/signal-cli.d.ts +30 -0
  110. package/dist/entry/signal-cli.js +207 -0
  111. package/dist/entry/start-ui-http.d.ts +1 -1
  112. package/dist/entry/start-ui-http.js +2 -2
  113. package/dist/events/event-types.d.ts +0 -7
  114. package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  115. package/dist/hooks/cortex-hook-api.mjs +2 -2
  116. package/dist/hooks/new-session-hook.mjs +2 -2
  117. package/dist/hooks/rules-loader.mjs +2 -2
  118. package/dist/hooks/status-md-guard.mjs +8 -8
  119. package/dist/hooks/task-status-check.mjs +18 -76
  120. package/dist/hooks/tasks-yaml-guard.mjs +2 -2
  121. package/dist/orchestration/agent-file-send.d.ts +9 -0
  122. package/dist/orchestration/agent-file-send.js +21 -2
  123. package/dist/orchestration/agent-runner.d.ts +3 -2
  124. package/dist/orchestration/agent-runner.js +17 -12
  125. package/dist/orchestration/attachments-store.d.ts +31 -0
  126. package/dist/orchestration/attachments-store.js +184 -0
  127. package/dist/orchestration/conversation-request.d.ts +4 -0
  128. package/dist/orchestration/conversation-request.js +13 -6
  129. package/dist/orchestration/interactions/plan-approvals.js +1 -1
  130. package/dist/orchestration/outputs-store.d.ts +11 -0
  131. package/dist/orchestration/outputs-store.js +32 -6
  132. package/dist/orchestration/routing/file-handler.d.ts +23 -2
  133. package/dist/orchestration/routing/file-handler.js +22 -5
  134. package/dist/orchestration/routing/webhook.js +193 -39
  135. package/dist/orchestration/session-gateway.d.ts +1 -1
  136. package/dist/orchestration/session-gateway.js +1 -0
  137. package/dist/orchestration/thread-executor.d.ts +2 -0
  138. package/dist/orchestration/thread-executor.js +11 -1
  139. package/dist/orchestration/thread-input.d.ts +3 -2
  140. package/dist/orchestration/thread-input.js +8 -9
  141. package/dist/orchestration/turn/turn-prep.d.ts +15 -1
  142. package/dist/orchestration/turn/turn-prep.js +19 -8
  143. package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
  144. package/dist/orchestration/waitpoint-ingress.js +172 -0
  145. package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
  146. package/dist/orchestration/waitpoint-notifier.js +119 -0
  147. package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
  148. package/dist/orchestration/waitpoint-remote-drain.js +147 -0
  149. package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
  150. package/dist/orchestration/waitpoint-sweep.js +87 -0
  151. package/dist/platform/adapters/feishu-image.d.ts +19 -0
  152. package/dist/platform/adapters/feishu-image.js +71 -0
  153. package/dist/platform/adapters/feishu.d.ts +2 -0
  154. package/dist/platform/adapters/feishu.js +26 -16
  155. package/dist/platform/ui-http/listening-ports.d.ts +1 -1
  156. package/dist/platform/ui-http/listening-ports.js +1 -1
  157. package/dist/platform/ui-http/ui-session.js +1 -1
  158. package/dist/store/conversation-ledger-repo.js +1 -1
  159. package/dist/store/execution-repo.d.ts +1 -19
  160. package/dist/store/execution-repo.js +1 -18
  161. package/dist/store/project-notes-repo.js +11 -2
  162. package/dist/store/prompt-migration-replacements.js +1 -1
  163. package/dist/store/session-registry-import.js +1 -1
  164. package/dist/store/session-registry-journal.js +1 -1
  165. package/dist/store/session-registry-repo.js +1 -1
  166. package/dist/store/version-migrations.d.ts +13 -3
  167. package/dist/store/version-migrations.js +254 -24
  168. package/dist/store/waitpoint-repo.d.ts +108 -0
  169. package/dist/store/waitpoint-repo.js +94 -0
  170. package/package.json +2 -2
  171. package/web/dist/assets/{index-CRDJo39X.css → index-CwwQNMpP.css} +1 -1
  172. package/web/dist/assets/index-DLSfgq3o.js +444 -0
  173. package/web/dist/assets/{index-CEZ0DSei.js → index-DZTuqUO4.js} +1 -1
  174. package/web/dist/index.html +2 -2
  175. package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
  176. package/dist/domain/executions/log-tailer.d.ts +0 -71
  177. package/dist/domain/executions/log-tailer.js +0 -194
  178. package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
  179. package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
  180. package/dist/domain/memory/cortex-md-scanner.js +0 -66
  181. package/dist/domain/remote/cortex-client.d.ts +0 -1
  182. package/dist/domain/remote/cortex-client.js +0 -662
  183. package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
  184. package/dist/domain/tasks/system/cortex-run.js +0 -360
  185. package/web/dist/assets/index-DjuPJVZE.js +0 -444
  186. /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
  187. /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
  188. /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
  189. /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
  190. /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
  191. /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
  192. /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
@@ -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
  }
@@ -0,0 +1,108 @@
1
+ export declare const WAITPOINTS_FILE: string;
2
+ /** Terminal signals resolve a waitpoint; `progress` is recorded but never resolves one. */
3
+ export type SignalStatus = 'ok' | 'fail' | 'progress';
4
+ export type WaitpointState = 'armed' | 'fired' | 'expired' | 'cancelled';
5
+ /** Where the signal is expected to come from. Drives whether the sweep drains a device's spool dir. */
6
+ export type WaitpointEmitFrom = {
7
+ kind: 'local';
8
+ } | {
9
+ kind: 'device';
10
+ device: string;
11
+ };
12
+ export interface WaitpointOwner {
13
+ /** Cortex session that created it. Diagnostic — delivery is addressed by `channel`. */
14
+ sessionId: string;
15
+ /** The conduit the wake turn is delivered to. Find-or-creates a session if it is gone. */
16
+ channel: string;
17
+ /** Recorded only; v1 never wakes a thread directly. */
18
+ threadId?: string | null;
19
+ project?: string | null;
20
+ }
21
+ export interface WaitpointSignal {
22
+ at: number;
23
+ status: SignalStatus;
24
+ /** Quorum member key this signal counts for. Absent ⇒ an anonymous slot is allocated. */
25
+ member?: string | null;
26
+ message?: string | null;
27
+ data?: unknown;
28
+ /** Free-form provenance for the notice, e.g. `http`, `spool`, `device:cluster`. */
29
+ source: string;
30
+ /** Idempotency key. A second signal carrying a key already present is dropped as a duplicate. */
31
+ dedupeKey?: string | null;
32
+ /** Set once this signal has been folded into a delivered wake notice, so a later wake on the
33
+ * same (mailbox) waitpoint reports only what is new. */
34
+ deliveredAt?: number | null;
35
+ }
36
+ export interface Waitpoint {
37
+ /** `wp_<12 hex>`. Public — appears in notices and logs. */
38
+ id: string;
39
+ /** sha256 of the capability secret. The plaintext is returned once, at creation, and never stored. */
40
+ secretHash: string;
41
+ label: string;
42
+ /** What the agent said it was waiting for. Echoed into the wake notice so a cold turn is self-contained. */
43
+ intent: string;
44
+ owner: WaitpointOwner;
45
+ emitFrom: WaitpointEmitFrom;
46
+ /** `need` terminal signals resolve it. `'all'` means "one per declared member". */
47
+ quorum: {
48
+ need: number | 'all';
49
+ members: string[];
50
+ got: string[];
51
+ };
52
+ /** A `fail` resolves immediately even when the quorum is unmet — "tell me when the first one breaks". */
53
+ failFast: boolean;
54
+ /** How many times it may fire before closing. 1 = one-shot (default); >1 = a mailbox. */
55
+ maxSignals: number;
56
+ fires: number;
57
+ /** Signals landing within this window after the first are folded into one wake notice. */
58
+ coalesceMs: number;
59
+ createdAt: number;
60
+ expiresAt: number;
61
+ /** Set when the waitpoint left `armed`. Echoed on a late signal so the caller can log it. */
62
+ resolvedAt?: number | null;
63
+ state: WaitpointState;
64
+ signals: WaitpointSignal[];
65
+ /** WAL bit: a fire that has not been delivered yet. Replayed at boot and by the sweep. */
66
+ delivery: {
67
+ pending: boolean;
68
+ attempts: number;
69
+ lastError?: string | null;
70
+ lastAt?: number | null;
71
+ };
72
+ /** Wake timestamps, newest last. Sliding-window rate limit input. */
73
+ wakes: number[];
74
+ /** Set once when the rate limit first bites, so the warning notice is emitted exactly once. */
75
+ rateLimitNotified?: boolean;
76
+ }
77
+ /** Shape of waitpoints.json: `{ "wp_…": Waitpoint, … }` */
78
+ export type WaitpointsData = Record<string, Waitpoint>;
79
+ export declare class WaitpointRepo {
80
+ private readonly _repo;
81
+ constructor(opts?: {
82
+ filePath?: string;
83
+ });
84
+ get(id: string): Promise<Waitpoint | null>;
85
+ list(): Promise<Waitpoint[]>;
86
+ listArmed(): Promise<Waitpoint[]>;
87
+ insert(wp: Waitpoint): Promise<void>;
88
+ /**
89
+ * Read-modify-write one waitpoint under the repo mutex. The callback receives the live record and
90
+ * returns `{ next, result }`; returning `next: null` deletes it. Resolves to `null` when the id is
91
+ * unknown, so callers can distinguish "gone" from "handled".
92
+ */
93
+ update<R>(id: string, fn: (wp: Waitpoint) => {
94
+ next: Waitpoint | null;
95
+ result: R;
96
+ }): Promise<R | null>;
97
+ remove(id: string): Promise<void>;
98
+ /** Generic mutate passthrough for composite operations (sweeps touching many records at once). */
99
+ mutate<R>(fn: (data: WaitpointsData) => {
100
+ next: WaitpointsData;
101
+ result: R;
102
+ }): Promise<R>;
103
+ /** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
104
+ flush(): Promise<void>;
105
+ /** Test hook. */
106
+ invalidate(): void;
107
+ }
108
+ export declare const waitpointRepo: WaitpointRepo;
@@ -0,0 +1,94 @@
1
+ // input: waitpoints.json
2
+ // output: WaitpointRepo (get / list / listArmed / insert / update / remove / mutate / flush) + the Waitpoint shape
3
+ // pos: Persistence for waitpoints — durable, externally addressable "wake me when X finishes" objects.
4
+ // A waitpoint is created by an agent, carries its own capability secret, and is resolved by a
5
+ // signal arriving from outside the process (HTTP route, local spool file, or a device spool drain).
6
+ // The shape lives here rather than in domain/ because store/ must not import from domain/ (D10).
7
+ import * as path from 'path';
8
+ import { JsonRepository } from '../core/json-repository.js';
9
+ import { STORE_DIR } from '../core/paths.js';
10
+ export const WAITPOINTS_FILE = path.join(STORE_DIR, 'waitpoints.json');
11
+ function defaultData() {
12
+ return {};
13
+ }
14
+ /**
15
+ * Shape guard. Must be idempotent: JsonRepository runs migrate on every cold read and writes the
16
+ * result straight back when it differs, so a non-idempotent migrate rewrites the file on every boot.
17
+ */
18
+ function migrate(raw) {
19
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
20
+ return defaultData();
21
+ const out = {};
22
+ for (const [id, value] of Object.entries(raw)) {
23
+ if (typeof value !== 'object' || value === null)
24
+ continue;
25
+ const wp = value;
26
+ if (typeof wp.id !== 'string' || typeof wp.secretHash !== 'string')
27
+ continue;
28
+ out[id] = wp;
29
+ }
30
+ return out;
31
+ }
32
+ export class WaitpointRepo {
33
+ _repo;
34
+ constructor(opts = {}) {
35
+ this._repo = new JsonRepository({
36
+ filePath: opts.filePath ?? WAITPOINTS_FILE,
37
+ defaultValue: defaultData,
38
+ migrate,
39
+ });
40
+ }
41
+ async get(id) {
42
+ const data = await this._repo.read();
43
+ return data[id] ?? null;
44
+ }
45
+ async list() {
46
+ return Object.values(await this._repo.read());
47
+ }
48
+ async listArmed() {
49
+ return (await this.list()).filter((wp) => wp.state === 'armed');
50
+ }
51
+ async insert(wp) {
52
+ await this._repo.mutate((data) => {
53
+ data[wp.id] = wp;
54
+ return { next: data, result: undefined };
55
+ });
56
+ }
57
+ /**
58
+ * Read-modify-write one waitpoint under the repo mutex. The callback receives the live record and
59
+ * returns `{ next, result }`; returning `next: null` deletes it. Resolves to `null` when the id is
60
+ * unknown, so callers can distinguish "gone" from "handled".
61
+ */
62
+ async update(id, fn) {
63
+ return this._repo.mutate((data) => {
64
+ const current = data[id];
65
+ if (!current)
66
+ return { next: data, result: null };
67
+ const { next, result } = fn(current);
68
+ if (next === null)
69
+ delete data[id];
70
+ else
71
+ data[id] = next;
72
+ return { next: data, result: result };
73
+ });
74
+ }
75
+ async remove(id) {
76
+ await this._repo.mutate((data) => {
77
+ delete data[id];
78
+ return { next: data, result: undefined };
79
+ });
80
+ }
81
+ /** Generic mutate passthrough for composite operations (sweeps touching many records at once). */
82
+ async mutate(fn) {
83
+ return this._repo.mutate(fn);
84
+ }
85
+ /** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
86
+ flush() {
87
+ return this._repo.flush();
88
+ }
89
+ /** Test hook. */
90
+ invalidate() {
91
+ this._repo.invalidate();
92
+ }
93
+ }
94
+ export const waitpointRepo = new WaitpointRepo();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortex-agent/server",
3
- "version": "2026.9.15",
3
+ "version": "2026.9.21",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Autonomous agent system for long-running projects — mission-driven, multi-agent pipelines, self-evolving skills.",
@@ -12,7 +12,7 @@
12
12
  "cortex": "dist/entry/cortex-cli.js",
13
13
  "cortex-evidence-export": "dist/entry/production-evidence-export-cli.js",
14
14
  "cortex-hook": "dist/entry/hook-cli.js",
15
- "cortex-run": "dist/domain/tasks/system/cortex-run.js",
15
+ "cortex-signal": "dist/entry/signal-cli.js",
16
16
  "cortex-task": "dist/domain/tasks/system/task-cli.js"
17
17
  },
18
18
  "files": [