@cortex-agent/server 2026.9.14 → 2026.9.15

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 (102) hide show
  1. package/defaults/plugins/cortex-commission/.claude-plugin/plugin.json +2 -2
  2. package/defaults/plugins/cortex-commission/plugin.json +2 -2
  3. package/defaults/plugins/cortex-commission/skills/commission/SKILL.md +3 -3
  4. package/dist/agent-adapter/claude/adapter.d.ts +0 -6
  5. package/dist/agent-adapter/claude/adapter.js +0 -8
  6. package/dist/agent-adapter/claude/defaults.d.ts +10 -7
  7. package/dist/agent-adapter/claude/defaults.js +18 -16
  8. package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
  9. package/dist/agent-adapter/claude/spawn-args.js +16 -16
  10. package/dist/agent-adapter/pi/mcp-bridge-logic.d.ts +11 -2
  11. package/dist/agent-adapter/pi/mcp-bridge-logic.js +32 -1
  12. package/dist/agent-adapter/pi/mcp-bridge.js +16 -15
  13. package/dist/agent-adapter/pi/session-options.d.ts +0 -6
  14. package/dist/agent-adapter/pi/session-options.js +1 -8
  15. package/dist/agent-adapter/types.d.ts +0 -1
  16. package/dist/core/mcp-tool-gate.d.ts +3 -17
  17. package/dist/core/mcp-tool-gate.js +3 -19
  18. package/dist/core/settings-spec.d.ts +1 -1
  19. package/dist/core/settings-spec.js +5 -1
  20. package/dist/domain/agents/config.d.ts +1 -1
  21. package/dist/domain/agents/config.js +1 -1
  22. package/dist/domain/agents/profile-switch.d.ts +1 -1
  23. package/dist/domain/agents/profile-switch.js +3 -5
  24. package/dist/domain/agents/subagent/runner.js +0 -1
  25. package/dist/domain/commissions/commission-draft.d.ts +58 -0
  26. package/dist/domain/commissions/commission-draft.js +87 -4
  27. package/dist/domain/commissions/commission-finalize.d.ts +8 -3
  28. package/dist/domain/commissions/commission-finalize.js +14 -0
  29. package/dist/domain/mcp/tools/commission-tools.d.ts +12 -1
  30. package/dist/domain/mcp/tools/commission-tools.js +68 -14
  31. package/dist/domain/remote/client-manager.js +66 -7
  32. package/dist/domain/remote/client-ssh-tunnel.d.ts +16 -5
  33. package/dist/domain/remote/client-ssh-tunnel.js +12 -5
  34. package/dist/domain/runs/builders.js +0 -1
  35. package/dist/domain/runs/compact.js +0 -1
  36. package/dist/domain/runs/engine-spec.d.ts +11 -4
  37. package/dist/domain/runs/engine-spec.js +7 -4
  38. package/dist/domain/runs/prompt.js +16 -10
  39. package/dist/domain/runs/request.d.ts +0 -1
  40. package/dist/domain/sessions/session-hooks.d.ts +5 -12
  41. package/dist/domain/sessions/session-hooks.js +6 -13
  42. package/dist/domain/sessions/session-lifecycle.d.ts +4 -4
  43. package/dist/domain/sessions/session-lifecycle.js +5 -6
  44. package/dist/domain/sessions/session-retention.d.ts +1 -3
  45. package/dist/domain/sessions/session-retention.js +9 -26
  46. package/dist/domain/sessions/session-use.d.ts +32 -0
  47. package/dist/domain/sessions/session-use.js +63 -0
  48. package/dist/domain/sessions/session.js +6 -5
  49. package/dist/domain/system/server-update-check.js +29 -1
  50. package/dist/domain/system/update-ui-state.d.ts +32 -0
  51. package/dist/domain/system/update-ui-state.js +63 -0
  52. package/dist/domain/threads/runner.js +0 -1
  53. package/dist/domain/ui-service/app-router.d.ts +30 -0
  54. package/dist/domain/ui-service/app-router.js +5 -1
  55. package/dist/domain/ui-service/input-schemas.d.ts +32 -0
  56. package/dist/domain/ui-service/input-schemas.js +22 -0
  57. package/dist/domain/ui-service/mutate/sessions.d.ts +13 -1
  58. package/dist/domain/ui-service/mutate/sessions.js +69 -3
  59. package/dist/domain/ui-service/mutate/system.d.ts +3 -1
  60. package/dist/domain/ui-service/mutate/system.js +13 -0
  61. package/dist/domain/ui-service/query/system.d.ts +2 -1
  62. package/dist/domain/ui-service/query/system.js +4 -0
  63. package/dist/domain/ui-service/types.d.ts +44 -3
  64. package/dist/domain/ui-service/ui-service.js +7 -3
  65. package/dist/entry/app.js +11 -23
  66. package/dist/entry/start-ui-http.js +3 -1
  67. package/dist/events/event-types.d.ts +5 -0
  68. package/dist/orchestration/agent-runner.d.ts +1 -1
  69. package/dist/orchestration/agent-runner.js +8 -11
  70. package/dist/orchestration/conversation-request.d.ts +26 -8
  71. package/dist/orchestration/conversation-request.js +49 -20
  72. package/dist/orchestration/edit-retry.js +2 -1
  73. package/dist/orchestration/interactions/ask-user-resume.js +2 -1
  74. package/dist/orchestration/interactions/ui-update-prompt.d.ts +8 -0
  75. package/dist/orchestration/interactions/ui-update-prompt.js +47 -0
  76. package/dist/orchestration/resume-dispatcher.js +2 -2
  77. package/dist/orchestration/routing/webhook.js +47 -0
  78. package/dist/orchestration/session-compact.d.ts +3 -0
  79. package/dist/orchestration/session-compact.js +3 -2
  80. package/dist/orchestration/session-events.d.ts +6 -0
  81. package/dist/orchestration/session-events.js +5 -0
  82. package/dist/orchestration/turn/turn-prep.js +2 -1
  83. package/dist/platform/ui-http/app-update.d.ts +11 -0
  84. package/dist/platform/ui-http/app-update.js +3 -0
  85. package/dist/store/conversation-ledger-repo.d.ts +10 -19
  86. package/dist/store/conversation-ledger-repo.js +143 -152
  87. package/dist/store/session-registry-import.d.ts +34 -0
  88. package/dist/store/session-registry-import.js +182 -0
  89. package/dist/store/session-registry-journal.d.ts +107 -0
  90. package/dist/store/session-registry-journal.js +307 -18
  91. package/dist/store/session-registry-repo.d.ts +113 -28
  92. package/dist/store/session-registry-repo.js +287 -104
  93. package/dist/store/version-migrations.d.ts +16 -0
  94. package/dist/store/version-migrations.js +34 -0
  95. package/package.json +1 -1
  96. package/web/dist/assets/{index-aHbOZSP6.js → index-CEZ0DSei.js} +1 -1
  97. package/web/dist/assets/{index-CCPxQ94C.css → index-CRDJo39X.css} +1 -1
  98. package/web/dist/assets/index-DjuPJVZE.js +444 -0
  99. package/web/dist/index.html +2 -2
  100. package/dist/store/session-repo.d.ts +0 -65
  101. package/dist/store/session-repo.js +0 -184
  102. package/web/dist/assets/index-BuXbCsuz.js +0 -444
