@cortex-agent/server 2026.6.11 → 2026.6.18

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 (105) hide show
  1. package/defaults/config/thread-templates.json +2 -2
  2. package/defaults/hooks/task-status-check.mjs +9 -7
  3. package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +103 -16
  4. package/defaults/plugins/cortex-system/skills/orient/SKILL.md +6 -6
  5. package/defaults/plugins/cortex-system/skills/thread/SKILL.md +29 -35
  6. package/defaults/prompts/directives/manager.md +21 -11
  7. package/dist/agent-adapter/claude/spawn-args.d.ts +5 -0
  8. package/dist/agent-adapter/claude/spawn-args.js +6 -0
  9. package/dist/agent-adapter/types.d.ts +4 -0
  10. package/dist/core/gateway-generator.js +24 -3
  11. package/dist/core/i18n.d.ts +19 -0
  12. package/dist/core/i18n.js +46 -0
  13. package/dist/core/locales/en.d.ts +438 -0
  14. package/dist/core/locales/en.js +24 -0
  15. package/dist/core/locales/slices/commands.d.ts +214 -0
  16. package/dist/core/locales/slices/commands.js +462 -0
  17. package/dist/core/locales/slices/init.d.ts +121 -0
  18. package/dist/core/locales/slices/init.js +380 -0
  19. package/dist/core/locales/slices/interactions.d.ts +47 -0
  20. package/dist/core/locales/slices/interactions.js +102 -0
  21. package/dist/core/locales/slices/lang.d.ts +8 -0
  22. package/dist/core/locales/slices/lang.js +18 -0
  23. package/dist/core/locales/slices/scheduling.d.ts +36 -0
  24. package/dist/core/locales/slices/scheduling.js +74 -0
  25. package/dist/core/locales/slices/startup.d.ts +6 -0
  26. package/dist/core/locales/slices/startup.js +14 -0
  27. package/dist/core/locales/slices/status.d.ts +20 -0
  28. package/dist/core/locales/slices/status.js +48 -0
  29. package/dist/core/locales/zh.d.ts +5 -0
  30. package/dist/core/locales/zh.js +23 -0
  31. package/dist/core/singleton-lock.d.ts +23 -0
  32. package/dist/core/singleton-lock.js +53 -0
  33. package/dist/core/status-format.js +2 -1
  34. package/dist/core/task-parser.d.ts +6 -0
  35. package/dist/core/task-parser.js +10 -0
  36. package/dist/core/types/thread-types.d.ts +29 -0
  37. package/dist/core/utils.d.ts +9 -1
  38. package/dist/core/utils.js +9 -1
  39. package/dist/domain/agents/config.d.ts +2 -1
  40. package/dist/domain/agents/config.js +25 -6
  41. package/dist/domain/agents/facade.d.ts +4 -0
  42. package/dist/domain/agents/facade.js +3 -1
  43. package/dist/domain/mcp/core-server.js +15 -9
  44. package/dist/domain/mcp/tools/task-monitor.d.ts +2 -0
  45. package/dist/domain/mcp/tools/task-monitor.js +99 -0
  46. package/dist/domain/mcp/tools/thread-ops.js +50 -85
  47. package/dist/domain/scheduling/jobs/task-dispatch.js +18 -16
  48. package/dist/domain/scheduling/schedule-command.js +38 -37
  49. package/dist/domain/system/github-release.d.ts +18 -0
  50. package/dist/domain/system/github-release.js +106 -0
  51. package/dist/domain/system/preferences.d.ts +12 -0
  52. package/dist/domain/system/preferences.js +36 -0
  53. package/dist/domain/tasks/dispatch-utils.d.ts +5 -0
  54. package/dist/domain/tasks/dispatch-utils.js +9 -1
  55. package/dist/domain/tasks/dispatcher.d.ts +11 -2
  56. package/dist/domain/tasks/dispatcher.js +41 -11
  57. package/dist/domain/tasks/system/task-cli.d.ts +1 -0
  58. package/dist/domain/tasks/system/task-cli.js +82 -6
  59. package/dist/domain/tasks/system/task-mutations.d.ts +6 -1
  60. package/dist/domain/tasks/system/task-mutations.js +10 -1
  61. package/dist/domain/threads/hook-runner.js +1 -0
  62. package/dist/domain/threads/prompt-builder.d.ts +6 -0
  63. package/dist/domain/threads/prompt-builder.js +34 -11
  64. package/dist/domain/threads/runner.d.ts +5 -0
  65. package/dist/domain/threads/runner.js +44 -11
  66. package/dist/domain/threads/state-machine.d.ts +9 -12
  67. package/dist/domain/threads/state-machine.js +27 -50
  68. package/dist/entry/app.js +36 -3
  69. package/dist/entry/daemon.js +12 -30
  70. package/dist/entry/init.d.ts +4 -3
  71. package/dist/entry/init.js +151 -208
  72. package/dist/entry/startup-notify.js +6 -3
  73. package/dist/hooks/task-status-check.mjs +9 -7
  74. package/dist/orchestration/interactions/interaction-handlers.js +12 -11
  75. package/dist/orchestration/interactions/update-prompt-slack.js +11 -10
  76. package/dist/orchestration/interactions/update-prompt.js +66 -11
  77. package/dist/orchestration/lifecycle.js +13 -12
  78. package/dist/orchestration/routing/commands/cancel.js +10 -9
  79. package/dist/orchestration/routing/commands/channel.js +27 -26
  80. package/dist/orchestration/routing/commands/cost.js +10 -2
  81. package/dist/orchestration/routing/commands/device.js +11 -9
  82. package/dist/orchestration/routing/commands/dispatch.js +10 -10
  83. package/dist/orchestration/routing/commands/index.js +6 -2
  84. package/dist/orchestration/routing/commands/lang.d.ts +3 -0
  85. package/dist/orchestration/routing/commands/lang.js +31 -0
  86. package/dist/orchestration/routing/commands/mode.js +28 -27
  87. package/dist/orchestration/routing/commands/nvtop.js +13 -12
  88. package/dist/orchestration/routing/commands/orient.js +2 -1
  89. package/dist/orchestration/routing/commands/schedule.js +23 -22
  90. package/dist/orchestration/routing/commands/sendfile.js +8 -7
  91. package/dist/orchestration/routing/commands/session.js +11 -10
  92. package/dist/orchestration/routing/commands/status.js +78 -71
  93. package/dist/orchestration/routing/commands/tail.js +6 -5
  94. package/dist/orchestration/routing/commands/task.js +23 -22
  95. package/dist/orchestration/routing/commands/thread-handlers.js +40 -39
  96. package/dist/orchestration/routing/webhook.js +38 -1
  97. package/dist/orchestration/status-helpers.js +6 -5
  98. package/dist/orchestration/thread-callback.d.ts +11 -1
  99. package/dist/orchestration/thread-callback.js +66 -30
  100. package/dist/platform/adapters/feishu.d.ts +11 -0
  101. package/dist/platform/adapters/feishu.js +74 -3
  102. package/dist/platform/interactive-builder.js +19 -18
  103. package/dist/store/version-migrations.d.ts +7 -0
  104. package/dist/store/version-migrations.js +88 -0
  105. package/package.json +1 -1
