@cortex-agent/server 2026.6.22 → 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 (95) hide show
  1. package/defaults/config/thread-templates.json +12 -6
  2. package/defaults/context/user/CORTEX.md +2 -2
  3. package/defaults/hooks/ask-user-question-hook.mjs +1 -0
  4. package/defaults/hooks/exit-plan-mode-hook.mjs +1 -0
  5. package/defaults/hooks/memory-ref-tracker.mjs +1 -0
  6. package/defaults/hooks/new-session-hook.mjs +1 -0
  7. package/defaults/hooks/post-task-hook.mjs +1 -0
  8. package/defaults/hooks/rules-loader.mjs +1 -0
  9. package/defaults/hooks/sensitive-file-edit.mjs +1 -0
  10. package/defaults/hooks/session-activity-tracker.mjs +1 -0
  11. package/defaults/hooks/task-status-check.mjs +1 -0
  12. package/defaults/hooks/tasks-yaml-guard.mjs +1 -0
  13. package/defaults/plugins/cortex-feishu/.claude-plugin/plugin.json +5 -0
  14. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +163 -0
  15. package/defaults/plugins/cortex-feishu/skills/feishu-doc/scripts/ensure-lark-cli.sh +53 -0
  16. package/defaults/prompts/directives/coder-reviewer.md +6 -6
  17. package/defaults/prompts/directives/coder.md +14 -15
  18. package/dist/agent-adapter/claude/adapter-tui.d.ts +12 -0
  19. package/dist/agent-adapter/claude/adapter-tui.js +15 -0
  20. package/dist/agent-adapter/claude/adapter.js +6 -2
  21. package/dist/agent-adapter/claude/bg-task-tracker.d.ts +8 -0
  22. package/dist/agent-adapter/claude/bg-task-tracker.js +18 -5
  23. package/dist/core/gateway-generator.js +10 -1
  24. package/dist/core/locales/en.d.ts +6 -0
  25. package/dist/core/locales/slices/interactions.d.ts +6 -0
  26. package/dist/core/locales/slices/interactions.js +14 -0
  27. package/dist/core/status-format.d.ts +14 -0
  28. package/dist/core/status-format.js +23 -1
  29. package/dist/core/types/thread-types.d.ts +3 -0
  30. package/dist/domain/agents/facade.d.ts +13 -0
  31. package/dist/domain/agents/facade.js +24 -1
  32. package/dist/domain/mcp/feishu/index.js +5 -51
  33. package/dist/domain/mcp/feishu-server.js +3 -2
  34. package/dist/domain/memory/user-context.d.ts +6 -5
  35. package/dist/domain/memory/user-context.js +12 -7
  36. package/dist/domain/remote/client-hot-reload.d.ts +9 -2
  37. package/dist/domain/remote/client-hot-reload.js +77 -6
  38. package/dist/domain/scheduling/jobs/task-dispatch.js +1 -0
  39. package/dist/domain/sessions/session-hooks.d.ts +31 -1
  40. package/dist/domain/sessions/session-hooks.js +69 -17
  41. package/dist/domain/system/doctor.d.ts +63 -0
  42. package/dist/domain/system/doctor.js +362 -0
  43. package/dist/domain/tasks/system/task-cli.js +7 -4
  44. package/dist/domain/tasks/system/task-state.d.ts +10 -1
  45. package/dist/domain/tasks/system/task-state.js +31 -1
  46. package/dist/domain/threads/prompt-builder.d.ts +7 -4
  47. package/dist/domain/threads/prompt-builder.js +9 -8
  48. package/dist/domain/threads/runner.js +30 -7
  49. package/dist/entry/app.js +38 -14
  50. package/dist/entry/cli.js +10 -0
  51. package/dist/entry/doctor-cli.d.ts +12 -0
  52. package/dist/entry/doctor-cli.js +76 -0
  53. package/dist/hooks/ask-user-question-hook.mjs +1 -0
  54. package/dist/hooks/exit-plan-mode-hook.mjs +1 -0
  55. package/dist/hooks/memory-ref-tracker.mjs +1 -0
  56. package/dist/hooks/new-session-hook.mjs +1 -0
  57. package/dist/hooks/post-task-hook.mjs +1 -0
  58. package/dist/hooks/rules-loader.mjs +1 -0
  59. package/dist/hooks/sensitive-file-edit.mjs +1 -0
  60. package/dist/hooks/session-activity-tracker.mjs +1 -0
  61. package/dist/hooks/task-status-check.mjs +1 -0
  62. package/dist/hooks/tasks-yaml-guard.mjs +1 -0
  63. package/dist/orchestration/agent-runner.js +3 -2
  64. package/dist/orchestration/conversation-runner.js +4 -1
  65. package/dist/orchestration/lifecycle.d.ts +2 -1
  66. package/dist/orchestration/lifecycle.js +15 -1
  67. package/dist/orchestration/manager-qa.d.ts +3 -2
  68. package/dist/orchestration/manager-qa.js +17 -12
  69. package/dist/orchestration/resume-dispatcher.d.ts +5 -0
  70. package/dist/orchestration/resume-dispatcher.js +38 -22
  71. package/dist/orchestration/thread-callback.d.ts +7 -3
  72. package/dist/orchestration/thread-callback.js +39 -35
  73. package/dist/store/plugin-sync.d.ts +21 -0
  74. package/dist/store/plugin-sync.js +119 -0
  75. package/dist/store/version-migrations.d.ts +9 -0
  76. package/dist/store/version-migrations.js +100 -0
  77. package/dist/tui/App.js +11 -7
  78. package/dist/tui/components/Dashboard.js +26 -11
  79. package/dist/tui/components/InputBox.js +43 -4
  80. package/dist/tui/components/SidePanel.js +1 -1
  81. package/package.json +1 -1
  82. package/dist/domain/mcp/feishu/bitable.d.ts +0 -3
  83. package/dist/domain/mcp/feishu/bitable.js +0 -168
  84. package/dist/domain/mcp/feishu/blocks-to-text.d.ts +0 -19
  85. package/dist/domain/mcp/feishu/blocks-to-text.js +0 -43
  86. package/dist/domain/mcp/feishu/docx.d.ts +0 -3
  87. package/dist/domain/mcp/feishu/docx.js +0 -163
  88. package/dist/domain/mcp/feishu/drive.d.ts +0 -23
  89. package/dist/domain/mcp/feishu/drive.js +0 -66
  90. package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +0 -40
  91. package/dist/domain/mcp/feishu/markdown-to-blocks.js +0 -191
  92. package/dist/domain/mcp/feishu/sheets.d.ts +0 -3
  93. package/dist/domain/mcp/feishu/sheets.js +0 -119
  94. package/dist/domain/mcp/feishu/wiki.d.ts +0 -3
  95. package/dist/domain/mcp/feishu/wiki.js +0 -77
