@cortex-agent/server 2026.5.23 → 2026.5.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/agent-adapter/pi/adapter.js +56 -7
  2. package/dist/agent-adapter/pi/agent-dir.d.ts +41 -4
  3. package/dist/agent-adapter/pi/agent-dir.js +101 -16
  4. package/dist/agent-adapter/pi/spawn-args.d.ts +4 -0
  5. package/dist/agent-adapter/pi/spawn-args.js +6 -3
  6. package/dist/agent-adapter/types.d.ts +7 -0
  7. package/dist/core/gateway-generator.d.ts +27 -14
  8. package/dist/core/gateway-generator.js +153 -169
  9. package/dist/{store → core}/json-repository.js +2 -2
  10. package/dist/core/profile-generator.d.ts +14 -15
  11. package/dist/core/profile-generator.js +52 -174
  12. package/dist/domain/agents/facade.js +6 -0
  13. package/dist/domain/system/server-update-check.d.ts +17 -0
  14. package/dist/domain/system/server-update-check.js +130 -0
  15. package/dist/domain/system/update-prompt.d.ts +8 -0
  16. package/dist/domain/system/update-prompt.js +5 -0
  17. package/dist/domain/system/update-state.d.ts +9 -0
  18. package/dist/domain/system/update-state.js +25 -0
  19. package/dist/entry/app.js +24 -2
  20. package/dist/entry/init.js +63 -21
  21. package/dist/orchestration/agent-runner.js +3 -4
  22. package/dist/orchestration/interactions/update-prompt-slack.d.ts +6 -0
  23. package/dist/orchestration/interactions/update-prompt-slack.js +95 -0
  24. package/dist/orchestration/lifecycle.js +3 -4
  25. package/dist/platform/adapter.d.ts +4 -0
  26. package/dist/platform/adapter.js +1 -1
  27. package/dist/platform/adapters/feishu.d.ts +1 -0
  28. package/dist/platform/adapters/feishu.js +7 -0
  29. package/dist/platform/adapters/slack-project-conduits.js +1 -1
  30. package/dist/platform/adapters/slack.d.ts +1 -0
  31. package/dist/platform/adapters/slack.js +8 -0
  32. package/dist/platform/index.js +1 -1
  33. package/dist/platform/testing.d.ts +1 -0
  34. package/dist/platform/testing.js +7 -0
  35. package/dist/store/conversation-ledger-repo.js +1 -1
  36. package/dist/store/cost-repo.js +2 -2
  37. package/dist/store/execution-repo.js +1 -1
  38. package/dist/store/outbound-queue.js +1 -1
  39. package/dist/store/profile-repo.js +1 -1
  40. package/dist/store/project-dir-repo.d.ts +0 -5
  41. package/dist/store/project-dir-repo.js +4 -15
  42. package/dist/store/schedule-repo.js +1 -1
  43. package/dist/store/session-registry-repo.js +6 -2
  44. package/dist/store/session-repo.js +1 -1
  45. package/dist/store/thread-repo.js +1 -1
  46. package/dist/store/version-migrations.d.ts +22 -0
  47. package/dist/store/version-migrations.js +200 -0
  48. package/package.json +2 -2
  49. package/dist/store/channel-repo.d.ts +0 -27
  50. package/dist/store/channel-repo.js +0 -64
  51. /package/dist/{store → core}/atomic-write.d.ts +0 -0
  52. /package/dist/{store → core}/atomic-write.js +0 -0
  53. /package/dist/{store → core}/json-repository.d.ts +0 -0
@@ -1129,9 +1129,11 @@ function detectExistingPlanOrExecute(configDir) {
1129
1129
  }
1130
1130
  }
1131
1131
  /**
1132
- * Interactively pick plan / execute (mode, model) from discovered endpoints.
1133
- * Pre-selects auto-inferred defaults. Returns undefined for either choice if the user
1134
- * declined to overwrite an existing profile.
1132
+ * Interactively pick plan / execute (mode, model) from discovered endpoints, plus optional
1133
+ * fallback chains. Lists are sorted lexicographically; the first entry is pre-selected.
1134
+ *
1135
+ * Returns `overwrite: false` if the user declined to overwrite an existing profile — in that
1136
+ * case all *Choice / *Fallback fields are undefined.
1135
1137
  */