@@ -0,0 +1,106 @@
1
+ // input: version string (CalVer format), fetch, file I/O
2
+ // output: ReleaseInfo | null, cached release notes
3
+ // pos: GitHub Release API client with local caching
4
+ import * as fs from 'node:fs';
5
+ import * as path from 'node:path';
6
+ import { STORE_DIR } from '../../core/paths.js';
7
+ import { createLogger } from '../../core/log.js';
8
+ const log = createLogger('github-release');
9
+ const GITHUB_API_BASE = 'https://api.github.com';
10
+ const REPO_OWNER = 'fangxm233';
11
+ const REPO_NAME = 'cortex-agent';
12
+ const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
13
+ const CACHE_FILE = path.join(STORE_DIR, 'release-cache.json');
14
+ /**
15
+ * Load cache from disk, or return empty structure if missing/invalid.
16
+ */
17
+ function loadCache() {
18
+ if (!fs.existsSync(CACHE_FILE)) {
19
+ return { releases: {} };
20
+ }
21
+ try {
22
+ const data = fs.readFileSync(CACHE_FILE, 'utf8');
23
+ return JSON.parse(data);
24
+ }
25
+ catch (e) {
26
+ log.warn(`Failed to load release cache: ${e.message}`);
27
+ return { releases: {} };
28
+ }
29
+ }
30
+ /**
31
+ * Save cache to disk.
32
+ */
33
+ function saveCache(cache) {
34
+ try {
35
+ fs.writeFileSync(CACHE_FILE, JSON.stringify(cache, null, 2));
36
+ }
37
+ catch (e) {
38
+ log.warn(`Failed to save release cache: ${e.message}`);
39
+ }
40
+ }
41
+ /**
42
+ * Build GitHub Release API URL for a given version.
43
+ * GitHub tag format: server-v{version}
44
+ */
45
+ function buildGitHubApiUrl(version) {
46
+ const tagName = `server-v${version}`;
47
+ return `${GITHUB_API_BASE}/repos/${REPO_OWNER}/${REPO_NAME}/releases/tags/${tagName}`;
48
+ }
49
+ /**
50
+ * Build GitHub Release web URL for a given version.
51
+ */
52
+ export function buildGitHubReleaseUrl(version) {
53
+ const tagName = `server-v${version}`;
54
+ return `https://github.com/${REPO_OWNER}/${REPO_NAME}/releases/tag/${tagName}`;
55
+ }
56
+ /**
57
+ * Fetch release notes from GitHub API for a given version.
58
+ * Returns cached result if available and not expired.
59
+ * Returns null if fetch fails or release doesn't exist.
60
+ */
61
+ export async function fetchReleaseNote(version) {
62
+ const cache = loadCache();
63
+ const cached = cache.releases[version];
64
+ // Check if cache is valid (not expired)
65
+ if (cached) {
66
+ const age = Date.now() - cached.fetchedAt;
67
+ if (age < CACHE_TTL_MS) {
68
+ log.debug(`Using cached release note for ${version}`);
69
+ return cached.info;
70
+ }
71
+ }
72
+ // Fetch from GitHub API
73
+ const url = buildGitHubApiUrl(version);
74
+ try {
75
+ const response = await fetch(url);
76
+ if (!response.ok) {
77
+ if (response.status === 404) {
78
+ log.warn(`Release not found for version ${version}`);
79
+ }
80
+ else {
81
+ log.warn(`GitHub API error: ${response.status} ${response.statusText}`);
82
+ }
83
+ return null;
84
+ }
85
+ const data = (await response.json());
86
+ const releaseInfo = {
87
+ tagName: data.tag_name,
88
+ version,
89
+ name: data.name || `Release ${version}`,
90
+ body: data.body || '',
91
+ htmlUrl: data.html_url,
92
+ publishedAt: data.published_at,
93
+ };
94
+ // Update cache
95
+ cache.releases[version] = {
96
+ info: releaseInfo,
97
+ fetchedAt: Date.now(),
98
+ };
99
+ saveCache(cache);
100
+ return releaseInfo;
101
+ }
102
+ catch (error) {
103
+ log.error(`Failed to fetch release note for ${version}: ${error.message}`);
104
+ return null;
105
+ }
106
+ }
@@ -0,0 +1,12 @@
1
+ import { type Locale } from '../../core/i18n.js';
2
+ /** Operator display preferences. Extensible — language today, room for date/number formats etc. */
3
+ export interface Preferences {
4
+ lang?: Locale;
5
+ }
6
+ export declare function loadPreferences(): Preferences;
7
+ /** Resolve the persisted UI language, defaulting to 'en'. */
8
+ export declare function loadLang(): Locale;
9
+ /** Persist the UI language, preserving any other preference keys already on disk. */
10
+ export declare function setLang(loc: Locale): void;
11
+ /** Test-only: redirect the preferences file to an isolated temp location. */
12
+ export declare function _testSetPreferencesFile(p: string): void;
@@ -0,0 +1,36 @@
1
+ // input: CONFIG_DIR constant, core/i18n normalizeLocale
2
+ // output: loadPreferences / loadLang / setLang for config/preferences.json
3
+ // pos: operator-level display preferences (language, future UI prefs). Set-once + runtime
4
+ // switchable via !lang. Separate from mode.json (LLM execution state) by design.
5
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
6
+ import * as fs from 'fs';
7
+ import * as path from 'path';
8
+ import { CONFIG_DIR } from '../../core/utils.js';
9
+ import { normalizeLocale } from '../../core/i18n.js';
10
+ // Mutable for test isolation — tests redirect this via _testSetPreferencesFile.
11
+ let prefsFilePath = path.join(CONFIG_DIR, 'preferences.json');
12
+ export function loadPreferences() {
13
+ try {
14
+ const parsed = JSON.parse(fs.readFileSync(prefsFilePath, 'utf8'));
15
+ return parsed && typeof parsed === 'object' ? parsed : {};
16
+ }
17
+ catch {
18
+ return {};
19
+ }
20
+ }
21
+ /** Resolve the persisted UI language, defaulting to 'en'. */
22
+ export function loadLang() {
23
+ return normalizeLocale(loadPreferences().lang);
24
+ }
25
+ /** Persist the UI language, preserving any other preference keys already on disk. */
26
+ export function setLang(loc) {
27
+ const normalized = normalizeLocale(loc);
28
+ const current = loadPreferences();
29
+ const next = { ...current, lang: normalized };
30
+ fs.mkdirSync(path.dirname(prefsFilePath), { recursive: true });
31
+ fs.writeFileSync(prefsFilePath, JSON.stringify(next, null, 2) + '\n');
32
+ }
33
+ /** Test-only: redirect the preferences file to an isolated temp location. */
34
+ export function _testSetPreferencesFile(p) {
35
+ prefsFilePath = p;
36
+ }
@@ -71,6 +71,11 @@ export interface AbortOutcome {
71
71
  note?: string;
72
72
  error?: string;
73
73
  }
