@cortex-agent/server 2026.5.19 → 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 +188 -0
  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 +15 -8
  134. package/dist/platform/virtual-message.d.ts +0 -68
@@ -1,6 +1,6 @@
1
- // input: platform/VirtualMessage, CORTEX_SHOW_TOOL_CALLS env
1
+ // input: platform/OutputStream, CORTEX_SHOW_TOOL_CALLS env
2
2
  // output: ToolTrace class + createToolTrace factory + isToolTraceEnabled
3
- // pos: Compact tool_use trace merged into the main VM message mutable tail
3
+ // pos: Compact tool_use trace rendered via OutputStream openMutable/update
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  const MAX_LINE_LEN = 120;
6
6
  const ELLIPSIS = '…';
@@ -118,14 +118,15 @@ function renderToolLine(toolName, summaries, opts) {
118
118
  return line;
119
119
  }
120
120
  export class ToolTrace {
121
- vm;
121
+ stream;
122
+ region = null;
122
123
  prefix;
123
124
  /** Name of the currently-open group (null if no open group). */
124
125
  groupName = null;
125
126
  /** Accumulated summaries for the open group; rendered on every update. */
126
127
  groupSummaries = [];
127
- constructor(vm, opts) {
128
- this.vm = vm;
128
+ constructor(stream, opts) {
129
+ this.stream = stream;
129
130
  this.prefix = opts?.slotPrefix || null;
130
131
  }
131
132
  onToolUse(name, input) {
@@ -133,33 +134,34 @@ export class ToolTrace {
133
134
  return;
134
135
  const summary = summarizeToolInput(name, input || {});
135
136
  if (this.groupName === name) {
136
- // Same group — append summary and edit the tail in place.
137
+ // Same group — append summary and update the mutable region in place.
137
138
  this.groupSummaries.push(summary);
138
139
  const text = renderToolLine(name, this.groupSummaries, { prefix: this.prefix });
139
- this.vm.editMutableTail(text);
140
+ this.region.update(text);
140
141
  return;
141
142
  }
142
- // New group — open a fresh mutable tail. VM seals the previous tail (if any)
143
- // into committed content as part of appendMutableTail().
143
+ // New group — open a fresh mutable region. Previous region (if any) is
144
+ // automatically sealed by openMutable.
144
145
  this.groupName = name;
145
146
  this.groupSummaries = [summary];
146
147
  const text = renderToolLine(name, this.groupSummaries, { prefix: this.prefix });
147
- this.vm.appendMutableTail(text);
148
+ this.region = this.stream.openMutable(text);
148
149
  }
149
- /** Seal the current group on the tool-trace side. VM's tail is not touched
150
- * here — the next `vm.append(text)` or `vm.appendMutableTail(...)` will
151
- * seal it naturally. */
150
+ /** Seal the current group on the tool-trace side. The stream's mutable region
151
+ * is not touched here — the next `stream.emitText(text)` or
152
+ * `stream.openMutable(...)` will seal it naturally. */
152
153
  flush() {
153
154
  this.groupName = null;
154
155
  this.groupSummaries = [];
156
+ this.region = null;
155
157
  }
156
158
  }
157
- /** Factory: returns a ToolTrace wired to the given VM, or null if the feature is disabled or VM is missing. */
158
- export function createToolTrace(vm, opts) {
159
+ /** Factory: returns a ToolTrace wired to the given OutputStream, or null if the feature is disabled or stream is missing. */
160
+ export function createToolTrace(stream, opts) {
159
161
  if (!isToolTraceEnabled())
160
162
  return null;
161
- if (!vm)
163
+ if (!stream)
162
164
  return null;
163
- return new ToolTrace(vm, opts);
165
+ return new ToolTrace(stream, opts);
164
166
  }
165
167
  export const _test = { summarizeToolInput, renderToolLine };
@@ -153,6 +153,26 @@ export interface PlatformCapabilities {
153
153
  maxMessageLength: number;
154
154
  maxThreadDepth: number;
155
155
  }
156
+ /** Declared intent for where and why a message is sent.
157
+ * Replaces raw `channel: string` in outbound adapter methods.
158
+ * - interactive-reply: reply in an ongoing conversation (conduit = channel)
159
+ * - project-report: push a report to a project's channel
160
+ * - system-notice: send to the platform-configured admin channel */
161
+ export type Destination = {
162
+ type: 'interactive-reply';
163
+ conduit: string;
164
+ sessionId?: string;
165
+ } | {
166
+ type: 'project-report';
167
+ projectId: string;
168
+ trigger: string;
169
+ sessionId?: string;
170
+ } | {
171
+ type: 'system-notice';
172
+ };
173
+ /** Resolve a Destination to a concrete channel string for the adapter.
174
+ * `adminChannel` is required for `system-notice` and ignored for other types. */
175
+ export declare function resolveDestinationConduit(dest: Destination, adminChannel?: string): string;
156
176
  export interface PostMessageOpts {
157
177
  threadId?: string;
158
178
  }
@@ -162,7 +182,7 @@ export interface FileUploadOpts {
162
182
  threadId?: string;
163
183
  }
164
184
  export interface DurableHooks {
165
- beforePost(channel: string, text: string, opts?: {
185
+ beforePost(destination: Destination, text: string, opts?: {
166
186
  threadId?: string;
167
187
  richBlocks?: RichBlock[];
168
188
  }): Promise<string>;
@@ -2,4 +2,20 @@
2
2
  // output: Platform-independent message/block/modal type family
3
3
  // pos: Type foundation of the Platform abstraction
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
- export {};
5
+ /** Resolve a Destination to a concrete channel string for the adapter.
6
+ * `adminChannel` is required for `system-notice` and ignored for other types. */
7
+ export function resolveDestinationConduit(dest, adminChannel) {
8
+ switch (dest.type) {
9
+ case 'interactive-reply':
10
+ return dest.conduit;
11
+ case 'project-report':
12
+ // FIXME: resolve projectId → channel via project store when the routing
13
+ // layer is added in the M3/M4 outbound refactoring.
14
+ return dest.projectId;
15
+ case 'system-notice':
16
+ if (!adminChannel) {
17
+ throw new Error('system-notice destination requires a configured admin channel');
18
+ }
19
+ return adminChannel;
20
+ }
21
+ }
@@ -4,16 +4,22 @@ export type ChannelRegistryData = Record<string, string>;
4
4
  interface ChannelRepoOptions {
5
5
  filePath?: string;
6
6
  projectsDir?: string;
7
+ /** Callback for listing project names. When set, listProjects() delegates here
8
+ * instead of reading the filesystem. Wired from app.ts (composition root). */
9
+ projectLister?: () => string[];
7
10
  }
8
11
  export declare class ChannelRepo {
9
12
  private readonly _repo;
10
13
  private readonly _projectsDir;
14
+ private _projectLister;
11
15
  constructor(opts?: ChannelRepoOptions);
12
16
  getProjectChannel(project: string): Promise<string | null>;
13
17
  setProjectChannel(project: string, channelId: string): Promise<void>;
14
18
  removeProjectChannel(project: string): Promise<void>;
15
19
  getAllRegistrations(): Promise<Record<string, string>>;
16
20
  listProjects(): Promise<string[]>;
21
+ /** Late injection of project lister callback (used by app.ts composition root). */
22
+ setProjectLister(lister: () => string[]): void;
17
23
  /** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
18
24
  flush(): Promise<void>;
19
25
  }
@@ -10,6 +10,7 @@ export const CHANNEL_REGISTRY_FILE = path.join(STORE_DIR, 'channel-registry.json
10
10
  export class ChannelRepo {
11
11
  _repo;
12
12
  _projectsDir;
13
+ _projectLister = null;
13
14
  constructor(opts = {}) {
14
15
  this._repo = new JsonRepository({
15
16
  filePath: opts.filePath ?? CHANNEL_REGISTRY_FILE,
@@ -17,6 +18,7 @@ export class ChannelRepo {
17
18
  migrate: (raw) => (typeof raw === 'object' && raw !== null ? raw : ({})),
18
19
  });
19
20
  this._projectsDir = opts.projectsDir ?? PROJECTS_DIR;
21
+ this._projectLister = opts.projectLister ?? null;
20
22
  }
21
23
  async getProjectChannel(project) {
22
24
  const data = await this._repo.read();
@@ -38,6 +40,9 @@ export class ChannelRepo {
38
40
  return { ...(await this._repo.read()) };
39
41
  }
40
42
  async listProjects() {
43
+ if (this._projectLister) {
44
+ return this._projectLister();
45
+ }
41
46
  try {
42
47
  return fsSync.readdirSync(this._projectsDir).filter((name) => {
43
48
  return fsSync.statSync(path.join(this._projectsDir, name)).isDirectory() && !name.startsWith('.');
@@ -47,6 +52,10 @@ export class ChannelRepo {
47
52
  return [];
48
53
  }
49
54
  }
55
+ /** Late injection of project lister callback (used by app.ts composition root). */
56
+ setProjectLister(lister) {
57
+ this._projectLister = lister;
58
+ }
50
59
  /** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
51
60
  flush() {
52
61
  return this._repo.flush();
@@ -54,7 +54,18 @@ export class JsonRepository {
54
54
  try {
55
55
  const raw = await fs.readFile(this.opts.filePath, 'utf8');
56
56
  const parsed = JSON.parse(raw);
57
- this.cache = this.opts.migrate ? this.opts.migrate(parsed) : parsed;
57
+ if (this.opts.migrate) {
58
+ const migrated = this.opts.migrate(parsed);
59
+ // Persist migrated data back to disk so the new shape survives
60
+ // across restarts even when no mutate() follows.
61
+ if (JSON.stringify(parsed) !== JSON.stringify(migrated)) {
62
+ await atomicWrite(this.opts.filePath, JSON.stringify(migrated, null, 2));
63
+ }
64
+ this.cache = migrated;
65
+ }
66
+ else {
67
+ this.cache = parsed;
68
+ }
58
69
  }
59
70
  catch (err) {
60
71
  if (err.code === 'ENOENT') {
@@ -1,6 +1,6 @@
1
- import type { RichBlock, MessageRef, MessageContent, PostMessageOpts } from '../platform/types.js';
1
+ import type { Destination, RichBlock, MessageRef, MessageContent, PostMessageOpts } from '../platform/types.js';
2
2
  interface MessageSender {
3
- postMessage(channel: string, content: MessageContent, opts?: PostMessageOpts): Promise<MessageRef>;
3
+ postMessage(destination: Destination, content: MessageContent, opts?: PostMessageOpts): Promise<MessageRef>;
4
4
  updateMessage(ref: MessageRef, content: MessageContent): Promise<void>;
5
5
  }
6
6
  export interface OutboundQueueOpts {
@@ -11,6 +11,7 @@ export interface OutboundQueueOpts {
11
11
  export interface EnqueueInput {
12
12
  type: 'post' | 'update';
13
13
  channel: string;
14
+ destination?: Destination;
14
15
  text: string;
15
16
  richBlocks?: RichBlock[];
16
17
  threadId?: string;
@@ -24,7 +25,7 @@ export declare class OutboundQueue {
24
25
  private pending;
25
26
  private sentIds;
26
27
  /**
27
- * IDs currently being processed by the inline send path (VirtualMessage /
28
+ * IDs currently being processed by the inline send path (OutputStream /
28
29
  * durablePost). drain() skips these to prevent double-sends. Entries are
29
30
  * claimed by buildDurableHooks.beforePost/beforeUpdate and released by
30
31
  * afterSent (on success) or onSendFailed (on permanent failure).
@@ -60,6 +61,6 @@ export declare function initOutboundQueue(adapter: MessageSender, opts?: {
60
61
  ttlMs?: number;
61
62
  }): OutboundQueue;
62
63
  export declare function getOutboundQueue(): OutboundQueue | null;
63
- export declare function durablePost(queue: OutboundQueue, sender: MessageSender, channel: string, content: MessageContent, opts?: PostMessageOpts): Promise<MessageRef>;
64
+ export declare function durablePost(queue: OutboundQueue, sender: MessageSender, destination: Destination, content: MessageContent, opts?: PostMessageOpts): Promise<MessageRef>;
64
65
  export declare function durableUpdate(queue: OutboundQueue, sender: MessageSender, ref: MessageRef, content: MessageContent): Promise<void>;
65
66
  export {};
@@ -20,7 +20,7 @@ export class OutboundQueue {
20
20
  pending = new Map();
21
21
  sentIds = new Set();
22
22
  /**
23
- * IDs currently being processed by the inline send path (VirtualMessage /
23
+ * IDs currently being processed by the inline send path (OutputStream /
24
24
  * durablePost). drain() skips these to prevent double-sends. Entries are
25
25
  * claimed by buildDurableHooks.beforePost/beforeUpdate and released by
26
26
  * afterSent (on success) or onSendFailed (on permanent failure).
@@ -44,6 +44,7 @@ export class OutboundQueue {
44
44
  type: input.type,
45
45
  channel: input.channel,
46
46
  text: input.text,
47
+ ...(input.destination && { destination: input.destination }),
47
48
  ...(input.richBlocks && { richBlocks: input.richBlocks }),
48
49
  ...(input.threadId && { threadId: input.threadId }),
49
50
  ...(input.messageId && { messageId: input.messageId }),
@@ -118,7 +119,8 @@ export class OutboundQueue {
118
119
  }
119
120
  try {
120
121
  if (entry.type === 'post') {
121
- await this.adapter.postMessage(entry.channel, {
122
+ const dest = entry.destination ?? { type: 'interactive-reply', conduit: entry.channel, sessionId: '' };
123
+ await this.adapter.postMessage(dest, {
122
124
  text: entry.text,
123
125
  ...(entry.richBlocks && { richBlocks: entry.richBlocks }),
124
126
  }, entry.threadId ? { threadId: entry.threadId } : undefined);
@@ -130,7 +132,7 @@ export class OutboundQueue {
130
132
  await this.markSent(entry.id);
131
133
  }
132
134
  catch {
133
- await this.adapter.postMessage(entry.channel, {
135
+ await this.adapter.postMessage({ type: 'interactive-reply', conduit: entry.channel }, {
134
136
  text: entry.text,
135
137
  ...(entry.richBlocks && { richBlocks: entry.richBlocks }),
136
138
  });
@@ -230,17 +232,18 @@ export function initOutboundQueue(adapter, opts) {
230
232
  export function getOutboundQueue() {
231
233
  return outboundQueue.instance;
232
234
  }
233
- export async function durablePost(queue, sender, channel, content, opts) {
235
+ export async function durablePost(queue, sender, destination, content, opts) {
234
236
  const walId = await queue.enqueue({
235
237
  type: 'post',
236
- channel,
238
+ channel: '',
239
+ destination,
237
240
  text: content.text,
238
241
  richBlocks: content.richBlocks,
239
242
  threadId: opts?.threadId,
240
243
  });
241
244
  queue.claim(walId);
242
245
  try {
243
- const ref = await sender.postMessage(channel, content, opts);
246
+ const ref = await sender.postMessage(destination, content, opts);
244
247
  await queue.markSent(walId, ref.messageId);
245
248
  return ref;
246
249
  }
@@ -1,4 +1,5 @@
1
1
  export declare const SCHEDULES_FILE: string;
2
+ export declare const CHANNEL_REGISTRY_FILE: string;
2
3
  /** Where a fired scheduled-task should land. Resolved by the cortex_schedule_add MCP tool
3
4
  * (or schedule-cli) at create time — `__current__` placeholders are concretized then, so
4
5
  * list/get always show real IDs. The 4 kinds map to the dispatch branches in
@@ -6,10 +7,10 @@ export declare const SCHEDULES_FILE: string;
6
7
  export type ScheduleTarget = {
7
8
  kind: 'fresh';
8
9
  }
9
- /** Fire into the channel — reuses any active thread / channel-default session. */
10
+ /** Fire into the project — spawns a fresh session in the project's channel. */
10
11
  | {
11
- kind: 'channel';
12
- channel: string;
12
+ kind: 'project';
13
+ projectId: string;
13
14
  }
14
15
  /** Fire into a specific cortex-XXXX session, reusing its sessionId. Channel+sessionId are locked at create time. */
15
16
  | {
@@ -28,7 +29,7 @@ export interface ScheduleTask {
28
29
  id: string;
29
30
  type: 'interval' | 'daily' | 'weekly' | 'once';
30
31
  message: string;
31
- channel: string;
32
+ projectId: string;
32
33
  profile: string | null;
33
34
  intervalMs?: number;
34
35
  time?: string;
@@ -61,9 +62,12 @@ export interface SchedulesData {
61
62
  modes?: string[];
62
63
  } | null;
63
64
  }
65
+ /** Convenience: reverse-lookup projectId from a Slack channel via channel-registry.json. */
66
+ export declare function channelToProjectId(channel: string): string | null;
64
67
  export declare class ScheduleRepo {
65
68
  private _repo;
66
- constructor(filePath?: string);
69
+ private _channelRegistryPath;
70
+ constructor(filePath?: string, channelRegistryPath?: string);
67
71
  read(): Promise<SchedulesData>;
68
72
  addTask(task: ScheduleTask): Promise<void>;
69
73
  removeTask(id: string): Promise<boolean>;
@@ -1,34 +1,79 @@
1
- // input: schedules.json + JsonRepository
2
- // output: ScheduleRepo (read / addTask / removeTask / updateTask / rateLimitThrottle)
1
+ // input: schedules.json + channel-registry.json + JsonRepository
2
+ // output: ScheduleRepo (read / addTask / removeTask / updateTask / rateLimitThrottle) + migration helpers
3
3
  // pos: Schedule persistence layer. Based on JsonRepository abstraction (Pattern A), AsyncMutex serializes reads/writes of schedules.json.
4
+ // Migration from channel→projectId reads channel-registry.json synchronously for reverse lookup.
4
5
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
6
  import * as path from 'path';
7
+ import * as fs from 'fs';
6
8
  import { JsonRepository } from './json-repository.js';
7
9
  import { STORE_DIR } from '../core/paths.js';
8
10
  export const SCHEDULES_FILE = path.join(STORE_DIR, 'schedules.json');
11
+ export const CHANNEL_REGISTRY_FILE = path.join(STORE_DIR, 'channel-registry.json');
9
12
  function defaultData() {
10
13
  return { tasks: [] };
11
14
  }
12
- function migrate(raw) {
13
- if (typeof raw !== 'object' || raw === null || !('tasks' in raw)) {
14
- return defaultData();
15
+ /**
16
+ * Read a channel-registry.json synchronously and build a reverse map: channel → projectId.
17
+ * Returns {} on ENOENT or parse error (graceful degradation — migration falls back to 'general').
18
+ */
19
+ function syncReadChannelToProject(registryPath) {
20
+ try {
21
+ const raw = fs.readFileSync(registryPath ?? CHANNEL_REGISTRY_FILE, 'utf8');
22
+ const registry = JSON.parse(raw);
23
+ const reverse = {};
24
+ for (const [project, ch] of Object.entries(registry)) {
25
+ reverse[ch] = project;
26
+ }
27
+ return reverse;
15
28
  }
16
- const data = raw;
17
- // Backfill target=fresh on records persisted before the multi-target dispatch landed,
18
- // so the scheduler can dispatch them through the unified branch table without null-checks.
19
- for (const task of data.tasks) {
20
- if (!task.target)
21
- task.target = { kind: 'fresh' };
29
+ catch {
30
+ return {};
22
31
  }
23
- return data;
32
+ }
33
+ /** Convenience: reverse-lookup projectId from a Slack channel via channel-registry.json. */
34
+ export function channelToProjectId(channel) {
35
+ return syncReadChannelToProject()[channel] ?? null;
36
+ }
37
+ function makeMigrate(channelRegistryPath) {
38
+ return function migrate(raw) {
39
+ if (typeof raw !== 'object' || raw === null || !('tasks' in raw)) {
40
+ return defaultData();
41
+ }
42
+ const data = raw;
43
+ // M4: Migrate channel→projectId. Reads channel-registry.json for reverse lookup.
44
+ // Idempotent: records already carrying projectId pass through unchanged.
45
+ const channelToProject = syncReadChannelToProject(channelRegistryPath);
46
+ for (const task of data.tasks) {
47
+ const t = task;
48
+ if ('channel' in t && !('projectId' in t)) {
49
+ // Legacy record — reverse-lookup projectId from channel
50
+ t.projectId = channelToProject[String(t.channel)] ?? 'general';
51
+ delete t.channel;
52
+ }
53
+ else if ('projectId' in t) {
54
+ // New format (idempotent) — remove stale channel if somehow present
55
+ if ('channel' in t)
56
+ delete t.channel;
57
+ }
58
+ }
59
+ // Backfill target=fresh on records persisted before the multi-target dispatch landed,
60
+ // so the scheduler can dispatch them through the unified branch table without null-checks.
61
+ for (const task of data.tasks) {
62
+ if (!task.target)
63
+ task.target = { kind: 'fresh' };
64
+ }
65
+ return data;
66
+ };
24
67
  }
25
68
  export class ScheduleRepo {
26
69
  _repo;
27
- constructor(filePath = SCHEDULES_FILE) {
70
+ _channelRegistryPath;
71
+ constructor(filePath = SCHEDULES_FILE, channelRegistryPath) {
72
+ this._channelRegistryPath = channelRegistryPath;
28
73
  this._repo = new JsonRepository({
29
74
  filePath,
30
75
  defaultValue: defaultData,
31
- migrate,
76
+ migrate: makeMigrate(channelRegistryPath),
32
77
  });
33
78
  }
34
79
  async read() {
@@ -1,6 +1,8 @@
1
1
  export declare const REGISTRY_FILE: string;
2
- export interface SessionRecord {
2
+ export interface Session {
3
+ name: string;
3
4
  sessionId: string;
5
+ projectId: string;
4
6
  channel: string;
5
7
  backend: string;
6
8
  kind: 'local' | 'scheduled';
@@ -10,29 +12,56 @@ export interface SessionRecord {
10
12
  /** Profile name active when the session was created. Restored on !resume. */
11
13
  profileName: string | null;
12
14
  }
13
- export type SessionRegistryData = Record<string, SessionRecord>;
15
+ export type SessionRegistryData = Record<string, Session>;
14
16
  export declare class SessionRegistryRepo {
15
17
  private readonly _repo;
18
+ /** name → sessionId index keeping lookupSession O(1). */
19
+ private _nameIndex;
20
+ /** Optional callback invoked when a session is pruned. Receives the sessionId. */
21
+ private _onPruneSession;
16
22
  constructor(filePath?: string);
23
+ private _rebuildNameIndex;
24
+ /** Read registry data, rebuilding the name index from cache when empty. */
25
+ private _readWithIndex;
26
+ /** Rebuild the name index from the current cached data (zero I/O on cache hit). */
27
+ private _syncIndex;
17
28
  generateSessionName(): Promise<string>;
18
29
  registerSession(name: string, opts: {
19
30
  sessionId: string;
20
31
  channel: string;
21
32
  backend: string;
22
33
  kind: 'local' | 'scheduled';
34
+ projectId?: string;
23
35
  label?: string | null;
24
36
  profileName?: string | null;
25
37
  }): Promise<void>;
26
- updateSession(name: string, updates: Partial<Pick<SessionRecord, 'sessionId' | 'lastUsedAt' | 'label' | 'profileName'>>): Promise<void>;
27
- lookupSession(name: string): Promise<SessionRecord | null>;
38
+ updateSession(name: string, updates: Partial<Pick<Session, 'sessionId' | 'lastUsedAt' | 'label' | 'profileName'>>): Promise<void>;
39
+ lookupSession(name: string): Promise<Session | null>;
28
40
  lookupBySessionId(sessionId: string): Promise<string | null>;
29
- listRecentSessions(limit?: number): Promise<Array<{
30
- name: string;
31
- } & SessionRecord>>;
41
+ listRecentSessions(limit?: number): Promise<Session[]>;
42
+ /** Return a session by sessionId, or null if not found. O(1) key lookup. */
43
+ getById(sessionId: string): Promise<Session | null>;
44
+ /** List sessions belonging to a project, most recently used first. */
45
+ listByProject(projectId: string): Promise<Session[]>;
46
+ /** List resumable (non-scheduled) sessions, optionally filtered by projectId. */
47
+ listResumable(projectId?: string): Promise<Session[]>;
48
+ /** Touch the lastUsedAt timestamp of a session to now. No-op if sessionId not found. */
49
+ markUsed(sessionId: string): Promise<void>;
50
+ /**
51
+ * Remove sessions whose lastUsedAt is older than maxAgeMs from now,
52
+ * and are not referenced by any executionRepo or threadStore record.
53
+ * Invokes the onPruneSession callback (if set) for each removed session.
54
+ * Returns the number of removed sessions.
55
+ */
56
+ pruneStale(maxAgeMs: number): Promise<number>;
57
+ /** Set a callback to invoke when a session is pruned (e.g. cleanup backup files). */
58
+ setOnPruneSession(fn: ((sessionId: string) => void) | null): void;
32
59
  getActiveSessionName(channel: string, backend: string): Promise<string | null>;
33
60
  /** Drop the in-memory cache so the next read() fetches from disk. Test hook. */
34
61
  invalidate(): void;
35
62
  /** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
36
63
  flush(): Promise<void>;
37
64
  }
65
+ export declare const sessionStore: SessionRegistryRepo;
66
+ /** @deprecated Use `sessionStore` instead. Alias for backward compatibility. */
38
67
  export declare const sessionRegistryRepo: SessionRegistryRepo;