1136
1138
  async function pickPlanExecuteInteractive(endpoints, configDir) {
1137
1139
  // If existing profiles.json has plan/execute, ask before overwriting
@@ -1148,34 +1150,67 @@ async function pickPlanExecuteInteractive(endpoints, configDir) {
1148
1150
  const choices = listChoices(endpoints);
1149
1151
  if (choices.length === 0)
1150
1152
  return { overwrite: true };
1151
- const autoDefaults = generateProfiles(endpoints).profiles;
1152
- const planDefault = autoDefaults.plan
1153
- ? `${autoDefaults.plan.mode}:${autoDefaults.plan.model}`
1154
- : `${choices[0].mode}:${choices[0].model}`;
1155
- const executeDefault = autoDefaults.execute
1156
- ? `${autoDefaults.execute.mode}:${autoDefaults.execute.model}`
1157
- : planDefault;
1153
+ const formatValue = (c) => `${c.mode}:${c.model}`;
1154
+ const parseValue = (v) => {
1155
+ const colonIdx = v.indexOf(':');
1156
+ return { mode: v.substring(0, colonIdx), model: v.substring(colonIdx + 1) };
1157
+ };
1158
1158
  const options = choices.map(c => ({
1159
- value: `${c.mode}:${c.model}`,
1159
+ value: formatValue(c),
1160
1160
  label: `${c.mode} / ${c.model}`,
1161
1161
  }));
1162
+ // Default = first lexicographic entry (no tier inference).
1163
+ const firstChoiceValue = formatValue(choices[0]);
1162
1164
  const planSel = await clack.select({
1163
1165
  message: 'Pick model for the `plan` profile (used by executor agents — planner, doc-writer, coder, etc.):',
1164
1166
  options,
1165
- initialValue: planDefault,
1167
+ initialValue: firstChoiceValue,
1166
1168
  });
1167
1169
  handleCancel(planSel);
1168
1170
  const execSel = await clack.select({
1169
1171
  message: 'Pick model for the `execute` profile (used by reviewer agents — reviewer, doc-reviewer, coder-reviewer, etc.):',
1170
1172
  options,
1171
- initialValue: executeDefault,
1173
+ initialValue: firstChoiceValue,
1172
1174
  });
1173
1175
  handleCancel(execSel);
1174
- const [planMode, planModel] = planSel.split(':');
1175
- const [execMode, execModel] = execSel.split(':');
1176
+ const planChoice = parseValue(planSel);
1177
+ const execChoice = parseValue(execSel);
1178
+ // ── Fallback selection (multi-select, ordered) ──
1179
+ // Build fallback options excluding the primary choice. If no candidates remain (e.g. only
1180
+ // one discovered model), skip the prompt entirely.
1181
+ const planFallbackOptions = options.filter(o => o.value !== planSel);
1182
+ const execFallbackOptions = options.filter(o => o.value !== execSel);
1183
+ let planFallback;
1184
+ if (planFallbackOptions.length > 0) {
1185
+ const sel = await clack.multiselect({
1186
+ message: 'Pick fallback models for `plan` (in order, space to toggle, enter to confirm, leave empty for no fallback):',
1187
+ options: planFallbackOptions,
1188
+ required: false,
1189
+ initialValues: [],
1190
+ });
1191
+ handleCancel(sel);
1192
+ const arr = sel;
1193
+ if (arr.length > 0)
1194
+ planFallback = arr.map(parseValue);
1195
+ }
1196
+ let executeFallback;
1197
+ if (execFallbackOptions.length > 0) {
1198
+ const sel = await clack.multiselect({
1199
+ message: 'Pick fallback models for `execute` (in order, space to toggle, enter to confirm, leave empty for no fallback):',
1200
+ options: execFallbackOptions,
1201
+ required: false,
1202
+ initialValues: [],
1203
+ });
1204
+ handleCancel(sel);
1205
+ const arr = sel;
1206
+ if (arr.length > 0)
1207
+ executeFallback = arr.map(parseValue);
1208
+ }
1176
1209
  return {
1177
- planChoice: { mode: planMode, model: planModel },
1178
- executeChoice: { mode: execMode, model: execModel },
1210
+ planChoice,
1211
+ executeChoice: execChoice,
1212
+ planFallback,
1213
+ executeFallback,
1179
1214
  overwrite: true,
1180
1215
  };
1181
1216
  }
@@ -1195,20 +1230,25 @@ async function runGatewaySetup(backends, paths, gatewayConfigDir, answers) {
1195
1230
  const yamlContent = generateGatewayYaml(endpoints);
1196
1231
  const gatewayPath = writeGatewayYaml(yamlContent, gatewayConfigDir);
1197
1232
  clack.log.success(`Gateway config written to ${gatewayPath}`);
1198
- // Resolve plan/execute choices + overwrite intent.
1233
+ // Resolve plan/execute choices + fallback chains + overwrite intent.
1199
1234
  let planChoice = answers?.planChoice;
1200
1235
  let executeChoice = answers?.executeChoice;
1236
+ let planFallback;
1237
+ let executeFallback;
1201
1238
  let overwrite;
1202
1239
  if (processStdin.isTTY) {
1203
1240
  // Interactive: prompt for selection (with overwrite confirmation if needed)
1204
1241
  const picked = await pickPlanExecuteInteractive(endpoints, paths.CONFIG_DIR);
1205
1242
  planChoice = picked.planChoice ?? planChoice;
1206
1243
  executeChoice = picked.executeChoice ?? executeChoice;
1244
+ planFallback = picked.planFallback;
1245
+ executeFallback = picked.executeFallback;
1207
1246
  overwrite = picked.overwrite;
1208
1247
  }
1209
1248
  else {
1210
- // Non-interactive: stdin already provided choices (or empty → auto-infer).
1211
- // Always overwrite — scripted (re)install assumes the operator knows the intent.
1249
+ // Non-interactive: stdin already provided choices (or empty → lex-first default).
1250
+ // Fallback chains are not configurable via stdin in this iteration — extend the stdin
1251
+ // protocol if scripted installs need fallback.
1212
1252
  overwrite = true;
1213
1253
  }
1214
1254
  // Generate profiles.json
@@ -1216,11 +1256,13 @@ async function runGatewaySetup(backends, paths, gatewayConfigDir, answers) {
1216
1256
  outputDir: paths.CONFIG_DIR,
1217
1257
  planChoice,
1218
1258
  executeChoice,
1259
+ planFallback,
1260
+ executeFallback,
1219
1261
  overwrite,
1220
1262
  });
1221
1263
  clack.log.success(`Profiles written to ${profilesPath}`);
1222
1264
  // Show profile summary (reflects what was actually generated, not what was merged)
1223
- const profiles = generateProfiles(endpoints, { planChoice, executeChoice });
1265
+ const profiles = generateProfiles(endpoints, { planChoice, executeChoice, planFallback, executeFallback });
1224
1266
  const profileNames = Object.keys(profiles.profiles).join(', ');
1225
1267
  clack.log.info(`Generated profiles: ${profileNames} (default: ${profiles.defaultProfile})`);
1226
1268
  }