74
+ /** Canonical block reason for a worker-aborted task. Single source so the runner's
75
+ * pre-onEnd block (DR-0015 problem 2) and processAbortOutcome produce byte-identical
76
+ * reasons — a second block with the same reason is a no-op commit (git porcelain sees no
77
+ * change), so blocking in both places is safe. */
78
+ export declare function formatWorkerAbortReason(raw: string | null): string;
74
79
  /** Process an aborted dispatch thread: the worker said "I can't" ([ABORT: <reason>]) —
75
80
  * block the task with the abort reason. taskMutator.block publishes task.blocked, which
76
81
  * wakes a manager thread waiting on this task (its parent re-plans); with no manager the
@@ -167,6 +167,14 @@ async function processSplitOutcome(args, deps) {
167
167
  await deps.unclaim(args.taskId);
168
168
  return { handled: true, note: `split into ${detection.subtasks.length} subtask(s) — parent kept as join node` };
169
169
  }
170
+ /** Canonical block reason for a worker-aborted task. Single source so the runner's
171
+ * pre-onEnd block (DR-0015 problem 2) and processAbortOutcome produce byte-identical
172
+ * reasons — a second block with the same reason is a no-op commit (git porcelain sees no
173
+ * change), so blocking in both places is safe. */
174
+ export function formatWorkerAbortReason(raw) {
175
+ const r = (raw || 'no reason given').replace(/\s+/g, ' ').trim() || 'no reason given';
176
+ return `worker-abort: ${r}`.slice(0, 280);
177
+ }
170
178
  /** Process an aborted dispatch thread: the worker said "I can't" ([ABORT: <reason>]) —
171
179
  * block the task with the abort reason. taskMutator.block publishes task.blocked, which
172
180
  * wakes a manager thread waiting on this task (its parent re-plans); with no manager the
@@ -182,7 +190,7 @@ async function processAbortOutcome(args, deps) {
182
190
  return { handled: false };
183
191
  }
184
192
  const rawReason = (thread.abortReason || 'no reason given').replace(/\s+/g, ' ').trim();
185
- const reason = `worker-abort: ${rawReason}`.slice(0, 280);
193
+ const reason = formatWorkerAbortReason(thread.abortReason);
186
194
  const result = await deps.block(args.taskId, reason);
187
195
  if (!result.success) {
188
196
  return { handled: true, error: result.message };
@@ -31,18 +31,27 @@ interface DispatchOutcome {
31
31
  interface FilterDeps {
32
32
  findActiveDispatchMatch?: (task: any, scheduleTaskId: string) => DispatchMatch | null;
33
33
  checkRealGpuOccupancy?: (machine: string) => Promise<GpuOccupancyResult>;
34
+ isTemplateRateLimited?: (templateName: string, dispatchProfile: string | null) => boolean;
35
+ /** Scheduler-resolved dispatch profile — used only to resolve `__active__` template slots. */
36
+ profileName?: string | null;
34
37
  }
