@cortex-agent/server 2026.6.18 → 2026.6.24

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 (153) hide show
  1. package/defaults/CORTEX.md +5 -0
  2. package/defaults/config/thread-templates.json +12 -6
  3. package/defaults/context/user/CORTEX.md +2 -2
  4. package/defaults/hooks/ask-user-question-hook.mjs +7 -1
  5. package/defaults/hooks/exit-plan-mode-hook.mjs +7 -1
  6. package/defaults/hooks/memory-ref-tracker.mjs +1 -0
  7. package/defaults/hooks/new-session-hook.mjs +1 -0
  8. package/defaults/hooks/post-task-hook.mjs +1 -0
  9. package/defaults/hooks/rules-loader.mjs +1 -0
  10. package/defaults/hooks/sensitive-file-edit.mjs +1 -0
  11. package/defaults/hooks/session-activity-tracker.mjs +1 -0
  12. package/defaults/hooks/task-status-check.mjs +1 -0
  13. package/defaults/hooks/tasks-yaml-guard.mjs +1 -0
  14. package/defaults/plugins/cortex-feishu/.claude-plugin/plugin.json +5 -0
  15. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +163 -0
  16. package/defaults/plugins/cortex-feishu/skills/feishu-doc/scripts/ensure-lark-cli.sh +53 -0
  17. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +7 -0
  18. package/defaults/prompts/directives/coder-reviewer.md +6 -6
  19. package/defaults/prompts/directives/coder.md +14 -15
  20. package/defaults/prompts/systemPrompts/coder.md +6 -1
  21. package/defaults/prompts/systemPrompts/direct.md +5 -0
  22. package/defaults/prompts/systemPrompts/web-opus-4-6.md +6 -1
  23. package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +6 -1
  24. package/defaults/prompts/systemPrompts/web.md +6 -1
  25. package/defaults/prompts/systemPrompts/worker.md +6 -1
  26. package/dist/agent-adapter/claude/adapter-tui.d.ts +12 -0
  27. package/dist/agent-adapter/claude/adapter-tui.js +15 -0
  28. package/dist/agent-adapter/claude/adapter.d.ts +110 -1
  29. package/dist/agent-adapter/claude/adapter.js +123 -2
  30. package/dist/agent-adapter/claude/bg-task-tracker.d.ts +45 -0
  31. package/dist/agent-adapter/claude/bg-task-tracker.js +91 -0
  32. package/dist/agent-adapter/normalize/event-types.d.ts +4 -0
  33. package/dist/agent-adapter/pi/event-parser.d.ts +3 -1
  34. package/dist/agent-adapter/pi/event-parser.js +12 -2
  35. package/dist/agent-adapter/types.d.ts +19 -0
  36. package/dist/core/auth.d.ts +36 -0
  37. package/dist/core/auth.js +85 -0
  38. package/dist/core/gateway-generator.js +10 -1
  39. package/dist/core/locales/en.d.ts +12 -0
  40. package/dist/core/locales/slices/interactions.d.ts +6 -0
  41. package/dist/core/locales/slices/interactions.js +14 -0
  42. package/dist/core/locales/slices/status.d.ts +6 -0
  43. package/dist/core/locales/slices/status.js +16 -0
  44. package/dist/core/status-format.d.ts +14 -0
  45. package/dist/core/status-format.js +23 -1
  46. package/dist/core/types/agent-types.d.ts +5 -0
  47. package/dist/core/types/thread-types.d.ts +15 -1
  48. package/dist/core/version.d.ts +3 -0
  49. package/dist/core/version.js +4 -1
  50. package/dist/domain/agents/facade.d.ts +13 -0
  51. package/dist/domain/agents/facade.js +36 -1
  52. package/dist/domain/costs/rate-limit-throttle.d.ts +1 -1
  53. package/dist/domain/costs/rate-limit-throttle.js +23 -2
  54. package/dist/domain/costs/resume-registry.d.ts +30 -0
  55. package/dist/domain/costs/resume-registry.js +68 -0
  56. package/dist/domain/mcp/core-server.js +5 -0
  57. package/dist/domain/mcp/feishu/index.js +5 -51
  58. package/dist/domain/mcp/feishu-server.js +3 -2
  59. package/dist/domain/mcp/tools/manager-qa.d.ts +2 -0
  60. package/dist/domain/mcp/tools/manager-qa.js +72 -0
  61. package/dist/domain/mcp/tools/task-ops.js +4 -2
  62. package/dist/domain/mcp/tools/thread-ops.js +2 -1
  63. package/dist/domain/mcp/tui-server.js +2 -1
  64. package/dist/domain/memory/user-context.d.ts +6 -5
  65. package/dist/domain/memory/user-context.js +12 -7
  66. package/dist/domain/remote/client-bootstrap.js +14 -2
  67. package/dist/domain/remote/client-hot-reload.d.ts +9 -2
  68. package/dist/domain/remote/client-hot-reload.js +77 -6
  69. package/dist/domain/remote/client-manager.d.ts +1 -1
  70. package/dist/domain/remote/client-manager.js +31 -5
  71. package/dist/domain/remote/cortex-client-config.d.ts +32 -0
  72. package/dist/domain/remote/cortex-client-config.js +49 -0
  73. package/dist/domain/remote/cortex-client.js +11 -7
  74. package/dist/domain/scheduling/jobs/scheduled-task.js +17 -1
  75. package/dist/domain/scheduling/jobs/task-dispatch.js +22 -0
  76. package/dist/domain/sessions/session-hooks.d.ts +31 -1
  77. package/dist/domain/sessions/session-hooks.js +69 -17
  78. package/dist/domain/system/doctor.d.ts +63 -0
  79. package/dist/domain/system/doctor.js +362 -0
  80. package/dist/domain/tasks/dispatcher.js +8 -0
  81. package/dist/domain/tasks/system/cortex-run.js +4 -2
  82. package/dist/domain/tasks/system/task-cli.js +7 -4
  83. package/dist/domain/tasks/system/task-state.d.ts +10 -1
  84. package/dist/domain/tasks/system/task-state.js +31 -1
  85. package/dist/domain/threads/prompt-builder.d.ts +7 -4
  86. package/dist/domain/threads/prompt-builder.js +9 -8
  87. package/dist/domain/threads/runner.d.ts +8 -1
  88. package/dist/domain/threads/runner.js +111 -18
  89. package/dist/domain/threads/state-machine.d.ts +5 -0
  90. package/dist/domain/threads/state-machine.js +16 -0
  91. package/dist/entry/app.js +44 -5
  92. package/dist/entry/cli.js +10 -0
  93. package/dist/entry/doctor-cli.d.ts +12 -0
  94. package/dist/entry/doctor-cli.js +76 -0
  95. package/dist/entry/init.js +6 -0
  96. package/dist/hooks/ask-user-question-hook.mjs +7 -1
  97. package/dist/hooks/exit-plan-mode-hook.mjs +7 -1
  98. package/dist/hooks/memory-ref-tracker.mjs +1 -0
  99. package/dist/hooks/new-session-hook.mjs +1 -0
  100. package/dist/hooks/post-task-hook.mjs +1 -0
  101. package/dist/hooks/rules-loader.mjs +1 -0
  102. package/dist/hooks/sensitive-file-edit.mjs +1 -0
  103. package/dist/hooks/session-activity-tracker.mjs +1 -0
  104. package/dist/hooks/task-status-check.mjs +1 -0
  105. package/dist/hooks/tasks-yaml-guard.mjs +1 -0
  106. package/dist/orchestration/agent-runner.js +30 -4
  107. package/dist/orchestration/bg-continuation.d.ts +26 -0
  108. package/dist/orchestration/bg-continuation.js +34 -0
  109. package/dist/orchestration/conversation-runner.d.ts +3 -0
  110. package/dist/orchestration/conversation-runner.js +5 -2
  111. package/dist/orchestration/interactions/interaction-handlers.js +13 -2
  112. package/dist/orchestration/lifecycle.d.ts +5 -2
  113. package/dist/orchestration/lifecycle.js +87 -3
  114. package/dist/orchestration/manager-qa.d.ts +56 -0
  115. package/dist/orchestration/manager-qa.js +223 -0
  116. package/dist/orchestration/resume-dispatcher.d.ts +27 -0
  117. package/dist/orchestration/resume-dispatcher.js +145 -0
  118. package/dist/orchestration/routing/webhook.d.ts +1 -1
  119. package/dist/orchestration/routing/webhook.js +75 -14
  120. package/dist/orchestration/status-helpers.d.ts +3 -0
  121. package/dist/orchestration/status-helpers.js +16 -0
  122. package/dist/orchestration/thread-callback.d.ts +17 -1
  123. package/dist/orchestration/thread-callback.js +57 -36
  124. package/dist/orchestration/turn-notify.d.ts +26 -0
  125. package/dist/orchestration/turn-notify.js +66 -0
  126. package/dist/platform/adapters/feishu.d.ts +16 -0
  127. package/dist/platform/adapters/feishu.js +67 -6
  128. package/dist/store/plugin-sync.d.ts +21 -0
  129. package/dist/store/plugin-sync.js +119 -0
  130. package/dist/store/schedule-repo.d.ts +6 -0
  131. package/dist/store/schedule-repo.js +11 -1
  132. package/dist/store/thread-repo.js +14 -0
  133. package/dist/store/version-migrations.d.ts +23 -4
  134. package/dist/store/version-migrations.js +167 -9
  135. package/dist/tui/App.js +11 -7
  136. package/dist/tui/components/Dashboard.js +26 -11
  137. package/dist/tui/components/InputBox.js +43 -4
  138. package/dist/tui/components/SidePanel.js +1 -1
  139. package/package.json +1 -1
  140. package/dist/domain/mcp/feishu/bitable.d.ts +0 -3
  141. package/dist/domain/mcp/feishu/bitable.js +0 -168
  142. package/dist/domain/mcp/feishu/blocks-to-text.d.ts +0 -19
  143. package/dist/domain/mcp/feishu/blocks-to-text.js +0 -43
  144. package/dist/domain/mcp/feishu/docx.d.ts +0 -3
  145. package/dist/domain/mcp/feishu/docx.js +0 -163
  146. package/dist/domain/mcp/feishu/drive.d.ts +0 -23
  147. package/dist/domain/mcp/feishu/drive.js +0 -66
  148. package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +0 -40
  149. package/dist/domain/mcp/feishu/markdown-to-blocks.js +0 -191
  150. package/dist/domain/mcp/feishu/sheets.d.ts +0 -3
  151. package/dist/domain/mcp/feishu/sheets.js +0 -119
  152. package/dist/domain/mcp/feishu/wiki.d.ts +0 -3
  153. package/dist/domain/mcp/feishu/wiki.js +0 -77
