@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
@@ -1,15 +1,19 @@
1
1
  // input: domain/threads, mode-manager, hook-runner, handles
2
- // output: runThread / continueThread / resumeThread / buildThreadSummary
2
+ // output: runThread / continueThread / resumeThread / resumeRateLimitedThread / buildThreadSummary
3
3
  // pos: runtime execution engine for the Thread system
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { threadStore } from '../../store/thread-repo.js';
6
- import { resolveNextStep, buildStepPrompt, recordStepResult, evaluateTransitions, completeThread, failThread, abortThread, peekPendingControl, clearPendingControl, tryEnterWaiting, checkContractBudget, isAdHocThread, getSessionKey, getTemplate, readArtifact, resolveSystemVars, } from './index.js';
6
+ import { resolveNextStep, buildStepPrompt, recordStepResult, evaluateTransitions, completeThread, failThread, markThreadRateLimited, abortThread, peekPendingControl, clearPendingControl, tryEnterWaiting, checkContractBudget, isAdHocThread, getSessionKey, getTemplate, readArtifact, resolveSystemVars, } from './index.js';
7
7
  import { runAgent, getClaudeMode, getActiveBackend, getActiveProfile } from '../agents/index.js';
8
+ import { isApiRateLimitError } from '../agents/config.js';
9
+ import { isThrottled } from '../costs/rate-limit-throttle.js';
10
+ import { recordResume } from '../costs/resume-registry.js';
8
11
  import { Icons } from '../../core/icons.js';
9
12
  import { closeSessionsByPrefix } from '../agents/index.js';
10
13
  import * as executionRegistry from '../executions/registry.js';
11
14
  import { sessionStore } from '../../store/session-registry-repo.js';
12
15
  import { formatDurationCompact } from '../../core/utils.js';
16
+ import { buildThreadStatusMessage } from '../../core/status-format.js';
13
17
  import { runningExecutions } from '../../core/running-executions.js';
14
18
  import { executeLifecycleHook } from './hook-runner.js';
15
19
  import { createToolTrace } from '../../platform/index.js';