35
38
  declare function isValidDispatchPrompt(value: unknown): boolean;
36
39
  declare function filterLockedProjects(tasks: any[]): any[];
37
40
  declare function checkRealGpuOccupancy(machine: string): Promise<GpuOccupancyResult>;
38
41
  declare function selectTask(tasks: any[] | null): any | null;
39
42
  declare function findActiveDispatchMatch(task: any, scheduleTaskId: string): DispatchMatch | null;
43
+ /** True when the task's template cannot run: ANY of its agents' profiles is fully
44
+ * rate-limited (a known-blocked later agent would fail the thread mid-pipeline and
45
+ * unclaim the task, discarding earlier agents' work). Empty resolution (unknown
46
+ * template / no concrete profiles) falls back to checking the dispatch profile. */
47
+ declare function isTemplateRateLimited(templateName: string, dispatchProfile: string | null, check?: (profile: string | null) => boolean): boolean;
40
48
  declare function filterDispatchableTasks(tasks: any[] | null, scheduleTaskId: string, gpuBusyCounts?: Map<string, number>, deps?: FilterDeps): Promise<any[]>;
41
49
  declare function computeNextInterval(outcome: DispatchOutcome): number;
42
50
  declare function hasRunningExecutionForSchedule(records: Pick<ExecutionRecord, 'status' | 'kind' | 'scheduleTaskId'>[], scheduleTaskId: string): boolean;
43
51
  declare function updateScheduleInterval(scheduler: any, scheduleTaskId: string, newIntervalMs: number): Promise<void>;