@@ -19,7 +19,6 @@ const log = createLogger('agent-runner');
19
19
  import { createToolTrace } from '../platform/index.js';
20
20
  import { setStreamingCallback, clearStreamingCallback, publishPlanSubmitted, publishAskUserRequested } from './routing/hook-bridge.js';
21
21
  import { maybeNotifyCodexLowUsage } from '../domain/costs/codex-usage-monitor.js';
22
- import { projectDirRepo } from '../store/project-dir-repo.js';
23
22
  import { getAgent, createDefaultThread } from '../domain/threads/index.js';
24
23
  import { runThread } from '../domain/threads/runner.js';
25
24
  import { downloadFiles as downloadPlatformFiles } from './routing/file-handler.js';
@@ -55,7 +54,7 @@ export class AgentRunner {
55
54
  const downloadedFiles = await downloadFiles(message.files, hasFiles, adapter);
56
55
  const startTime = Date.now();
57
56
  const sessionId = await getSessionAsync(channel, resolveBackendForChannel(channel));
58
- const sessionName = await resolveSessionName(sessionId, channel, userMessage);
57
+ const sessionName = await resolveSessionName(sessionId, channel, userMessage, adapter);
59
58
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: sessionId ?? '' };
60
59
  // 1. Orchestration side effects (keep — ledger, status, hook-bridge)
61
60
  const statusText = buildUserProcessingMessage({ startTime, profileName: getActiveProfile(channel), sessionName, sessionId });