@@ -57,7 +61,15 @@ async function resolveAndNotifyStep(threadId, ctx, opts) {
57
61
  // Update status message (multi-agent thread format; skip if caller provides onProgress)
58
62
  if (ctx.stream && multiAgent && !opts.onProgress) {
59
63
  const elapsed = (Date.now() - opts.startTime) / 1000;
60
- const statusText = `${Icons.processing} Thread ${threadRecord.id.substring(0, 12)} | Step ${threadRecord.currentStepIndex + 1}: *${label}* | ${Icons.stopwatch} ${formatDurationCompact(elapsed)}`;
64
+ const statusText = buildThreadStatusMessage({
65
+ threadId: threadRecord.id,
66
+ stepNumber: threadRecord.currentStepIndex + 1,
67
+ label,
68
+ elapsedS: elapsed,
69
+ taskProject: threadRecord.metadata?.taskProject ?? null,
70
+ taskId: threadRecord.metadata?.taskId ?? null,
71
+ taskText: threadRecord.metadata?.taskText ?? null,
72
+ });
61
73
  try {
62
74
  if (opts.statusMsg) {
63
75
  await opts.adapter.updateMessage(opts.statusMsg, { text: statusText });
@@ -122,15 +134,20 @@ function setupStepCallbacks(threadId, stepCtx, ctx, opts) {
122
134
  // Aggregate assistant output into the thread-runner's OutputStream; prefix only for multi-agent.
123
135
  const slotPrefix = multiAgent ? `*[${label}]*` : null;
124
136
  const baseAssistantMessage = (text) => { stream.emitText(slotPrefix ? `${slotPrefix} ${text}` : text); };
125
- // Tool trace (env-gated): caller-supplied onToolUse takes precedence. Otherwise build one bound
126
- // to the runner's own stream.
137
+ // Tool trace (env-gated): emit a compact per-tool line to the runner's stream when
138
+ // CORTEX_SHOW_TOOL_CALLS is on, while STILL firing any caller-supplied onToolUse
139
+ // (interactive plan/ask capture). Both must run — compose, don't choose — so dispatch /
140
+ // scheduled / webhook threads stream tool calls like a direct session. The trace fires
141
+ // first; the caller (interactive) fires after, preserving the onToolUse-before-ask ordering.
127
142
  const callerOnToolUse = opts.onToolUse ?? null;
128
- const toolTrace = callerOnToolUse ? null : createToolTrace(stream, { slotPrefix });
143
+ const toolTrace = createToolTrace(stream, { slotPrefix });
129
144
  const onAssistantMessage = toolTrace
130
145
  ? (text) => { toolTrace.flush(); baseAssistantMessage(text); }
131
146
  : baseAssistantMessage;
132
- const onToolUse = callerOnToolUse
133
- ?? (toolTrace ? (name, input) => toolTrace.onToolUse(name, input) : null);
147
+ const traceToolUse = toolTrace ? (name, input) => toolTrace.onToolUse(name, input) : null;
148
+ const onToolUse = traceToolUse && callerOnToolUse
149
+ ? (name, input) => { traceToolUse(name, input); callerOnToolUse(name, input); }
150
+ : (traceToolUse ?? callerOnToolUse);
134
151
  // onProgress: caller override (e.g. scheduler's buildUserProcessingMessage) takes precedence;
135
152
  // fallback to thread-specific status format for multi-agent pipelines
136
153
  const onProgress = opts.onProgress
@@ -139,7 +156,16 @@ function setupStepCallbacks(threadId, stepCtx, ctx, opts) {
139
156
  const elapsed = (Date.now() - opts.startTime) / 1000;
140
157
  if (opts.statusMsg) {
141
158
  opts.adapter.updateMessage(opts.statusMsg, {
142
- text: `${Icons.processing} Thread ${threadRecord.id.substring(0, 12)} | Step ${threadRecord.currentStepIndex + 1}: *${label}* (${progress?.num_turns || '?'} turns) | ${Icons.stopwatch} ${formatDurationCompact(elapsed)}`,
159
+ text: buildThreadStatusMessage({
160
+ threadId: threadRecord.id,
161
+ stepNumber: threadRecord.currentStepIndex + 1,
162
+ label,
163
+ elapsedS: elapsed,
164
+ numTurns: progress?.num_turns ?? null,
165
+ taskProject: threadRecord.metadata?.taskProject ?? null,
166
+ taskId: threadRecord.metadata?.taskId ?? null,
167
+ taskText: threadRecord.metadata?.taskText ?? null,
168
+ }),
143
169
  }).catch(() => { });
144
170
  }
145
171
  }
@@ -219,6 +245,19 @@ async function recordStepOutcome(threadId, stepCtx, result, ctx, opts) {
219
245
  // Record the step result
220
246
  const stepEndTime = new Date().toISOString();
221
247
  const stepDurationS = (new Date(stepEndTime).getTime() - new Date(stepStartTime).getTime()) / 1000;
248
+ // Rate-limit interruption (graceful path): the API window is exhausted and the throttle is
249
+ // active. Do NOT record the step result — leaving currentStepIndex unadvanced so resume
250
+ // re-runs THIS step (matches the thrown path). Tear down the execution as failed and pause the
251
+ // thread for auto-resume. Gate on isThrottled() so a stray rateLimited without an active
252
+ // throttle (no onResume will ever fire) falls through to the normal terminal path below.
253
+ if (result?.rateLimited && isThrottled()) {
254
+ executionRegistry.teardownExecution({
255
+ executionId: execution.id, status: 'failed', durationS: stepDurationS,
256
+ error: { message: 'Rate limited' },
257
+ });
258
+ await handleRateLimitInterruption(threadId, ctx, opts);
259
+ return;
260
+ }
222
261
  await recordStepResult(threadId, agentSlotId, {
223
262
  sessionId: result?.sessionId || null,
224
263
  sessionName,
@@ -258,6 +297,22 @@ async function recordStepOutcome(threadId, stepCtx, result, ctx, opts) {
258
297
  });
259
298
  }
260
299
  }
300
+ /** Pause the thread for auto-resume after an API rate limit interrupted a step. Records the
301
+ * thread in the resume registry (drained by resume-dispatcher when the window resets) and
302
+ * flips it to the non-terminal 'rate_limited' status. Sets ctx.rateLimited so the loop breaks
303
+ * and skips completeThread / onEnd. Shared by the graceful (recordStepOutcome) and thrown
304
+ * (runThread catch) paths. */
305
+ async function handleRateLimitInterruption(threadId, ctx, opts) {
306
+ ctx.rateLimited = true;
307
+ await markThreadRateLimited(threadId);
308
+ recordResume({
309
+ kind: 'thread',
310
+ threadId,
311
+ channel: opts.channel,
312
+ userMessage: threadStore.get(threadId)?.userMessage ?? '',
313
+ recordedAt: Date.now(),
314
+ });
315
+ }
261
316
  /** Decide whether the loop continues; run onTransition hook when transitioning.
262
317
  * Returns false to break the loop. */
263
318
  async function evaluateAndTransition(threadId, stepCtx, ctx, opts) {
@@ -326,6 +381,10 @@ async function runThread(threadId, opts) {
326
381
  const callbacks = setupStepCallbacks(threadId, stepCtx, ctx, opts);
327
382
  const result = await executeAndAwaitAgent(threadId, stepCtx, callbacks, ctx, opts);
328
383
  await recordStepOutcome(threadId, stepCtx, result, ctx, opts);
384
+ // Rate-limit pause (graceful path): recordStepOutcome paused the thread. Break out so the
385
+ // thread is NOT completed; resume-dispatcher re-enters it when the window resets.
386
+ if (ctx.rateLimited)
387
+ break;
329
388
  // Out-of-band control plane (DR-0015 problem 1): the agent signals abort / split / wait by
330
389
  // calling the thread_abort / thread_split / thread_wait MCP tools, which write a typed
331
390
  // metadata.pendingControl on this thread. Read it here at the step boundary — never scan the
@@ -394,13 +453,16 @@ async function runThread(threadId, opts) {
394
453
  // Skipped on suspension: onEnd semantics are "thread truly finished" (e.g. the dispatch
395
454
  // task-status-check hook must not nag while children are still working). The re-entry
396
455
  // path re-runs runThread, so onEnd still fires exactly once at final termination.
397
- if (!enteredWaiting) {
456
+ // Also skipped on rate-limit pause (like suspension): the dispatch task-status-check onEnd
457
+ // hook must not fire and release the still-claimed task while the thread is only paused.
458
+ if (!enteredWaiting && !ctx.rateLimited) {
398
459
  const threadForEnd = threadStore.get(threadId);
399
460
  const lastStep = threadForEnd.steps[threadForEnd.steps.length - 1];
400
461
  await executeLifecycleHook(threadId, 'end', ctx.template?.hooks?.onEnd, opts, lastStep?.agentSlotId);
401
462
  await executeLifecycleHook(threadId, 'end', opts.extraHooks?.onEnd, opts, lastStep?.agentSlotId);
402
463
  }
403
- // Only complete if not already in a terminal state (e.g. cancelled during loop)
464
+ // Only complete if not already in a terminal state (e.g. cancelled during loop). A
465
+ // rate-limit pause leaves status='rate_limited', so this guard also skips it.
404
466
  const threadBeforeComplete = threadStore.get(threadId);
405
467
  if (threadBeforeComplete && threadBeforeComplete.status === 'running') {
406
468
  await completeThread(threadId);
@@ -408,10 +470,18 @@ async function runThread(threadId, opts) {
408
470
  }
409
471
  catch (error) {
410
472
  const t = threadStore.get(threadId);
411
- if (t && t.status === 'running') {
412
- await failThread(threadId, error.message || 'Unknown error');
473
+ // Thrown rate-limit path: the agent threw a rate-limit error while the throttle is active.
474
+ // Pause for auto-resume instead of failing, and do NOT rethrow — the thread is left in
475
+ // 'rate_limited' and finalizeThread returns normally so wrappers see thread.status, not a throw.
476
+ if (t && t.status === 'running' && isApiRateLimitError(error?.message) && isThrottled()) {
477
+ await handleRateLimitInterruption(threadId, ctx, opts);
478
+ }
479
+ else {
480
+ if (t && t.status === 'running') {
481
+ await failThread(threadId, error.message || 'Unknown error');
482
+ }
483
+ throw error;
413
484
  }
414
- throw error;
415
485
  }
416
486
  finally {
417
487
  // Defensive: the per-step path finalizes each execution on success (recordStepOutcome) and on
@@ -442,13 +512,33 @@ async function continueThread(threadId, userMessage, opts) {
442
512
  const thread = threadStore.get(threadId);
443
513
  if (!thread)
444
514
  throw new Error(`Thread not found: ${threadId}`);
445
- if (thread.status !== 'running' && thread.status !== 'waiting') {
515
+ if (thread.status !== 'running' && thread.status !== 'waiting' && thread.status !== 'rate_limited') {
446
516
  throw new Error(`Thread ${threadId} is ${thread.status}, cannot continue`);
447
517
  }
448
518
  // Update the thread's user message for the new input
449
519
  await threadStore.mutate(threadId, (t) => {
450
520
  t.userMessage = userMessage;
451
521
  t.status = 'running';
522
+ if (t.metadata)
523
+ t.metadata.interruptedByRateLimit = false;
524
+ });
525
+ return runThread(threadId, opts);
526
+ }
527
+ // --- Resume a rate-limit-paused thread (auto-resume) ---
528
+ /** Re-enter a thread paused by an API rate limit (status==='rate_limited'). Like resumeThread,
529
+ * the userMessage is NOT overwritten — the thread re-runs its interrupted step from the original
530
+ * prompt/contract. Called by resume-dispatcher when the rate-limit window resets. */
531
+ async function resumeRateLimitedThread(threadId, opts) {
532
+ const thread = threadStore.get(threadId);
533
+ if (!thread)
534
+ throw new Error(`Thread not found: ${threadId}`);
535
+ if (thread.status !== 'rate_limited') {
536
+ throw new Error(`Thread ${threadId} is ${thread.status}, cannot resume (expected rate_limited)`);
537
+ }
538
+ await threadStore.mutate(threadId, (t) => {
539
+ t.status = 'running';
540
+ if (t.metadata)
541
+ t.metadata.interruptedByRateLimit = false;
452
542
  });
453
543
  return runThread(threadId, opts);
454
544
  }
@@ -479,10 +569,13 @@ function buildThreadSummary(result) {
479
569
  : thread.status === 'cancelled' ? Icons.blocked
480
570
  : thread.status === 'aborted' ? Icons.stopped
481
571
  : thread.status === 'waiting' ? Icons.processing
482
- : Icons.error;
572
+ : thread.status === 'rate_limited' ? Icons.warning
573
+ : Icons.error;
483
574
  const headline = thread.status === 'waiting'
484
575
  ? `${statusEmoji} Thread suspended — waiting on ${(thread.metadata?.waitingOn?.length ?? 0) + (thread.metadata?.waitingOnTasks?.length ?? 0)} child(ren) | ${steps.length} steps | $${totalCostUsd.toFixed(4)}`
485
- : `${statusEmoji} Thread complete | ${steps.length} steps | $${totalCostUsd.toFixed(4)} | ${formatDurationCompact(elapsed)}`;
576
+ : thread.status === 'rate_limited'
577
+ ? `${statusEmoji} Thread paused — rate limited, will auto-resume | ${steps.length} steps | $${totalCostUsd.toFixed(4)}`
578
+ : `${statusEmoji} Thread complete | ${steps.length} steps | $${totalCostUsd.toFixed(4)} | ${formatDurationCompact(elapsed)}`;
486
579
  const lines = [headline];
487
580
  if (steps.length > 1) {
488
581
  for (const step of steps) {
@@ -512,7 +605,7 @@ function cancelActiveThread(channel) {
512
605
  function getActiveHandle(channel) {
513
606
  return runningExecutions.getByChannel(channel)[0] ?? null;
514
607
  }
515
- export { runThread, continueThread, resumeThread, buildThreadSummary, cancelActiveThread, getActiveHandle,
608
+ export { runThread, continueThread, resumeThread, resumeRateLimitedThread, buildThreadSummary, cancelActiveThread, getActiveHandle,
516
609
  // Internal helpers — exported to support focused unit tests from agent-server/tests/thread-runner.test.ts.
517
610
  // Not part of the public API; callers outside the test harness should continue to use runThread().
518
611
  initThreadContext, resolveAndNotifyStep, buildStepConfig, setupStepCallbacks, executeAndAwaitAgent, recordStepOutcome, evaluateAndTransition, finalizeThread, };
@@ -60,4 +60,9 @@ export interface SplitDetection {
60
60
  export declare function abortThread(threadId: string, reason: string | null): Promise<boolean>;
61
61
  export declare function completeThread(threadId: string): Promise<boolean>;
62
62
  export declare function failThread(threadId: string, error: string): Promise<boolean>;
63
+ /** Pause a thread that was interrupted mid-run by an API rate limit. Non-terminal: the
64
+ * thread keeps its currentStepIndex/agents and is re-entered (from the interrupted step)
65
+ * by the resume-dispatcher when the rate-limit window resets. Does NOT set endedAt.
66
+ * Idempotent. */
67
+ export declare function markThreadRateLimited(threadId: string, note?: string): Promise<boolean>;
63
68
  export {};
@@ -478,3 +478,19 @@ export async function failThread(threadId, error) {
478
478
  log.info(`Failed thread ${threadId}: ${error}`);
479
479
  return true;
480
480
  }
481
+ /** Pause a thread that was interrupted mid-run by an API rate limit. Non-terminal: the
482
+ * thread keeps its currentStepIndex/agents and is re-entered (from the interrupted step)
483
+ * by the resume-dispatcher when the rate-limit window resets. Does NOT set endedAt.
484
+ * Idempotent. */
485
+ export async function markThreadRateLimited(threadId, note) {
486
+ const thread = threadStore.get(threadId);
487
+ if (!thread)
488
+ return false;
489
+ await threadStore.mutate(threadId, (t) => {
490
+ t.status = 'rate_limited';
491
+ t.error = note ?? 'Paused — interrupted by API rate limit';
492
+ (t.metadata ??= {}).interruptedByRateLimit = true;
493
+ });
494
+ log.info(`Rate-limit paused thread ${threadId}`);
495
+ return true;
496
+ }
package/dist/entry/app.js CHANGED
@@ -38,6 +38,7 @@ import { loadLang } from '../domain/system/preferences.js';
38
38
  // Extracted modules
39
39
  import { cleanupLogs, ensureMcpConfig } from './startup-helpers.js';
40
40
  import { createLogger } from '../core/log.js';
41
+ import { ensureAuthTokens } from '../core/auth.js';
41
42
  import { runningExecutions } from '../core/running-executions.js';
42
43
  import { planApprovals } from '../orchestration/interactions/plan-approvals.js';
43
44
  import { busyTracker } from '../orchestration/busy-tracker.js';
@@ -51,10 +52,13 @@ import { registerInteractionHandlers, initInteractionHandlers } from '../orchest
51
52
  import { CommandActionRouter } from '../orchestration/interactions/command-action-router.js';
52
53
  import { createUpdatePrompt } from '../orchestration/interactions/update-prompt.js';
53
54
  import { registerMessageHandler } from '../orchestration/routing/message-router.js';
54
- import { initRateLimitThrottle } from '../domain/costs/rate-limit-throttle.js';
55
+ import { initRateLimitThrottle, isThrottled } from '../domain/costs/rate-limit-throttle.js';
56
+ import { initResumeRegistry, getResumeCount, recordResume } from '../domain/costs/resume-registry.js';
57
+ import { dispatchPendingResumes } from '../orchestration/resume-dispatcher.js';
55
58
  import { scheduleRepo } from '../store/schedule-repo.js';
56
59
  import { runMigrations, migrateAistatusConfigLocation } from '../store/version-migrations.js';
57
60
  import { syncManagedHooks } from '../store/hook-sync.js';
61
+ import { syncManagedPlugins } from '../store/plugin-sync.js';
58
62
  import { costRepo } from '../store/cost-repo.js';
59
63
  import { profileRepo, startProfileWatcher, setAdminNotifier as setProfileNotifier } from '../store/profile-repo.js';
60
64
  import { sessionStore } from '../store/session-registry-repo.js';
@@ -71,6 +75,10 @@ import { createTuiSessionService } from '../domain/tui-session/index.js';
71
75
  import { enqueue, conduitQueues } from '../orchestration/conduit-queue.js';
72
76
  import { getCostSummary } from '../domain/costs/cost-tracker.js';
73
77
  dotenv.config({ path: path.join(CONFIG_DIR, '.env') });
78
+ // Ensure the WebSocket + webhook bearer tokens exist before either server starts. Generates
79
+ // and persists them to .env on first run (fail-closed auth — see core/auth.ts). Must run after
80
+ // dotenv.config() so pre-existing tokens are honored, and before startClientManager/startWebhookServer.
81
+ ensureAuthTokens();
74
82
  // Apply the persisted mode to env now that .env is loaded. This used to be an import-time
75
83
  // side effect inside domain/agents/config.ts; it is explicit here so that CLI processes
76
84
  // (cortex init / setup-gateway) importing that module don't get their env mutated.
@@ -180,10 +188,9 @@ setInteractiveCallbacksFactory(buildInteractiveCallbacks);
180
188
  const scheduler = createScheduler();
181
189
  scheduler.setAdminNotifier(notifyAdmin);
182
190
  setSchedulerRef(scheduler);
183
- initRateLimitThrottle(adapter, {
184
- save: (state) => scheduleRepo.setRateLimitThrottle(state),
185
- load: () => scheduleRepo.getRateLimitThrottle(),
186
- }).catch(e => log.error(`initRateLimitThrottle failed: ${e.message}`));
191
+ // Rate-limit resume registry + throttle are initialized later, inside main(), as one ordered
192
+ // awaited sequence (initRateLimitRecovery) — it must run AFTER threadStore.load() so it can
193
+ // reconcile orphaned rate-limited threads back into the resume queue.
187
194
  initDiskMonitor(adapter);
188
195
  const commandRouter = new CommandActionRouter();
189
196
  const dispatchCommand = registerCommands({
@@ -250,6 +257,10 @@ process.on('SIGTERM', async () => {
250
257
  // Refresh version-stamped hooks in DATA_DIR/hooks from the shipped defaults. init's deployHooks
251
258
  // only copies-if-missing, so without this an existing install never picks up hook code fixes.
252
259
  await syncManagedHooks();
260
+ // Deploy new plugins and refresh updated skills in DATA_DIR/plugins from the shipped defaults.
261
+ // init's copyDefaults (copy-if-missing, only on `cortex init`) never reaches an existing install,
262
+ // so without this a new plugin or an updated skill never propagates on upgrade.
263
+ await syncManagedPlugins();
253
264
  // DR-0012 §3.6: clean up orphan TUI tmux sessions from a previous agent-server lifetime.
254
265
  // We can't re-adopt them (sessionKey↔tmux mapping was never persisted) so the honest move
255
266
  // is to kill any leftovers — otherwise a later session that reuses the same sessionId will
@@ -313,6 +324,34 @@ process.on('SIGTERM', async () => {
313
324
  threadStore.load();
314
325
  await threadStore.markRunningAsFailedOnStartup();
315
326
  await threadStore.cleanup();
327
+ // --- Rate-limit recovery (ordered; must run after threadStore.load) ---
328
+ // 1) hydrate the persisted resume queue. 2) Reconcile orphaned rate-limited threads: any thread
329
+ // left in 'rate_limited' (markRunningAsFailedOnStartup deliberately spares them) that is not
330
+ // represented in the queue — dropped by a prior dispatcher skip, or a queue/throttle desync
331
+ // across restart — is re-queued (idempotent, dedupe by threadId). 3) Arm the throttle; its
332
+ // restart-recovery may fire onResume synchronously, draining the (already-reconciled) queue.
333
+ // 4) If nothing is throttled and entries remain, drain now so a clean window resumes them.
334
+ await initResumeRegistry({
335
+ save: (entries) => scheduleRepo.setResumeQueue(entries),
336
+ load: () => scheduleRepo.getResumeQueue(),
337
+ });
338
+ let reQueuedRateLimited = 0;
339
+ for (const t of threadStore.getAll()) {
340
+ if (t.status === 'rate_limited') {
341
+ recordResume({ kind: 'thread', threadId: t.id, channel: t.channel, userMessage: t.userMessage ?? '', recordedAt: Date.now() });
342
+ reQueuedRateLimited++;
343
+ }
344
+ }
345
+ if (reQueuedRateLimited > 0)
346
+ log.info(`Reconciled ${reQueuedRateLimited} rate-limited thread(s) into the resume queue`);
347
+ await initRateLimitThrottle(adapter, {
348
+ save: (state) => scheduleRepo.setRateLimitThrottle(state),
349
+ load: () => scheduleRepo.getRateLimitThrottle(),
350
+ }, () => { void dispatchPendingResumes(adapter); });
351
+ if (!isThrottled() && getResumeCount() > 0) {
352
+ log.info(`Startup: ${getResumeCount()} pending resume(s), no active throttle — draining`);
353
+ void dispatchPendingResumes(adapter);
354
+ }
316
355
  // GC: prune stale sessions (older than 7 days, unreferenced by running executions or active threads)
317
356
  sessionStore.setOnPruneSession(cleanupAllBackups);
318
357
  try {
package/dist/entry/cli.js CHANGED
@@ -29,6 +29,7 @@ import { runCli as taskRunCli } from '../domain/tasks/system/task-cli.js';
29
29
  import { runCli as installRunCli, getInstallHelp } from '../domain/system/install-cli.js';
30
30
  import { getResolvedPaths, formatConfigOutput, runInit, } from './init.js';
31
31
  import { cmdFeishu } from './feishu-login.js';
32
+ import { cmdDoctor, getDoctorHelp } from './doctor-cli.js';
32
33
  import { discoverEndpoints, writeMergedGatewayYaml, validateProfilesAgainstGateway, dryRunGatewayYaml } from '../core/gateway-generator.js';
33
34
  import { generateProfiles, writeProfilesJson } from '../core/profile-generator.js';
34
35
  import { CORTEX_VERSION } from '../core/version.js';
@@ -165,6 +166,7 @@ export function getCliHelp() {
165
166
  { name: 'task', description: 'Task system CLI (delegate to cortex-task)' },
166
167
  { name: 'install latest', description: 'Install the latest version of Cortex from npm' },
167
168
  { name: 'config', description: 'Show resolved paths and initialization status' },
169
+ { name: 'doctor', description: 'Health-check the install (runtime, login, platform, gateway); --fix to repair' },
168
170
  { name: 'feishu', description: 'Manage Feishu user-identity login (login / status / logout)' },
169
171
  { name: 'setup-gateway', description: 'Auto-detect Claude/PI configs and generate gateway.yaml + profiles.json' },
170
172
  { name: 'tui', description: 'Start the Terminal UI (TUI) client for local interaction' },
@@ -176,6 +178,8 @@ export function getCliHelp() {
176
178
  { description: 'Interactive init', command: 'cortex init' },
177
179
  { description: 'Init to custom directory', command: 'cortex init --home /tmp/my-cortex' },
178
180
  { description: 'Show resolved paths', command: 'cortex config' },
181
+ { description: 'Health-check the install', command: 'cortex doctor' },
182
+ { description: 'Diagnose and auto-repair', command: 'cortex doctor --fix' },
179
183
  { description: 'Re-generate gateway config', command: 'cortex setup-gateway' },
180
184
  { description: 'Start the server', command: 'cortex start' },
181
185
  { description: 'Stop the daemon', command: 'cortex daemon stop' },
@@ -551,6 +555,12 @@ export async function runCli(argv) {
551
555
  }
552
556
  case 'config':
553
557
  return { exitCode: 0, stdout: getConfigOutput(), stderr: '' };
558
+ case 'doctor': {
559
+ if (rest.includes('--help') || rest.includes('-h')) {
560
+ return { exitCode: 0, stdout: getDoctorHelp(), stderr: '' };
561
+ }
562
+ return cmdDoctor(rest);
563
+ }
554
564
  case 'feishu':
555
565
  return cmdFeishu(rest);
556
566
  case 'restart': {
@@ -0,0 +1,12 @@
1
+ import { type DoctorDeps, type FixActuators } from '../domain/system/doctor.js';
2
+ export interface CliResult {
3
+ exitCode: number;
4
+ stdout: string;
5
+ stderr: string;
6
+ }
7
+ export interface CmdDoctorDeps {
8
+ diag: DoctorDeps;
9
+ fix: FixActuators;
10
+ }
11
+ export declare function getDoctorHelp(): string;
12
+ export declare function cmdDoctor(args: string[], override?: Partial<CmdDoctorDeps>): Promise<CliResult>;
@@ -0,0 +1,76 @@
1
+ // input: argv (cortex doctor [--json] [--fix] [--help]) + optional injected deps
2
+ // output: cmdDoctor(args) → CliResult; getDoctorHelp() → help string
3
+ // pos: CLI wrapper for `cortex doctor`. Runs the diagnostic engine, optionally
4
+ // applies safe idempotent fixes, and renders a plain-text or JSON report.
5
+ // Exit code 1 when any check fails, else 0 (CLI Rule ④/exit-code).
6
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
7
+ import { formatHelp } from '../core/cli-utils.js';
8
+ import { runDiagnostics, applySafeFixes, createDefaultDoctorDeps, createDefaultFixActuators, } from '../domain/system/doctor.js';
9
+ export function getDoctorHelp() {
10
+ return formatHelp({
11
+ name: 'cortex doctor',
12
+ description: 'Health-check the Cortex installation — runtime, backend/login, messaging platform, gateway.',
13
+ usage: 'cortex doctor [options]',
14
+ options: [
15
+ { flag: '--fix', description: 'Apply safe, idempotent repairs (generate missing tokens, create dirs, rebuild mcp-config)' },
16
+ { flag: '--json', description: 'Emit the report as JSON' },
17
+ { flag: '--help, -h', description: 'Show this help' },
18
+ ],
19
+ examples: [
20
+ { description: 'Run a read-only diagnosis', command: 'cortex doctor' },
21
+ { description: 'Diagnose and auto-repair fixable issues', command: 'cortex doctor --fix' },
22
+ { description: 'Machine-readable output', command: 'cortex doctor --json' },
23
+ ],
24
+ });
25
+ }
26
+ const MARKER = {
27
+ pass: '[OK] ',
28
+ warn: '[WARN]',
29
+ fail: '[FAIL]',
30
+ skip: '[--] ',
31
+ };
32
+ function renderText(report, fixes) {
33
+ const lines = ['Cortex Doctor', ''];
34
+ for (const section of report.sections) {
35
+ lines.push(section.title);
36
+ for (const c of section.checks) {
37
+ lines.push(` ${MARKER[c.status]} ${c.label} — ${c.detail}`);
38
+ if (c.hint && (c.status === 'fail' || c.status === 'warn'))
39
+ lines.push(` ↳ ${c.hint}`);
40
+ }
41
+ lines.push('');
42
+ }
43
+ if (fixes.length > 0) {
44
+ lines.push('Fixes applied:');
45
+ for (const f of fixes)
46
+ lines.push(` ${f.applied ? '[OK] ' : '[--] '} ${f.label} — ${f.detail}`);
47
+ lines.push('');
48
+ }
49
+ const { pass, warn, fail } = report.counts;
50
+ lines.push(`Summary: ${pass} passed, ${warn} warning${warn === 1 ? '' : 's'}, ${fail} failed`);
51
+ if (fail > 0 || warn > 0) {
52
+ const anyFixable = report.sections.some(s => s.checks.some(c => c.fixable && (c.status === 'fail' || c.status === 'warn')));
53
+ if (anyFixable)
54
+ lines.push('Run `cortex doctor --fix` to auto-repair fixable issues.');
55
+ }
56
+ return lines.join('\n').trimEnd() + '\n';
57
+ }
58
+ export async function cmdDoctor(args, override) {
59
+ if (args.includes('--help') || args.includes('-h')) {
60
+ return { exitCode: 0, stdout: getDoctorHelp(), stderr: '' };
61
+ }
62
+ const asJson = args.includes('--json');
63
+ const doFix = args.includes('--fix');
64
+ const diag = override?.diag ?? createDefaultDoctorDeps();
65
+ const fix = override?.fix ?? createDefaultFixActuators();
66
+ let report = await runDiagnostics(diag);
67
+ let fixes = [];
68
+ if (doFix) {
69
+ fixes = await applySafeFixes(report, diag, fix);
70
+ report = await runDiagnostics(diag);
71
+ }
72
+ const stdout = asJson
73
+ ? JSON.stringify({ ...report, fixes: doFix ? fixes : undefined }, null, 2) + '\n'
74
+ : renderText(report, fixes);
75
+ return { exitCode: report.ok ? 0 : 1, stdout, stderr: '' };
76
+ }
@@ -9,6 +9,7 @@
9
9
  // DATA_DIR is resolved via the --home arg, $CORTEX_HOME env, or ~/.cortex/ default.
10
10
  // Run with: node dist/entry/cli.js init [--home <path>] [--force]
11
11
  import { mkdirSync, writeFileSync, copyFileSync, existsSync, readFileSync, readdirSync } from 'fs';
12
+ import { randomBytes } from 'crypto';
12
13
  import { execSync } from 'child_process';
13
14
  import * as path from 'path';
14
15
  import * as os from 'os';
@@ -87,6 +88,11 @@ export function generateDotEnvContent(answers) {
87
88
  '# Generated by `cortex init`',
88
89
  '',
89
90
  `CORTEX_MACHINE=${answers.machineName}`,
91
+ '',
92
+ '# Auth tokens — WS client (cortex-client ↔ server) + webhook bearer. Required (fail-closed).',
93
+ '# Remote cortex-client machines must share CORTEX_CLIENT_TOKEN. Rotate by editing here + restart.',
94
+ `CORTEX_CLIENT_TOKEN=${randomBytes(32).toString('hex')}`,
95
+ `CORTEX_WEBHOOK_TOKEN=${randomBytes(32).toString('hex')}`,
90
96
  ];
91
97
  // CORTEX_PLATFORM is a comma-separated list (runtime composes adapters via CompositeAdapter).
92
98
  // Each platform's token block is emitted independently when its config is present, so a
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin Claude Code PreToolUse event, node:http
3
4
  // output: stdout updatedInput containing user answers received from Slack
4
5
  // pos: PreToolUse hook: intercept AskUserQuestion and forward to Slack to collect answers
@@ -30,7 +31,12 @@ async function main() {
30
31
  port,
31
32
  path: '/hook/ask-user-question',
32
33
  method: 'POST',
33
- headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
34
+ headers: {
35
+ 'Content-Type': 'application/json',
36
+ 'Content-Length': Buffer.byteLength(body),
37
+ // Bearer token for the webhook auth gate (inherited from the session env).
38
+ 'x-cortex-token': process.env.CORTEX_WEBHOOK_TOKEN || '',
39
+ },
34
40
  timeout: 60 * 60 * 1000, // 60 minutes — user may take time to respond
35
41
  }, (res) => {
36
42
  let data = '';
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin Claude Code PreToolUse event, node:http
3
4
  // output: stdout permissionDecision (plan injected back after Slack approval)
4
5
  // pos: PreToolUse hook: intercept ExitPlanMode and forward plan to Slack for approval
@@ -36,7 +37,12 @@ async function main() {
36
37
  port,
37
38
  path: '/hook/exit-plan-mode',
38
39
  method: 'POST',
39
- headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
40
+ headers: {
41
+ 'Content-Type': 'application/json',
42
+ 'Content-Length': Buffer.byteLength(body),
43
+ // Bearer token for the webhook auth gate (inherited from the session env).
44
+ 'x-cortex-token': process.env.CORTEX_WEBHOOK_TOKEN || '',
45
+ },
40
46
  timeout: 60 * 60 * 1000, // 60 minutes — user may take time to respond
41
47
  }, (res) => {
42
48
  let data = '';
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin JSON from Claude PostToolUse hook
3
4
  // output: appends to _meta/access-log.jsonl per project
4
5
  // pos: Read/Grep memory access tracking hook
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin { channel, sessionId, sessionName, trigger, timestampIso } + env CORTEX_HOOK_*
3
4
  // output: stdout — prompt to inject into the closing session (empty stdout = skip)
4
5
  // pos: !new pre-close memory flush hook — recall valuable user and project info from the session, write to corresponding context files
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin HookContext, argv [targetAgent]
3
4
  // output: HookResult — compound + git commit prompt to targetAgent
4
5
  // pos: scheduler and *-review template onEnd compound/commit hook
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin JSON — Claude Code PostToolUse event or PI hook-bridge payload
3
4
  // output: { matched: [...], hookSpecificOutput: { additionalContext: "..." } }
4
5
  // pos: Read/Grep hook — check if file path matches scoped rules in ~/.cortex/rules/
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin Claude Code PreToolUse event, node:fs
3
4
  // output: Direct-write target file + deny to prevent Claude from re-running built-in Edit/Write
4
5
  // pos: PreToolUse hook: bypass Claude Code's hardcoded protection on .claude/ paths
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin Claude Code PostToolUse event, node:fs
3
4
  // output: Appends records to logs/session-activity/<session_id>.jsonl
4
5
  // pos: PostToolUse hook: track Read/Edit/Write/Skill for diff reconstruction
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin HookContext, argv [project, taskId]
3
4
  // output: HookResult — checks TASKS.yaml task status after thread ends
4
5
  // pos: task-dispatch thread onEnd status check hook
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin JSON — Claude Code PreToolUse event payload
3
4
  // output: stdout JSON — { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision, permissionDecisionReason } }
4
5
  // pos: PreToolUse hook — intercepts Edit/Write on **/TASKS.yaml, checks project lock