@@ -5,12 +5,31 @@ export interface Migration {
5
5
  /** CalVer when this migration was introduced. Compared against the per-file
6
6
  * version tracked in versions.json to decide whether to run. */
7
7
  version: string;
8
- /** Idempotent migration function. Receives the parsed JSON of the target file
9
- * and optionally the parsed JSON of the corresponding defaults file (or undefined
10
- * if no defaults file applies or it couldn't be loaded). Must return the migrated
11
- * data — the runner compares before/after to decide whether to write. */
8
+ /** Target file format. 'json' (default) parses/serializes JSON; 'text' passes
9
+ * the raw file contents (string) through unchanged. Determines how the runner
10
+ * reads, diffs, and writes the file. */
11
+ format?: 'json' | 'text';
12
+ /** Idempotent migration function. For 'json' migrations, receives the parsed JSON
13
+ * of the target file and optionally the parsed JSON of the corresponding defaults
14
+ * file. For 'text' migrations, receives the raw file string and optionally the raw
15
+ * defaults string. Must return the migrated data (object for json, string for text)
16
+ * — the runner compares before/after to decide whether to write. */
12
17
  migrate(data: unknown, defaults?: unknown): unknown;
13
18
  }
19
+ /** Replace any existing `<!-- cortex:docs ... -->` … `<!-- /cortex:docs -->` region with
20
+ * `block`, or append `block` (separated by a blank line) when absent. Idempotent: feeding
21
+ * the output back in is a no-op. Matches any block version on the start marker so an old
22
+ * block is upgraded in place rather than duplicated. */
23
+ export declare function upsertMarkerBlock(content: string, block: string): string;
24
+ /** Apply an ordered list of literal `[from, to]` replacements, each only when `from`
25
+ * is present in the content. Used by text migrations that neutralize opinionated or
26
+ * project-specific phrasing in shipped default prompts (e.g. a hard TDD mandate, a
27
+ * hardcoded `npm test`, a named lint tool) on existing installs whose prompt copies
28
+ * predate the edit. Idempotent provided no `to` re-introduces another rule's `from`:
29
+ * once replaced the `from` is gone, so re-runs are no-ops. A prompt the user has
30
+ * customized away from the shipped wording simply won't match and is left untouched,
31
+ * preserving their edits. */
32
+ export declare function applyReplacements(content: string, pairs: ReadonlyArray<readonly [string, string]>): string;
14
33
  export interface MigrationOptions {
15
34
  /** Override DATA_DIR (user config location). Defaults to the real CORTEX_HOME. */
16
35
  dataDir?: string;
@@ -2,12 +2,14 @@
2
2
  // output: runMigrations() — applies pending file migrations before config loading
3
3
  // pos: Version-tracked file migration runner. Tracks per-file applied migration versions
4
4
  // in DATA_DIR/data/versions.json; on startup compares against CORTEX_VERSION and
5
- // runs pending migrations in version order. Idempotent and crash-safe via atomicWrite.
5
+ // runs pending migrations in version order. Supports JSON (parse/serialize) and text
6
+ // (raw string, e.g. markdown system prompts) migrations. Idempotent and crash-safe
7
+ // via atomicWrite.
6
8
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
7
9
  import * as path from 'node:path';
8
10
  import * as fs from 'node:fs/promises';
9
11
  import * as os from 'node:os';
10
- import { CORTEX_VERSION } from '../core/version.js';
12
+ import { CORTEX_VERSION, CORTEX_DOCS_URL } from '../core/version.js';
11
13
  import { DATA_DIR, DEFAULTS_DIR } from '../core/paths.js';
12
14
  import { atomicWrite } from '../core/atomic-write.js';
13
15
  import { createLogger } from '../core/log.js';
@@ -31,6 +33,106 @@ export function compareCalVer(a, b) {
31
33
  return aMonth - bMonth;
32
34
  return aDay - bDay;
33
35
  }
36
+ // ── Marker-block helpers (text migrations) ─────────────────────
37
+ // Text migrations edit human-owned markdown (system prompts, CORTEX.md) without
38
+ // clobbering user customizations: a versioned, marker-delimited block is upserted
39
+ // (replaced in place if present, appended otherwise). Bumping the block version token
40
+ // makes a future migration replace an older block cleanly.
41
+ const DOCS_BLOCK_VERSION = 'v1';
42
+ const DOCS_MARKER_START = `<!-- cortex:docs ${DOCS_BLOCK_VERSION} -->`;
43
+ const DOCS_MARKER_END = '<!-- /cortex:docs -->';
44
+ /** The canonical Cortex-docs block inserted into system prompts and CORTEX.md. */
45
+ const DOCS_BLOCK = [
46
+ DOCS_MARKER_START,
47
+ '# Cortex documentation',
48
+ `For how to use Cortex — tasks, threads, scheduling, memory, skills, safety & approvals — consult the docs: ${CORTEX_DOCS_URL}`,
49
+ DOCS_MARKER_END,
50
+ ].join('\n');
51
+ /** Replace any existing `<!-- cortex:docs ... -->` … `<!-- /cortex:docs -->` region with
52
+ * `block`, or append `block` (separated by a blank line) when absent. Idempotent: feeding
53
+ * the output back in is a no-op. Matches any block version on the start marker so an old
54
+ * block is upgraded in place rather than duplicated. */
55
+ export function upsertMarkerBlock(content, block) {
56
+ const re = /<!-- cortex:docs[^>]*-->[\s\S]*?<!-- \/cortex:docs -->/;
57
+ if (re.test(content)) {
58
+ return content.replace(re, block);
59
+ }
60
+ const trimmed = content.replace(/\s+$/, '');
61
+ return `${trimmed}\n\n${block}\n`;
62
+ }
63
+ /** Apply an ordered list of literal `[from, to]` replacements, each only when `from`
64
+ * is present in the content. Used by text migrations that neutralize opinionated or
65
+ * project-specific phrasing in shipped default prompts (e.g. a hard TDD mandate, a
66
+ * hardcoded `npm test`, a named lint tool) on existing installs whose prompt copies
67
+ * predate the edit. Idempotent provided no `to` re-introduces another rule's `from`:
68
+ * once replaced the `from` is gone, so re-runs are no-ops. A prompt the user has
69
+ * customized away from the shipped wording simply won't match and is left untouched,
70
+ * preserving their edits. */
71
+ export function applyReplacements(content, pairs) {
72
+ let out = content;
73
+ for (const [from, to] of pairs) {
74
+ if (out.includes(from))
75
+ out = out.split(from).join(to);
76
+ }
77
+ return out;
78
+ }
79
+ // ── Directive-prompt neutralization tables (text migrations) ───
80
+ // The shipped coder / coder-reviewer directives baked in three non-portable
81
+ // assumptions that leaked Cortex's own toolchain into every install: a hard
82
+ // "TDD is non-negotiable" mandate, `npm test` as THE test command, and the
83
+ // dependency-cruiser linter named by brand. These tables rewrite that wording
84
+ // to be project-agnostic (test only if the project has a suite; use the project's
85
+ // own command; speak of lint/architecture checks generically). git-commit
86
+ // discipline is intentionally left in place — it is core to the Coder role's
87
+ // deliverable contract, not a personal preference.
88
+ const CODER_DIRECTIVE_REPLACEMENTS = [
89
+ [
90
+ 'TDD, reading before editing, and not improvising on ambiguous specs are cheaper than a re-run.',
91
+ 'Testing, reading before editing, and not improvising on ambiguous specs are cheaper than a re-run.',
92
+ ],
93
+ [
94
+ '### TDD via `/develop`\n- Before implementing non-trivial logic, write a failing test.\n- Run the test, confirm it fails, implement, confirm it passes.\n- Trivial glue code and obvious one-liners are exempt; use judgment but bias toward tests.\n- Code that governs correctness (computation, data handling, seed handling) **requires** a test regardless.',
95
+ '### Testing\n- Follow the project\'s existing testing practice. If the project has a test setup, add or update tests covering the logic you change. If the project practices test-driven development, write the failing test first, confirm it fails, implement, then confirm it passes.\n- Code that governs correctness (computation, data handling, seed handling) should be tested whenever the project provides a way to test it. Trivial glue code and obvious one-liners are exempt.\n- If the project has no test harness, verify by the means it already uses; do not scaffold a test framework unless the spec asks for it.',
96
+ ],
97
+ [
98
+ '### Full-suite pass (non-negotiable)\n- After implementing and committing, run the project\'s full test suite (`npm test` or equivalent).\n- The full suite includes unit tests, architecture linters (e.g. dependency-cruiser), integration tests, and regression suites. Every stage must pass.\n- Do NOT commit or hand off until the full suite is green. A single red test or architecture violation means you are not done.\n- If the test suite had pre-existing failures before your invocation, note them explicitly in the implementation summary; you must still verify that no NEW failures were introduced by your changes.',
99
+ '### Full-suite pass\n- If the project has a test suite, run it after implementing and committing, using whatever command the project defines (e.g. `npm test`, `pytest`, `make test`).\n- Run every stage the project configures — unit tests, linters or architecture checks, integration tests, regression suites. Every configured stage must pass.\n- Do NOT commit or hand off until the suite is green. A single red test or lint violation means you are not done.\n- If the suite had pre-existing failures before your invocation, note them explicitly in the implementation summary; you must still verify that no NEW failures were introduced by your changes.',
100
+ ],
101
+ [
102
+ '3. Implement per spec. Use `/develop` for TDD on non-trivial logic.',
103
+ '3. Implement per spec. If the project practices TDD, use `/develop` to drive it on non-trivial logic.',
104
+ ],
105
+ [
106
+ '4. Run the **full test suite** (`npm test` or equivalent) locally; confirm every stage passes (architecture linter, unit tests, integration tests, regression suite). If it fails, fix before committing.',
107
+ '4. If the project has a test suite, run it locally with the project\'s own command; confirm every configured stage passes (linters or architecture checks, unit tests, integration tests, regression suite). If it fails, fix before committing.',
108
+ ],
109
+ [
110
+ '6. Run the full test suite one more time after committing to confirm the SHA is green.',
111
+ '6. If the project has a test suite, run it once more after committing to confirm the SHA is green.',
112
+ ],
113
+ [
114
+ '- **Partial test pass**: running only unit tests for the changed module while skipping integration tests, regression suites, or architecture linters. The full suite (`npm test`) must pass.',
115
+ '- **Partial test pass**: running only unit tests for the changed module while skipping integration tests, regression suites, or lint/architecture checks the project configures. The project\'s full suite must pass when one exists.',
116
+ ],
117
+ ];
118
+ const CODER_REVIEWER_DIRECTIVE_REPLACEMENTS = [
119
+ [
120
+ '### TDD discipline\nCoder must land tests alongside (or before) the implementation, with coverage over the spec\'s happy path **and** edge cases (boundaries, empty/null inputs, error paths, concurrency hazards relevant to the diff); missing tests, tests that don\'t exercise the new control-flow paths, or untested edge cases called out by the spec are **Blockers**.',
121
+ '### Test discipline\nWhen the project has a test setup, Coder must land tests alongside (or before) the implementation, with coverage over the spec\'s happy path **and** edge cases (boundaries, empty/null inputs, error paths, concurrency hazards relevant to the diff); missing tests, tests that don\'t exercise the new control-flow paths, or untested edge cases called out by the spec are **Blockers**. If the project has no test harness, verify correctness by the means the project already uses and do not treat the absence of tests as a Blocker.',
122
+ ],
123
+ [
124
+ '### Full-suite pass (non-negotiable)\nRun the project\'s full test suite (`npm test` or equivalent). This includes not just unit tests but also architecture linters, integration tests, and regression suites. **Any test failure or architecture violation (e.g. dependency-cruiser error) is a Blocker.** Do not rely on Coder\'s claim that tests passed — run them yourself. If the suite had pre-existing failures before this invocation, verify that no NEW failures were introduced; new failures are Blockers regardless of pre-existing state.',
125
+ '### Full-suite pass\nIf the project has a test suite, run it using the project\'s own command (e.g. `npm test`, `pytest`, `make test`). This includes not just unit tests but also any linters or architecture checks, integration tests, and regression suites the project configures. **Any test failure or lint/architecture violation is a Blocker.** Do not rely on Coder\'s claim that tests passed — run them yourself. If the suite had pre-existing failures before this invocation, verify that no NEW failures were introduced; new failures are Blockers regardless of pre-existing state.',
126
+ ],
127
+ [
128
+ '4. **Run the full test suite** (`npm test` or equivalent). Confirm that every stage passes: architecture linter, unit tests, integration tests, regression suite. If any test or lint stage fails, it is a Blocker — do not proceed to code review until Coder fixes it (or mark it as a pre-existing failure with evidence).',
129
+ '4. **If the project has a test suite, run it** with the project\'s own command. Confirm that every configured stage passes: linters or architecture checks, unit tests, integration tests, regression suite. If any test or lint stage fails, it is a Blocker — do not proceed to code review until Coder fixes it (or mark it as a pre-existing failure with evidence).',
130
+ ],
131
+ [
132
+ '- **Test run omission**: signing off on an implementation without running the full test suite yourself. Coder\'s claim that tests pass is not evidence. Run `npm test` and check every stage. A dependency-cruiser error or a test regression that Coder missed is as much your failure as theirs.',
133
+ '- **Test run omission**: signing off on an implementation without running the project\'s test suite yourself when one exists. Coder\'s claim that tests pass is not evidence. Run the suite and check every stage. A lint/architecture error or a test regression that Coder missed is as much your failure as theirs.',
134
+ ],
135
+ ];
34
136
  // ── Registry ───────────────────────────────────────────────────
35
137
  // Add new migrations here. The runner groups them by filePath and applies
36
138
  // pending ones in version-ascending order.
@@ -166,6 +268,58 @@ const migrations = [
166
268
  return out;
167
269
  },
168
270
  },