@@ -1,68 +1,92 @@
1
- import * as path from 'path';
2
- import { JsonRepository } from '../core/json-repository.js';
3
- import { STORE_DIR } from '../core/paths.js';
4
- const LEDGER_FILE = path.join(STORE_DIR, 'conversation-ledger.json');
1
+ // input: SessionRegistryRepo (channel bindings + conversation headers + turn history)
2
+ // output: ConversationLedgerRepo — a thin FAÇADE over the session registry that keeps the historical
3
+ // ledger API (getConversation / beginTurn / rollbackTo / …) while the registry owns the data.
4
+ // pos: Compatibility surface for turn-history callers; NO storage of its own (no JSON file — the
5
+ // registry journal is the only store)
6
+ // >>> Once I am updated, be sure to update my header comment and the parent folder CORTEX.md <<<
7
+ //
8
+ // The ledger no longer has a JSON file. Every method maps onto the registry's channel-keyed
9
+ // conversation header + turn history, most under a single `registry.batch(...)` critical section so a
10
+ // header + turn mutation is atomic (the same guarantee the old JsonRepository.mutate gave). The
11
+ // exported names/signatures (ConversationLedgerRepo, conversationLedger, LedgerTurn, TurnStatus,
12
+ // ChannelConversation, LedgerData) are unchanged so downstream callers compile untouched.
13
+ import { sessionStore, } from './session-registry-repo.js';
5
14
  function nowIso() {
6
15
  return new Date().toISOString();
7
16
  }
