@cortex-agent/server 2026.5.22 → 2026.5.24-1

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 (56) hide show
  1. package/defaults/config/thread-templates.json +13 -0
  2. package/dist/agent-adapter/pi/adapter.js +56 -7
  3. package/dist/agent-adapter/pi/agent-dir.d.ts +41 -4
  4. package/dist/agent-adapter/pi/agent-dir.js +101 -16
  5. package/dist/agent-adapter/pi/spawn-args.d.ts +4 -0
  6. package/dist/agent-adapter/pi/spawn-args.js +6 -3
  7. package/dist/agent-adapter/types.d.ts +7 -0
  8. package/dist/core/gateway-generator.d.ts +27 -14
  9. package/dist/core/gateway-generator.js +179 -173
  10. package/dist/{store → core}/json-repository.js +2 -2
  11. package/dist/core/profile-generator.d.ts +14 -15
  12. package/dist/core/profile-generator.js +52 -173
  13. package/dist/domain/agents/facade.js +6 -0
  14. package/dist/domain/system/server-update-check.d.ts +17 -0
  15. package/dist/domain/system/server-update-check.js +130 -0
  16. package/dist/domain/system/update-prompt.d.ts +8 -0
  17. package/dist/domain/system/update-prompt.js +5 -0
  18. package/dist/domain/system/update-state.d.ts +9 -0
  19. package/dist/domain/system/update-state.js +25 -0
  20. package/dist/domain/threads/template-loader.d.ts +10 -0
  21. package/dist/domain/threads/template-loader.js +71 -1
  22. package/dist/entry/app.js +24 -2
  23. package/dist/entry/init.js +122 -62
  24. package/dist/orchestration/agent-runner.js +3 -4
  25. package/dist/orchestration/interactions/update-prompt-slack.d.ts +6 -0
  26. package/dist/orchestration/interactions/update-prompt-slack.js +95 -0
  27. package/dist/orchestration/lifecycle.js +3 -4
  28. package/dist/platform/adapter.d.ts +4 -0
  29. package/dist/platform/adapter.js +1 -1
  30. package/dist/platform/adapters/feishu.d.ts +1 -0
  31. package/dist/platform/adapters/feishu.js +7 -0
  32. package/dist/platform/adapters/slack-project-conduits.js +1 -1
  33. package/dist/platform/adapters/slack.d.ts +1 -0
  34. package/dist/platform/adapters/slack.js +8 -0
  35. package/dist/platform/index.js +1 -1
  36. package/dist/platform/testing.d.ts +1 -0
  37. package/dist/platform/testing.js +7 -0
  38. package/dist/store/conversation-ledger-repo.js +1 -1
  39. package/dist/store/cost-repo.js +2 -2
  40. package/dist/store/execution-repo.js +1 -1
  41. package/dist/store/outbound-queue.js +1 -1
  42. package/dist/store/profile-repo.js +1 -1
  43. package/dist/store/project-dir-repo.d.ts +0 -5
  44. package/dist/store/project-dir-repo.js +4 -15
  45. package/dist/store/schedule-repo.js +1 -1
  46. package/dist/store/session-registry-repo.js +6 -2
  47. package/dist/store/session-repo.js +1 -1
  48. package/dist/store/thread-repo.js +1 -1
  49. package/dist/store/version-migrations.d.ts +22 -0
  50. package/dist/store/version-migrations.js +200 -0
  51. package/package.json +2 -2
  52. package/dist/store/channel-repo.d.ts +0 -27
  53. package/dist/store/channel-repo.js +0 -64
  54. /package/dist/{store → core}/atomic-write.d.ts +0 -0
  55. /package/dist/{store → core}/atomic-write.js +0 -0
  56. /package/dist/{store → core}/json-repository.d.ts +0 -0