@@ -14,6 +14,11 @@ export interface ResumeDeps {
14
14
  buildResumeOptions: (thread: ThreadRecord) => RunThreadOptions | null;
15
15
  getThread: (threadId: string) => ThreadRecord | null;
16
16
  channelBusy: (channel: string) => boolean;
17
+ /** True if a DIRECT (interactive) session is live on the channel — i.e. an execution with no
18
+ * threadId. Only direct sessions force a channel to serialize (a Slack conversation cannot
19
+ * interleave two assistant turns). Threads are channel-parallel-safe, so a rate-limited thread
20
+ * only needs to avoid a live direct session, not other threads. */
21
+ directSessionBusy: (channel: string) => boolean;
17
22
  now: () => number;
18
23
  delay: (ms: number) => Promise<void>;
19
24
  }
@@ -1,9 +1,11 @@
1
1
  // input: rate-limit-throttle onResume → resume-registry (takeAllResumes) + agentRunner / resumeRateLimitedThread
2
2
  // output: dispatchPendingResumes — wakes sessions/threads interrupted by a rate limit
3
- // pos: orch/ — runs when the rate-limit window resets. Direct sessions are re-entered with a
4
- // <system-reminder>; threads (status 'rate_limited') are re-run from the interrupted step
5
- // via resumeRateLimitedThread with options rebuilt by buildResumeOptions (dispatch onEnd
6
- // hook + destination). All deps injectable for tests.
3
+ // pos: orch/ — runs when the rate-limit window resets (or on startup if the queue has orphans
4
+ // and no throttle is active). Direct sessions are re-entered with a <system-reminder> and
5
+ // serialized per channel; threads (status 'rate_limited') are re-run from the interrupted
6
+ // step via resumeRateLimitedThread, fired concurrently (channel-parallel-safe) and only
7
+ // skipped if a live direct session holds the channel. Options rebuilt by buildResumeOptions
8
+ // (dispatch onEnd hook + destination). All deps injectable for tests.
7
9
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
8
10
  import { takeAllResumes } from '../domain/costs/resume-registry.js';
9
11
  import { agentRunner } from './agent-runner.js';
@@ -16,8 +18,9 @@ const log = createLogger('resume-dispatcher');
16
18
  /** Entries older than this are considered obsolete (user moved on / thread finished).
17
19
  * 6h = the 5-hour window plus restart slack. */
18
20
  const MAX_RESUME_AGE_MS = 6 * 60 * 60 * 1000;