8
- // --- Repo class ---
17
+ /** `updatedAt` is derived, not stored twice: the freshest of the header stamp and any turn stamp.
18
+ * This preserves the old "bump on every mutation" contract without a second write. */
19
+ function deriveUpdatedAt(header, turns) {
20
+ let latest = header.updatedAt;
21
+ for (const turn of turns)
22
+ if (turn.updatedAt > latest)
23
+ latest = turn.updatedAt;
24
+ return latest;
25
+ }
26
+ function toChannelConversation(header, turns) {
27
+ return {
28
+ sessionId: header.sessionId,
29
+ sessionName: header.sessionName,
30
+ backend: header.backend,
31
+ profileName: header.profileName,
32
+ turns,
33
+ updatedAt: deriveUpdatedAt(header, turns),
34
+ };
35
+ }
36
+ // --- Repo class (façade) ---
9
37
  export class ConversationLedgerRepo {
10
- repo;
11
- constructor(filePath = LEDGER_FILE) {
12
- this.repo = new JsonRepository({
13
- filePath,
14
- defaultValue: () => ({}),
15
- });
38
+ registry;
39
+ constructor(registry = sessionStore) {
40
+ this.registry = registry;
16
41
  }
17
- // --- Read-only queries (no mutex, use repo cache) ---
42
+ // --- Read-only queries ---
18
43
  async getConversation(channel) {
19
- const data = await this.repo.read();
20
- return data[channel] || null;
44
+ const found = await this.registry.readConversation(channel);
45
+ return found ? toChannelConversation(found.header, found.turns) : null;
21
46
  }
22
47
  async findTurn(channel, userMessageTs) {
23
- const data = await this.repo.read();
24
- const conv = data[channel];
25
- if (!conv)
48
+ const found = await this.registry.readConversation(channel);
49
+ if (!found)
26
50
  return null;
27
- const idx = conv.turns.findIndex(t => t.userMessageTs === userMessageTs);
51
+ const idx = found.turns.findIndex(t => t.userMessageTs === userMessageTs);
28
52
  if (idx === -1)
29
53
  return null;
30
- return { conversation: conv, turn: conv.turns[idx], turnIndex: idx };
54
+ return {
55
+ conversation: toChannelConversation(found.header, found.turns),
56
+ turn: found.turns[idx],
57
+ turnIndex: idx,
58
+ };
31
59
  }
32
- // --- Mutations (mutex-serialized via repo.mutate) ---
60
+ // --- Mutations (registry.batch → one critical section per call) ---
33
61
  async initConversation(channel, opts) {
34
- return this.repo.mutate(data => {
35
- const now = nowIso();
36
- const conv = {
37
- sessionId: opts.sessionId,
38
- sessionName: opts.sessionName,
39
- backend: opts.backend,
40
- profileName: opts.profileName ?? null,
41
- turns: [],
42
- updatedAt: now,
43
- };
44
- data[channel] = conv;
45
- return { next: data, result: conv };
62
+ const now = nowIso();
63
+ const header = {
64
+ sessionId: opts.sessionId,
65
+ sessionName: opts.sessionName,
66
+ backend: opts.backend,
67
+ profileName: opts.profileName ?? null,
68
+ updatedAt: now,
69
+ };
70
+ await this.registry.batch(async (ops) => {
71
+ await ops.setConversation(channel, header);
72
+ await ops.clearTurns(channel);
46
73
  });
74
+ return toChannelConversation(header, []);
47
75
  }
48
76
  async updateSessionId(channel, sessionId) {
49
- await this.repo.mutate(data => {
50
- const conv = data[channel];
51
- if (!conv)
52
- return { next: data, result: undefined };
53
- conv.sessionId = sessionId;
54
- conv.updatedAt = nowIso();
55
- return { next: data, result: undefined };
77
+ await this.registry.batch(async (ops) => {
78
+ if (!ops.getConversationHeader(channel))
79
+ return;
80
+ await ops.setConversation(channel, { sessionId, updatedAt: nowIso() });
56
81
  });
57
82
  }
58
83
  async beginTurn(channel, opts) {
59
- return this.repo.mutate(data => {
60
- const conv = data[channel];
61
- if (!conv)
84
+ return this.registry.batch(async (ops) => {
85
+ if (!ops.getConversationHeader(channel))
62
86
  throw new Error(`No conversation for channel ${channel}`);
63
87
  const now = nowIso();
64
88
  const turn = {
65
- turnIndex: conv.turns.length,
89
+ turnIndex: ops.getTurns(channel).length,
66
90
  userMessageTs: opts.userMessageTs,
67
91
  userMessageText: opts.userMessageText,
68
92
  statusMessageTs: opts.statusMessageTs ?? null,
@@ -73,84 +97,71 @@ export class ConversationLedgerRepo {
73
97
  createdAt: now,
74
98
  updatedAt: now,
75
99
  };
76
- conv.turns.push(turn);
77
- conv.updatedAt = now;
78
- return { next: data, result: turn };
100
+ await ops.beginTurn(channel, turn);
101
+ return turn;
79
102
  });
80
103
  }
81
104
  async addResponseTs(channel, userMessageTs, responseTs) {
82
- await this.repo.mutate(data => {
83
- const conv = data[channel];
84
- if (!conv)
85
- return { next: data, result: undefined };
86
- const turn = conv.turns.find(t => t.userMessageTs === userMessageTs);
105
+ await this.registry.batch(async (ops) => {
106
+ const turn = ops.getTurns(channel).find(t => t.userMessageTs === userMessageTs);
87
107
  if (!turn)
88
- return { next: data, result: undefined };
89
- turn.responseMessageTimestamps.push(responseTs);
90
- turn.updatedAt = nowIso();
91
- return { next: data, result: undefined };
108
+ return;
109
+ await ops.patchTurn(channel, turn.turnIndex, {
110
+ responseMessageTimestamps: [...turn.responseMessageTimestamps, responseTs],
111
+ updatedAt: nowIso(),
112
+ });
92
113
  });
93
114
  }
94
115
  async completeTurn(channel, userMessageTs, opts) {
95
- await this.repo.mutate(data => {
96
- const conv = data[channel];
97
- if (!conv)
98
- return { next: data, result: undefined };
99
- const turn = conv.turns.find(t => t.userMessageTs === userMessageTs);
116
+ await this.registry.batch(async (ops) => {
117
+ const turn = ops.getTurns(channel).find(t => t.userMessageTs === userMessageTs);
100
118
  if (!turn || turn.status !== 'processing')
101
- return { next: data, result: undefined };
102
- turn.status = 'completed';
103
- if (opts?.executionId)
104
- turn.executionId = opts.executionId;
105
- turn.updatedAt = nowIso();
106
- conv.updatedAt = nowIso();
107
- return { next: data, result: undefined };
119
+ return;
120
+ await ops.patchTurn(channel, turn.turnIndex, {
121
+ status: 'completed',
122
+ ...(opts?.executionId ? { executionId: opts.executionId } : {}),
123
+ updatedAt: nowIso(),
124
+ });
108
125
  });
109
126
  }
110
127
  async rollbackTo(channel, turnIndex) {
111
- return this.repo.mutate(data => {
112
- const conv = data[channel];
113
- if (!conv)
114
- return { next: data, result: null };
115
- if (turnIndex < 0 || turnIndex > conv.turns.length)
116
- return { next: data, result: null };
117
- const superseded = [];
128
+ return this.registry.batch(async (ops) => {
129
+ const header = ops.getConversationHeader(channel);
130
+ if (!header)
131
+ return null;
132
+ const turns = ops.getTurns(channel);
133
+ if (turnIndex < 0 || turnIndex > turns.length)
134
+ return null;
118
135
  const now = nowIso();
119
- for (let i = turnIndex; i < conv.turns.length; i++) {
120
- conv.turns[i].status = 'superseded';
121
- conv.turns[i].updatedAt = now;
122
- superseded.push(conv.turns[i]);
136
+ for (let i = turnIndex; i < turns.length; i++) {
137
+ await ops.patchTurn(channel, turns[i].turnIndex, { status: 'superseded', updatedAt: now });
123
138
  }
124
- conv.updatedAt = now;
125
- return { next: data, result: { supersededTurns: superseded, conversation: conv } };
139
+ const updated = ops.getTurns(channel);
140
+ return {
141
+ supersededTurns: updated.slice(turnIndex),
142
+ conversation: toChannelConversation(header, updated),
143
+ };
126
144
  });
127
145
  }
128
146
  async truncateTurns(channel, fromIndex) {
129
- await this.repo.mutate(data => {
130
- const conv = data[channel];
131
- if (!conv)
132
- return { next: data, result: undefined };
133
- conv.turns = conv.turns.slice(0, fromIndex);
134
- conv.updatedAt = nowIso();
135
- return { next: data, result: undefined };
136
- });
147
+ await this.registry.truncateTurns(channel, fromIndex);
137
148
  }
138
149
  async clearConversation(channel) {
139
- await this.repo.mutate(data => {
140
- delete data[channel];
141
- return { next: data, result: undefined };
150
+ await this.registry.batch(async (ops) => {
151
+ await ops.clearConversation(channel);
152
+ await ops.clearTurns(channel);
142
153
  });
143
154
  }
144
155
  async listBySessionIds(sessionIds) {
145
156
  const targets = new Set(sessionIds);
146
157
  if (targets.size === 0)
147
158
  return [];
148
- const data = await this.repo.read();
159
+ const all = await this.registry.listConversations();
149
160
  const matches = [];
150
- for (const [channel, conversation] of Object.entries(data)) {
151
- if (!conversation?.sessionId || !targets.has(conversation.sessionId))
161
+ for (const { channel, header, turns } of all) {
162
+ if (!header.sessionId || !targets.has(header.sessionId))
152
163
  continue;
153
- matches.push({ ...conversation, channel });
164
+ matches.push({ ...toChannelConversation(header, turns), channel });
154
165
  }
155
166
  return matches;
156
167
  }
@@ -158,64 +169,50 @@ export class ConversationLedgerRepo {
158
169
  const targets = new Set(sessionIds);
159
170
  if (targets.size === 0)
160
171
  return 0;
161
- return this.repo.mutate(data => {
162
- let removed = 0;
163
- for (const [channel, conversation] of Object.entries(data)) {
164
- if (!conversation?.sessionId || !targets.has(conversation.sessionId))
165
- continue;
166
- delete data[channel];
167
- removed += 1;
168
- }
169
- return { next: data, result: removed };
170
- });
171
- }
172
- async deleteExceptSessionIds(sessionIds) {
173
- const live = new Set(sessionIds);
174
- return this.repo.mutate(data => {
175
- let removed = 0;
176
- for (const [channel, conversation] of Object.entries(data)) {
177
- if (!conversation?.sessionId || live.has(conversation.sessionId))
178
- continue;
179
- delete data[channel];
180
- removed += 1;
172
+ const all = await this.registry.listConversations();
173
+ const channels = all
174
+ .filter(({ header }) => header.sessionId && targets.has(header.sessionId))
175
+ .map(({ channel }) => channel);
176
+ if (channels.length === 0)
177
+ return 0;
178
+ await this.registry.batch(async (ops) => {
179
+ for (const channel of channels) {
180
+ await ops.clearConversation(channel);
181
+ await ops.clearTurns(channel);
181
182
  }
182
- return { next: data, result: removed };
183
183
  });
184
+ return channels.length;
184
185
  }
185
186
  async switchSession(channel, opts) {
186
- await this.repo.mutate(data => {
187
- const now = nowIso();
188
- data[channel] = {
189
- sessionId: opts.sessionId,
190
- sessionName: opts.sessionName,
191
- backend: opts.backend,
192
- profileName: opts.profileName ?? null,
193
- turns: [],
194
- updatedAt: now,
195
- };
196
- return { next: data, result: undefined };
187
+ const header = {
188
+ sessionId: opts.sessionId,
189
+ sessionName: opts.sessionName,
190
+ backend: opts.backend,
191
+ profileName: opts.profileName ?? null,
192
+ updatedAt: nowIso(),
193
+ };
194
+ await this.registry.batch(async (ops) => {
195
+ await ops.setConversation(channel, header);
196
+ await ops.clearTurns(channel);
197
197
  });
198
198
  }
199
199
  /**
200
- * Atomic init-if-missing + beginTurn. Captures the turn index under mutex
200
+ * Atomic init-if-missing + beginTurn. Captures the turn index under one lock
201
201
  * so callers can safely pass it to sessionBackup.createBackup.
202
202
  * Returns { turn, turnIndex } for the caller.
203
203
  */
204
204
  async initAndBeginTurn(channel, opts) {
205
- return this.repo.mutate(data => {
206
- let conv = data[channel];
207
- if (!conv) {
208
- conv = {
205
+ return this.registry.batch(async (ops) => {
206
+ if (!ops.getConversationHeader(channel)) {
207
+ await ops.setConversation(channel, {
209
208
  sessionId: opts.sessionId,
210
209
  sessionName: opts.sessionName,
211
210
  backend: opts.backend,
212
211
  profileName: opts.profileName ?? null,
213
- turns: [],
214
212
  updatedAt: nowIso(),
215
- };
216
- data[channel] = conv;
213
+ });
217
214
  }
218
- const turnIndex = conv.turns.length;
215
+ const turnIndex = ops.getTurns(channel).length;
219
216
  const now = nowIso();
220
217
  const turn = {
221
218
  turnIndex,
@@ -229,32 +226,26 @@ export class ConversationLedgerRepo {
229
226
  createdAt: now,
230
227
  updatedAt: now,
231
228
  };
232
- conv.turns.push(turn);
233
- conv.updatedAt = now;
234
- return { next: data, result: { turn, turnIndex } };
229
+ await ops.beginTurn(channel, turn);
230
+ return { turn, turnIndex };
235
231
  });
236
232
  }
237
233
  /** Set the backup path on the turn identified by userMessageTs. */
238
234
  async setBackupPath(channel, userMessageTs, backupPath) {
239
- await this.repo.mutate(data => {
240
- const conv = data[channel];
241
- if (!conv)
242
- return { next: data, result: undefined };
243
- const turn = conv.turns.find(t => t.userMessageTs === userMessageTs);
235
+ await this.registry.batch(async (ops) => {
236
+ const turn = ops.getTurns(channel).find(t => t.userMessageTs === userMessageTs);
244
237
  if (!turn)
245
- return { next: data, result: undefined };
246
- turn.backupPath = backupPath;
247
- turn.updatedAt = nowIso();
248
- return { next: data, result: undefined };
238
+ return;
239
+ await ops.patchTurn(channel, turn.turnIndex, { backupPath, updatedAt: nowIso() });
249
240
  });
250
241
  }
251
- /** Drop the in-memory cache so the next read() fetches from disk. For testing. */
242
+ /** Drop the registry's in-memory cache so the next read fetches from disk. For testing. */
252
243
  invalidate() {
253
- this.repo.invalidate();
244
+ this.registry.invalidate();
254
245
  }
255
- /** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
246
+ /** Wait for any in-flight registry mutation to complete. For graceful SIGTERM drain. */
256
247
  flush() {
257
- return this.repo.flush();
248
+ return this.registry.flush();
258
249
  }
259
250
  }
260
251
  export const conversationLedger = new ConversationLedgerRepo();
@@ -0,0 +1,34 @@
1
+ export interface LegacyImportSummary {
2
+ /** channel→sessionId bindings imported from sessions.json. */
3
+ bindings: number;
4
+ /** conversation headers imported from conversation-ledger.json. */
5
+ conversations: number;
6
+ /** total turns imported across all conversations. */
7
+ turns: number;
8
+ /** conversations whose header carried a non-null profileName. */
9
+ profileNames: number;
10
+ /** source basenames left in place because their JSON was corrupt. */
11
+ skipped: string[];
12
+ /** `.bak` basenames the sources were renamed to. */
13
+ renamed: string[];
14
+ }
15
+ /**
16
+ * Fold `<storeDir>/sessions.json` (bindings) and `<storeDir>/conversation-ledger.json` (headers +
17
+ * turns) into `<storeDir>/session-registry.jsonl` via the repo API, then rename each successfully
18
+ * consumed source to `<file>.pre-<version>.bak`.
19
+ *
20
+ * Semantics:
21
+ * - A missing source contributes 0 counts and is not renamed.
22
+ * - A corrupt source (unparseable JSON) is logged, listed in `skipped`, and LEFT ON DISK for manual
23
+ * inspection; the other source is still imported and the migration still succeeds (the caller
24
+ * bumps its version). Re-importing the good source on a retry is harmless: the good source has
25
+ * already been renamed away, so the retry sees it as missing.
26
+ * - Bindings whose session id is absent from the registry are imported anyway (bind is a free map).
27
+ * - Idempotent: after the rename, a second run finds no sources and does nothing (no journal growth).
28
+ * - Crash-safe: on a crash between the journal appends and the renames the sources are still present,
29
+ * so the next boot re-imports; per-channel turns are cleared before re-appending (only when the
30
+ * channel already carries turns), so the imported state converges rather than duplicating turns.
31
+ */
32
+ export declare function importLegacySessionStores(storeDir: string, opts?: {
33
+ version?: string;
34
+ }): Promise<LegacyImportSummary>;
@@ -0,0 +1,182 @@
1
+ // input: the two flat legacy JSON stores under a store dir (sessions.json bindings +
2
+ // conversation-ledger.json headers/turns) and SessionRegistryRepo
3
+ // output: importLegacySessionStores() — one-shot fold of the legacy stores into the JSONL session
4
+ // registry (channel bindings + conversation headers + ordered turn history), then renames the
5
+ // sources aside as `<file>.pre-<version>.bak`. Writes ONLY through the repo API so the journal
6
+ // whitelist/replay contract stays the single source of truth for what a field means.
7
+ // pos: Migration helper invoked as a step migration from store/version-migrations.ts (B.T4).
8
+ // Idempotent via the rename: a second run finds no sources and is a no-op.
9
+ // >>> Once I am updated, be sure to update my header comment and the parent folder CORTEX.md <<<
10
+ import * as fs from 'node:fs/promises';
11
+ import * as path from 'node:path';
12
+ import { createLogger } from '../core/log.js';
13
+ import { SessionRegistryRepo } from './session-registry-repo.js';
14
+ const log = createLogger('session-registry-import');
15
+ const SESSIONS_FILE = 'sessions.json';
16
+ const LEDGER_FILE = 'conversation-ledger.json';
17
+ const REGISTRY_FILE = 'session-registry.jsonl';
18
+ const DEFAULT_VERSION = '2026.9.14';
19
+ /**
20
+ * Fold `<storeDir>/sessions.json` (bindings) and `<storeDir>/conversation-ledger.json` (headers +
21
+ * turns) into `<storeDir>/session-registry.jsonl` via the repo API, then rename each successfully
22
+ * consumed source to `<file>.pre-<version>.bak`.
23
+ *
24
+ * Semantics:
25
+ * - A missing source contributes 0 counts and is not renamed.
26
+ * - A corrupt source (unparseable JSON) is logged, listed in `skipped`, and LEFT ON DISK for manual
27
+ * inspection; the other source is still imported and the migration still succeeds (the caller
28
+ * bumps its version). Re-importing the good source on a retry is harmless: the good source has
29
+ * already been renamed away, so the retry sees it as missing.
30
+ * - Bindings whose session id is absent from the registry are imported anyway (bind is a free map).
31
+ * - Idempotent: after the rename, a second run finds no sources and does nothing (no journal growth).
32
+ * - Crash-safe: on a crash between the journal appends and the renames the sources are still present,
33
+ * so the next boot re-imports; per-channel turns are cleared before re-appending (only when the
34
+ * channel already carries turns), so the imported state converges rather than duplicating turns.
35
+ */
36
+ export async function importLegacySessionStores(storeDir, opts = {}) {
37
+ const version = opts.version ?? DEFAULT_VERSION;
38
+ const summary = {
39
+ bindings: 0, conversations: 0, turns: 0, profileNames: 0, skipped: [], renamed: [],
40
+ };
41
+ const sessionsRead = await readLegacyStore(path.join(storeDir, SESSIONS_FILE));
42
+ const ledgerRead = await readLegacyStore(path.join(storeDir, LEDGER_FILE));
43
+ if (sessionsRead.kind === 'corrupt') {
44
+ log.warn(`Corrupt ${SESSIONS_FILE} (${sessionsRead.message}); leaving it in place and skipping its bindings`);
45
+ summary.skipped.push(SESSIONS_FILE);
46
+ }
47
+ if (ledgerRead.kind === 'corrupt') {
48
+ log.warn(`Corrupt ${LEDGER_FILE} (${ledgerRead.message}); leaving it in place and skipping its conversations`);
49
+ summary.skipped.push(LEDGER_FILE);
50
+ }
51
+ const bindings = sessionsRead.kind === 'ok' ? parseBindings(sessionsRead.data) : [];
52
+ const conversations = ledgerRead.kind === 'ok' ? parseConversations(ledgerRead.data) : [];
53
+ if (bindings.length > 0 || conversations.length > 0) {
54
+ const repo = new SessionRegistryRepo(path.join(storeDir, REGISTRY_FILE));
55
+ // One admission lock for the whole import: every bind/header/turn lands before we rename the
56
+ // sources, so a reader that opens the journal after the rename sees the complete import.
57
+ await repo.batch(async (ops) => {
58
+ for (const [channel, sessionId] of bindings) {
59
+ await ops.bindChannel(channel, sessionId);
60
+ summary.bindings += 1;
61
+ }
62
+ for (const conv of conversations) {
63
+ await ops.setConversation(conv.channel, conv.header);
64
+ summary.conversations += 1;
65
+ if (conv.hasProfileName)
66
+ summary.profileNames += 1;
67
+ // Clear only when the channel already has turns — a crashed prior import may have left a
68
+ // partial list. On the clean first run channels have none, so no redundant clear is written.
69
+ if (ops.getTurns(conv.channel).length > 0)
70
+ await ops.clearTurns(conv.channel);
71
+ for (const turn of conv.turns) {
72
+ await ops.beginTurn(conv.channel, turn);
73
+ summary.turns += 1;
74
+ }
75
+ }
76
+ });
77
+ }
78
+ // Rename only sources we actually consumed (present + parseable). A corrupt or missing source is
79
+ // left untouched. Deterministic name keyed off the migration version so retries are predictable.
80
+ if (sessionsRead.kind === 'ok')
81
+ await renameSource(storeDir, SESSIONS_FILE, version, summary);
82
+ if (ledgerRead.kind === 'ok')
83
+ await renameSource(storeDir, LEDGER_FILE, version, summary);
84
+ return summary;
85
+ }
86
+ async function readLegacyStore(filePath) {
87
+ let raw;
88
+ try {
89
+ raw = await fs.readFile(filePath, 'utf8');
90
+ }
91
+ catch (err) {
92
+ if (err.code === 'ENOENT')
93
+ return { kind: 'missing' };
94
+ throw err;
95
+ }
96
+ try {
97
+ return { kind: 'ok', data: JSON.parse(raw) };
98
+ }
99
+ catch (err) {
100
+ return { kind: 'corrupt', message: err.message };
101
+ }
102
+ }
103
+ /** sessions.json is a flat `{ "<channel>": "<sessionId>" }`. Keys are literal channel strings and
104
+ * are imported verbatim; entries whose channel or session id is not a non-empty string are dropped
105
+ * (an empty id would make the bind line unreadable on replay). */
106
+ function parseBindings(data) {
107
+ if (!isPlainObject(data))
108
+ return [];
109
+ const out = [];
110
+ for (const [channel, sessionId] of Object.entries(data)) {
111
+ if (channel && typeof sessionId === 'string' && sessionId)
112
+ out.push([channel, sessionId]);
113
+ }
114
+ return out;
115
+ }
116
+ /** conversation-ledger.json is a flat `{ "<channel>": { sessionId, sessionName, backend, profileName,
117
+ * turns[], updatedAt } }`. Every header field (including `sessionId: null`) and the source
118
+ * `updatedAt` are preserved; turns keep their order and indices. */
119
+ function parseConversations(data) {
120
+ if (!isPlainObject(data))
121
+ return [];
122
+ const out = [];
123
+ for (const [channel, value] of Object.entries(data)) {
124
+ if (!channel || !isPlainObject(value))
125
+ continue;
126
+ const header = {
127
+ sessionId: headerString(value.sessionId),
128
+ sessionName: headerString(value.sessionName),
129
+ backend: typeof value.backend === 'string' ? value.backend : '',
130
+ profileName: headerString(value.profileName),
131
+ updatedAt: typeof value.updatedAt === 'string' ? value.updatedAt : '',
132
+ };
133
+ const turns = Array.isArray(value.turns) ? value.turns.filter(isPlainObject).map(toTurnRecord) : [];
134
+ out.push({
135
+ channel,
136
+ header,
137
+ turns,
138
+ hasProfileName: typeof value.profileName === 'string' && value.profileName.length > 0,
139
+ });
140
+ }
141
+ return out;
142
+ }
143
+ /** Preserve the header string EXACTLY as the ledger stored it: `null` stays null, a string (incl. the
144
+ * empty string) stays a string. Mirrors the journal's `toTurnNullableString` reader so the value
145
+ * survives replay unchanged; anything else collapses to null. */
146
+ function headerString(value) {
147
+ if (value === null)
148
+ return null;
149
+ return typeof value === 'string' ? value : null;
150
+ }
151
+ function toTurnRecord(value) {
152
+ return {
153
+ turnIndex: typeof value.turnIndex === 'number' ? value.turnIndex : Number(value.turnIndex),
154
+ userMessageTs: asString(value.userMessageTs),
155
+ userMessageText: asString(value.userMessageText),
156
+ statusMessageTs: asNullableString(value.statusMessageTs),
157
+ responseMessageTimestamps: Array.isArray(value.responseMessageTimestamps)
158
+ ? value.responseMessageTimestamps.map((t) => String(t))
159
+ : [],
160
+ executionId: asNullableString(value.executionId),
161
+ backupPath: asNullableString(value.backupPath),
162
+ status: value.status,
163
+ createdAt: asString(value.createdAt),
164
+ updatedAt: asString(value.updatedAt),
165
+ };
166
+ }
167
+ function asString(value) {
168
+ return typeof value === 'string' ? value : String(value ?? '');
169
+ }
170
+ function asNullableString(value) {
171
+ if (value === null || value === undefined)
172
+ return null;
173
+ return typeof value === 'string' ? value : String(value);
174
+ }
175
+ function isPlainObject(value) {
176
+ return !!value && typeof value === 'object' && !Array.isArray(value);
177
+ }
178
+ async function renameSource(dir, file, version, summary) {
179
+ const target = `${file}.pre-${version}.bak`;
180
+ await fs.rename(path.join(dir, file), path.join(dir, target));
181
+ summary.renamed.push(target);
182
+ }