@cortex-agent/server 2026.5.19-3 → 2026.5.22-2

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 (134) hide show
  1. package/README.md +5 -1
  2. package/defaults/config/thread-templates.json +65 -39
  3. package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +4 -4
  4. package/defaults/prompts/directives/coder-reviewer.md +9 -4
  5. package/defaults/prompts/directives/coder.md +10 -2
  6. package/dist/core/gateway-generator.js +26 -4
  7. package/dist/core/log.js +61 -12
  8. package/dist/core/profile-generator.js +4 -3
  9. package/dist/core/status-format.js +1 -1
  10. package/dist/core/task-parser.d.ts +1 -1
  11. package/dist/core/task-parser.js +13 -6
  12. package/dist/core/types/thread-types.d.ts +4 -2
  13. package/dist/domain/costs/codex-usage-monitor.d.ts +1 -2
  14. package/dist/domain/costs/codex-usage-monitor.js +2 -2
  15. package/dist/domain/costs/cost-tracker.d.ts +2 -0
  16. package/dist/domain/costs/cost-tracker.js +4 -20
  17. package/dist/domain/costs/rate-limit-throttle.js +1 -4
  18. package/dist/domain/mcp/tools/context.d.ts +4 -2
  19. package/dist/domain/mcp/tools/context.js +7 -5
  20. package/dist/domain/mcp/tools/schedule.d.ts +1 -1
  21. package/dist/domain/mcp/tools/schedule.js +24 -20
  22. package/dist/domain/memory/index-regen.js +8 -5
  23. package/dist/domain/monitor/disk-monitor.js +1 -6
  24. package/dist/domain/projects/index.d.ts +2 -0
  25. package/dist/domain/projects/index.js +3 -0
  26. package/dist/domain/projects/project-store.d.ts +54 -0
  27. package/dist/domain/projects/project-store.js +194 -0
  28. package/dist/domain/projects/project-types.d.ts +11 -0
  29. package/dist/domain/projects/project-types.js +5 -0
  30. package/dist/domain/remote/client-hot-reload.d.ts +1 -0
  31. package/dist/domain/remote/client-hot-reload.js +284 -53
  32. package/dist/domain/scheduling/jobs/_shared.d.ts +1 -1
  33. package/dist/domain/scheduling/jobs/_shared.js +6 -5
  34. package/dist/domain/scheduling/jobs/memory-index-regen.js +2 -2
  35. package/dist/domain/scheduling/jobs/scheduled-task.d.ts +2 -2
  36. package/dist/domain/scheduling/jobs/scheduled-task.js +38 -36
  37. package/dist/domain/scheduling/jobs/sync-public.d.ts +1 -0
  38. package/dist/domain/scheduling/jobs/sync-public.js +34 -0
  39. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +3 -7
  40. package/dist/domain/scheduling/jobs/target-dispatch.js +7 -9
  41. package/dist/domain/scheduling/jobs/task-archive.js +2 -2
  42. package/dist/domain/scheduling/jobs/task-dispatch.js +18 -16
  43. package/dist/domain/scheduling/runner.d.ts +1 -0
  44. package/dist/domain/scheduling/runner.js +2 -0
  45. package/dist/domain/scheduling/schedule-cli.d.ts +1 -0
  46. package/dist/domain/scheduling/schedule-cli.js +14 -14
  47. package/dist/domain/scheduling/schedule-command.js +45 -36
  48. package/dist/domain/scheduling/scheduler.d.ts +1 -1
  49. package/dist/domain/scheduling/scheduler.js +12 -11
  50. package/dist/domain/sessions/session-hooks.d.ts +10 -11
  51. package/dist/domain/sessions/session-hooks.js +26 -27
  52. package/dist/domain/sessions/session-registry.d.ts +10 -5
  53. package/dist/domain/sessions/session-registry.js +24 -9
  54. package/dist/domain/tasks/pending-tracker.js +8 -9
  55. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  56. package/dist/domain/tasks/system/task-cli.js +189 -29
  57. package/dist/domain/tasks/system/task-lifecycle-edit.js +3 -3
  58. package/dist/domain/threads/hook-runner.js +12 -7
  59. package/dist/domain/threads/runner.d.ts +3 -3
  60. package/dist/domain/threads/runner.js +30 -28
  61. package/dist/domain/threads/state-machine.d.ts +3 -0
  62. package/dist/domain/threads/state-machine.js +4 -0
  63. package/dist/entry/app.js +30 -9
  64. package/dist/entry/cli.js +19 -4
  65. package/dist/entry/daemon.js +28 -2
  66. package/dist/entry/startup-notify.js +8 -6
  67. package/dist/orchestration/agent-runner.js +19 -13
  68. package/dist/orchestration/durable-helpers.js +3 -2
  69. package/dist/orchestration/interactions/ask-user-question.d.ts +2 -3
  70. package/dist/orchestration/interactions/ask-user-question.js +5 -4
  71. package/dist/orchestration/interactions/interaction-handlers.js +8 -5
  72. package/dist/orchestration/interactions/plan-handler.js +3 -3
  73. package/dist/orchestration/lifecycle.js +43 -38
  74. package/dist/orchestration/routing/commands/cancel.js +9 -8
  75. package/dist/orchestration/routing/commands/channel.js +32 -26
  76. package/dist/orchestration/routing/commands/cost.js +5 -3
  77. package/dist/orchestration/routing/commands/device.js +2 -1
  78. package/dist/orchestration/routing/commands/dispatch.js +8 -7
  79. package/dist/orchestration/routing/commands/index.js +7 -4
  80. package/dist/orchestration/routing/commands/mode.js +24 -18
  81. package/dist/orchestration/routing/commands/nvtop.js +14 -12
  82. package/dist/orchestration/routing/commands/orient.js +2 -1
  83. package/dist/orchestration/routing/commands/schedule.js +2 -1
  84. package/dist/orchestration/routing/commands/sendfile.js +12 -9
  85. package/dist/orchestration/routing/commands/session.js +12 -10
  86. package/dist/orchestration/routing/commands/status.js +2 -2
  87. package/dist/orchestration/routing/commands/tail.js +10 -6
  88. package/dist/orchestration/routing/commands/task.js +5 -4
  89. package/dist/orchestration/routing/commands/thread-handlers.js +19 -12
  90. package/dist/orchestration/routing/hook-bridge-subscribers.js +15 -13
  91. package/dist/orchestration/status-helpers.d.ts +4 -5
  92. package/dist/orchestration/status-helpers.js +7 -8
  93. package/dist/orchestration/thread-executor.js +21 -12
  94. package/dist/platform/adapter.d.ts +13 -9
  95. package/dist/platform/adapter.js +1 -1
  96. package/dist/platform/adapters/feishu-output-stream.d.ts +27 -0
  97. package/dist/platform/adapters/feishu-output-stream.js +114 -0
  98. package/dist/platform/adapters/feishu.d.ts +16 -7
  99. package/dist/platform/adapters/feishu.js +64 -18
  100. package/dist/platform/adapters/index.d.ts +4 -1
  101. package/dist/platform/adapters/index.js +1 -1
  102. package/dist/platform/adapters/slack-output-stream.d.ts +55 -0
  103. package/dist/platform/{virtual-message.js → adapters/slack-output-stream.js} +98 -165
  104. package/dist/platform/adapters/slack-project-conduits.d.ts +9 -0
  105. package/dist/platform/adapters/slack-project-conduits.js +40 -0
  106. package/dist/platform/adapters/slack.d.ts +18 -8
  107. package/dist/platform/adapters/slack.js +82 -24
  108. package/dist/platform/index.d.ts +3 -2
  109. package/dist/platform/index.js +1 -1
  110. package/dist/platform/output-stream-chunk.d.ts +6 -0
  111. package/dist/platform/output-stream-chunk.js +45 -0
  112. package/dist/platform/output-stream-helpers.d.ts +6 -0
  113. package/dist/platform/output-stream-helpers.js +11 -0
  114. package/dist/platform/output-stream.d.ts +28 -0
  115. package/dist/platform/output-stream.js +4 -0
  116. package/dist/platform/testing.d.ts +41 -8
  117. package/dist/platform/testing.js +93 -11
  118. package/dist/platform/tool-trace.d.ts +9 -8
  119. package/dist/platform/tool-trace.js +19 -17
  120. package/dist/platform/types.d.ts +21 -1
  121. package/dist/platform/types.js +17 -1
  122. package/dist/store/channel-repo.d.ts +6 -0
  123. package/dist/store/channel-repo.js +9 -0
  124. package/dist/store/json-repository.js +12 -1
  125. package/dist/store/outbound-queue.d.ts +5 -4
  126. package/dist/store/outbound-queue.js +9 -6
  127. package/dist/store/schedule-repo.d.ts +9 -5
  128. package/dist/store/schedule-repo.js +59 -14
  129. package/dist/store/session-registry-repo.d.ts +36 -7
  130. package/dist/store/session-registry-repo.js +186 -25
  131. package/dist/store/thread-repo.d.ts +1 -0
  132. package/dist/store/thread-repo.js +8 -0
  133. package/package.json +1 -1
  134. package/dist/platform/virtual-message.d.ts +0 -68