19
- /** Gap between consecutive resumes so we don't instantly re-trip the limit. */
20
- const RESUME_STAGGER_MS = 3_000;
21
+ /** Gap between consecutive resume starts so we don't re-trip the limit / overload the API right
22
+ * after a window reset. Resumes begin one every 30s. */
23
+ const RESUME_STAGGER_MS = 30_000;
21
24
  /** Auto-resume is on by default; disable with CORTEX_AUTO_RESUME=0 (or "false"). */
22
25
  export function isAutoResumeEnabled() {
23
26
  const v = process.env.CORTEX_AUTO_RESUME;
@@ -28,10 +31,10 @@ export function isAutoResumeEnabled() {
28
31
  export function buildResumeReminder() {
29
32
  return [
30
33
  '<system-reminder>',
31
- '上一轮因命中 API 限流(五小时窗口)被中断。该窗口现已重置,你可以继续。',
32
- '请从中断处接着做:回顾上方最近的对话上下文,判断还有什么没完成并完成它。',
33
- '不要从头重启任务、也不要重复询问用户已提供的信息。若上一轮其实已经完成,简短确认后停止。',
34
- '本条消息仅为恢复信号,不应改变你原本的任务。',
34
+ 'The previous turn was interrupted by an API rate limit (the 5-hour window). That window has now reset; you may continue.',
35
+ 'Resume from where you left off: review the recent conversation context above, work out what is still unfinished, and finish it.',
36
+ 'Do not restart the task from scratch, and do not re-ask for information the user already provided. If the previous turn was in fact already complete, briefly confirm and stop.',
37
+ 'This message is only a resume signal; it should not change your original task.',
35
38
  '</system-reminder>',
36
39
  ].join('\n');
37
40
  }
@@ -43,6 +46,7 @@ function defaultDeps() {
43
46
  buildResumeOptions: (thread) => buildResumeOptions(thread),
44
47
  getThread: (id) => threadStore.get(id),
45
48
  channelBusy: (ch) => runningExecutions.hasChannel(ch),
49
+ directSessionBusy: (ch) => runningExecutions.getByChannel(ch).some(e => !e.threadId),
46
50
  now: () => Date.now(),
47
51
  delay: (ms) => new Promise((r) => setTimeout(r, ms)),
48
52
  };
@@ -73,11 +77,17 @@ export async function dispatchPendingResumes(adapter, overrides = {}) {
73
77
  }
74
78
  try {
75
79
  if (dispatched > 0)
76
- await deps.delay(RESUME_STAGGER_MS); // stagger between actual dispatches
77
- if (entry.kind === 'direct')
80
+ await deps.delay(RESUME_STAGGER_MS); // stagger START times, not completion
81
+ if (entry.kind === 'direct') {
82
+ // Direct sessions are serial per channel — await so the next dispatch sees it as busy.
78
83
  await resumeDirect(entry, adapter, deps);
79
- else
80
- await resumeThread(entry, deps.getThread(entry.threadId), adapter, deps);
84
+ }
85
+ else {
86
+ // Threads are channel-parallel-safe: fire-and-forget so multiple rate-limited threads on
87
+ // the same channel resume concurrently instead of serializing behind the first one.
88
+ void resumeThread(entry, deps.getThread(entry.threadId), adapter, deps)
89
+ .catch(e => log.error(`Resume failed (${entryKey(entry)}): ${e.message}`));
90
+ }
81
91
  dispatched++;
82
92
  }
83
93
  catch (e) {
@@ -90,15 +100,21 @@ export async function dispatchPendingResumes(adapter, overrides = {}) {
90
100
  function guardSkipReason(entry, deps) {
91
101
  if (deps.now() - entry.recordedAt > MAX_RESUME_AGE_MS)
92
102
  return 'stale';
93
- if (deps.channelBusy(entry.channel))
94
- return 'channel already has a running execution';
95
- if (entry.kind === 'thread') {
96
- const thread = deps.getThread(entry.threadId);
97
- if (!thread)
98
- return 'thread no longer exists';
99
- if (thread.status !== 'rate_limited')
100
- return `thread is ${thread.status}`;
103
+ if (entry.kind === 'direct') {
104
+ // A direct session is a live conversation — serialize per channel (no interleaved turns).
105
+ if (deps.channelBusy(entry.channel))
106
+ return 'channel already has a running execution';
107
+ return null;
101
108
  }
109
+ // Thread: channel-parallel-safe. Only avoid a live direct session (interactive turn) on the
110
+ // channel; concurrent threads on the same channel are fine and must not skip each other.
111
+ if (deps.directSessionBusy(entry.channel))
112
+ return 'direct session active on channel';
113
+ const thread = deps.getThread(entry.threadId);
114
+ if (!thread)
115
+ return 'thread no longer exists';
116
+ if (thread.status !== 'rate_limited')
117
+ return `thread is ${thread.status}`;
102
118
  return null;
103
119
  }
104
120
  async function resumeDirect(entry, adapter, deps) {
@@ -7,9 +7,13 @@ export declare function _testResetCallbackState(): void;
7
7
  * delegation contract and demands acceptance verification before the result is trusted
8
8
  * (DR-0014 L1 纠偏: verify the deliverable, never the child's self-report). */
9
9
  export declare function buildChildResultNotice(child: ThreadRecord): string;
10
- /** Rebuild RunThreadOptions for re-entering a suspended parent. extraHooks are not
11
- * persisted on ThreadRecord, so the dispatch task-status-check hook is reconstructed
12
- * from metadata.taskId/taskProject (the reason dispatch threads must store them). */
10
+ /** Rebuild RunThreadOptions for re-entering a suspended parent OR a rate-limit-paused thread.
11
+ * extraHooks are not persisted on ThreadRecord, so the dispatch task-status-check hook is
12
+ * reconstructed from metadata.taskId/taskProject (the reason dispatch threads must store them).
13
+ * statusMsg is restored from metadata.statusMsgRef (persisted at dispatch by task-dispatch /
14
+ * webhook) so the resumed run keeps updating the SAME live status message — without it the run
15
+ * carries statusMsg=null and the message freezes at "Paused — rate limited" forever even though
16
+ * the thread runs to completion (2026-06-23 finding: rate-limit resume status-message freeze). */
13
17
  export declare function buildResumeOptions(parent: ThreadRecord): RunThreadOptions | null;
14
18
  /** Refresh the status message persisted at suspension (metadata.statusMsgRef): a resumed
15
19
  * thread's terminal summary, or the new suspension count if it suspended again. Without
@@ -31,10 +31,10 @@ function buildNotice(threadId) {
31
31
  const t = threadStore.get(threadId);
32
32
  const cost = `$${(t.totalCostUsd || 0).toFixed(4)}`;
33
33
  const last = t.steps.length ? t.steps[t.steps.length - 1].output : null;
34
- const tail = t.abortReason || t.error || last || '(无输出)';
34
+ const tail = t.abortReason || t.error || last || '(no output)';
35
35
  const summary = tail.length > 200 ? tail.slice(0, 200) + '…' : tail;
36
36
  const label = t.templateName || t.activeAgent || 'thread';
37
- return `[后台线程完成] 你启动的线程 ${threadId} (${label}) 状态=${t.status} | ${cost}\n摘要: ${summary}\n调用 thread_result("${threadId}") 查看完整产出。`;
37
+ return `[Background thread done] Your thread ${threadId} (${label}) status=${t.status} | ${cost}\nSummary: ${summary}\nCall thread_result("${threadId}") to see the full output.`;
38
38
  }
39
39
  /** Child-result notice delivered into a suspended parent's pendingMessages. Echoes the
40
40
  * delegation contract and demands acceptance verification before the result is trusted
@@ -47,27 +47,27 @@ export function buildChildResultNotice(child) {
47
47
  const childCount = parent?.metadata?.childThreadIds?.length ?? 0;
48
48
  const maxChildren = parseInt(process.env.CORTEX_THREAD_MAX_CHILDREN || '8', 10) || 8;
49
49
  const lines = [
50
- `[子线程完成] ${child.id} (${label}) 状态=${child.status} | ${cost}`,
50
+ `[Child thread done] ${child.id} (${label}) status=${child.status} | ${cost}`,
51
51
  ];
52
52
  if (child.abortReason)
53
- lines.push(`子线程升级/中止原因: ${child.abortReason}`);
53
+ lines.push(`Child escalation/abort reason: ${child.abortReason}`);
54
54
  if (child.error)
55
- lines.push(`子线程错误: ${child.error}`);
55
+ lines.push(`Child error: ${child.error}`);
56
56
  if (contract) {
57
- lines.push(`契约: ${contract.goal}`);
57
+ lines.push(`Contract: ${contract.goal}`);
58
58
  if (contract.doneWhen)
59
59
  lines.push(`Done when: ${contract.doneWhen}`);
60
60
  if (contract.deliverablePath)
61
61
  lines.push(`Deliverable: ${contract.deliverablePath}`);
62
62
  }
63
- lines.push(`完整产出: thread_result("${child.id}")${child.artifactPath ? `;artifact: ${child.artifactPath}` : ''}`);
63
+ lines.push(`Full output: thread_result("${child.id}")${child.artifactPath ? `; artifact: ${child.artifactPath}` : ''}`);
64
64
  lines.push('');
65
- lines.push('验收要求(必须执行,不得凭子线程的汇报文本直接采信):');
66
- lines.push('1. 读取 deliverable 实物,逐条核对 done_when;涉及代码的跑测试验证。');
67
- lines.push('2. 达标 → 蒸馏关键结论进你的 artifact,继续你的计划。');
68
- lines.push('3. 未达标 → 写出 expected/actual 差异与失败假设,用修订后的契约重新 thread_start' +
69
- `(你已使用 ${childCount}/${maxChildren} 个子线程额度;额度耗尽时 thread_start 会被拒绝)。`);
70
- lines.push('4. 无法判断或方向性问题 → 调用 thread_abort 工具(附一行诊断)升级到你的上层。');
65
+ lines.push('Acceptance (mandatory — do NOT trust the child\'s self-reported summary):');
66
+ lines.push('1. Read the actual deliverable; check it against done_when item by item; for code, run the tests.');
67
+ lines.push('2. Passes → distill the key conclusions into your artifact and continue your plan.');
68
+ lines.push('3. Fails → write out the expected/actual gap and your failure hypothesis, then thread_start again with a revised contract' +
69
+ ` (you have used ${childCount}/${maxChildren} child-thread slots; thread_start is rejected once the quota is exhausted).`);
70
+ lines.push('4. Cannot judge, or a directional question → call the thread_abort tool (with a one-line diagnosis) to escalate to your manager.');
71
71
  return lines.join('\n');
72
72
  }
73
73
  /** Durable degraded-path notice to the project-report channel. */
@@ -86,9 +86,13 @@ async function postProjectNotice(t, text) {
86
86
  await adapter.postMessage(dest, { text });
87
87
  }
88
88
  }
89
- /** Rebuild RunThreadOptions for re-entering a suspended parent. extraHooks are not
90
- * persisted on ThreadRecord, so the dispatch task-status-check hook is reconstructed
91
- * from metadata.taskId/taskProject (the reason dispatch threads must store them). */
89
+ /** Rebuild RunThreadOptions for re-entering a suspended parent OR a rate-limit-paused thread.
90
+ * extraHooks are not persisted on ThreadRecord, so the dispatch task-status-check hook is
91
+ * reconstructed from metadata.taskId/taskProject (the reason dispatch threads must store them).
92
+ * statusMsg is restored from metadata.statusMsgRef (persisted at dispatch by task-dispatch /
93
+ * webhook) so the resumed run keeps updating the SAME live status message — without it the run
94
+ * carries statusMsg=null and the message freezes at "Paused — rate limited" forever even though
95
+ * the thread runs to completion (2026-06-23 finding: rate-limit resume status-message freeze). */
92
96
  export function buildResumeOptions(parent) {
93
97
  const adapter = jobCtx.adapter;
94
98
  if (!adapter)
@@ -105,7 +109,7 @@ export function buildResumeOptions(parent) {
105
109
  channel: parent.channel,
106
110
  destination: dest,
107
111
  threadAnchorId: parent.platformThreadId ?? null,
108
- statusMsg: null,
112
+ statusMsg: m?.statusMsgRef ?? null,
109
113
  startTime: Date.now(),
110
114
  onProgress: null,
111
115
  onToolUse: null,
@@ -237,26 +241,26 @@ export async function notifyThreadParent(childId, deps = {}) {
237
241
  export function buildTaskResultNotice(task, kind) {
238
242
  const lines = [];
239
243
  if (kind === 'completed') {
240
- lines.push(`[子任务完成] #${task.id} ${task.text}`);
244
+ lines.push(`[Subtask done] #${task.id} ${task.text}`);
241
245
  if (task.done_when)
242
246
  lines.push(`Done when: ${task.done_when}`);
243
247
  if (task.completed_note)
244
- lines.push(`完成备注: ${task.completed_note}`);
248
+ lines.push(`Completion note: ${task.completed_note}`);
245
249
  lines.push('');
246
- lines.push('验收要求(必须执行,不得凭完成备注直接采信):');
247
- lines.push('1. 读取实际产出(代码/文档/实验记录),逐条核对 done_when;涉及代码的跑测试验证。');
248
- lines.push('2. 达标 → 蒸馏关键结论进你的 artifact,继续你的计划。');
249
- lines.push(`3. 未达标 → cortex-task uncomplete 后修订该任务,或用 decompose --keep-parent 增加修订子任务,再调用 thread_wait。`);
250
- lines.push('4. 方向性问题 → 调用 thread_abort 工具(附一行诊断)升级。');
250
+ lines.push('Acceptance (mandatory — do NOT trust the completion note at face value):');
251
+ lines.push('1. Read the actual output (code/docs/experiment records); check it against done_when item by item; for code, run the tests.');
252
+ lines.push('2. Passes → distill the key conclusions into your artifact and continue your plan.');
253
+ lines.push(`3. Fails → cortex-task uncomplete then revise the task, or add a revision subtask with decompose --keep-parent, then call thread_wait.`);
254
+ lines.push('4. Directional question → call the thread_abort tool (with a one-line diagnosis) to escalate.');
251
255
  }
252
256
  else {
253
- lines.push(`[子任务被阻塞 — 升级信号] #${task.id} ${task.text}`);
254
- lines.push(`阻塞原因: ${task.blocked_by || '(未记录)'}`);
257
+ lines.push(`[Subtask blocked — escalation signal] #${task.id} ${task.text}`);
258
+ lines.push(`Blocked by: ${task.blocked_by || '(unrecorded)'}`);
255
259
  lines.push('');
256
- lines.push('这是子任务的升级:它无法自行完成。你必须处理:');
257
- lines.push('1. 诊断原因(读它的产出/日志;too-big 类原因 = 你当初的分解需要修订)。');
258
- lines.push('2. 可修复 → cortex-task unblock 并修订任务描述/done_when,或重建修订后的子任务(decompose --keep-parent),再调用 thread_wait。');
259
- lines.push('3. 超出你的职权或方向性问题 → 调用 thread_abort 工具(附一行诊断)向上升级。');
260
+ lines.push('This is the subtask escalating: it cannot finish on its own. You must handle it:');
261
+ lines.push('1. Diagnose the cause (read its output/logs; a too-big cause = your original decomposition needs revising).');
262
+ lines.push('2. Fixable → cortex-task unblock and revise the task description/done_when, or rebuild a revised subtask (decompose --keep-parent), then call thread_wait.');
263
+ lines.push('3. Beyond your authority or a directional question → call the thread_abort tool (with a one-line diagnosis) to escalate upward.');
260
264
  }
261
265
  return lines.join('\n');
262
266
  }
@@ -352,10 +356,10 @@ async function wakeSession(channel, notice, tag) {
352
356
  * no manager-style verification ceremony (the recipient is the requester, not a join node). */
353
357
  function buildTaskOriginNotice(task, kind) {
354
358
  if (kind === 'completed') {
355
- const note = task.completed_note ? `\n备注: ${task.completed_note}` : '';
356
- return `[任务完成] 你布置的任务 #${task.id} (${task.project})「${task.text}」已完成。${note}\n用 cortex-task show --task-id ${task.id} 查看详情。`;
359
+ const note = task.completed_note ? `\nNote: ${task.completed_note}` : '';
360
+ return `[Task done] The task you dispatched #${task.id} (${task.project}) "${task.text}" is complete.${note}\nRun cortex-task show --task-id ${task.id} for details.`;
357
361
  }
358
- return `[任务受阻] 你布置的任务 #${task.id} (${task.project})「${task.text}」被阻塞。\n阻塞原因: ${task.blocked_by || '(未记录)'}\n用 cortex-task show --task-id ${task.id} 查看详情,处理后可 cortex-task unblock。`;
362
+ return `[Task blocked] The task you dispatched #${task.id} (${task.project}) "${task.text}" is blocked.\nBlocked by: ${task.blocked_by || '(unrecorded)'}\nRun cortex-task show --task-id ${task.id} for details; once handled, cortex-task unblock.`;
359
363
  }
360
364
  /** Session→task wake (Problem 1): when a task created by an interactive session/agent turns
361
365
  * terminal, route a notice back to its origin channel. Default-on, no fallback — if origin_channel
@@ -405,7 +409,7 @@ export async function reconcileWaitingTasks(threadId, deps = {}) {
405
409
  m.waitingOnTasks = (m.waitingOnTasks ?? []).filter((id) => id !== taskId);
406
410
  if (!Array.isArray(m.pendingMessages))
407
411
  m.pendingMessages = [];
408
- m.pendingMessages.push(`[子任务丢失] #${taskId} 已不在 TASKS.yaml(可能被归档或删除),按失败处理。`);
412
+ m.pendingMessages.push(`[Subtask lost] #${taskId} is no longer in TASKS.yaml (likely archived or deleted); treating as failed.`);
409
413
  });
410
414
  log.warn(`reconcile: dropped missing task ${taskId} from waiting thread ${threadId}`);
411
415
  }
@@ -454,7 +458,7 @@ export async function recoverWaitingThreads(deps = {}) {
454
458
  meta.waitingOn = (meta.waitingOn ?? []).filter((id) => id !== childId);
455
459
  if (!Array.isArray(meta.pendingMessages))
456
460
  meta.pendingMessages = [];
457
- meta.pendingMessages.push(`[子线程丢失] ${childId} 的记录已不存在(可能被清理),按失败处理。`);
461
+ meta.pendingMessages.push(`[Child thread lost] the record for ${childId} no longer exists (likely cleaned up); treating as failed.`);
458
462
  });
459
463
  log.warn(`recover: dropped missing child ${childId} from waiting parent ${parent.id}`);
460
464
  }
@@ -0,0 +1,21 @@
1
+ /** Parse the `version` field from a plugin.json manifest string, or null if absent/malformed.
2
+ * compareCalVer is a generic numeric dotted-version comparator, so plain semver ("0.1.0") works. */
3
+ export declare function parsePluginVersion(manifestJson: string): string | null;
4
+ /**
5
+ * Keep version-managed plugins in PLUGINS_DIR in sync with the shipped defaults.
6
+ *
7
+ * A default plugin that declares a `version` in `.claude-plugin/plugin.json` is deployed when
8
+ * missing, and refreshed (all its shipped files rewritten) whenever the shipped version is newer
9
+ * than the deployed one. A missing or unversioned deployed copy counts as oldest, so legacy installs
10
+ * are brought under management on first run. Unversioned default plugins (no manifest version) are
11
+ * left to init's copy-if-missing and never touched here. User-added files inside a managed plugin are
12
+ * preserved (only shipped files are written, nothing is deleted). Idempotent and crash-safe via
13
+ * atomicWrite.
14
+ *
15
+ * `opts` exists for tests; production calls it with no args (real DEFAULTS_DIR/plugins + PLUGINS_DIR).
16
+ * Returns the list of plugin names that were deployed or refreshed.
17
+ */
18
+ export declare function syncManagedPlugins(opts?: {
19
+ srcDir?: string;
20
+ dstDir?: string;
21
+ }): Promise<string[]>;
@@ -0,0 +1,119 @@
1
+ // input: DEFAULTS_DIR/plugins/<plugin> (each with .claude-plugin/plugin.json `version`) + PLUGINS_DIR (DATA_DIR/plugins)
2
+ // output: syncManagedPlugins() — deploys a new plugin, or refreshes a deployed one when the shipped version is newer
3
+ // pos: Startup asset-sync sibling to runMigrations / syncManagedHooks; keeps DATA_DIR/plugins in sync
4
+ // with defaults. init.ts copyDefaults() uses safeCopyDir (copy-if-missing) and only runs on
5
+ // `cortex init`, so an existing install never gets a NEW plugin or an UPDATED skill on upgrade.
6
+ // This closes that gap, keyed on each plugin's .claude-plugin/plugin.json `version`.
7
+ //
8
+ // CONVENTION: whenever you change ANY file inside a plugin (a skill's SKILL.md, a script, the
9
+ // manifest), bump that plugin's `version` in .claude-plugin/plugin.json — the analog of bumping
10
+ // @cortex-hook-version on a hook. Without a bump the change will NOT propagate to existing installs.
11
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
12
+ import * as fs from 'node:fs/promises';
13
+ import { existsSync } from 'node:fs';
14
+ import * as path from 'node:path';
15
+ import { DEFAULTS_DIR, PLUGINS_DIR } from '../core/paths.js';
16
+ import { atomicWrite } from '../core/atomic-write.js';
17
+ import { compareCalVer } from './version-migrations.js';
18
+ import { createLogger } from '../core/log.js';
19
+ const log = createLogger('plugin-sync');
20
+ const MANIFEST_REL = path.join('.claude-plugin', 'plugin.json');
21
+ /** Parse the `version` field from a plugin.json manifest string, or null if absent/malformed.
22
+ * compareCalVer is a generic numeric dotted-version comparator, so plain semver ("0.1.0") works. */
23
+ export function parsePluginVersion(manifestJson) {
24
+ try {
25
+ const parsed = JSON.parse(manifestJson);
26
+ if (parsed && typeof parsed === 'object' && typeof parsed.version === 'string') {
27
+ const v = parsed.version.trim();
28
+ return v.length > 0 ? v : null;
29
+ }
30
+ }
31
+ catch {
32
+ // malformed JSON → treat as unversioned
33
+ }
34
+ return null;
35
+ }
36
+ /** Read a plugin's manifest version from `<pluginDir>/.claude-plugin/plugin.json`, or null. */
37
+ async function readPluginVersion(pluginDir) {
38
+ try {
39
+ return parsePluginVersion(await fs.readFile(path.join(pluginDir, MANIFEST_REL), 'utf8'));
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ /** Recursively walk every file under `src` and atomicWrite it into `dst` at the same relative
46
+ * path, creating parent dirs as needed. Overwrites shipped files; never deletes anything already
47
+ * in `dst` (so user-added skills/files inside a managed plugin are preserved). */
48
+ async function copyPluginTree(src, dst) {
49
+ const entries = await fs.readdir(src, { withFileTypes: true });
50
+ for (const entry of entries) {
51
+ const srcPath = path.join(src, entry.name);
52
+ const dstPath = path.join(dst, entry.name);
53
+ if (entry.isDirectory()) {
54
+ await copyPluginTree(srcPath, dstPath);
55
+ }
56
+ else if (entry.isFile()) {
57
+ await fs.mkdir(path.dirname(dstPath), { recursive: true });
58
+ await atomicWrite(dstPath, await fs.readFile(srcPath, 'utf8'));
59
+ }
60
+ }
61
+ }
62
+ /**
63
+ * Keep version-managed plugins in PLUGINS_DIR in sync with the shipped defaults.
64
+ *
65
+ * A default plugin that declares a `version` in `.claude-plugin/plugin.json` is deployed when
66
+ * missing, and refreshed (all its shipped files rewritten) whenever the shipped version is newer
67
+ * than the deployed one. A missing or unversioned deployed copy counts as oldest, so legacy installs
68
+ * are brought under management on first run. Unversioned default plugins (no manifest version) are
69
+ * left to init's copy-if-missing and never touched here. User-added files inside a managed plugin are
70
+ * preserved (only shipped files are written, nothing is deleted). Idempotent and crash-safe via
71
+ * atomicWrite.
72
+ *
73
+ * `opts` exists for tests; production calls it with no args (real DEFAULTS_DIR/plugins + PLUGINS_DIR).
74
+ * Returns the list of plugin names that were deployed or refreshed.
75
+ */
76
+ export async function syncManagedPlugins(opts = {}) {
77
+ const srcDir = opts.srcDir ?? path.join(DEFAULTS_DIR, 'plugins');
78
+ const dstDir = opts.dstDir ?? PLUGINS_DIR;
79
+ if (!existsSync(srcDir))
80
+ return [];
81
+ let entries;
82
+ try {
83
+ entries = await fs.readdir(srcDir, { withFileTypes: true });
84
+ }
85
+ catch {
86
+ return [];
87
+ }
88
+ await fs.mkdir(dstDir, { recursive: true });
89
+ const updated = [];
90
+ for (const entry of entries) {
91
+ if (!entry.isDirectory())
92
+ continue;
93
+ const name = entry.name;
94
+ const srcPlugin = path.join(srcDir, name);
95
+ const srcVer = await readPluginVersion(srcPlugin);
96
+ if (!srcVer)
97
+ continue; // unversioned default → leave to init's copy-if-missing
98
+ const dstPlugin = path.join(dstDir, name);
99
+ if (existsSync(dstPlugin)) {
100
+ const dstVer = await readPluginVersion(dstPlugin);
101
+ // Deployed copy already at or ahead of the shipped version → current; skip.
102
+ // A missing/unparseable deployed version (dstVer === null) counts as oldest → refresh.
103
+ if (dstVer && compareCalVer(dstVer, srcVer) >= 0)
104
+ continue;
105
+ }
106
+ try {
107
+ await copyPluginTree(srcPlugin, dstPlugin);
108
+ updated.push(name);
109
+ log.info(`synced plugin ${name} → ${srcVer}`);
110
+ }
111
+ catch (e) {
112
+ log.error(`failed to sync plugin ${name}: ${e.message}`);
113
+ }
114
+ }
115
+ if (updated.length === 0) {
116
+ log.info('managed plugins up to date');
117
+ }
118
+ return updated;
119
+ }
@@ -21,6 +21,15 @@ export interface Migration {
21
21
  * the output back in is a no-op. Matches any block version on the start marker so an old
22
22
  * block is upgraded in place rather than duplicated. */
23
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;
24
33
  export interface MigrationOptions {
25
34
  /** Override DATA_DIR (user config location). Defaults to the real CORTEX_HOME. */
26
35
  dataDir?: string;
@@ -60,6 +60,79 @@ export function upsertMarkerBlock(content, block) {
60
60
  const trimmed = content.replace(/\s+$/, '');
61
61
  return `${trimmed}\n\n${block}\n`;
62
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
+ ];
63
136
  // ── Registry ───────────────────────────────────────────────────
64
137
  // Add new migrations here. The runner groups them by filePath and applies
65
138
  // pending ones in version-ascending order.
@@ -220,6 +293,33 @@ const migrations = [
220
293
  return upsertMarkerBlock(data, DOCS_BLOCK);
221
294
  },
222
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
+ },
223
323
  ];
224
324
  // ── Versions file I/O ──────────────────────────────────────────
225
325
  async function loadVersionsFrom(filePath) {
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 }) }));