271
+ // M4: Inject the Cortex usage-docs block into the user's system prompts and CORTEX.md.
272
+ // These are user-owned copies seeded at `cortex init` with force=false, so editing the
273
+ // shipped defaults only reaches new installs — existing installs need this migration to
274
+ // pick up the docs URL. Uses upsertMarkerBlock (text format) so the block is inserted
275
+ // once and user customizations around it are preserved. Idempotent: re-runs are no-ops,
276
+ // and fresh installs (whose seeded files already carry the block from defaults) match the
277
+ // existing-block branch and are left unchanged. New files skip gracefully via ENOENT.
278
+ ...[
279
+ 'CORTEX.md',
280
+ 'prompts/systemPrompts/direct.md',
281
+ 'prompts/systemPrompts/web.md',
282
+ 'prompts/systemPrompts/web-opus-4-6.md',
283
+ 'prompts/systemPrompts/web-sonnet-4-6.md',
284
+ 'prompts/systemPrompts/worker.md',
285
+ 'prompts/systemPrompts/coder.md',
286
+ ].map((filePath) => ({
287
+ filePath,
288
+ version: '2026.6.22',
289
+ format: 'text',
290
+ migrate(data) {
291
+ if (typeof data !== 'string')
292
+ return data;
293
+ return upsertMarkerBlock(data, DOCS_BLOCK);
294
+ },
295
+ })),
296
+ // M5: De-personalize the coder / coder-reviewer directives. The shipped wording
297
+ // hardcoded Cortex's own toolchain (a non-negotiable TDD mandate, `npm test` as THE
298
+ // test command, the dependency-cruiser linter by name) — fine for this repo, wrong as
299
+ // a default for every install. These two text migrations rewrite the user-owned prompt
300
+ // copies under DATA_DIR/prompts/directives to project-agnostic phrasing. Idempotent via
301
+ // applyReplacements (already-rewritten or user-customized copies don't match → no-op),
302
+ // and missing files skip gracefully via ENOENT in the runner.
303
+ {
304
+ filePath: 'prompts/directives/coder.md',
305
+ version: '2026.6.22-2',
306
+ format: 'text',
307
+ migrate(data) {
308
+ if (typeof data !== 'string')
309
+ return data;
310
+ return applyReplacements(data, CODER_DIRECTIVE_REPLACEMENTS);
311
+ },
312
+ },
313
+ {
314
+ filePath: 'prompts/directives/coder-reviewer.md',
315
+ version: '2026.6.22-2',
316
+ format: 'text',
317
+ migrate(data) {
318
+ if (typeof data !== 'string')
319
+ return data;
320
+ return applyReplacements(data, CODER_REVIEWER_DIRECTIVE_REPLACEMENTS);
321
+ },
322
+ },
169
323
  ];