@@ -362,18 +362,25 @@ function formatTaskCompact(task, tags) {
362
362
  const compactTags = tags.length > 0 ? ` (${tags.join(', ')})` : '';
363
363
  return `${status}${idText} [${task.project}] ${task.text} [P:${task.priority}]${compactTags}`;
364
364
  }
365
- function printTaskListToString(tasks, actionableHeader = false) {
365
+ function printTaskListToString(tasks, actionableHeader = false, showDeps = false) {
366
366
  const out = [];
367
367
  if (actionableHeader) {
368
368
  out.push('Actionable Tasks (sorted by priority)');
369
369
  out.push('='.repeat(50));
370
370
  }
371
- for (const [index, task] of tasks.entries()) {
371
+ for (const task of tasks) {
372
372
  const tags = taskDisplayTags(task);
373
- if (actionableHeader)
374
- out.push(...formatTaskVerbose(task, index, tags));
375
- else
376
- out.push(formatTaskCompact(task, tags));
373
+ let line;
374
+ if (actionableHeader) {
375
+ line = formatTaskVerbose(task, tasks.indexOf(task), tags).join('\n');
376
+ }
377
+ else {
378
+ line = formatTaskCompact(task, tags);
379
+ }
380
+ if (showDeps && task.depends_on.length > 0) {
381
+ line += ` → [${task.depends_on.join(', ')}]`;
382
+ }
383
+ out.push(line);
377
384
  }
378
385
  return out.join('\n');
379
386
  }
@@ -175,6 +175,7 @@ export interface ThreadRecord {
175
175
  templateName: string | null;
176
176
  status: ThreadStatus;
177
177
  channel: string;
178
+ projectId: string;
178
179
  platformThreadId: string | null;
179
180
  userMessage: string;
180
181
  userMessageTs: string;
@@ -200,7 +201,6 @@ export interface ThreadRecord {
200
201
  export interface ThreadMetadata {
201
202
  scheduleTaskId?: string | null;
202
203
  trigger?: string | null;
203
- project?: string | null;
204
204
  profileOverride?: string | null;
205
205
  /** Messages buffered while a step was executing, to be included in the next step's prompt. */
206
206
  pendingMessages?: string[];
@@ -217,10 +217,12 @@ export interface TransitionResult {
217
217
  nextStage?: string | null;
218
218
  reason: 'transition' | 'converged' | 'max_iterations' | 'cost_limit' | 'no_matching_transition';
219
219
  }
220
- import type { PlatformAdapter, MessageRef } from '../../platform/index.js';
220
+ import type { PlatformAdapter, MessageRef, Destination } from '../../platform/index.js';
221
221
  export interface RunThreadOptions {
222
222
  adapter: PlatformAdapter;
223
223
  channel: string;
224
+ /** Destination for the thread's OutputStream. Caller must supply — never inferred. */
225
+ destination: Destination;
224
226
  threadTs: string | null;
225
227
  statusMsg: MessageRef | null;
226
228
  startTime: number;
@@ -1,7 +1,6 @@
1
1
  import type { PlatformAdapter } from '../../platform/adapter.js';
2
- declare function maybeNotifyCodexLowUsage({ adapter, channel, result }: {
2
+ declare function maybeNotifyCodexLowUsage({ adapter, result }: {
3
3
  adapter: PlatformAdapter;
4
- channel: string;
5
4
  result: any;
6
5
  }): Promise<void>;
7
6
  export { maybeNotifyCodexLowUsage };
@@ -41,7 +41,7 @@ function collectLowEntries(result) {
41
41
  }
42
42
  return entries.sort((a, b) => a.remainingPercent - b.remainingPercent);
43
43
  }
44
- async function maybeNotifyCodexLowUsage({ adapter, channel, result }) {
44
+ async function maybeNotifyCodexLowUsage({ adapter, result }) {
45
45
  const lowEntries = collectLowEntries(result);
46
46
  if (!lowEntries.length)
47
47
  return;
@@ -63,7 +63,7 @@ async function maybeNotifyCodexLowUsage({ adapter, channel, result }) {
63
63
  const logHint = result?.codexRawLogPath ? `\nlog: \`${result.codexRawLogPath}\`` : '';
64
64
  const text = [`:warning: Codex usage low (threshold: ${THRESHOLD_PERCENT}%)`, ...lines].join('\n') + logHint;
65
65
  try {
66
- await adapter.postMessage(channel, { text });
66
+ await adapter.postMessage({ type: 'system-notice' }, { text });
67
67
  }
68
68
  catch (error) {
69
69
  log.error('Failed to send low-usage alert:', error.message);
@@ -80,6 +80,8 @@ declare function recordCost({ project, trigger, cost_usd, num_turns, duration_s,
80
80
  /**
81
81
  * Detect project from a message string.
82
82
  *
83
+ * @deprecated Use projectStore.resolveFromMessage() instead.
84
+ *
83
85
  * Priority:
84
86
  * 1. [project:xxx] explicit tag — always wins
85
87
  * 2. Case-insensitive substring match against context/projects/ directory names
@@ -2,30 +2,12 @@
2
2
  // output: recordCost / checkBudget / formatCostReport / ...
3
3
  // pos: budget check and cost record aggregation
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
- import * as fsSync from 'fs';
6
- import * as path from 'path';
7
- import { PROJECTS_DIR } from '../../core/utils.js';
8
5
  import { costRepo } from '../../store/cost-repo.js';
6
+ import { projectStore } from '../projects/index.js';
9
7
  // ── Dynamic project name discovery (from context/projects/) ──
10
8
  let _projectNames = null;
11
9
  function loadProjectNames() {
12
- try {
13
- if (!fsSync.existsSync(PROJECTS_DIR))
14
- return [];
15
- return fsSync.readdirSync(PROJECTS_DIR)
16
- .filter(name => {
17
- try {
18
- return fsSync.statSync(path.join(PROJECTS_DIR, name)).isDirectory()
19
- && !name.startsWith('.');
20
- }
21
- catch {
22
- return false;
23
- }
24
- });
25
- }
26
- catch {
27
- return [];
28
- }
10
+ return projectStore.list().map(p => p.id);
29
11
  }
30
12
  function getProjectNames() {
31
13
  if (_projectNames === null) {
@@ -81,6 +63,8 @@ async function recordCost({ project, trigger, cost_usd, num_turns, duration_s, b
81
63
  /**
82
64
  * Detect project from a message string.
83
65
  *
66
+ * @deprecated Use projectStore.resolveFromMessage() instead.
67
+ *
84
68
  * Priority:
85
69
  * 1. [project:xxx] explicit tag — always wins
86
70
  * 2. Case-insensitive substring match against context/projects/ directory names
@@ -18,10 +18,7 @@ const _rateLimitedModes = new Set();
18
18
  function sendDM(text) {
19
19
  if (!_adapter)
20
20
  return;
21
- const adminChannel = _adapter.getAdminChannel();
22
- if (!adminChannel)
23
- return;
24
- _adapter.postMessage(adminChannel, { text }).catch(e => {
21
+ _adapter.postMessage({ type: 'system-notice' }, { text }).catch(e => {
25
22
  log.error(`DM failed: ${e.message}`);
26
23
  });
27
24
  }
@@ -3,7 +3,9 @@ export interface ContextToolDeps {
3
3
  /** Path to the per-route context.json written by Codex's writeRouteContext (codex backend only). Null on Claude. */
4
4
  routeContextFile: string | null;
5
5
  }
6
- interface CortexContextResponse {
6
+ /** Internal context — includes channel for downstream consumers (schedule.ts session/thread
7
+ * target resolution). Not exposed via MCP. */
8
+ interface CortexContextInternal {
7
9
  channel: string | null;
8
10
  sessionId: string | null;
9
11
  sessionName: string | null;
@@ -18,6 +20,6 @@ interface CortexContextResponse {
18
20
  * per turn for Codex) and falling back to the env vars set at MCP server spawn time
19
21
  * (Claude path; sticky for the session lifetime). When sessionId is known but sessionName
20
22
  * is not, look up the session-registry to get the cortex-XXXX short name. */
21
- export declare function resolveCortexContext(deps: ContextToolDeps): Promise<CortexContextResponse>;
23
+ export declare function resolveCortexContext(deps: ContextToolDeps): Promise<CortexContextInternal>;
22
24
  export declare function registerContextTools(server: McpServer, deps: ContextToolDeps): void;
23
25
  export {};
@@ -1,10 +1,10 @@
1
1
  // input: McpServer + route-context-file + CORTEX_* env + thread/session stores
2
2
  // output: cortex_context tool registration
3
- // pos: MCP tool letting the running LLM self-discover its channel/thread/session/profile,
3
+ // pos: MCP tool letting the running LLM self-discover its project/thread/session/profile,
4
4
  // so cortex_schedule_add can target the current scope without guessing IDs.
5
5
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
6
6
  import * as fs from 'fs';
7
- import { sessionRegistryRepo } from '../../../store/session-registry-repo.js';
7
+ import { sessionStore } from '../../../store/session-registry-repo.js';
8
8
  function readRouteContext(routeContextFile) {
9
9
  if (!routeContextFile)
10
10
  return null;
@@ -24,7 +24,7 @@ export async function resolveCortexContext(deps) {
24
24
  const sessionId = route?.sessionId ?? process.env.CORTEX_SESSION_ID ?? null;
25
25
  let sessionName = route?.sessionName ?? process.env.CORTEX_SESSION_NAME ?? null;
26
26
  if (!sessionName && sessionId) {
27
- sessionName = await sessionRegistryRepo.lookupBySessionId(sessionId);
27
+ sessionName = await sessionStore.lookupBySessionId(sessionId);
28
28
  }
29
29
  return {
30
30
  channel: route?.channel ?? process.env.SLACK_CHANNEL ?? null,
@@ -39,9 +39,11 @@ export async function resolveCortexContext(deps) {
39
39
  };
40
40
  }
41
41
  export function registerContextTools(server, deps) {
42
- server.tool('cortex_context', 'Return the current Cortex execution context: channel, sessionId, sessionName (cortex-XXXX), threadId, profile, project, backend. Use this to discover the current scope before calling cortex_schedule_add with target=current-channel/current-session/current-thread.', {}, { readOnlyHint: true }, async () => {
42
+ server.tool('cortex_context', 'Return the current Cortex execution context: sessionId, sessionName (cortex-XXXX), threadId, profile, project, backend. Use this to discover the current scope before calling cortex_schedule_add with target=current-project/current-session/current-thread.', {}, { readOnlyHint: true }, async () => {
43
43
  try {
44
- const ctxResponse = await resolveCortexContext(deps);
44
+ const ctxInternal = await resolveCortexContext(deps);
45
+ // Strip channel from public response — consumers address by project/sessionId/threadId.
46
+ const { channel: _channel, ...ctxResponse } = ctxInternal;
45
47
  return { content: [{ type: 'text', text: JSON.stringify(ctxResponse, null, 2) }] };
46
48
  }
47
49
  catch (e) {
@@ -18,6 +18,6 @@ export interface CortexContextSnapshot {
18
18
  /** Target spec accepted by cortex_schedule_add: shorthand string OR explicit object.
19
19
  * Shorthand strings are resolved to concrete ScheduleTarget objects at create time
20
20
  * (decision: list/get always shows real IDs). */
21
- export type TargetSpec = undefined | 'fresh' | 'current-channel' | 'current-session' | 'current-thread' | ScheduleTarget;
21
+ export type TargetSpec = undefined | 'fresh' | 'current-project' | 'current-session' | 'current-thread' | ScheduleTarget;
22
22
  export declare function resolveTargetShorthand(spec: TargetSpec, ctx: CortexContextSnapshot): ScheduleTarget;
23
23
  export declare function registerScheduleTools(server: McpServer, deps: ContextToolDeps): void;
@@ -1,20 +1,21 @@
1
1
  // input: McpServer + scheduleRepo + Scheduler (for timing math) + cortex_context resolver
2
2
  // output: cortex_schedule_{add,list,get,remove,pause,resume} tool registrations
3
3
  // pos: MCP entry that lets the running LLM CRUD scheduled tasks without shelling out
4
- // to bin/schedule. Resolves __current__ shorthand against the live execution context
5
- // at create time so the persisted record always shows real channel/session/thread IDs.
4
+ // to bin/schedule. Resolves __current__ shorthand (current-project/current-session/
5
+ // current-thread) against the live execution context at create time so the persisted
6
+ // record always shows real project/session/thread IDs.
6
7
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
7
8
  import { z } from 'zod';
8
9
  import { Scheduler, parseDuration } from '../../scheduling/scheduler.js';
9
- import { scheduleRepo } from '../../../store/schedule-repo.js';
10
+ import { scheduleRepo, channelToProjectId } from '../../../store/schedule-repo.js';
10
11
  import { resolveCortexContext } from './context.js';
11
12
  export function resolveTargetShorthand(spec, ctx) {
12
13
  if (spec === undefined || spec === 'fresh')
13
14
  return { kind: 'fresh' };
14
- if (spec === 'current-channel') {
15
- if (!ctx.channel)
16
- throw new Error('current-channel requested but no channel in current context');
17
- return { kind: 'channel', channel: ctx.channel };
15
+ if (spec === 'current-project') {
16
+ if (!ctx.project)
17
+ throw new Error('current-project requested but no project in current context');
18
+ return { kind: 'project', projectId: ctx.project };
18
19
  }
19
20
  if (spec === 'current-session') {
20
21
  if (!ctx.sessionName || !ctx.sessionId || !ctx.channel) {
@@ -32,10 +33,10 @@ export function resolveTargetShorthand(spec, ctx) {
32
33
  if (typeof spec === 'object' && spec !== null && 'kind' in spec) {
33
34
  if (spec.kind === 'fresh')
34
35
  return { kind: 'fresh' };
35
- if (spec.kind === 'channel') {
36
- if (!spec.channel)
37
- throw new Error('channel target requires { channel }');
38
- return { kind: 'channel', channel: spec.channel };
36
+ if (spec.kind === 'project') {
37
+ if (!spec.projectId)
38
+ throw new Error('project target requires { projectId }');
39
+ return { kind: 'project', projectId: spec.projectId };
39
40
  }
40
41
  if (spec.kind === 'session') {
41
42
  if (!spec.sessionName || !spec.sessionId || !spec.channel) {
@@ -87,11 +88,11 @@ function makeWriteOnlyScheduler() {
87
88
  // --- Tool implementation: cortex_schedule_add ---
88
89
  const targetSchema = z.union([
89
90
  z.literal('fresh'),
90
- z.literal('current-channel'),
91
+ z.literal('current-project'),
91
92
  z.literal('current-session'),
92
93
  z.literal('current-thread'),
93
94
  z.object({ kind: z.literal('fresh') }),
94
- z.object({ kind: z.literal('channel'), channel: z.string() }),
95
+ z.object({ kind: z.literal('project'), projectId: z.string() }),
95
96
  z.object({ kind: z.literal('session'), sessionName: z.string(), sessionId: z.string(), channel: z.string() }),
96
97
  z.object({ kind: z.literal('thread'), threadId: z.string(), channel: z.string() }),
97
98
  ]).optional();
@@ -103,11 +104,12 @@ const addInputShape = {
103
104
  time: z.string().optional().describe('For type=daily/weekly: HH:MM 24-hour'),
104
105
  dayOfWeek: z.union([z.string(), z.number()]).optional().describe('For type=weekly: 0-6 (0=Sun) or sun/mon/tue/wed/thu/fri/sat'),
105
106
  delay: z.union([z.string(), z.number()]).optional().describe('For type=once: delay from now (duration string or ms)'),
106
- target: targetSchema.describe('Where to land the fired task. Shorthand: "fresh" (default) | "current-channel" | "current-session" | "current-thread", or explicit { kind, ...ids }. __current__ shorthand is resolved to concrete IDs at create time.'),
107
+ target: targetSchema.describe('Where to land the fired task. Shorthand: "fresh" (default) | "current-project" | "current-session" | "current-thread", or explicit { kind, ...ids }. __current__ shorthand is resolved to concrete IDs at create time.'),
107
108
  fallback: fallbackSchema.describe('What to do if target session/thread is gone at fire time. fresh (default): silently fall back. skip: post one-line note, do not run. wait: not yet implemented (treated as fresh).'),
108
109
  profile: z.string().optional().describe('Agent profile name (defaults to active profile)'),
109
110
  preCheck: z.string().optional().describe('Optional shell command; non-zero exit → skip this fire. 15s timeout. Receives PRECHECK_LAST_RUN env var.'),
110
111
  channel: z.string().optional().describe('Override the channel used for fresh-fallback. Defaults to current-context channel.'),
112
+ projectId: z.string().optional().describe('Project id for the schedule. If omitted, resolved from channel via channel-registry.'),
111
113
  };
112
114
  async function runScheduleAdd(input, deps) {
113
115
  const ctxSnapshot = await resolveCortexContext(deps);
@@ -119,7 +121,9 @@ async function runScheduleAdd(input, deps) {
119
121
  if (!channel)
120
122
  channel = ctxSnapshot.channel;
121
123
  if (!channel)
122
- throw new Error('No channel: pass --channel or run inside a context with SLACK_CHANNEL set.');
124
+ throw new Error('No channel resolved for fresh-fallback: pass --channel or run inside a context with a resolved channel.');
125
+ // Resolve projectId: explicit > channel-to-project reverse lookup > 'general'.
126
+ const projectId = input.projectId ?? channelToProjectId(channel) ?? 'general';
123
127
  const scheduler = makeWriteOnlyScheduler();
124
128
  let task;
125
129
  try {
@@ -128,13 +132,13 @@ async function runScheduleAdd(input, deps) {
128
132
  throw new Error('interval is required for type=interval');
129
133
  task = await scheduler.add('interval', {
130
134
  intervalMs: parseIntervalSpec(input.interval),
131
- message: input.message, channel, profile: input.profile ?? null, preCheck: input.preCheck,
135
+ message: input.message, projectId, profile: input.profile ?? null, preCheck: input.preCheck,
132
136
  });
133
137
  }
134
138
  else if (input.type === 'daily') {
135
139
  if (!input.time)
136
140
  throw new Error('time is required for type=daily');
137
- task = await scheduler.add('daily', { time: input.time, message: input.message, channel, profile: input.profile ?? null, preCheck: input.preCheck });
141
+ task = await scheduler.add('daily', { time: input.time, message: input.message, projectId, profile: input.profile ?? null, preCheck: input.preCheck });
138
142
  }
139
143
  else if (input.type === 'weekly') {
140
144
  if (input.dayOfWeek === undefined)
@@ -143,7 +147,7 @@ async function runScheduleAdd(input, deps) {
143
147
  throw new Error('time is required for type=weekly');
144
148
  task = await scheduler.add('weekly', {
145
149
  dayOfWeek: parseDayOfWeek(input.dayOfWeek),
146
- time: input.time, message: input.message, channel, profile: input.profile ?? null, preCheck: input.preCheck,
150
+ time: input.time, message: input.message, projectId, profile: input.profile ?? null, preCheck: input.preCheck,
147
151
  });
148
152
  }
149
153
  else { // once
@@ -151,7 +155,7 @@ async function runScheduleAdd(input, deps) {
151
155
  throw new Error('delay is required for type=once');
152
156
  task = await scheduler.add('once', {
153
157
  delay: parseDelaySpec(input.delay),
154
- message: input.message, channel, profile: input.profile ?? null, preCheck: input.preCheck,
158
+ message: input.message, projectId, profile: input.profile ?? null, preCheck: input.preCheck,
155
159
  });
156
160
  }
157
161
  // Backfill target + fallback fields after add() so timing math (which doesn't know about them) ran first.
@@ -169,7 +173,7 @@ async function runScheduleAdd(input, deps) {
169
173
  }
170
174
  // --- Tool registrations ---
171
175
  export function registerScheduleTools(server, deps) {
172
- server.tool('cortex_schedule_add', 'Create a scheduled task. Supports interval/daily/weekly/once. target shorthand "current-channel" | "current-session" | "current-thread" | "fresh" auto-resolves to concrete IDs against the running agent context — no need to call cortex_context first unless you need an explicit ID.', addInputShape, async (input) => {
176
+ server.tool('cortex_schedule_add', 'Create a scheduled task. Supports interval/daily/weekly/once. target shorthand "current-project" | "current-session" | "current-thread" | "fresh" auto-resolves to concrete IDs against the running agent context — no need to call cortex_context first unless you need an explicit ID.', addInputShape, async (input) => {
173
177
  try {
174
178
  const result = await runScheduleAdd(input, deps);
175
179
  return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
@@ -331,12 +331,15 @@ function generateIndex(dir, title) {
331
331
  }
332
332
  // --- CLI: regenerate indexes for all or specific projects ---
333
333
  export function regenAll() {
334
- const projects = fs.readdirSync(PROJECTS_DIR).filter(d => {
334
+ // Use withFileTypes to avoid ENOENT on broken symlinks (e.g. AGENTS.md -> CLAUDE.md)
335
+ const projects = fs.readdirSync(PROJECTS_DIR, { withFileTypes: true })
336
+ .filter(d => d.isDirectory() && !d.name.startsWith('.'))
337
+ .map(d => d.name)
338
+ .filter(d => {
335
339
  const dir = path.join(PROJECTS_DIR, d);
336
- return fs.statSync(dir).isDirectory()
337
- && (fs.existsSync(path.join(dir, 'experiments'))
338
- || fs.existsSync(path.join(dir, 'knowledge'))
339
- || fs.existsSync(path.join(dir, 'patterns')));
340
+ return fs.existsSync(path.join(dir, 'experiments'))
341
+ || fs.existsSync(path.join(dir, 'knowledge'))
342
+ || fs.existsSync(path.join(dir, 'patterns'));
340
343
  });
341
344
  for (const p of projects) {
342
345
  regenProject(p);
@@ -44,12 +44,7 @@ async function getFreeBytes(path) {
44
44
  function sendDM(text) {
45
45
  if (!_adapter)
46
46
  return;
47
- const adminChannel = _adapter.getAdminChannel();
48
- if (!adminChannel) {
49
- log.info('No admin channel configured, skipping DM');
50
- return;
51
- }
52
- _adapter.postMessage(adminChannel, { text }).catch(e => {
47
+ _adapter.postMessage({ type: 'system-notice' }, { text }).catch(e => {
53
48
  log.error(`DM failed: ${e.message}`);
54
49
  });
55
50
  }
@@ -0,0 +1,2 @@
1
+ export type { Project } from './project-types.js';
2
+ export { ProjectStore, projectStore } from './project-store.js';
@@ -0,0 +1,3 @@
1
+ // Barrel re-export for domain/projects/ — single import surface for all callers.
2
+ // Physical split: project-types + project-store
3
+ export { ProjectStore, projectStore } from './project-store.js';
@@ -0,0 +1,54 @@
1
+ import type { Project } from './project-types.js';
2
+ export interface ProjectStoreOptions {
3
+ /** Overrideable for tests. Defaults to PROJECTS_DIR from @core/paths. */
4
+ projectsDir?: string;
5
+ /** Disable fs.watch — for tests that manipulate dirs synchronously. Defaults to true. */
6
+ watchEnabled?: boolean;
7
+ }
8
+ export declare class ProjectStore {
9
+ private readonly projectsDir;
10
+ private readonly watchEnabled;
11
+ private projects;
12
+ private initialized;
13
+ private watcher;
14
+ private debounceTimer;
15
+ constructor(opts?: ProjectStoreOptions);
16
+ /**
17
+ * Scan PROJECTS_DIR, scaffold general if absent, build cache, start watcher.
18
+ * Idempotent — safe to call multiple times.
19
+ */
20
+ initialize(): Promise<void>;
21
+ /** Return all known projects. Always includes "general". */
22
+ list(): Project[];
23
+ /** Look up a project by id. Returns undefined for unknown ids. */
24
+ get(id: string): Project | undefined;
25
+ /** True if a project with the given id exists. */
26
+ exists(id: string): boolean;
27
+ /** Return the "general" umbrella project. Always present. */
28
+ getDefault(): Project;
29
+ /**
30
+ * Resolve a project from a message string using heuristic patterns.
31
+ *
32
+ * Priority:
33
+ * 1. [project:xxx] explicit tag — always wins
34
+ * 2. Case-insensitive substring match against scanned project ids
35
+ * (longest match wins when multiple project names appear in the message)
36
+ * 3. 'general' fallback
37
+ *
38
+ * Returns the matching Project or the default general project.
39
+ */
40
+ resolveFromMessage(msg: string | null | undefined): Project | null;
41
+ /** Force a rescan of PROJECTS_DIR (e.g. after watcher event or manual trigger). */
42
+ refresh(): void;
43
+ /** Stop the fs.watch watcher and release resources. */
44
+ destroy(): void;
45
+ /** Create general/ scaffold if the directory does not exist. */
46
+ private scaffoldGeneral;
47
+ /** Read PROJECTS_DIR and rebuild the in-memory cache. */
48
+ private scan;
49
+ private makeGeneralProject;
50
+ /** Watch PROJECTS_DIR for add/remove of subdirectories. */
51
+ private startWatcher;
52
+ private debouncedRescan;
53
+ }
54
+ export declare const projectStore: ProjectStore;
@@ -0,0 +1,194 @@
1
+ // input: PROJECTS_DIR (from @core/paths.js or constructor arg)
2
+ // output: ProjectStore — list / get / exists / getDefault / resolveFromMessage / refresh
3
+ // + auto-scaffold of general/ project on first initialize()
4
+ // pos: Read-only project registry with fs.watch cache invalidation
5
+ // "general" is always synthesized; never persisted.
6
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
7
+ import * as fs from 'node:fs';
8
+ import * as path from 'node:path';
9
+ import { PROJECTS_DIR } from '../../core/paths.js';
10
+ import { createLogger } from '../../core/log.js';
11
+ const log = createLogger('project-store');
12
+ const DEBOUNCE_MS = 1000;
13
+ const GENERAL_SCAFFOLD_STATUS = `# general
14
+
15
+ Status: active
16
+
17
+ `;
18
+ const GENERAL_SCAFFOLD_CORTEX = `# general
19
+
20
+ Synthetic umbrella project — always present. Created automatically by the system.
21
+ `;
22
+ export class ProjectStore {
23
+ projectsDir;
24
+ watchEnabled;
25
+ projects = [];
26
+ initialized = false;
27
+ watcher = null;
28
+ debounceTimer = null;
29
+ constructor(opts = {}) {
30
+ this.projectsDir = opts.projectsDir ?? PROJECTS_DIR;
31
+ this.watchEnabled = opts.watchEnabled ?? true;
32
+ }
33
+ /**
34
+ * Scan PROJECTS_DIR, scaffold general if absent, build cache, start watcher.
35
+ * Idempotent — safe to call multiple times.
36
+ */
37
+ async initialize() {
38
+ if (this.initialized)
39
+ return;
40
+ this.scaffoldGeneral();
41
+ this.scan();
42
+ this.initialized = true;
43
+ if (this.watchEnabled) {
44
+ this.startWatcher();
45
+ }
46
+ log.info(`ProjectStore initialized: ${this.projects.length} projects (${this.projectsDir})`);
47
+ }
48
+ /** Return all known projects. Always includes "general". */
49
+ list() {
50
+ return [...this.projects];
51
+ }
52
+ /** Look up a project by id. Returns undefined for unknown ids. */
53
+ get(id) {
54
+ return this.projects.find((p) => p.id === id);
55
+ }
56
+ /** True if a project with the given id exists. */
57
+ exists(id) {
58
+ return this.projects.some((p) => p.id === id);
59
+ }
60
+ /** Return the "general" umbrella project. Always present. */
61
+ getDefault() {
62
+ // Guaranteed to exist after initialize()
63
+ return this.projects.find((p) => p.kind === 'general');
64
+ }
65
+ /**
66
+ * Resolve a project from a message string using heuristic patterns.
67
+ *
68
+ * Priority:
69
+ * 1. [project:xxx] explicit tag — always wins
70
+ * 2. Case-insensitive substring match against scanned project ids
71
+ * (longest match wins when multiple project names appear in the message)
72
+ * 3. 'general' fallback
73
+ *
74
+ * Returns the matching Project or the default general project.
75
+ */
76
+ resolveFromMessage(msg) {
77
+ if (!msg)
78
+ return this.getDefault();
79
+ // 1. [project:xxx] tag — always wins
80
+ const tagMatch = msg.match(/\[project:([^\]]+)\]/);
81
+ if (tagMatch)
82
+ return this.get(tagMatch[1]) ?? this.getDefault();
83
+ // 2. Case-insensitive substring match (longest project id wins)
84
+ const lower = msg.toLowerCase();
85
+ let bestMatch = null;
86
+ let bestLen = 0;
87
+ for (const project of this.projects) {
88
+ if (project.kind === 'general')
89
+ continue;
90
+ const lowerName = project.id.toLowerCase();
91
+ if (lower.includes(lowerName) && project.id.length > bestLen) {
92
+ bestMatch = project;
93
+ bestLen = project.id.length;
94
+ }
95
+ }
96
+ // 3. Fallback
97
+ return bestMatch ?? this.getDefault();
98
+ }
99
+ /** Force a rescan of PROJECTS_DIR (e.g. after watcher event or manual trigger). */
100
+ refresh() {
101
+ this.scan();
102
+ }
103
+ /** Stop the fs.watch watcher and release resources. */
104
+ destroy() {
105
+ if (this.debounceTimer) {
106
+ clearTimeout(this.debounceTimer);
107
+ this.debounceTimer = null;
108
+ }
109
+ if (this.watcher) {
110
+ this.watcher.close();
111
+ this.watcher = null;
112
+ }
113
+ this.initialized = false;
114
+ }
115
+ // ── Private ──────────────────────────────────────────────────
116
+ /** Create general/ scaffold if the directory does not exist. */
117
+ scaffoldGeneral() {
118
+ const generalDir = path.join(this.projectsDir, 'general');
119
+ if (fs.existsSync(generalDir))
120
+ return;
121
+ fs.mkdirSync(generalDir, { recursive: true });
122
+ fs.writeFileSync(path.join(generalDir, 'STATUS.md'), GENERAL_SCAFFOLD_STATUS, 'utf8');
123
+ fs.writeFileSync(path.join(generalDir, 'CORTEX.md'), GENERAL_SCAFFOLD_CORTEX, 'utf8');
124
+ log.info(`Scaffolded general project at ${generalDir}`);
125
+ }
126
+ /** Read PROJECTS_DIR and rebuild the in-memory cache. */
127
+ scan() {
128
+ const result = [];
129
+ // Always synthesize "general"
130
+ result.push(this.makeGeneralProject());
131
+ // Enumerate real project directories
132
+ try {
133
+ const entries = fs.readdirSync(this.projectsDir, { withFileTypes: true });
134
+ for (const entry of entries) {
135
+ if (!entry.isDirectory())
136
+ continue;
137
+ if (entry.name.startsWith('.'))
138
+ continue;
139
+ if (entry.name === 'general')
140
+ continue; // already added
141
+ result.push({
142
+ id: entry.name,
143
+ name: entry.name,
144
+ kind: 'user',
145
+ contextDir: path.join(this.projectsDir, entry.name),
146
+ });
147
+ }
148
+ }
149
+ catch {
150
+ // PROJECTS_DIR missing or unreadable — only "general" will be present
151
+ }
152
+ this.projects = result;
153
+ }
154
+ makeGeneralProject() {
155
+ return {
156
+ id: 'general',
157
+ name: 'general',
158
+ kind: 'general',
159
+ contextDir: path.join(this.projectsDir, 'general'),
160
+ };
161
+ }
162
+ /** Watch PROJECTS_DIR for add/remove of subdirectories. */
163
+ startWatcher() {
164
+ try {
165
+ this.watcher = fs.watch(this.projectsDir, (eventType, filename) => {
166
+ // On Linux 'rename' fires for create/delete; filter to directory-relevant events
167
+ if (!filename)
168
+ return;
169
+ // Ignore events for dotfiles and non-directory files (we can't easily check
170
+ // what type the changed entry is from the event alone, so we just debounce-scan)
171
+ if (filename.startsWith('.'))
172
+ return;
173
+ this.debouncedRescan();
174
+ });
175
+ this.watcher.on('error', (err) => {
176
+ log.error(`Watcher error for ${this.projectsDir}:`, err.message);
177
+ });
178
+ }
179
+ catch (err) {
180
+ log.error(`Failed to start watcher for ${this.projectsDir}:`, err);
181
+ }
182
+ }
183
+ debouncedRescan() {
184
+ if (this.debounceTimer)
185
+ clearTimeout(this.debounceTimer);
186
+ this.debounceTimer = setTimeout(() => {
187
+ this.debounceTimer = null;
188
+ this.scan();
189
+ log.debug(`Rescanned projects after directory change`);
190
+ }, DEBOUNCE_MS);
191
+ }
192
+ }
193
+ // --- Singleton ---
194
+ export const projectStore = new ProjectStore();