@@ -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>;
@@ -0,0 +1,200 @@
1
+ // input: CORTEX_VERSION, DATA_DIR/DEFAULTS_DIR, atomicWrite, createLogger
2
+ // output: runMigrations() — applies pending file migrations before config loading
3
+ // pos: Version-tracked file migration runner. Tracks per-file applied migration versions
4
+ // in DATA_DIR/data/versions.json; on startup compares against CORTEX_VERSION and
5
+ // runs pending migrations in version order. Idempotent and crash-safe via atomicWrite.
6
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
7
+ import * as path from 'node:path';
8
+ import * as fs from 'node:fs/promises';
9
+ import { CORTEX_VERSION } from '../core/version.js';
10
+ import { DATA_DIR, DEFAULTS_DIR } from '../core/paths.js';
11
+ import { atomicWrite } from '../core/atomic-write.js';
12
+ import { createLogger } from '../core/log.js';
13
+ const log = createLogger('version-migrations');
14
+ // ── CalVer comparison ──────────────────────────────────────────
15
+ // CalVer format: YYYY.M.D (no zero-padding, e.g. 2026.5.23).
16
+ // String comparison fails on cross-digit boundaries (2026.5.9 vs 2026.5.23)
17
+ // so we parse into numeric components and compare element-wise.
18
+ // Returns negative if a < b, positive if a > b, 0 if equal.
19
+ export function compareCalVer(a, b) {
20
+ const [aYear, aMonth, aDay] = a.split('.').map(Number);
21
+ const [bYear, bMonth, bDay] = b.split('.').map(Number);
22
+ if (aYear !== bYear)
23
+ return aYear - bYear;
24
+ if (aMonth !== bMonth)
25
+ return aMonth - bMonth;
26
+ return aDay - bDay;
27
+ }
28
+ // ── Registry ───────────────────────────────────────────────────
29
+ // Add new migrations here. The runner groups them by filePath and applies
30
+ // pending ones in version-ascending order.
31
+ const migrations = [
32
+ // M1: Backfill systemPrompt on user agents that are missing it.
33
+ // Agents that exist in both user config and defaults, but whose user version
34
+ // has no systemPrompt field, get the default agent's systemPrompt value copied.
35
+ // Agents that already have systemPrompt are left untouched. User-only agents
36
+ // (not in defaults) are skipped.
37
+ {
38
+ filePath: 'config/thread-templates.json',
39
+ version: '2026.5.23',
40
+ migrate(data, defaultsData) {
41
+ if (!defaultsData || typeof defaultsData !== 'object' || defaultsData === null)
42
+ return data;
43
+ if (typeof data !== 'object' || data === null)
44
+ return data;
45
+ const d = data;
46
+ const defs = defaultsData;
47
+ const userAgents = d.agents;
48
+ const defaultAgents = defs.agents;
49
+ if (!userAgents || !defaultAgents)
50
+ return data;
51
+ let changed = false;
52
+ for (const [name, defAgent] of Object.entries(defaultAgents)) {
53
+ const userAgent = userAgents[name];
54
+ if (!userAgent || typeof userAgent !== 'object')
55
+ continue; // agent not in user config
56
+ const ua = userAgent;
57
+ const da = defAgent;
58
+ if (ua.systemPrompt === undefined && da.systemPrompt !== undefined) {
59
+ ua.systemPrompt = da.systemPrompt;
60
+ changed = true;
61
+ }
62
+ }
63
+ if (changed)
64
+ d.agents = userAgents;
65
+ return data;
66
+ },
67
+ },
68
+ ];
69
+ // ── Versions file I/O ──────────────────────────────────────────
70
+ async function loadVersionsFrom(filePath) {
71
+ try {
72
+ const raw = await fs.readFile(filePath, 'utf8');
73
+ const parsed = JSON.parse(raw);
74
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
75
+ log.warn('versions.json has unexpected shape; resetting');
76
+ return {};
77
+ }
78
+ return parsed;
79
+ }
80
+ catch (err) {
81
+ const e = err;
82
+ if (e.code === 'ENOENT') {
83
+ log.info('versions.json not found; all migrations will be considered pending');
84
+ return {};
85
+ }
86
+ if (err instanceof SyntaxError) {
87
+ log.warn(`Corrupt versions.json (${e.message}); resetting`);
88
+ return {};
89
+ }
90
+ throw err;
91
+ }
92
+ }
93
+ async function saveVersionsTo(filePath, versions) {
94
+ await atomicWrite(filePath, JSON.stringify(versions, null, 2) + '\n');
95
+ }
96
+ // ── Defaults loader ────────────────────────────────────────────
97
+ /** Map of target filePath → corresponding defaults filePath (relative to DEFAULTS_DIR).
98
+ * When a migration needs defaults data, the runner looks up the defaults path here,
99
+ * reads it once, and passes it to every pending migration for that target file. */
100
+ const DEFAULTS_MAP = {
101
+ 'config/thread-templates.json': 'config/thread-templates.json',
102
+ };
103
+ async function loadDefaultsForWith(filePath, defaultsDir) {
104
+ const defaultsRel = DEFAULTS_MAP[filePath];
105
+ if (!defaultsRel)
106
+ return undefined;
107
+ const defaultsPath = path.join(defaultsDir, defaultsRel);
108
+ try {
109
+ const raw = await fs.readFile(defaultsPath, 'utf8');
110
+ return JSON.parse(raw);
111
+ }
112
+ catch (err) {
113
+ const e = err;
114
+ if (e.code === 'ENOENT') {
115
+ log.warn(`Defaults file not found: ${defaultsPath}; migrations for ${filePath} may be skipped`);
116
+ }
117
+ else if (err instanceof SyntaxError) {
118
+ log.warn(`Defaults file corrupt (${defaultsPath}): ${e.message}`);
119
+ }
120
+ else {
121
+ log.warn(`Could not load defaults for ${filePath}: ${e.message}`);
122
+ }
123
+ return undefined;
124
+ }
125
+ }
126
+ // ── Runner ─────────────────────────────────────────────────────
127
+ export async function runMigrations(opts = {}) {
128
+ const dataDir = opts.dataDir ?? DATA_DIR;
129
+ const defaultsDir = opts.defaultsDir ?? DEFAULTS_DIR;
130
+ const storeDir = opts.storeDir ?? path.join(dataDir, 'data');
131
+ const versionsFile = path.join(storeDir, 'versions.json');
132
+ const versions = await loadVersionsFrom(versionsFile);
133
+ // Group migrations by filePath
134
+ const byFilePath = new Map();
135
+ for (const m of migrations) {
136
+ const list = byFilePath.get(m.filePath) ?? [];
137
+ list.push(m);
138
+ byFilePath.set(m.filePath, list);
139
+ }
140
+ for (const [filePath, fileMigrations] of byFilePath) {
141
+ const trackedVersion = versions[filePath] || '0.0.0';
142
+ // Pending: migrations whose version > trackedVersion and <= CORTEX_VERSION
143
+ const pending = fileMigrations
144
+ .filter(m => compareCalVer(trackedVersion, m.version) < 0 && compareCalVer(CORTEX_VERSION, m.version) >= 0)
145
+ .sort((a, b) => compareCalVer(a.version, b.version));
146
+ if (pending.length === 0)
147
+ continue;
148
+ // Read target file
149
+ const absPath = path.join(dataDir, filePath);
150
+ let data;
151
+ try {
152
+ const raw = await fs.readFile(absPath, 'utf8');
153
+ data = JSON.parse(raw);
154
+ }
155
+ catch (err) {
156
+ const e = err;
157
+ if (e.code === 'ENOENT') {
158
+ log.info(`Skipping migrations for ${filePath}: file does not exist yet`);
159
+ continue;
160
+ }
161
+ if (err instanceof SyntaxError) {
162
+ log.warn(`Skipping migrations for ${filePath}: corrupt JSON (${e.message})`);
163
+ continue;
164
+ }
165
+ throw err;
166
+ }
167
+ // Load defaults once for this file (if any)
168
+ const defaultsData = await loadDefaultsForWith(filePath, defaultsDir);
169
+ // Apply all pending migrations in version order
170
+ let changed = false;
171
+ let anyFailed = false;
172
+ for (const m of pending) {
173
+ const before = JSON.stringify(data);
174
+ try {
175
+ data = m.migrate(data, defaultsData);
176
+ }
177
+ catch (err) {
178
+ log.error(`Migration ${m.version} for ${filePath} failed: ${err.message}; skipping remaining migrations for this file`);
179
+ changed = false;
180
+ anyFailed = true;
181
+ break;
182
+ }
183
+ if (JSON.stringify(data) !== before) {
184
+ log.info(`Migration ${m.version} applied to ${filePath}`);
185
+ changed = true;
186
+ }
187
+ }
188
+ if (changed) {
189
+ await atomicWrite(absPath, JSON.stringify(data, null, 2) + '\n');
190
+ }
191
+ // Only bump the tracked version if ALL pending migrations succeeded.
192
+ // If any failed: we did not write the file (changed=false), so the data on
193
+ // disk is unchanged. Leave version at the old value → all pending migrations
194
+ // retry next boot. Idempotent migrations guarantee this is safe.
195
+ if (!anyFailed) {
196
+ versions[filePath] = pending[pending.length - 1].version;
197
+ }
198
+ }
199
+ await saveVersionsTo(versionsFile, versions);
200
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortex-agent/server",
3
- "version": "2026.5.22",
3
+ "version": "2026.5.24-1",
4
4
  "type": "module",
5
5
  "description": "Autonomous agent system for long-running projects — mission-driven, multi-agent pipelines, self-evolving skills.",
6
6
  "engines": {
@@ -36,7 +36,7 @@
36
36
  "@modelcontextprotocol/sdk": "^1.27.1",
37
37
  "@slack/bolt": "^4.6.0",
38
38
  "@slack/web-api": "^7.14.1",
39
- "aistatus": "^0.0.5",
39
+ "aistatus": "^0.0.6",
40
40
  "diff": "^7.0.0",
41
41
  "dotenv": "^16.4.7",
42
42
  "ws": "^8.20.0",
@@ -1,27 +0,0 @@
1
- export declare const CHANNEL_REGISTRY_FILE: string;
2
- /** Shape of channel-registry.json: `{"projectName": "channelId", ...}` */
3
- export type ChannelRegistryData = Record<string, string>;
4
- interface ChannelRepoOptions {
5
- filePath?: string;
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[];
10
- }
11
- export declare class ChannelRepo {
12
- private readonly _repo;
13
- private readonly _projectsDir;
14
- private _projectLister;
15
- constructor(opts?: ChannelRepoOptions);
16
- getProjectChannel(project: string): Promise<string | null>;
17
- setProjectChannel(project: string, channelId: string): Promise<void>;
18
- removeProjectChannel(project: string): Promise<void>;
19
- getAllRegistrations(): Promise<Record<string, string>>;
20
- listProjects(): Promise<string[]>;
21
- /** Late injection of project lister callback (used by app.ts composition root). */
22
- setProjectLister(lister: () => string[]): void;
23
- /** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
24
- flush(): Promise<void>;
25
- }
26
- export declare const channelRepo: ChannelRepo;
27
- export {};
@@ -1,64 +0,0 @@
1
- // input: channel-registry.json + context/projects/ directory
2
- // output: ChannelRepo (async getProjectChannel / setProjectChannel / removeProjectChannel / getAllRegistrations / listProjects)
3
- // pos: Project-Channel mapping persistence layer. Based on JsonRepository abstraction, AsyncMutex serializes reads/writes of channel-registry.json.
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 { JsonRepository } from './json-repository.js';
8
- import { STORE_DIR, PROJECTS_DIR } from '../core/paths.js';
9
- export const CHANNEL_REGISTRY_FILE = path.join(STORE_DIR, 'channel-registry.json');
10
- export class ChannelRepo {
11
- _repo;
12
- _projectsDir;
13
- _projectLister = null;
14
- constructor(opts = {}) {
15
- this._repo = new JsonRepository({
16
- filePath: opts.filePath ?? CHANNEL_REGISTRY_FILE,
17
- defaultValue: () => ({}),
18
- migrate: (raw) => (typeof raw === 'object' && raw !== null ? raw : ({})),
19
- });
20
- this._projectsDir = opts.projectsDir ?? PROJECTS_DIR;
21
- this._projectLister = opts.projectLister ?? null;
22
- }
23
- async getProjectChannel(project) {
24
- const data = await this._repo.read();
25
- return data[project] ?? null;
26
- }
27
- async setProjectChannel(project, channelId) {
28
- await this._repo.mutate((data) => {
29
- data[project] = channelId;
30
- return { next: data, result: undefined };
31
- });
32
- }
33
- async removeProjectChannel(project) {
34
- await this._repo.mutate((data) => {
35
- delete data[project];
36
- return { next: data, result: undefined };
37
- });
38
- }
39
- async getAllRegistrations() {
40
- return { ...(await this._repo.read()) };
41
- }
42
- async listProjects() {
43
- if (this._projectLister) {
44
- return this._projectLister();
45
- }
46
- try {
47
- return fsSync.readdirSync(this._projectsDir).filter((name) => {
48
- return fsSync.statSync(path.join(this._projectsDir, name)).isDirectory() && !name.startsWith('.');
49
- });
50
- }
51
- catch {
52
- return [];
53
- }
54
- }
55
- /** Late injection of project lister callback (used by app.ts composition root). */
56
- setProjectLister(lister) {
57
- this._projectLister = lister;
58
- }
59
- /** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
60
- flush() {
61
- return this._repo.flush();
62
- }
63
- }
64
- export const channelRepo = new ChannelRepo();
File without changes
File without changes
File without changes