170
324
  // ── Versions file I/O ──────────────────────────────────────────
171
325
  async function loadVersionsFrom(filePath) {
@@ -201,14 +355,14 @@ async function saveVersionsTo(filePath, versions) {
201
355
  const DEFAULTS_MAP = {
202
356
  'config/thread-templates.json': 'config/thread-templates.json',
203
357
  };
204
- async function loadDefaultsForWith(filePath, defaultsDir) {
358
+ async function loadDefaultsForWith(filePath, defaultsDir, format = 'json') {
205
359
  const defaultsRel = DEFAULTS_MAP[filePath];
206
360
  if (!defaultsRel)
207
361
  return undefined;
208
362
  const defaultsPath = path.join(defaultsDir, defaultsRel);
209
363
  try {
210
364
  const raw = await fs.readFile(defaultsPath, 'utf8');
211
- return JSON.parse(raw);
365
+ return format === 'text' ? raw : JSON.parse(raw);
212
366
  }
213
367
  catch (err) {
214
368
  const e = err;
@@ -246,12 +400,15 @@ export async function runMigrations(opts = {}) {
246
400
  .sort((a, b) => compareCalVer(a.version, b.version));
247
401
  if (pending.length === 0)
248
402
  continue;
403
+ // A file is either JSON or text — take the format from the pending migrations.
404
+ const format = pending.find(m => m.format === 'text') ? 'text' : 'json';
405
+ const serialize = (d) => (format === 'text' ? String(d) : JSON.stringify(d));
249
406
  // Read target file
250
407
  const absPath = path.join(dataDir, filePath);
251
408
  let data;
252
409
  try {
253
410
  const raw = await fs.readFile(absPath, 'utf8');
254
- data = JSON.parse(raw);
411
+ data = format === 'text' ? raw : JSON.parse(raw);
255
412
  }
256
413
  catch (err) {
257
414
  const e = err;
@@ -266,12 +423,12 @@ export async function runMigrations(opts = {}) {
266
423
  throw err;
267
424
  }
268
425
  // Load defaults once for this file (if any)
269
- const defaultsData = await loadDefaultsForWith(filePath, defaultsDir);
426
+ const defaultsData = await loadDefaultsForWith(filePath, defaultsDir, format);
270
427
  // Apply all pending migrations in version order
271
428
  let changed = false;
272
429
  let anyFailed = false;
273
430
  for (const m of pending) {
274
- const before = JSON.stringify(data);
431
+ const before = serialize(data);
275
432
  try {
276
433
  data = m.migrate(data, defaultsData);
277
434
  }
@@ -281,13 +438,14 @@ export async function runMigrations(opts = {}) {
281
438
  anyFailed = true;
282
439
  break;
283
440
  }
284
- if (JSON.stringify(data) !== before) {
441
+ if (serialize(data) !== before) {
285
442
  log.info(`Migration ${m.version} applied to ${filePath}`);
286
443
  changed = true;
287
444
  }
288
445
  }
289
446
  if (changed) {
290
- await atomicWrite(absPath, JSON.stringify(data, null, 2) + '\n');
447
+ const out = format === 'text' ? String(data) : JSON.stringify(data, null, 2) + '\n';
448
+ await atomicWrite(absPath, out);
291
449
  }
292
450
  // Only bump the tracked version if ALL pending migrations succeeded.
293
451
  // If any failed: we did not write the file (changed=false), so the data on
package/dist/tui/App.js CHANGED
@@ -199,16 +199,20 @@ export function App({ sendFrame, connectionState, ack, onReconnect, onDisconnect
199
199
  allowScroll: focusZone === 'input',
200
200
  allowReconnect: connectionState !== 'connected',
201
201
  });
202
- // Dashboard subscription management callbacks
202
+ // Dashboard subscription management callbacks. Depend on the stable inner
203
+ // functions (each a useCallback in useDashboardData), NOT the whole `dashboard`
204
+ // object — that object is recreated every render, which previously made these
205
+ // wrappers (and thus the Dashboard effect deps) change identity on every render.
206
+ const { markPending, registerSubscription, unregisterSubscription } = dashboard;
203
207
  const handleMarkPending = useCallback((tab) => {
204
- dashboard.markPending(tab);
205
- }, [dashboard]);
208
+ markPending(tab);
209
+ }, [markPending]);
206
210
  const handleRegisterSubscription = useCallback((queryId, tab) => {
207
- dashboard.registerSubscription(queryId, tab);
208
- }, [dashboard]);
211
+ registerSubscription(queryId, tab);
212
+ }, [registerSubscription]);
209
213
  const handleUnregisterSubscription = useCallback((queryId) => {
210
- dashboard.unregisterSubscription(queryId);
211
- }, [dashboard]);
214
+ unregisterSubscription(queryId);
215
+ }, [unregisterSubscription]);
212
216
  // If resume mode with sessions to pick, show picker instead of main layout
213
217
  if (resumableSessions && resumableSessions.length > 0 && onResumeSelect && onResumeCancel) {
214
218
  return (_jsx(Box, { flexDirection: "column", height: "100%", justifyContent: "center", alignItems: "center", children: _jsx(SessionPicker, { sessions: resumableSessions, onSelect: onResumeSelect, onCancel: onResumeCancel }) }));
@@ -20,6 +20,21 @@ export const DASHBOARD_TABS = [
20
20
  // ── Tab content renderer ──
21
21
  function TabContent({ tab, active, sendFrame, mutate, projectId, dashState, onMarkPending, onRegisterSubscription, onUnregisterSubscription, }) {
22
22
  const initialQuerySent = useRef(false);
23
+ // The parent (App) hands us fresh callback / sendFrame identities on every render.
24
+ // Holding them in refs lets the query/subscribe effect depend only on
25
+ // [tab, projectId], so it never re-fires (and re-subscribes) merely because the
26
+ // parent re-rendered. Without this the effect cleaned up + re-ran every render,
27
+ // each run calling onMarkPending → setState → re-render → infinite loop (the
28
+ // Ctrl+D render storm that pegged a CPU core at ~95% with "Maximum update depth
29
+ // exceeded").
30
+ const sendFrameRef = useRef(sendFrame);
31
+ sendFrameRef.current = sendFrame;
32
+ const onMarkPendingRef = useRef(onMarkPending);
33
+ onMarkPendingRef.current = onMarkPending;
34
+ const onRegisterSubscriptionRef = useRef(onRegisterSubscription);
35
+ onRegisterSubscriptionRef.current = onRegisterSubscription;
36
+ const onUnregisterSubscriptionRef = useRef(onUnregisterSubscription);
37
+ onUnregisterSubscriptionRef.current = onUnregisterSubscription;
23
38
  // Initial query + subscribe (runs once per tab mount)
24
39
  React.useEffect(() => {
25
40
  const scope = TAB_SCOPES[tab];
@@ -29,29 +44,29 @@ function TabContent({ tab, active, sendFrame, mutate, projectId, dashState, onMa
29
44
  if (!initialQuerySent.current) {
30
45
  initialQuerySent.current = true;
31
46
  // Send query for initial data
32
- sendFrame({ type: 'ui.query', id: queryId, scope: tab === 'cost' ? 'cost.summary' : `${tab}.list`, params: projectId ? { projectId } : {} });
33
- onMarkPending(tab);
47
+ sendFrameRef.current({ type: 'ui.query', id: queryId, scope: tab === 'cost' ? 'cost.summary' : `${tab}.list`, params: projectId ? { projectId } : {} });
48
+ onMarkPendingRef.current(tab);
34
49
  // Subscribe to events
35
- sendFrame({ type: 'ui.subscribe', id: queryId, filter: { events: scope.events, projectId } });
36
- onRegisterSubscription(queryId, tab);
50
+ sendFrameRef.current({ type: 'ui.subscribe', id: queryId, filter: { events: scope.events, projectId } });
51
+ onRegisterSubscriptionRef.current(queryId, tab);
37
52
  }
38
53
  // Cleanup on unmount
39
54
  return () => {
40
- sendFrame({ type: 'ui.unsubscribe', id: queryId });
41
- onUnregisterSubscription(queryId);
55
+ sendFrameRef.current({ type: 'ui.unsubscribe', id: queryId });
56
+ onUnregisterSubscriptionRef.current(queryId);
42
57
  initialQuerySent.current = false;
43
58
  };
44
- }, [tab, projectId, sendFrame, onMarkPending, onRegisterSubscription, onUnregisterSubscription]);
59
+ }, [tab, projectId]);
45
60
  // Re-fetch when loading is triggered by a subscription event
46
61
  React.useEffect(() => {
47
62
  const scope = TAB_SCOPES[tab];
48
63
  if (!scope || !initialQuerySent.current)
49
64
  return;
50
65
  if (dashState.tabs[tab].loading) {
51
- sendFrame({ type: 'ui.query', id: scope.queryId, scope: tab === 'cost' ? 'cost.summary' : `${tab}.list`, params: projectId ? { projectId } : {} });
52
- onMarkPending(tab);
66
+ sendFrameRef.current({ type: 'ui.query', id: scope.queryId, scope: tab === 'cost' ? 'cost.summary' : `${tab}.list`, params: projectId ? { projectId } : {} });
67
+ onMarkPendingRef.current(tab);
53
68
  }
54
- }, [dashState.tabs[tab].loading, tab, projectId, sendFrame, onMarkPending]);
69
+ }, [dashState.tabs[tab].loading, tab, projectId]);
55
70
  switch (tab) {
56
71
  case 'threads':
57
72
  return _jsx(DashboardThreadsTab, { data: dashState.tabs.threads, mutate: mutate, active: active });
@@ -76,5 +91,5 @@ export function Dashboard({ active, sendFrame, mutate, projectId, dashState, onM
76
91
  onSetActiveTab(DASHBOARD_TABS[nextIdx].key);
77
92
  }
78
93
  }, { isActive: active });
79
- return (_jsxs(Box, { flexDirection: "column", width: "100%", children: [_jsx(Box, { children: DASHBOARD_TABS.map(t => (_jsx(Box, { paddingX: 1, borderStyle: t.key === activeTab ? 'bold' : 'single', borderDimColor: t.key !== activeTab, children: _jsx(Text, { bold: t.key === activeTab, children: t.label }) }, t.key))) }), _jsx(Box, { flexDirection: "column", flexGrow: 1, paddingX: 1, children: _jsx(TabContent, { tab: activeTab, active: active, sendFrame: sendFrame, mutate: mutate, projectId: projectId, dashState: dashState, onMarkPending: onMarkPending, onRegisterSubscription: onRegisterSubscription, onUnregisterSubscription: onUnregisterSubscription }) })] }));
94
+ return (_jsxs(Box, { flexDirection: "column", width: "100%", children: [_jsx(Box, { children: DASHBOARD_TABS.map((t, i) => (_jsxs(React.Fragment, { children: [i > 0 ? _jsx(Text, { dimColor: true, children: " " }) : null, _jsx(Text, { bold: t.key === activeTab, inverse: t.key === activeTab, children: t.label })] }, t.key))) }), _jsx(Box, { flexDirection: "column", flexGrow: 1, paddingX: 1, children: _jsx(TabContent, { tab: activeTab, active: active, sendFrame: sendFrame, mutate: mutate, projectId: projectId, dashState: dashState, onMarkPending: onMarkPending, onRegisterSubscription: onRegisterSubscription, onUnregisterSubscription: onUnregisterSubscription }) })] }));
80
95
  }
@@ -1,12 +1,18 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- // input: ink-text-input TextInput (controlled)
2
+ // input: ink useInput (custom controlled single-line input)
3
3
  // output: Message input — always typeable; submission blocked while awaiting a response
4
4
  // pos: User text input component
5
+ //
6
+ // A minimal in-house input replaces ink-text-input here so that Ctrl/Meta combos
7
+ // (Ctrl+D dashboard, Ctrl+N notifications, Ctrl+P projects, Ctrl+L clear, Ctrl+C
8
+ // cancel) are ignored instead of leaking their letter into the message buffer.
9
+ // ink-text-input inserts the bare character for unhandled Ctrl combos, which left a
10
+ // stray 'd' in the box every time the dashboard was toggled.
5
11
  import { useCallback, useState } from 'react';
6
- import { Box, Text } from 'ink';
7
- import TextInput from 'ink-text-input';
12
+ import { Box, Text, useInput } from 'ink';
8
13
  export function InputBox({ onSubmit, awaitingResponse, focus = true }) {
9
14
  const [value, setValue] = useState('');
15
+ const [cursor, setCursor] = useState(0);
10
16
  const handleSubmit = useCallback((text) => {
11
17
  if (awaitingResponse)
12
18
  return; // block send, keep typed text
@@ -14,6 +20,39 @@ export function InputBox({ onSubmit, awaitingResponse, focus = true }) {
14
20
  return;
15
21
  onSubmit(text);
16
22
  setValue('');
23
+ setCursor(0);
17
24
  }, [awaitingResponse, onSubmit]);
18
- return (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsx(Box, { borderStyle: "single", borderDimColor: true, paddingX: 1, children: _jsx(Box, { flexGrow: 1, children: _jsx(TextInput, { value: value, onChange: setValue, onSubmit: handleSubmit, focus: focus, placeholder: "Type a message..." }) }) }), awaitingResponse ? (_jsx(Text, { dimColor: true, children: "Waiting for response \u2014 Enter is disabled until the agent replies (Ctrl+C to cancel)" })) : !focus ? (_jsx(Text, { dimColor: true, children: "Press Ctrl+D to return to the input" })) : null] }));
25
+ useInput((input, key) => {
26
+ // Ignore modifier combos so global hotkeys never leak their letter into the box.
27
+ if (key.ctrl || key.meta)
28
+ return;
29
+ // Escape / Tab are owned by other zones; arrows up/down scroll the transcript.
30
+ if (key.escape || key.tab || key.upArrow || key.downArrow || key.pageUp || key.pageDown)
31
+ return;
32
+ if (key.return) {
33
+ handleSubmit(value);
34
+ return;
35
+ }
36
+ if (key.leftArrow) {
37
+ setCursor(c => Math.max(0, c - 1));
38
+ return;
39
+ }
40
+ if (key.rightArrow) {
41
+ setCursor(c => Math.min(value.length, c + 1));
42
+ return;
43
+ }
44
+ if (key.backspace || key.delete) {
45
+ if (cursor > 0) {
46
+ setValue(v => v.slice(0, cursor - 1) + v.slice(cursor));
47
+ setCursor(c => Math.max(0, c - 1));
48
+ }
49
+ return;
50
+ }
51
+ // Printable input (may be multiple characters on paste).
52
+ if (input && input.length > 0) {
53
+ setValue(v => v.slice(0, cursor) + input + v.slice(cursor));
54
+ setCursor(c => c + input.length);
55
+ }
56
+ }, { isActive: focus });
57
+ return (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsx(Box, { borderStyle: "single", borderDimColor: true, paddingX: 1, children: _jsx(Box, { flexGrow: 1, children: value.length === 0 && !focus ? (_jsx(Text, { dimColor: true, children: "Type a message..." })) : value.length === 0 ? (_jsxs(Text, { children: [_jsx(Text, { inverse: true, children: " " }), _jsx(Text, { dimColor: true, children: "Type a message..." })] })) : focus ? (_jsxs(Text, { children: [value.slice(0, cursor), _jsx(Text, { inverse: true, children: value.slice(cursor, cursor + 1) || ' ' }), value.slice(cursor + 1)] })) : (_jsx(Text, { children: value })) }) }), awaitingResponse ? (_jsx(Text, { dimColor: true, children: "Waiting for response \u2014 Enter is disabled until the agent replies (Ctrl+C to cancel)" })) : !focus ? (_jsx(Text, { dimColor: true, children: "Press Ctrl+D to return to the input" })) : null] }));
19
58
  }