44
- declare function selectAndClaimTask({ scheduleTaskId, dryRun }: {
52
+ declare function selectAndClaimTask({ scheduleTaskId, dryRun, profileName }: {
45
53
  scheduleTaskId: string;
46
54
  dryRun?: boolean;
55
+ profileName?: string | null;
47
56
  }): Promise<SelectAndClaimResult | null>;
48
- export { selectAndClaimTask, hasRunningExecutionForSchedule, computeNextInterval, updateScheduleInterval, isValidDispatchPrompt, selectTask, filterLockedProjects, filterDispatchableTasks, findActiveDispatchMatch, checkRealGpuOccupancy, };
57
+ export { selectAndClaimTask, hasRunningExecutionForSchedule, computeNextInterval, updateScheduleInterval, isValidDispatchPrompt, isTemplateRateLimited, selectTask, filterLockedProjects, filterDispatchableTasks, findActiveDispatchMatch, checkRealGpuOccupancy, };
@@ -1,6 +1,6 @@
1
- // input: task-store, client-manager, execution-registry
2
- // output: selectAndClaimTask + schedule/interval helpers
3
- // pos: programmatic dispatch for task selection and claiming
1
+ // input: task-store, client-manager, execution-registry, threads (template profiles), agents facade (rate limits)
2
+ // output: selectAndClaimTask + isTemplateRateLimited + schedule/interval helpers
3
+ // pos: programmatic dispatch for task selection and claiming; rate-limit eligibility is per-task, resolved from each task's template profiles
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { createLogger } from '../../core/log.js';
6
6
  import { isProjectLocked } from './system/task-lock.js';
@@ -13,6 +13,8 @@ import * as executionRegistry from '../executions/registry.js';
13
13
  import { taskStore } from './store.js';
14
14
  import { taskMutator } from './mutator.js';
15
15
  import { listTemplateNames } from '../threads/template-loader.js';
16
+ import { resolveTemplateProfiles } from '../threads/index.js';
17
+ import { allConfigsRateLimited } from '../agents/facade.js';
16
18
  // --- Null/empty prompt guard (ISS-CS-005 durable fix) ---
17
19
  function isValidDispatchPrompt(value) {
18
20
  if (!value || typeof value === 'object')
@@ -112,6 +114,22 @@ function findActiveDispatchMatch(task, scheduleTaskId) {
112
114
  }
113
115
  return null;
114
116
  }
117
+ // --- Template-profile rate-limit eligibility ---
118
+ // A task's thread runs with its TEMPLATE's agent profiles (hardcoded profiles win;
119
+ // metadata.profileOverride only applies to __active__ slots — see threads/runner.ts).
120
+ // Gating on the scheduler-resolved dispatch profile was wrong in both directions:
121
+ // it over-blocked templates whose profiles were fine and under-blocked templates
122
+ // whose profiles were limited.
123
+ /** True when the task's template cannot run: ANY of its agents' profiles is fully
124
+ * rate-limited (a known-blocked later agent would fail the thread mid-pipeline and
125
+ * unclaim the task, discarding earlier agents' work). Empty resolution (unknown
126
+ * template / no concrete profiles) falls back to checking the dispatch profile. */
127
+ function isTemplateRateLimited(templateName, dispatchProfile, check = allConfigsRateLimited) {
128
+ const profiles = resolveTemplateProfiles(templateName, dispatchProfile);
129
+ if (profiles.length === 0)
130
+ return check(dispatchProfile);
131
+ return profiles.some((p) => check(p));
132
+ }
115
133
  // --- Unknown-template warning dedup (per-process, per-(task_hash, template) pair) ---
116
134
  const _unknownTemplateWarnedKeys = new Set();
117
135
  function warnOnceUnknownTemplate(task) {
@@ -127,11 +145,14 @@ async function filterDispatchableTasks(tasks, scheduleTaskId, gpuBusyCounts = ne
127
145
  return [];
128
146
  const findDuplicate = deps.findActiveDispatchMatch || findActiveDispatchMatch;
129
147
  const checkGpu = deps.checkRealGpuOccupancy || checkRealGpuOccupancy;
148
+ const checkTemplateRateLimited = deps.isTemplateRateLimited || isTemplateRateLimited;
149
+ const dispatchProfile = deps.profileName ?? null;
130
150
  const gpuStatusCache = new Map();
131
151
  // Fail-open if templates haven't been loaded yet (size === 0): let downstream
132
152
  // createThread surface the error rather than silently dropping every task.
133
153
  const validTemplates = new Set(listTemplateNames());
134
154
  const eligible = [];
155
+ let rateLimitedCount = 0;
135
156
  for (const task of tasks) {
136
157
  if (!task.template) {
137
158
  continue;
@@ -140,6 +161,12 @@ async function filterDispatchableTasks(tasks, scheduleTaskId, gpuBusyCounts = ne
140
161
  warnOnceUnknownTemplate(task);
141
162
  continue;
142
163
  }
164
+ // Skip tasks whose template profiles are rate-limited; later tasks with
165
+ // usable templates still flow through (per-task gating, not whole-cycle).
166
+ if (checkTemplateRateLimited(task.template, dispatchProfile)) {
167
+ rateLimitedCount += 1;
168
+ continue;
169
+ }
143
170
  // Check remote GPU device is online (local machine is always reachable)
144
171
  if (task.gpu && task.gpu !== getLocalMachine() && !isDeviceOnline(task.gpu)) {
145
172
  continue;
@@ -173,6 +200,9 @@ async function filterDispatchableTasks(tasks, scheduleTaskId, gpuBusyCounts = ne
173
200
  }
174
201
  eligible.push(task);
175
202
  }
203
+ if (rateLimitedCount > 0) {
204
+ log.info(`Skipped ${rateLimitedCount} task(s) — template profiles rate-limited`);
205
+ }
176
206
  return eligible;
177
207
  }
178
208
  // --- Interval computation ---
@@ -230,13 +260,13 @@ function buildDispatchPrompt(task) {
230
260
  ];
231
261
  sections.push(isolation.join('\n'));
232
262
  const escalation = [
233
- '## If This Task Is Mis-Scoped ([ABORT])',
263
+ '## If This Task Is Mis-Scoped (thread_abort)',
234
264
  '',
235
- 'If during execution you discover this task is far bigger than its description suggests, or its scope is wrong (multiple independent work units crammed together, missing prerequisites, contradictory requirements), do NOT grind through it. Append to the artifact:',
265
+ 'If during execution you discover this task is far bigger than its description suggests, or its scope is wrong (multiple independent work units crammed together, missing prerequisites, contradictory requirements), do NOT grind through it. Call the `thread_abort` tool:',
236
266
  '',
237
- ' [ABORT: too-big — <one-line diagnosis of what the real structure is>]',
267
+ ' thread_abort(kind="too-big", diagnosis="<one-line diagnosis of what the real structure is>")',
238
268
  '',
239
- 'The task will be blocked with your diagnosis and escalated: its manager (or a human) re-plans the decomposition with full context. A precise diagnosis is the most valuable thing you can produce here — it beats a half-done grind every time.',
269
+ 'The task will be blocked with your diagnosis and escalated: its manager (or a human) re-plans the decomposition with full context. A precise diagnosis is the most valuable thing you can produce here — it beats a half-done grind every time. (Use kind="too-big" or "mis-scoped" for structural problems, "blocked-external" for a missing external resource.) If instead you can already see the right decomposition, call `thread_split` with the subtasks.',
240
270
  ];
241
271
  sections.push(escalation.join('\n'));
242
272
  const completion = [
@@ -259,15 +289,15 @@ function buildDispatchPrompt(task) {
259
289
  return sections.join('\n\n');
260
290
  }
261
291
  // --- Main entry point: select and claim a task for local execution ---
262
- async function selectAndClaimTask({ scheduleTaskId, dryRun = false }) {
292
+ async function selectAndClaimTask({ scheduleTaskId, dryRun = false, profileName = null }) {
263
293
  log.info('Starting task selection cycle');
264
294
  // Get actionable tasks + GPU busy machines
265
295
  let tasks = taskStore.getActionable();
266
296
  tasks = filterLockedProjects(tasks);
267
297
  const gpuBusyMachines = taskStore.getGpuBusyMachines();
268
298
  log.info(`Found ${tasks.length} actionable task(s)`);
269
- // Filter to dispatchable tasks
270
- const dispatchableTasks = await filterDispatchableTasks(tasks, scheduleTaskId, gpuBusyMachines);
299
+ // Filter to dispatchable tasks (incl. per-template rate-limit eligibility)
300
+ const dispatchableTasks = await filterDispatchableTasks(tasks, scheduleTaskId, gpuBusyMachines, { profileName });
271
301
  log.info(`${dispatchableTasks.length} task(s) dispatchable after preflight`);
272
302
  // Select task
273
303
  const selectedTask = selectTask(dispatchableTasks);
@@ -306,6 +336,6 @@ async function selectAndClaimTask({ scheduleTaskId, dryRun = false }) {
306
336
  template: selectedTask.template || null,
307
337
  };
308
338
  }
309
- export { selectAndClaimTask, hasRunningExecutionForSchedule, computeNextInterval, updateScheduleInterval, isValidDispatchPrompt,
339
+ export { selectAndClaimTask, hasRunningExecutionForSchedule, computeNextInterval, updateScheduleInterval, isValidDispatchPrompt, isTemplateRateLimited,
310
340
  // For testing
311
341
  selectTask, filterLockedProjects, filterDispatchableTasks, findActiveDispatchMatch, checkRealGpuOccupancy, };
@@ -29,6 +29,7 @@ interface ParsedValues {
29
29
  force: boolean;
30
30
  showDeps: boolean;
31
31
  autoLock: boolean;
32
+ noNotify: boolean;
32
33
  }
33
34
  declare function getCliHelp(): string;
34
35
  declare function splitCommand(argv: string[]): {
@@ -19,7 +19,7 @@ const WRITE_COMMANDS = new Set([
19
19
  'claim', 'unclaim', 'pause', 'resume', 'pending', 'complete', 'uncomplete',
20
20
  'request-approval', 'approve', 'clear-approval',
21
21
  'block', 'unblock',
22
- 'add', 'edit', 'batch-edit', 'bulk-add', 'decompose',
22
+ 'add', 'spawn', 'edit', 'batch-edit', 'bulk-add', 'decompose',
23
23
  'assign-ids', 'validate', 'stop',
24
24
  'lock-acquire', 'lock-release', 'lock-status', 'lock-force-release',
25
25
  ]);
@@ -35,7 +35,7 @@ const COMMANDS_NEEDING_PROJECT = new Set([
35
35
  'claim', 'unclaim', 'pause', 'resume', 'pending', 'complete', 'uncomplete',
36
36
  'request-approval', 'approve', 'clear-approval',
37
37
  'block', 'unblock',
38
- 'add', 'edit', 'batch-edit', 'bulk-add', 'decompose',
38
+ 'add', 'spawn', 'edit', 'batch-edit', 'bulk-add', 'decompose',
39
39
  'lock-acquire', 'lock-release', 'lock-force-release',
40
40
  ]);
41
41
  const COMMON_FLAGS = new Set(['--base-dir', '--project', '--task-id']);
@@ -46,7 +46,8 @@ const COMMAND_FLAG_ALLOWLIST = {
46
46
  show: new Set([...COMMON_FLAGS, '--json', '--task-ids']),
47
47
  deps: new Set([...COMMON_FLAGS, '--json', '--task-ids']),
48
48
  tree: new Set([...COMMON_FLAGS]),
49
- add: new Set([...COMMON_FLAGS, '--text', '--why', '--done-when', '--plan', '--priority', '--template', '--depends-on', '--auto-lock']),
49
+ add: new Set([...COMMON_FLAGS, '--text', '--why', '--done-when', '--plan', '--priority', '--template', '--depends-on', '--auto-lock', '--no-notify']),
50
+ spawn: new Set([...COMMON_FLAGS, '--text', '--why', '--done-when', '--plan', '--priority', '--template', '--depends-on', '--auto-lock']),
50
51
  lint: new Set([...COMMON_FLAGS, '--json']),
51
52
  stats: new Set([...COMMON_FLAGS, '--json']),
52
53
  claim: new Set([...COMMON_FLAGS, '--task', '--agent']),
@@ -126,7 +127,8 @@ const HELP_CONFIG = {
126
127
  {
127
128
  heading: 'Mutation',
128
129
  commands: [
129
- { name: 'add', description: 'Add new task (--text, --why, --done-when, --plan, --template ...)' },
130
+ { name: 'add', description: 'Add new task (--text, --why, --done-when, --plan, --template ...). Captures origin from env for completion wake.' },
131
+ { name: 'spawn', description: 'Create a child of the current task (CORTEX_TASK_ID or --task-id); parent becomes a join node. Pair with the thread_wait tool to await it.' },
130
132
  { name: 'bulk-add', description: 'Bulk-add tasks from JSON file (--file, use "key" for intra-batch deps)' },
131
133
  { name: 'edit', description: 'Edit task fields (--text, --why, --done-when, ...)' },
132
134
  { name: 'batch-edit', description: 'Apply same edit to multiple tasks (--task-ids)' },
@@ -181,6 +183,7 @@ const HELP_CONFIG = {
181
183
  { flag: '--dry-run', description: 'Preview without executing (stop, decompose)' },
182
184
  { flag: '--keep-parent', description: 'decompose: keep the original task as a join/acceptance node depending on all subtasks (DR-0014 task tree)' },
183
185
  { flag: '--auto-lock', description: 'Auto-acquire project lock before write (does NOT auto-release)' },
186
+ { flag: '--no-notify', description: 'add: do not capture origin session/channel (suppresses completion wake)' },
184
187
  { flag: '--skip-verify', description: 'Skip completion evidence check for `complete` (escape hatch)' },
185
188
  { flag: '--skip-verify-reason <text>', description: 'Reason for skipping verification (logged in result)' },
186
189
  { flag: '--help', description: 'Show this help' },
@@ -263,6 +266,7 @@ function createDefaults() {
263
266
  force: false,
264
267
  showDeps: false,
265
268
  autoLock: false,
269
+ noNotify: false,
266
270
  };
267
271
  }
268
272
  function splitCommand(argv) {
@@ -356,6 +360,10 @@ function parseOptions(args, values, seen) {
356
360
  seen.add(token);
357
361
  values.autoLock = true;
358
362
  }
363
+ else if (token === '--no-notify') {
364
+ seen.add(token);
365
+ values.noNotify = true;
366
+ }
359
367
  else {
360
368
  throw cliError(`Unknown argument: ${token}`);
361
369
  }
@@ -399,6 +407,14 @@ function validateCommand(command, values) {
399
407
  if (command === 'add' && !values.text) {
400
408
  throw cliError('--text is required for add');
401
409
  }
410
+ if (command === 'spawn') {
411
+ if (!values.text)
412
+ throw cliError('--text is required for spawn');
413
+ const parent = values.taskId || process.env.CORTEX_TASK_ID;
414
+ if (!parent) {
415
+ throw cliError('spawn needs a current task: run inside a dispatched task (CORTEX_TASK_ID set) or pass --task-id <parent>');
416
+ }
417
+ }
402
418
  if (command === 'add' && values.template && (values.template === 'default' || values.template === 'scheduler')) {
403
419
  throw cliError(`Template '${values.template}' is forbidden. The 'default' and 'scheduler' templates are single-agent templates with no review pipeline and are not allowed for task dispatch. Use a multi-agent review template instead (run 'cortex-task --help' to see available templates).`);
404
420
  }
@@ -409,6 +425,17 @@ function validateCommand(command, values) {
409
425
  throw cliError('--project is required');
410
426
  }
411
427
  }
428
+ /** Context-aware defaults: a running agent already knows its project (and current task) via
429
+ * CORTEX_* env. Fill --project from env for write commands so agents don't re-declare it.
430
+ * `spawn` lives under the current task, so it prefers that task's project. */
431
+ function applyContextDefaults(command, values) {
432
+ if (!values.project && COMMANDS_NEEDING_PROJECT.has(command)) {
433
+ const envProject = (command === 'spawn' ? process.env.CORTEX_TASK_PROJECT : null)
434
+ || process.env.CORTEX_PROJECT || null;
435
+ if (envProject)
436
+ values.project = envProject;
437
+ }
438
+ }
412
439
  function parseArgs(argv) {
413
440
  const split = splitCommand(argv);
414
441
  const command = split.command ?? 'list';
@@ -416,6 +443,7 @@ function parseArgs(argv) {
416
443
  const seen = new Set();
417
444
  parseOptions(split.args, values, seen);
418
445
  validateFlagsForCommand(command, seen);
446
+ applyContextDefaults(command, values);
419
447
  validateCommand(command, values);
420
448
  return { command, values };
421
449
  }
@@ -635,6 +663,53 @@ function handleDecompose(v) {
635
663
  function handleStop(v) {
636
664
  return v.dryRun ? stopTaskDryRun(v.taskId) : stopTask(v.taskId);
637
665
  }
666
+ /** Capture provenance from env so task.completed can wake the originating session (Problem 1).
667
+ * Suppressed by --no-notify. Returns null when no env context (e.g. a human at a raw shell). */
668
+ function readOriginFromEnv(noNotify) {
669
+ if (noNotify)
670
+ return null;
671
+ const channel = process.env.SLACK_CHANNEL || process.env.FEISHU_CHANNEL || null;
672
+ const sessionId = process.env.CORTEX_SESSION_ID || null;
673
+ const threadId = process.env.CORTEX_THREAD_ID || null;
674
+ if (!channel && !sessionId && !threadId)
675
+ return null;
676
+ return { sessionId, channel, threadId };
677
+ }
678
+ const MAX_SPAWN_DEPTH = 6;
679
+ /** `spawn`: create a single child under the current task (CORTEX_TASK_ID, or --task-id override),
680
+ * reusing decompose's keep-parent join semantics. The child inherits the parent template unless
681
+ * overridden. No origin is captured — an in-task agent resumes via the thread_wait path, not the
682
+ * session-wake path. A parent-chain depth cap bounds runaway recursion (replaces thread tree guard). */
683
+ function handleSpawn(v) {
684
+ const parentId = v.taskId || process.env.CORTEX_TASK_ID || null;
685
+ if (!parentId) {
686
+ return { success: false, message: 'spawn needs a current task (CORTEX_TASK_ID) or --task-id <parent>' };
687
+ }
688
+ // Depth guard: walk the parent chain.
689
+ const tasks = scanAllTasks(v.project);
690
+ const byId = new Map(tasks.filter((t) => t.id).map((t) => [t.id, t]));
691
+ let cur = byId.get(parentId);
692
+ for (let depth = 0; cur && cur.parent; depth++) {
693
+ if (depth >= MAX_SPAWN_DEPTH) {
694
+ return { success: false, message: `spawn refused: task tree deeper than ${MAX_SPAWN_DEPTH} — fold the work in or escalate instead of nesting further` };
695
+ }
696
+ cur = byId.get(cur.parent);
697
+ }
698
+ const subtask = {
699
+ text: v.text,
700
+ why: v.why || undefined,
701
+ done_when: v.doneWhen || undefined,
702
+ template: v.template || undefined,
703
+ priority: v.priority || undefined,
704
+ plan: v.plan || undefined,
705
+ depends_on: v.dependsOn.length > 0 ? v.dependsOn : undefined,
706
+ };
707
+ const result = decomposeTask(v.project, null, [subtask], parentId, { keepParent: true });
708
+ if (result.success && result.child_ids?.length) {
709
+ return { success: true, message: `Spawned child of ${parentId}`, child_id: result.child_ids[0], parent_id: parentId };
710
+ }
711
+ return result;
712
+ }
638
713
  // ── Lock helpers ──
639
714
  function formatLockResult(project, owner, lock, opts) {
640
715
  return {
@@ -706,7 +781,8 @@ const WRITE_HANDLERS = {
706
781
  'clear-approval': (v) => clearApprovalTask(v.task, v.project, v.taskId),
707
782
  block: (v) => blockTask(v.task, v.project, v.reason, v.taskId),
708
783
  unblock: (v) => unblockTask(v.task, v.project, v.taskId),
709
- add: (v) => addTask(v.project, v.text, v.why, v.doneWhen, v.priority || 'medium', v.template, v.dependsOn.length > 0 ? v.dependsOn : null, v.plan),
784
+ add: (v) => addTask(v.project, v.text, v.why, v.doneWhen, v.priority || 'medium', v.template, v.dependsOn.length > 0 ? v.dependsOn : null, v.plan, readOriginFromEnv(v.noNotify)),
785
+ spawn: handleSpawn,
710
786
  edit: handleEdit,
711
787
  'batch-edit': handleBatchEdit,
712
788
  decompose: handleDecompose,
@@ -731,7 +807,7 @@ const WRITE_HANDLERS = {
731
807
  'lock-status': handleLockStatus,
732
808
  'lock-force-release': handleLockForceRelease,
733
809
  };
734
- const LOCK_GUARD_COMMANDS = new Set(['add', 'edit', 'batch-edit', 'bulk-add', 'decompose']);
810
+ const LOCK_GUARD_COMMANDS = new Set(['add', 'spawn', 'edit', 'batch-edit', 'bulk-add', 'decompose']);
735
811
  const LOCK_GUARD_ASSIGN_IDS = 'assign-ids';
736
812
  function runWrite(command, values) {
737
813
  if (command === 'lock-status') {
@@ -1,3 +1,8 @@
1
+ export interface TaskOrigin {
2
+ sessionId?: string | null;
3
+ channel?: string | null;
4
+ threadId?: string | null;
5
+ }
1
6
  interface BulkTaskInput {
2
7
  key: string;
3
8
  text: string;
@@ -10,7 +15,7 @@ interface BulkTaskInput {
10
15
  gpu?: string;
11
16
  'gpu-count'?: number;
12
17
  }
13
- declare function addTask(project: string, text: string | null, why: string | null, doneWhen: string | null, priority?: string, template?: string | null, dependsOn?: string[] | null, plan?: string | null): {
18
+ declare function addTask(project: string, text: string | null, why: string | null, doneWhen: string | null, priority?: string, template?: string | null, dependsOn?: string[] | null, plan?: string | null, origin?: TaskOrigin | null): {
14
19
  success: boolean;
15
20
  message: string;
16
21
  task_id?: undefined;
@@ -1,7 +1,7 @@
1
1
  import * as fs from 'node:fs';
2
2
  import { collectAllExistingHashes, generateHash } from './task-id-utils.js';
3
3
  import { editTask, findTask, getTasksPath, readTasks, VALID_PRIORITIES, validateTemplateName, writeTasks } from './task-lifecycle-edit.js';
4
- function addTask(project, text, why, doneWhen, priority = 'medium', template = null, dependsOn = null, plan = null) {
4
+ function addTask(project, text, why, doneWhen, priority = 'medium', template = null, dependsOn = null, plan = null, origin = null) {
5
5
  if (!text || text === 'null') {
6
6
  return { success: false, message: '--text is required and must not be empty' };
7
7
  }
@@ -45,6 +45,9 @@ function addTask(project, text, why, doneWhen, priority = 'medium', template = n
45
45
  completed_at: null,
46
46
  completed_note: null,
47
47
  pending_at: null,
48
+ origin_session_id: origin?.sessionId ?? null,
49
+ origin_channel: origin?.channel ?? null,
50
+ origin_thread_id: origin?.threadId ?? null,
48
51
  };
49
52
  tasks.push(newTask);
50
53
  writeTasks(project, tasks);
@@ -128,6 +131,9 @@ function decomposeTask(project, originalText, subtasks, taskId = null, options =
128
131
  completed_at: null,
129
132
  completed_note: null,
130
133
  pending_at: null,
134
+ origin_session_id: null,
135
+ origin_channel: null,
136
+ origin_thread_id: null,
131
137
  });
132
138
  }
133
139
  if (keepParent) {
@@ -254,6 +260,9 @@ function bulkAddTasks(project, inputs) {
254
260
  completed_at: null,
255
261
  completed_note: null,
256
262
  pending_at: null,
263
+ origin_session_id: null,
264
+ origin_channel: null,
265
+ origin_thread_id: null,
257
266
  };
258
267
  tasks.push(newTask);
259
268
  created.push({ key: inp.key.trim(), id: taskId, text: inp.text });
@@ -34,6 +34,7 @@ function buildHookContext(threadId, phase, previousAgent) {
34
34
  artifactContent,
35
35
  userMessage: thread.userMessage,
36
36
  totalCostUsd: thread.totalCostUsd,
37
+ pendingControlAction: thread.metadata?.pendingControl?.action ?? null,
37
38
  };
38
39
  }
39
40
  /** Execute a hook script and parse its JSON result. Returns { insertAgent: false } on any error.
@@ -11,6 +11,12 @@ export declare function resolveAgentSlotConfig(ref: TemplateAgentRef): AgentSlot
11
11
  export declare function resolveAgentSlotConfigByName(agentName: string): AgentSlotConfig | null;
12
12
  /** Resolve all agent refs in a template to AgentSlotConfigs */
13
13
  export declare function resolveTemplateAgents(template: ThreadTemplate): AgentSlotConfig[];
14
+ /** Resolve the unique profile names a template's agents will actually run with.
15
+ * Mirrors thread-runner profile resolution (runner.ts): hardcoded agent profiles win;
16
+ * `__active__` slots resolve to `activeProfile` (the dispatch/scheduler profile that
17
+ * would be injected via metadata.profileOverride). Null/empty entries are dropped.
18
+ * Unknown template or no resolvable agents → [] (fail-open; callers decide fallback). */
19
+ export declare function resolveTemplateProfiles(templateName: string, activeProfile: string | null): string[];
14
20
  /** Render an `(agent, stage)` pair as the canonical endpoint string used for iterationCounts keys
15
21
  * and transition-rule matching. Stages that are null render as bare agent names. */
16
22
  export declare function formatEndpoint(agent: string, stage: string | null): string;