@cortex-agent/server 2026.9.14 → 2026.9.21

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 (259) hide show
  1. package/README.md +3 -2
  2. package/defaults/config/hooks/08-agents-md-injector-post-tool.json +10 -0
  3. package/defaults/config/hooks/{10-cortex-md-injector-session-start.json → 10-agents-md-injector-session-start.json} +3 -3
  4. package/defaults/config/hooks/{CORTEX.md → AGENTS.md} +2 -2
  5. package/defaults/hooks/{CORTEX.md → AGENTS.md} +1 -1
  6. package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  7. package/defaults/hooks/cortex-hook-api.mjs +2 -2
  8. package/defaults/hooks/new-session-hook.mjs +2 -2
  9. package/defaults/hooks/rules-loader.mjs +2 -2
  10. package/defaults/hooks/status-md-guard.mjs +8 -8
  11. package/defaults/hooks/task-status-check.mjs +18 -76
  12. package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
  13. package/defaults/plugins/cortex-commission/.claude-plugin/plugin.json +2 -2
  14. package/defaults/plugins/cortex-commission/plugin.json +2 -2
  15. package/defaults/plugins/cortex-commission/skills/commission/SKILL.md +3 -3
  16. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
  17. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
  18. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
  19. package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
  20. package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
  21. package/defaults/rules/decision-records.md +1 -1
  22. package/defaults/rules/meta-conventions.md +4 -4
  23. package/defaults/rules/mission-md.md +1 -1
  24. package/dist/agent-adapter/claude/adapter.d.ts +0 -6
  25. package/dist/agent-adapter/claude/adapter.js +0 -8
  26. package/dist/agent-adapter/claude/defaults.d.ts +10 -7
  27. package/dist/agent-adapter/claude/defaults.js +18 -16
  28. package/dist/agent-adapter/claude/hooks-builder.js +2 -2
  29. package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
  30. package/dist/agent-adapter/claude/spawn-args.js +20 -16
  31. package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
  32. package/dist/agent-adapter/claude/turn-machine.js +46 -5
  33. package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
  34. package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
  35. package/dist/agent-adapter/pi/mcp-bridge-logic.d.ts +11 -2
  36. package/dist/agent-adapter/pi/mcp-bridge-logic.js +32 -1
  37. package/dist/agent-adapter/pi/mcp-bridge.js +16 -15
  38. package/dist/agent-adapter/pi/session-options.d.ts +0 -6
  39. package/dist/agent-adapter/pi/session-options.js +1 -8
  40. package/dist/agent-adapter/types.d.ts +1 -1
  41. package/dist/core/mcp-tool-gate.d.ts +3 -17
  42. package/dist/core/mcp-tool-gate.js +4 -19
  43. package/dist/core/media-types.d.ts +10 -0
  44. package/dist/core/media-types.js +34 -0
  45. package/dist/core/platform-settings-spec.js +1 -1
  46. package/dist/core/settings-spec.d.ts +22 -1
  47. package/dist/core/settings-spec.js +33 -2
  48. package/dist/core/types/agent-types.d.ts +3 -1
  49. package/dist/core/utils.d.ts +1 -1
  50. package/dist/core/utils.js +1 -1
  51. package/dist/domain/agents/config.d.ts +1 -1
  52. package/dist/domain/agents/config.js +1 -1
  53. package/dist/domain/agents/profile-switch.d.ts +1 -1
  54. package/dist/domain/agents/profile-switch.js +3 -5
  55. package/dist/domain/agents/subagent/runner.js +0 -1
  56. package/dist/domain/commissions/commission-draft.d.ts +58 -0
  57. package/dist/domain/commissions/commission-draft.js +87 -4
  58. package/dist/domain/commissions/commission-finalize.d.ts +8 -3
  59. package/dist/domain/commissions/commission-finalize.js +14 -0
  60. package/dist/domain/executions/registry.d.ts +1 -2
  61. package/dist/domain/executions/registry.js +0 -3
  62. package/dist/domain/mcp/bundled-server.js +4 -3
  63. package/dist/domain/mcp/feishu/file.js +37 -18
  64. package/dist/domain/mcp/feishu/types.d.ts +3 -0
  65. package/dist/domain/mcp/feishu-server.js +1 -1
  66. package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
  67. package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
  68. package/dist/domain/mcp/tools/commission-tools.d.ts +12 -1
  69. package/dist/domain/mcp/tools/commission-tools.js +68 -14
  70. package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
  71. package/dist/domain/mcp/tools/remote-file.js +44 -0
  72. package/dist/domain/mcp/tools/slack.d.ts +2 -0
  73. package/dist/domain/mcp/tools/slack.js +22 -7
  74. package/dist/domain/mcp/tools/task-ops.js +5 -13
  75. package/dist/domain/mcp/tools/ui-file.js +23 -10
  76. package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
  77. package/dist/domain/mcp/tools/waitpoint.js +122 -0
  78. package/dist/domain/memory/agents-md-injector.d.ts +24 -0
  79. package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
  80. package/dist/domain/projects/project-store.d.ts +1 -1
  81. package/dist/domain/projects/project-store.js +3 -3
  82. package/dist/domain/remote/client-hot-reload.js +3 -1
  83. package/dist/domain/remote/client-manager.js +105 -126
  84. package/dist/domain/remote/client-ssh-tunnel.d.ts +16 -5
  85. package/dist/domain/remote/client-ssh-tunnel.js +12 -5
  86. package/dist/domain/remote/cortex-client-config.d.ts +1 -1
  87. package/dist/domain/remote/cortex-client-config.js +1 -1
  88. package/dist/domain/remote/device-file.d.ts +51 -0
  89. package/dist/domain/remote/device-file.js +193 -0
  90. package/dist/domain/remote/device-port.js +3 -0
  91. package/dist/domain/remote/reverse-stream.d.ts +18 -7
  92. package/dist/domain/remote/reverse-stream.js +19 -6
  93. package/dist/domain/runs/builders.js +0 -1
  94. package/dist/domain/runs/compact.js +0 -1
  95. package/dist/domain/runs/engine-spec.d.ts +11 -4
  96. package/dist/domain/runs/engine-spec.js +7 -4
  97. package/dist/domain/runs/prompt.js +16 -10
  98. package/dist/domain/runs/request.d.ts +0 -1
  99. package/dist/domain/sessions/session-hooks.d.ts +5 -12
  100. package/dist/domain/sessions/session-hooks.js +6 -13
  101. package/dist/domain/sessions/session-lifecycle.d.ts +4 -4
  102. package/dist/domain/sessions/session-lifecycle.js +5 -6
  103. package/dist/domain/sessions/session-retention.d.ts +1 -3
  104. package/dist/domain/sessions/session-retention.js +9 -26
  105. package/dist/domain/sessions/session-use.d.ts +32 -0
  106. package/dist/domain/sessions/session-use.js +63 -0
  107. package/dist/domain/sessions/session.js +6 -5
  108. package/dist/domain/system/server-update-check.js +29 -1
  109. package/dist/domain/system/update-ui-state.d.ts +32 -0
  110. package/dist/domain/system/update-ui-state.js +63 -0
  111. package/dist/domain/tasks/claim-recovery.js +2 -2
  112. package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
  113. package/dist/domain/tasks/dispatch-utils.js +46 -1
  114. package/dist/domain/tasks/dispatcher.js +4 -5
  115. package/dist/domain/tasks/mutator.d.ts +2 -2
  116. package/dist/domain/tasks/mutator.js +2 -2
  117. package/dist/domain/tasks/system/task-cli.js +2 -2
  118. package/dist/domain/tasks/system/task-state.js +1 -1
  119. package/dist/domain/threads/runner.js +3 -2
  120. package/dist/domain/ui-service/app-router.d.ts +54 -3
  121. package/dist/domain/ui-service/app-router.js +12 -14
  122. package/dist/domain/ui-service/input-schemas.d.ts +49 -5
  123. package/dist/domain/ui-service/input-schemas.js +35 -9
  124. package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
  125. package/dist/domain/ui-service/mutate/sessions.d.ts +17 -1
  126. package/dist/domain/ui-service/mutate/sessions.js +83 -3
  127. package/dist/domain/ui-service/mutate/system.d.ts +3 -1
  128. package/dist/domain/ui-service/mutate/system.js +13 -0
  129. package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
  130. package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
  131. package/dist/domain/ui-service/platform-settings.js +1 -1
  132. package/dist/domain/ui-service/plugins-shared.js +1 -1
  133. package/dist/domain/ui-service/query/config.js +1 -1
  134. package/dist/domain/ui-service/query/executions.js +0 -2
  135. package/dist/domain/ui-service/query/machine-detail.js +3 -8
  136. package/dist/domain/ui-service/query/memory.js +1 -1
  137. package/dist/domain/ui-service/query/sessions.js +7 -0
  138. package/dist/domain/ui-service/query/system.d.ts +2 -1
  139. package/dist/domain/ui-service/query/system.js +4 -0
  140. package/dist/domain/ui-service/query/threads.js +1 -54
  141. package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
  142. package/dist/domain/ui-service/query/waitpoints.js +117 -0
  143. package/dist/domain/ui-service/query-input-schemas.d.ts +3 -0
  144. package/dist/domain/ui-service/query-input-schemas.js +3 -0
  145. package/dist/domain/ui-service/trpc.js +1 -1
  146. package/dist/domain/ui-service/types.d.ts +175 -50
  147. package/dist/domain/ui-service/types.js +1 -1
  148. package/dist/domain/ui-service/ui-service.js +13 -33
  149. package/dist/domain/waitpoints/notices.d.ts +21 -0
  150. package/dist/domain/waitpoints/notices.js +115 -0
  151. package/dist/domain/waitpoints/service.d.ts +91 -0
  152. package/dist/domain/waitpoints/service.js +243 -0
  153. package/dist/entry/app.js +39 -29
  154. package/dist/entry/auth-login-cli.js +1 -1
  155. package/dist/entry/auth-login-terminal.js +1 -1
  156. package/dist/entry/init-auth.js +1 -1
  157. package/dist/entry/init.js +6 -6
  158. package/dist/entry/signal-cli.d.ts +30 -0
  159. package/dist/entry/signal-cli.js +207 -0
  160. package/dist/entry/start-ui-http.d.ts +1 -1
  161. package/dist/entry/start-ui-http.js +5 -3
  162. package/dist/events/event-types.d.ts +5 -7
  163. package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  164. package/dist/hooks/cortex-hook-api.mjs +2 -2
  165. package/dist/hooks/new-session-hook.mjs +2 -2
  166. package/dist/hooks/rules-loader.mjs +2 -2
  167. package/dist/hooks/status-md-guard.mjs +8 -8
  168. package/dist/hooks/task-status-check.mjs +18 -76
  169. package/dist/hooks/tasks-yaml-guard.mjs +2 -2
  170. package/dist/orchestration/agent-file-send.d.ts +9 -0
  171. package/dist/orchestration/agent-file-send.js +21 -2
  172. package/dist/orchestration/agent-runner.d.ts +4 -3
  173. package/dist/orchestration/agent-runner.js +25 -23
  174. package/dist/orchestration/attachments-store.d.ts +31 -0
  175. package/dist/orchestration/attachments-store.js +184 -0
  176. package/dist/orchestration/conversation-request.d.ts +30 -8
  177. package/dist/orchestration/conversation-request.js +62 -26
  178. package/dist/orchestration/edit-retry.js +2 -1
  179. package/dist/orchestration/interactions/ask-user-resume.js +2 -1
  180. package/dist/orchestration/interactions/plan-approvals.js +1 -1
  181. package/dist/orchestration/interactions/ui-update-prompt.d.ts +8 -0
  182. package/dist/orchestration/interactions/ui-update-prompt.js +47 -0
  183. package/dist/orchestration/outputs-store.d.ts +11 -0
  184. package/dist/orchestration/outputs-store.js +32 -6
  185. package/dist/orchestration/resume-dispatcher.js +2 -2
  186. package/dist/orchestration/routing/file-handler.d.ts +23 -2
  187. package/dist/orchestration/routing/file-handler.js +22 -5
  188. package/dist/orchestration/routing/webhook.js +240 -39
  189. package/dist/orchestration/session-compact.d.ts +3 -0
  190. package/dist/orchestration/session-compact.js +3 -2
  191. package/dist/orchestration/session-events.d.ts +6 -0
  192. package/dist/orchestration/session-events.js +5 -0
  193. package/dist/orchestration/session-gateway.d.ts +1 -1
  194. package/dist/orchestration/session-gateway.js +1 -0
  195. package/dist/orchestration/thread-executor.d.ts +2 -0
  196. package/dist/orchestration/thread-executor.js +11 -1
  197. package/dist/orchestration/thread-input.d.ts +3 -2
  198. package/dist/orchestration/thread-input.js +8 -9
  199. package/dist/orchestration/turn/turn-prep.d.ts +15 -1
  200. package/dist/orchestration/turn/turn-prep.js +21 -9
  201. package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
  202. package/dist/orchestration/waitpoint-ingress.js +172 -0
  203. package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
  204. package/dist/orchestration/waitpoint-notifier.js +119 -0
  205. package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
  206. package/dist/orchestration/waitpoint-remote-drain.js +147 -0
  207. package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
  208. package/dist/orchestration/waitpoint-sweep.js +87 -0
  209. package/dist/platform/adapters/feishu-image.d.ts +19 -0
  210. package/dist/platform/adapters/feishu-image.js +71 -0
  211. package/dist/platform/adapters/feishu.d.ts +2 -0
  212. package/dist/platform/adapters/feishu.js +26 -16
  213. package/dist/platform/ui-http/app-update.d.ts +11 -0
  214. package/dist/platform/ui-http/app-update.js +3 -0
  215. package/dist/platform/ui-http/listening-ports.d.ts +1 -1
  216. package/dist/platform/ui-http/listening-ports.js +1 -1
  217. package/dist/platform/ui-http/ui-session.js +1 -1
  218. package/dist/store/conversation-ledger-repo.d.ts +10 -19
  219. package/dist/store/conversation-ledger-repo.js +143 -152
  220. package/dist/store/execution-repo.d.ts +1 -19
  221. package/dist/store/execution-repo.js +1 -18
  222. package/dist/store/project-notes-repo.js +11 -2
  223. package/dist/store/prompt-migration-replacements.js +1 -1
  224. package/dist/store/session-registry-import.d.ts +34 -0
  225. package/dist/store/session-registry-import.js +182 -0
  226. package/dist/store/session-registry-journal.d.ts +107 -0
  227. package/dist/store/session-registry-journal.js +308 -19
  228. package/dist/store/session-registry-repo.d.ts +113 -28
  229. package/dist/store/session-registry-repo.js +288 -105
  230. package/dist/store/version-migrations.d.ts +29 -3
  231. package/dist/store/version-migrations.js +288 -24
  232. package/dist/store/waitpoint-repo.d.ts +108 -0
  233. package/dist/store/waitpoint-repo.js +94 -0
  234. package/package.json +2 -2
  235. package/web/dist/assets/index-CwwQNMpP.css +1 -0
  236. package/web/dist/assets/index-DLSfgq3o.js +444 -0
  237. package/web/dist/assets/{index-aHbOZSP6.js → index-DZTuqUO4.js} +1 -1
  238. package/web/dist/index.html +2 -2
  239. package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
  240. package/dist/domain/executions/log-tailer.d.ts +0 -71
  241. package/dist/domain/executions/log-tailer.js +0 -194
  242. package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
  243. package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
  244. package/dist/domain/memory/cortex-md-scanner.js +0 -66
  245. package/dist/domain/remote/cortex-client.d.ts +0 -1
  246. package/dist/domain/remote/cortex-client.js +0 -662
  247. package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
  248. package/dist/domain/tasks/system/cortex-run.js +0 -360
  249. package/dist/store/session-repo.d.ts +0 -65
  250. package/dist/store/session-repo.js +0 -184
  251. package/web/dist/assets/index-BuXbCsuz.js +0 -444
  252. package/web/dist/assets/index-CCPxQ94C.css +0 -1
  253. /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
  254. /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
  255. /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
  256. /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
  257. /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
  258. /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
  259. /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