@@ -4,5 +4,5 @@ import { Dashboard } from './Dashboard.js';
4
4
  export function SidePanel({ visible, active, sendFrame, projectId, dashState, onMarkPending, onRegisterSubscription, onUnregisterSubscription, activeTab, onSetActiveTab, onMutate, }) {
5
5
  if (!visible)
6
6
  return null;
7
- return (_jsx(Box, { width: 40, borderStyle: "single", borderDimColor: true, marginLeft: 1, flexShrink: 0, children: _jsx(Dashboard, { active: active, sendFrame: sendFrame, projectId: projectId, dashState: dashState, onMarkPending: onMarkPending, onRegisterSubscription: onRegisterSubscription, onUnregisterSubscription: onUnregisterSubscription, activeTab: activeTab, onSetActiveTab: onSetActiveTab, mutate: onMutate }) }));
7
+ return (_jsx(Box, { width: 44, borderStyle: "single", borderDimColor: true, marginLeft: 1, flexShrink: 0, children: _jsx(Dashboard, { active: active, sendFrame: sendFrame, projectId: projectId, dashState: dashState, onMarkPending: onMarkPending, onRegisterSubscription: onRegisterSubscription, onUnregisterSubscription: onUnregisterSubscription, activeTab: activeTab, onSetActiveTab: onSetActiveTab, mutate: onMutate }) }));
8
8
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortex-agent/server",
3
- "version": "2026.6.18",
3
+ "version": "2026.6.24",
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.",
@@ -1,3 +0,0 @@
1
- import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
- import { type FeishuToolDeps } from './types.js';
3
- export declare function registerBitableTools(server: McpServer, deps: FeishuToolDeps): void;