@@ -159,13 +158,13 @@ async function handleDefaultAgentResult({ result, channel, adapter, statusMsg, s
159
158
  await handleAgentSuccess({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, trigger: 'user', sessionName, threadTs, userMessageTs: messageTs, onAssistantMessage: callbacks.onAssistantMsg });
160
159
  // NOTE: createAutoThread removed — thread was created pre-execution via createDefaultThread
161
160
  }
162
- async function resolveSessionName(sessionId, channel, userMessage) {
161
+ async function resolveSessionName(sessionId, channel, userMessage, adapter) {
163
162
  if (sessionId) {
164
163
  const existing = await sessionStore.lookupBySessionId(sessionId);
165
164
  if (existing)
166
165
  return existing;
167
166
  const name = await sessionStore.generateSessionName();
168
- const channelProject = await projectDirRepo.getChannelProject(channel);
167
+ const channelProject = await adapter.resolveInboundProject(channel);
169
168
  await sessionStore.registerSession(name, { sessionId, channel, backend: resolveBackendForChannel(channel), kind: 'local', label: userMessage?.substring(0, 60), profileName: getActiveProfile(channel), projectId: channelProject ?? 'general' });
170
169
  return name;
171
170
  }
@@ -0,0 +1,6 @@
1
+ import type { PlatformAdapter } from '../../platform/index.js';
2
+ import type { CommandActionRouter } from '../interactions/command-action-router.js';
3
+ import type { UpdatePrompt } from '../../domain/system/update-prompt.js';
4
+ export declare function createSlackUpdatePrompt(adapter: PlatformAdapter, router: CommandActionRouter, opts?: {
5
+ timeoutMs?: number;
6
+ }): UpdatePrompt;
@@ -0,0 +1,95 @@
1
+ // input: @platform/index.js + @orch/interactions/command-action-router.js + @domain/system/update-prompt.js
2
+ // output: createSlackUpdatePrompt(adapter, router, opts?) => UpdatePrompt
3
+ // pos: Slack-specific UpdatePrompt implementation — pre-registers three actionIds on router,
4
+ // posts interactive message to system-notice, resolves ask() promise on button click.
5
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
6
+ const DEFAULT_TIMEOUT_MS = 86_400_000; // 24h
7
+ // --- Factory ---
8
+ export function createSlackUpdatePrompt(adapter, router, opts) {
9
+ const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
10
+ let pending = null;
11
+ let timerHandle;
12
+ // --- Internal helpers ---
13
+ const clearPending = () => {
14
+ if (timerHandle !== undefined) {
15
+ clearTimeout(timerHandle);
16
+ timerHandle = undefined;
17
+ }
18
+ pending = null;
19
+ };
20
+ const resolveText = (choice, version) => {
21
+ switch (choice) {
22
+ case 'apply':
23
+ return `Installing @cortex-agent/server@${version}... daemon will restart shortly.`;
24
+ case 'skip':
25
+ return `Skipped version ${version}.`;
26
+ case 'cancel':
27
+ return `Update cancelled. Will check again at next interval.`;
28
+ }
29
+ };
30
+ // --- Build click handlers ---
31
+ const buildHandler = (choice) => {
32
+ return async (ctx) => {
33
+ if (!pending)
34
+ return; // stale click — no pending prompt
35
+ const p = pending;
36
+ const version = p.latestVersion;
37
+ clearPending();
38
+ p.resolve(choice);
39
+ if (ctx.messageRef) {
40
+ await adapter.updateMessage(ctx.messageRef, { text: resolveText(choice, version) }).catch(() => { });
41
+ }
42
+ };
43
+ };
44
+ // --- Pre-register three actionIds on router ---
45
+ router.registerCommand('update', {
46
+ actions: [
47
+ { actionId: 'apply', handler: buildHandler('apply') },
48
+ { actionId: 'skip', handler: buildHandler('skip') },
49
+ { actionId: 'cancel', handler: buildHandler('cancel') },
50
+ ],
51
+ });
52
+ // --- Button templates (value filled in at ask time) ---
53
+ const buttonTemplates = [
54
+ { type: 'button', text: 'Update', actionId: 'cmd:update:apply', value: '', style: 'primary' },
55
+ { type: 'button', text: 'Skip this version', actionId: 'cmd:update:skip', value: '' },
56
+ { type: 'button', text: 'Cancel', actionId: 'cmd:update:cancel', value: '', style: 'danger' },
57
+ ];
58
+ // --- Return the UpdatePrompt implementation ---
59
+ return {
60
+ async ask(spec) {
61
+ // Resolve any existing pending prompt
62
+ if (pending) {
63
+ const old = pending;
64
+ clearPending();
65
+ old.resolve(null);
66
+ if (old.messageRef) {
67
+ await adapter.updateMessage(old.messageRef, { text: 'Superseded by a newer update prompt.' }).catch(() => { });
68
+ }
69
+ }
70
+ // Stamp version onto buttons
71
+ const versionedButtons = buttonTemplates.map(b => ({ ...b, value: spec.latestVersion }));
72
+ // Post interactive message to admin DM
73
+ const messageRef = await adapter.postInteractive({ type: 'system-notice' }, {
74
+ text: `Cortex Server v${spec.latestVersion} is available. Update now?`,
75
+ richBlocks: [
76
+ { type: 'section', text: `Cortex Server v${spec.latestVersion} is available.` },
77
+ { type: 'actions', elements: versionedButtons },
78
+ ],
79
+ actions: versionedButtons,
80
+ });
81
+ // Create new pending promise
82
+ return new Promise((resolve) => {
83
+ pending = { resolve, messageRef, latestVersion: spec.latestVersion };
84
+ timerHandle = setTimeout(() => {
85
+ if (!pending || pending.resolve !== resolve)
86
+ return; // already handled
87
+ const ref = pending.messageRef;
88
+ clearPending();
89
+ resolve(null);
90
+ adapter.updateMessage(ref, { text: 'Update prompt timed out.' }).catch(() => { });
91
+ }, timeoutMs).unref();
92
+ });
93
+ },
94
+ };
95
+ }
@@ -17,7 +17,6 @@ import * as executionRegistry from '../domain/executions/registry.js';
17
17
  import * as askUserQuestion from './interactions/ask-user-question.js';
18
18
  import { runAgent, getClaudeMode, getActiveProfile, resolveBackendForChannel } from '../domain/agents/index.js';
19
19
  import { projectStore } from '../domain/projects/index.js';
20
- import { projectDirRepo } from '../store/project-dir-repo.js';
21
20
  import { setStreamingCallback, clearStreamingCallback } from './routing/hook-bridge.js';
22
21
  import { maybeNotifyCodexLowUsage } from '../domain/costs/codex-usage-monitor.js';
23
22
  import { normalizeSkillCommandPrefix } from '../domain/memory/skill-scanner.js';
@@ -113,7 +112,7 @@ export async function handleAgentError({ error, channel, adapter, statusMsg, sta
113
112
  await sealStatus(adapter, statusMsg, supersededText, buildSealedStatusActionBlocks(supersededText, { channel, sessionName, isDm: true }));
114
113
  return;
115
114
  }
116
- await persistErrorSession(resolvedSessionId, sessionName, channel);
115
+ await persistErrorSession(resolvedSessionId, sessionName, channel, adapter);
117
116
  if (userMessageTs)
118
117
  await conversationLedger.completeTurn(channel, userMessageTs, { executionId });
119
118
  if (error?.cancelled) {
@@ -135,7 +134,7 @@ export async function handleAgentError({ error, channel, adapter, statusMsg, sta
135
134
  await adapter.postMessage(errorDest, { text: `Error: ${error.message}` }, threadTs ? { threadId: threadTs } : undefined);
136
135
  }
137
136
  }
138
- async function persistErrorSession(resolvedSessionId, sessionName, channel) {
137
+ async function persistErrorSession(resolvedSessionId, sessionName, channel, adapter) {
139
138
  if (!resolvedSessionId)
140
139
  return;
141
140
  const backend = resolveBackendForChannel(channel);
@@ -145,7 +144,7 @@ async function persistErrorSession(resolvedSessionId, sessionName, channel) {
145
144
  return;
146
145
  const existing = await sessionStore.lookupBySessionId(resolvedSessionId);
147
146
  if (!existing) {
148
- await sessionStore.registerSession(sessionName, { sessionId: resolvedSessionId, channel, backend, kind: 'local', profileName: getActiveProfile(channel), projectId: (await projectDirRepo.getChannelProject(channel)) ?? 'general' });
147
+ await sessionStore.registerSession(sessionName, { sessionId: resolvedSessionId, channel, backend, kind: 'local', profileName: getActiveProfile(channel), projectId: (await adapter.resolveInboundProject(channel)) ?? 'general' });
149
148
  }
150
149
  }
151
150
  // --- AskUserQuestion resume ---
@@ -29,4 +29,8 @@ export interface PlatformAdapter {
29
29
  unbindProjectConduit(projectId: string): Promise<void>;
30
30
  /** Get all registered project→conduit mappings. */
31
31
  getProjectConduits(): Promise<Record<string, string>>;
32
+ /** Inverse lookup: given an inbound conduit (e.g., a Slack channel id), return
33
+ * the project it is currently bound to, or null if unbound. Used by the
34
+ * orchestration layer to attach inbound messages to their project. */
35
+ resolveInboundProject(conduit: string): Promise<string | null>;
32
36
  }
@@ -1,5 +1,5 @@
1
1
  // input: ./types.js platform-agnostic message types
2
- // output: PlatformAdapter interface (21 methods: 17 core + openOutputStream + 3 conduit methods)
2
+ // output: PlatformAdapter interface (22 methods: 17 core + openOutputStream + 4 conduit methods)
3
3
  // pos: Single abstraction boundary between core modules and messaging platform
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  export {};
@@ -43,6 +43,7 @@ export declare class FeishuAdapter implements PlatformAdapter {
43
43
  bindProjectConduit(projectId: string, conduitHint: string): Promise<void>;
44
44
  unbindProjectConduit(projectId: string): Promise<void>;
45
45
  getProjectConduits(): Promise<Record<string, string>>;
46
+ resolveInboundProject(conduit: string): Promise<string | null>;
46
47
  /**
47
48
  * Resolve a Destination to a concrete Feishu chat_id + kind label.
48
49
  * Returns channel=null for destinations that should be silently dropped
@@ -265,6 +265,13 @@ export class FeishuAdapter {
265
265
  async getProjectConduits() {
266
266
  return { ...this._feishuConduits };
267
267
  }
268
+ async resolveInboundProject(conduit) {
269
+ for (const [project, ch] of Object.entries(this._feishuConduits)) {
270
+ if (ch === conduit)
271
+ return project;
272
+ }
273
+ return null;
274
+ }
268
275
  /**
269
276
  * Resolve a Destination to a concrete Feishu chat_id + kind label.
270
277
  * Returns channel=null for destinations that should be silently dropped
@@ -3,7 +3,7 @@
3
3
  // pos: File-backed project→conduit mapping, same path as channel-registry.json
4
4
  // for backward compatibility with existing bindings.
5
5
  import * as path from 'path';
6
- import { JsonRepository } from '../../store/json-repository.js';
6
+ import { JsonRepository } from '../../core/json-repository.js';
7
7
  import { STORE_DIR } from '../../core/paths.js';
8
8
  const CHANNEL_REGISTRY_FILE = path.join(STORE_DIR, 'channel-registry.json');
9
9
  export class SlackProjectConduitsStore {
@@ -84,6 +84,7 @@ export declare class SlackAdapter implements PlatformAdapter {
84
84
  bindProjectConduit(projectId: string, conduitHint: string): Promise<void>;
85
85
  unbindProjectConduit(projectId: string): Promise<void>;
86
86
  getProjectConduits(): Promise<Record<string, string>>;
87
+ resolveInboundProject(conduit: string): Promise<string | null>;
87
88
  private _conduitsStore;
88
89
  private _getConduitsStore;
89
90
  /**
@@ -509,6 +509,14 @@ export class SlackAdapter {
509
509
  async getProjectConduits() {
510
510
  return this._getConduitsStore().getAll();
511
511
  }
512
+ async resolveInboundProject(conduit) {
513
+ const conduits = await this._getConduitsStore().getAll();
514
+ for (const [project, ch] of Object.entries(conduits)) {
515
+ if (ch === conduit)
516
+ return project;
517
+ }
518
+ return null;
519
+ }
512
520
  _conduitsStore = null;
513
521
  _getConduitsStore() {
514
522
  if (!this._conduitsStore) {
@@ -1,4 +1,4 @@
1
- // input: adapter + types + virtual-message + adapters/*
1
+ // input: adapter + types + output-stream + adapters/*
2
2
  // output: Re-export full family of PlatformAdapter public APIs
3
3
  // pos: Public API export of the Platform abstraction
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
@@ -108,6 +108,7 @@ export declare class MockAdapter implements PlatformAdapter {
108
108
  bindProjectConduit(projectId: string, conduitHint: string): Promise<void>;
109
109
  unbindProjectConduit(projectId: string): Promise<void>;
110
110
  getProjectConduits(): Promise<Record<string, string>>;
111
+ resolveInboundProject(conduit: string): Promise<string | null>;
111
112
  /** Simulate an inbound message for testing event handlers. */
112
113
  simulateMessage(channel: string, text: string, opts?: {
113
114
  senderId?: string;
@@ -186,6 +186,13 @@ export class MockAdapter {
186
186
  async getProjectConduits() {
187
187
  return Object.fromEntries(this._projectConduits);
188
188
  }
189
+ async resolveInboundProject(conduit) {
190
+ for (const [project, ch] of this._projectConduits) {
191
+ if (ch === conduit)
192
+ return project;
193
+ }
194
+ return null;
195
+ }
189
196
  // --- Test helpers ---
190
197
  /** Simulate an inbound message for testing event handlers. */
191
198
  async simulateMessage(channel, text, opts) {
@@ -3,7 +3,7 @@
3
3
  // pos: Claude session turns to Slack message mapping persistence (based on JsonRepository, AsyncMutex serialized)
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import * as path from 'path';
6
- import { JsonRepository } from './json-repository.js';
6
+ import { JsonRepository } from '../core/json-repository.js';
7
7
  import { STORE_DIR } from '../core/paths.js';
8
8
  const LEDGER_FILE = path.join(STORE_DIR, 'conversation-ledger.json');
9
9
  function nowIso() {
@@ -5,8 +5,8 @@
5
5
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
6
6
  import * as path from 'path';
7
7
  import fs from 'node:fs/promises';
8
- import { JsonRepository } from './json-repository.js';
9
- import { atomicWrite } from './atomic-write.js';
8
+ import { JsonRepository } from '../core/json-repository.js';
9
+ import { atomicWrite } from '../core/atomic-write.js';
10
10
  import { AsyncMutex } from '../core/async-mutex.js';
11
11
  import { STORE_DIR, CONFIG_DIR } from '../core/paths.js';
12
12
  const NINETY_DAYS_MS = 90 * 24 * 60 * 60 * 1000;
@@ -5,7 +5,7 @@
5
5
  // >>> If I am updated, update my header comment and CORTEX.md <<<
6
6
  import * as path from 'path';
7
7
  import { readFileSync } from 'fs';
8
- import { JsonRepository } from './json-repository.js';
8
+ import { JsonRepository } from '../core/json-repository.js';
9
9
  import { createLogger } from '../core/log.js';
10
10
  import { AsyncMutex } from '../core/async-mutex.js';
11
11
  import { STORE_DIR } from '../core/paths.js';
@@ -7,7 +7,7 @@ import path from 'node:path';
7
7
  import { randomUUID } from 'node:crypto';
8
8
  import { createLogger } from '../core/log.js';
9
9
  import { AsyncMutex } from '../core/async-mutex.js';
10
- import { atomicWrite } from './atomic-write.js';
10
+ import { atomicWrite } from '../core/atomic-write.js';
11
11
  const log = createLogger('outbound-queue');
12
12
  import { STORE_DIR } from '../core/paths.js';
13
13
  const DEFAULT_TTL_MS = 30 * 60 * 1000; // 30 minutes
@@ -11,7 +11,7 @@
11
11
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
12
12
  import { readFileSync, watch, existsSync } from 'fs';
13
13
  import * as path from 'path';
14
- import { JsonRepository } from './json-repository.js';
14
+ import { JsonRepository } from '../core/json-repository.js';
15
15
  import { CONFIG_DIR } from '../core/paths.js';
16
16
  import { createLogger } from '../core/log.js';
17
17
  const log = createLogger('profile-repo');
@@ -1,20 +1,15 @@
1
- import { ChannelRepo } from './channel-repo.js';
2
1
  /** Shape of project-dirs.json: `{"projectName": {"machineName": "dirPath", ...}, ...}` */
3
2
  export type ProjectDirsData = Record<string, Record<string, string>>;
4
3
  interface ProjectDirRepoOptions {
5
4
  filePath?: string;
6
- channelRepoOverride?: ChannelRepo;
7
5
  }
8
6
  export declare class ProjectDirRepo {
9
7
  private readonly _repo;
10
- private readonly _channelRepo;
11
8
  constructor(opts?: ProjectDirRepoOptions);
12
9
  getProjectDir(project: string, machine: string): Promise<string | null>;
13
10
  setProjectDir(project: string, machine: string, dirPath: string): Promise<void>;
14
11
  removeProjectDir(project: string, machine: string): Promise<void>;
15
12
  getAllProjectDirs(): Promise<Record<string, Record<string, string>>>;
16
- /** Reverse-lookup: channelId → project name (via channel-registry.json). */
17
- getChannelProject(channelId: string): Promise<string | null>;
18
13
  /** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
19
14
  flush(): Promise<void>;
20
15
  }
@@ -1,22 +1,20 @@
1
- // input: project-dirs.json (+ channel-registry.json for reverse lookup)
2
- // output: ProjectDirRepo (async getProjectDir / setProjectDir / removeProjectDir / getAllProjectDirs / getChannelProject)
1
+ // input: project-dirs.json
2
+ // output: ProjectDirRepo (async getProjectDir / setProjectDir / removeProjectDir / getAllProjectDirs)
3
3
  // pos: Project-device code directory mapping persistence layer. Based on JsonRepository abstraction, AsyncMutex serializes reads/writes of project-dirs.json.
4
+ // Channel→project reverse lookup used to live here (getChannelProject); it now lives on PlatformAdapter as resolveInboundProject.
4
5
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
6
  import * as path from 'path';
6
- import { JsonRepository } from './json-repository.js';
7
+ import { JsonRepository } from '../core/json-repository.js';
7
8
  import { STORE_DIR } from '../core/paths.js';
8
- import { channelRepo } from './channel-repo.js';
9
9
  const PROJECT_DIRS_FILE = path.join(STORE_DIR, 'project-dirs.json');
10
10
  export class ProjectDirRepo {
11
11
  _repo;
12
- _channelRepo;
13
12
  constructor(opts = {}) {
14
13
  this._repo = new JsonRepository({
15
14
  filePath: opts.filePath ?? PROJECT_DIRS_FILE,
16
15
  defaultValue: () => ({}),
17
16
  migrate: (raw) => (typeof raw === 'object' && raw !== null ? raw : ({})),
18
17
  });
19
- this._channelRepo = opts.channelRepoOverride ?? channelRepo;
20
18
  }
21
19
  async getProjectDir(project, machine) {
22
20
  const data = await this._repo.read();
@@ -43,15 +41,6 @@ export class ProjectDirRepo {
43
41
  async getAllProjectDirs() {
44
42
  return { ...(await this._repo.read()) };
45
43
  }
46
- /** Reverse-lookup: channelId → project name (via channel-registry.json). */
47
- async getChannelProject(channelId) {
48
- const channelReg = await this._channelRepo.getAllRegistrations();
49
- for (const [project, ch] of Object.entries(channelReg)) {
50
- if (ch === channelId)
51
- return project;
52
- }
53
- return null;
54
- }
55
44
  /** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
56
45
  flush() {
57
46
  return this._repo.flush();
@@ -5,7 +5,7 @@
5
5
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
6
6
  import * as path from 'path';
7
7
  import * as fs from 'fs';
8
- import { JsonRepository } from './json-repository.js';
8
+ import { JsonRepository } from '../core/json-repository.js';
9
9
  import { STORE_DIR } from '../core/paths.js';
10
10
  export const SCHEDULES_FILE = path.join(STORE_DIR, 'schedules.json');
11
11
  export const CHANNEL_REGISTRY_FILE = path.join(STORE_DIR, 'channel-registry.json');
@@ -5,9 +5,13 @@
5
5
  import * as fs from 'fs';
6
6
  import * as path from 'path';
7
7
  import * as crypto from 'crypto';
8
- import { JsonRepository } from './json-repository.js';
8
+ import { JsonRepository } from '../core/json-repository.js';
9
9
  import { STORE_DIR } from '../core/paths.js';
10
- import { CHANNEL_REGISTRY_FILE } from './channel-repo.js';
10
+ // Path of the Slack project→channel registry file. Defined here (rather than
11
+ // imported from store/channel-repo.ts) because that file has been removed in
12
+ // favour of platform/adapters/slack-project-conduits.ts. We still read the file
13
+ // directly for the legacy session-registry name-keyed → sessionId-keyed migration.
14
+ const CHANNEL_REGISTRY_FILE = path.join(STORE_DIR, 'channel-registry.json');
11
15
  import { sessionRepo } from './session-repo.js';
12
16
  import { executionRepo } from './execution-repo.js';
13
17
  import { threadStore } from './thread-repo.js';
@@ -3,7 +3,7 @@
3
3
  // pos: Session persistence layer. Based on JsonRepository abstraction, AsyncMutex serializes reads/writes of sessions.json.
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import * as path from 'path';
6
- import { JsonRepository } from './json-repository.js';
6
+ import { JsonRepository } from '../core/json-repository.js';
7
7
  import { STORE_DIR } from '../core/paths.js';
8
8
  const SESSIONS_FILE = path.join(STORE_DIR, 'sessions.json');
9
9
  /** Key format: `backend:channel`. */
@@ -5,7 +5,7 @@
5
5
  import * as path from 'path';
6
6
  import * as crypto from 'crypto';
7
7
  import { readFileSync, rmSync } from 'fs';
8
- import { JsonRepository } from './json-repository.js';
8
+ import { JsonRepository } from '../core/json-repository.js';
9
9
  import { createLogger } from '../core/log.js';
10
10
  import { AsyncMutex } from '../core/async-mutex.js';
11
11
  import { STORE_DIR } from '../core/paths.js';
@@ -0,0 +1,22 @@
1
+ export declare function compareCalVer(a: string, b: string): number;
2
+ export interface Migration {
3
+ /** File path relative to DATA_DIR, e.g. "config/thread-templates.json". */
4
+ filePath: string;
5
+ /** CalVer when this migration was introduced. Compared against the per-file
6
+ * version tracked in versions.json to decide whether to run. */
7
+ version: string;
8
+ /** Idempotent migration function. Receives the parsed JSON of the target file
9
+ * and optionally the parsed JSON of the corresponding defaults file (or undefined
10
+ * if no defaults file applies or it couldn't be loaded). Must return the migrated
11
+ * data — the runner compares before/after to decide whether to write. */
12
+ migrate(data: unknown, defaults?: unknown): unknown;
13
+ }
14
+ export interface MigrationOptions {
15
+ /** Override DATA_DIR (user config location). Defaults to the real CORTEX_HOME. */
16
+ dataDir?: string;
17
+ /** Override DEFAULTS_DIR (default config location). Defaults to INSTALL_ROOT/defaults. */
18
+ defaultsDir?: string;
19
+ /** Override versions.json location. Defaults to dataDir/data. */
20
+ storeDir?: string;
21
+ }
22
+ export declare function runMigrations(opts?: MigrationOptions): Promise<void>;