@@ -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 AGENTS.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
+ }
@@ -37,9 +37,51 @@ export interface SessionRecord {
37
37
  * has not been named yet. Cleared at finalize, when commissionId is filled in. Mode is ON when
38
38
  * either this or commissionId is set. */
39
39
  commissionDraft?: string | null;
40
+ /** Which commission binding the `[Commission]` prompt block has already been delivered for —
41
+ * `draft:<dir>` or `active:<commissionId>` (DR-0037 v4). The block used to be a first-turn-only
42
+ * injection, which meant a session that entered the mode (or bound its contract) MID-session
43
+ * never received it at all. Comparing this marker against the current binding is what makes the
44
+ * block follow the state instead of the session's age; compaction clears it, because compaction
45
+ * is what removes the already-delivered copy from backend history. */
46
+ commissionBlockFor?: string | null;
40
47
  contextUsage?: unknown;
41
48
  browser?: SessionBrowserOption | null;
42
49
  }
50
+ /** Copied VERBATIM from store/conversation-ledger-repo.ts:9-22 (B.T1). The journal owns turn history
51
+ * now, but must NOT import the ledger module (dependency direction). Keep this in lock-step with the
52
+ * ledger's LedgerTurn until the ledger is retired in a later task. */
53
+ export type TurnStatus = 'processing' | 'completed' | 'superseded';
54
+ export interface TurnRecord {
55
+ turnIndex: number;
56
+ userMessageTs: string;
57
+ userMessageText: string;
58
+ statusMessageTs: string | null;
59
+ responseMessageTimestamps: string[];
60
+ executionId: string | null;
61
+ backupPath: string | null;
62
+ status: TurnStatus;
63
+ createdAt: string;
64
+ updatedAt: string;
65
+ }
66
+ /** Per-channel conversation header — the identity of the conversation currently hosted on a channel,
67
+ * independent of the live session record. Turns live in `turns` keyed by the same channel. Both are
68
+ * dropped together on `conversation clear` and on `delete-commit` (for every channel bound to the
69
+ * committed session). `sessionId`/`sessionName` are null before the first backend session lands. */
70
+ export interface ConversationHeader {
71
+ sessionId: string | null;
72
+ sessionName: string | null;
73
+ backend: string;
74
+ profileName: string | null;
75
+ updatedAt: string;
76
+ }
77
+ /** Header mutation payload for a `conversation set` event. A key present overwrites; a key absent is
78
+ * left untouched (the reducer merges onto the previous header, or onto a null base for a new one). */
79
+ export type ConversationFields = Partial<ConversationHeader>;
80
+ /** Patch payload: only the record keys a `patch` may carry. `name`/`sessionId` are identity and
81
+ * never travel in a patch (the event keys off them). A key set to `null` means "store null"; a key
82
+ * listed in `unset` is deleted (→ `undefined`); a key in neither is untouched. */
83
+ export type SessionPatchFields = Partial<Omit<SessionRecord, 'name' | 'sessionId'>>;
84
+ export type SessionPatchUnsetKey = keyof SessionPatchFields;
43
85
  export type SessionRegistryEvent = {
44
86
  v: 1;
45
87
  op: 'put';
@@ -55,11 +97,72 @@ export type SessionRegistryEvent = {
55
97
  v: 1;
56
98
  op: 'delete-commit';
57
99
  id: string;
100
+ } | {
101
+ v: 1;
102
+ op: 'patch';
103
+ id: string;
104
+ name: string;
105
+ fields: SessionPatchFields;
106
+ unset?: SessionPatchUnsetKey[];
107
+ } | {
108
+ v: 1;
109
+ op: 'bind';
110
+ channel: string;
111
+ sessionId: string;
112
+ } | {
113
+ v: 1;
114
+ op: 'unbind';
115
+ channel: string;
116
+ } | {
117
+ v: 1;
118
+ op: 'turn';
119
+ channel: string;
120
+ kind: 'begin';
121
+ turn: TurnRecord;
122
+ } | {
123
+ v: 1;
124
+ op: 'turn';
125
+ channel: string;
126
+ kind: 'patch';
127
+ turnIndex: number;
128
+ fields: Partial<TurnRecord>;
129
+ } | {
130
+ v: 1;
131
+ op: 'turn';
132
+ channel: string;
133
+ kind: 'truncate';
134
+ fromIndex: number;
135
+ } | {
136
+ v: 1;
137
+ op: 'turn';
138
+ channel: string;
139
+ kind: 'clear';
140
+ } | {
141
+ v: 1;
142
+ op: 'conversation';
143
+ channel: string;
144
+ kind: 'set';
145
+ fields: ConversationFields;
146
+ } | {
147
+ v: 1;
148
+ op: 'conversation';
149
+ channel: string;
150
+ kind: 'clear';
58
151
  };
59
152
  export interface SessionRegistryState {
60
153
  live: Map<string, SessionRecord>;
61
154
  pending: Map<string, PendingSessionDelete>;
62
155
  nameIndex: Map<string, string>;
156
+ /** channel → sessionId of the conversation session hosted on that channel (an explicit index; a
157
+ * channel can host several sessions but binds to one at a time). A free map: bind never checks
158
+ * liveness (an unknown or pending session id may be bound). Cleared on delete-commit. */
159
+ bindings: Map<string, string>;
160
+ /** channel → ordered turn history for the conversation hosted on that channel. Independent of
161
+ * liveness; dropped on `conversation clear` and on delete-commit (for every bound channel). */
162
+ turns: Map<string, TurnRecord[]>;
163
+ /** channel → conversation header (session identity of the hosted conversation). Dropped with the
164
+ * turns on `conversation clear` and on delete-commit (for every bound channel). */
165
+ conversations: Map<string, ConversationHeader>;
63
166
  eventCount: number;
64
167
  fileSize: number;
65
168
  }
@@ -81,3 +184,7 @@ export declare function shouldCompactSessionRegistry(state: SessionRegistryState
81
184
  export declare function loadSessionRegistryState(filePath: string, options?: SessionRegistryJournalOptions): Promise<SessionRegistryState>;
82
185
  export declare function appendSessionRegistryEvent(filePath: string, state: SessionRegistryState, event: SessionRegistryEvent, options?: SessionRegistryJournalOptions): Promise<void>;
83
186
  export declare function compactSessionRegistry(filePath: string, state: SessionRegistryState, options?: SessionRegistryJournalOptions): Promise<void>;
187
+ /** Every key a `patch` may carry, derived from the exhaustive reader table so the WRITER (repo
188
+ * `diffRecord`) and the READER can never disagree: adding a field to SessionRecord without a
189
+ * reader is a compile error above, and the writer picks it up from here automatically. */
190
+ export declare const PATCH_KEYS: SessionPatchUnsetKey[];