@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
@@ -1,17 +1,40 @@
1
1
  // input: session-registry-journal, execution/thread stores, and AsyncMutex
2
2
  // output: SessionRegistryRepo JSONL-backed registry and admission APIs
3
+ // (patch-delta updates, channel bindings + conduit resolvers, turn history, batch())
3
4
  // pos: Stable session identity store with delete-intent guards
4
- // >>> Once I am updated, be sure to update my header comment and the parent folder CORTEX.md <<<
5
+ // >>> Once I am updated, be sure to update my header comment and the parent folder AGENTS.md <<<
5
6
  import * as crypto from 'node:crypto';
6
7
  import * as path from 'node:path';
8
+ import { isDeepStrictEqual } from 'node:util';
7
9
  import { AsyncMutex } from '../core/async-mutex.js';
8
10
  import { STORE_DIR } from '../core/paths.js';
9
- import { executionRepo } from './execution-repo.js';
10
- import { sessionRepo } from './session-repo.js';
11
- import { appendSessionRegistryEvent, compactSessionRegistry, createSessionRegistryState, deriveSessionOrigin, loadSessionRegistryState, shouldCompactSessionRegistry, } from './session-registry-journal.js';
12
- import { threadStore } from './thread-repo.js';
11
+ import { appendSessionRegistryEvent, compactSessionRegistry, createSessionRegistryState, deriveSessionOrigin, loadSessionRegistryState, shouldCompactSessionRegistry, PATCH_KEYS, } from './session-registry-journal.js';
13
12
  export const REGISTRY_FILE = path.join(STORE_DIR, 'session-registry.jsonl');
14
- export { deriveSessionOrigin };
13
+ export { deriveSessionOrigin, };
14
+ /** Compute the minimal patch from `current` to `next`. A key present in `current` but gone from
15
+ * `next` (→ `undefined`) is unset; a changed key (incl. an explicit `null`) is set; unchanged keys
16
+ * are omitted. Returns `null` when nothing changed so the caller appends no event. */
17
+ function diffRecord(current, next) {
18
+ const fields = {};
19
+ const unset = [];
20
+ for (const key of PATCH_KEYS) {
21
+ const cur = current[key];
22
+ const nxt = next[key];
23
+ const curHas = cur !== undefined;
24
+ const nxtHas = nxt !== undefined;
25
+ if (!curHas && !nxtHas)
26
+ continue;
27
+ if (curHas && !nxtHas) {
28
+ unset.push(key);
29
+ continue;
30
+ }
31
+ if (!isDeepStrictEqual(cur, nxt))
32
+ fields[key] = nxt;
33
+ }
34
+ if (Object.keys(fields).length === 0 && unset.length === 0)
35
+ return null;
36
+ return { fields: fields, unset };
37
+ }
15
38
  function cloneSession(record) {
16
39
  return { ...record };
17
40
  }
@@ -55,7 +78,7 @@ export class SessionRegistryRepo {
55
78
  options;
56
79
  state = createSessionRegistryState();
57
80
  loaded = false;
58
- activeUses = new Map();
81
+ conduitResolvers = [];
59
82
  constructor(filePath = REGISTRY_FILE, options = {}) {
60
83
  this.filePath = filePath;
61
84
  this.options = options;
@@ -72,8 +95,11 @@ export class SessionRegistryRepo {
72
95
  });
73
96
  }
74
97
  async registerSession(name, opts) {
98
+ await this.withState((state) => this.doRegisterSession(state, name, opts));
99
+ }
100
+ async doRegisterSession(state, name, opts) {
75
101
  const now = new Date().toISOString();
76
- return this.appendPut({
102
+ await this.writePut(state, {
77
103
  name,
78
104
  sessionId: opts.sessionId,
79
105
  projectId: opts.projectId ?? 'general',
@@ -103,23 +129,25 @@ export class SessionRegistryRepo {
103
129
  async updateSession(name, updates) {
104
130
  if ('sessionId' in updates)
105
131
  throw new Error('updateSession may not change sessionId');
106
- await this.withState(async (state) => {
107
- const sessionId = state.nameIndex.get(name);
108
- if (!sessionId)
109
- return;
110
- const current = state.live.get(sessionId);
111
- if (!current)
112
- return;
113
- await this.writePut(state, {
114
- ...current,
115
- lastUsedAt: updates.lastUsedAt ?? current.lastUsedAt,
116
- label: updates.label !== undefined ? trimLabel(updates.label) : current.label,
117
- profileName: updates.profileName !== undefined ? updates.profileName : current.profileName,
118
- backendSessionId: updates.backendSessionId !== undefined
119
- ? updates.backendSessionId
120
- : current.backendSessionId,
121
- contextUsage: updates.contextUsage !== undefined ? updates.contextUsage : current.contextUsage,
122
- });
132
+ await this.withState((state) => this.doUpdateSession(state, name, updates));
133
+ }
134
+ async doUpdateSession(state, name, updates) {
135
+ const sessionId = state.nameIndex.get(name);
136
+ if (!sessionId)
137
+ return;
138
+ const current = state.live.get(sessionId);
139
+ if (!current)
140
+ return;
141
+ await this.writePatch(state, current, {
142
+ ...current,
143
+ lastUsedAt: updates.lastUsedAt ?? current.lastUsedAt,
144
+ label: updates.label !== undefined ? trimLabel(updates.label) : current.label,
145
+ profileName: updates.profileName !== undefined ? updates.profileName : current.profileName,
146
+ backendSessionId: updates.backendSessionId !== undefined
147
+ ? updates.backendSessionId
148
+ : current.backendSessionId,
149
+ browser: updates.browser !== undefined ? updates.browser : current.browser,
150
+ contextUsage: updates.contextUsage !== undefined ? updates.contextUsage : current.contextUsage,
123
151
  });
124
152
  }
125
153
  async updateContextUsage(sessionId, usage) {
@@ -153,47 +181,18 @@ export class SessionRegistryRepo {
153
181
  async listResumable(projectId) {
154
182
  return this.withState(async (state) => sortRecent(filterLive(state, s => s.kind !== 'scheduled' && (projectId === undefined || s.projectId === projectId))));
155
183
  }
156
- async touchForUse(sessionId) {
157
- const release = await this.acquireSessionUse(sessionId);
158
- if (!release)
159
- return false;
160
- release();
161
- return true;
162
- }
163
- async acquireSessionUse(sessionId) {
184
+ /** Storage primitive behind use-count admission — the in-memory counter and lease semantics live
185
+ * in `@domain/sessions/session-use.ts`. Patches `lastUsedAt=now` iff the session is live and NOT
186
+ * pending deletion; returns whether the touch landed. */
187
+ async touchSessionUse(sessionId) {
164
188
  return this.withState(async (state) => {
165
189
  const current = state.live.get(sessionId);
166
190
  if (!current || state.pending.has(sessionId))
167
- return null;
168
- await this.writePut(state, { ...current, lastUsedAt: new Date().toISOString() });
169
- this.activeUses.set(sessionId, (this.activeUses.get(sessionId) ?? 0) + 1);
170
- let released = false;
171
- return () => {
172
- if (released)
173
- return;
174
- released = true;
175
- const next = (this.activeUses.get(sessionId) ?? 1) - 1;
176
- if (next <= 0)
177
- this.activeUses.delete(sessionId);
178
- else
179
- this.activeUses.set(sessionId, next);
180
- };
191
+ return false;
192
+ await this.writePatch(state, current, { ...current, lastUsedAt: new Date().toISOString() });
193
+ return true;
181
194
  });
182
195
  }
183
- async withSessionUse(sessionId, fn) {
184
- const release = await this.acquireSessionUse(sessionId);
185
- if (!release)
186
- return null;
187
- try {
188
- return await fn();
189
- }
190
- finally {
191
- release();
192
- }
193
- }
194
- async markUsed(sessionId) {
195
- await this.touchForUse(sessionId);
196
- }
197
196
  async markRead(sessionId) {
198
197
  await this.updateById(sessionId, (record) => ({
199
198
  ...record,
@@ -202,7 +201,10 @@ export class SessionRegistryRepo {
202
201
  }
203
202
  /** Bind (or unbind with null) a session to a commission. Called by the commission finalize path
204
203
  * (DR-0037) and by commission-mode session creation. Binding also clears commissionDraft: once
205
- * the contract is named, the draft directory no longer exists under that name. */
204
+ * the contract is named, the draft directory no longer exists under that name.
205
+ *
206
+ * `commissionBlockFor` is deliberately left alone: binding CHANGES the key (`draft:x` →
207
+ * `active:id`), and that mismatch is exactly what makes the next turn deliver the active block. */
206
208
  async bindCommission(sessionId, commissionId) {
207
209
  return this.updateById(sessionId, (record) => ({
208
210
  ...record,
@@ -210,6 +212,179 @@ export class SessionRegistryRepo {
210
212
  commissionDraft: commissionId ? null : record.commissionDraft,
211
213
  }));
212
214
  }
215
+ /** Enter (or leave, with null) the drafting half of commission mode. Called by
216
+ * `cortex_commission_start`, by the composer's "new" on a live session, and by session creation.
217
+ * Refuses to touch a session already bound to a commission — that is a terminal state. */
218
+ async setCommissionDraft(sessionId, draftDir) {
219
+ return this.updateById(sessionId, (record) => (record.commissionId
220
+ ? record
221
+ : { ...record, commissionDraft: draftDir }));
222
+ }
223
+ /** Record that the `[Commission]` block for `key` is now in this session's backend history. */
224
+ async markCommissionBlockDelivered(sessionId, key) {
225
+ return this.updateById(sessionId, (record) => ({ ...record, commissionBlockFor: key }));
226
+ }
227
+ /** Forget the delivery marker so the next turn re-injects the block. Called after compaction,
228
+ * which drops the copy that was in backend history. */
229
+ async clearCommissionBlockDelivery(sessionId) {
230
+ return this.updateById(sessionId, (record) => ({ ...record, commissionBlockFor: null }));
231
+ }
232
+ // --- Channel bindings (channel → conversation sessionId) ------------------------------------
233
+ /** Register an in-memory conduit resolver. Never persisted; a resolver answer wins over a
234
+ * persisted bind (§6). Returns an unregister callback. */
235
+ registerConduitResolver(fn) {
236
+ this.conduitResolvers.push(fn);
237
+ return () => {
238
+ const idx = this.conduitResolvers.indexOf(fn);
239
+ if (idx >= 0)
240
+ this.conduitResolvers.splice(idx, 1);
241
+ };
242
+ }
243
+ /** Resolve the conversation session for a channel: in-memory resolvers first (a string wins),
244
+ * then the persisted bindings index. */
245
+ async getBoundSessionId(channel) {
246
+ for (const resolve of this.conduitResolvers) {
247
+ const answer = resolve(channel);
248
+ if (typeof answer === 'string' && answer)
249
+ return answer;
250
+ }
251
+ return this.withState(async (state) => state.bindings.get(channel) ?? null);
252
+ }
253
+ async bindChannel(channel, sessionId) {
254
+ await this.withState((state) => this.doBindChannel(state, channel, sessionId));
255
+ }
256
+ async unbindChannel(channel) {
257
+ await this.withState((state) => this.doUnbindChannel(state, channel));
258
+ }
259
+ /** Remove every binding pointing at one of `sessionIds`. Used when sessions are torn down.
260
+ * Returns the number of bindings removed. */
261
+ async unbindBySessionIds(sessionIds) {
262
+ const targets = new Set(sessionIds);
263
+ return this.withState(async (state) => {
264
+ const channels = Array.from(state.bindings)
265
+ .filter(([, boundId]) => targets.has(boundId))
266
+ .map(([channel]) => channel);
267
+ for (const channel of channels)
268
+ await this.doUnbindChannel(state, channel);
269
+ return channels.length;
270
+ });
271
+ }
272
+ async listBindings() {
273
+ return this.withState(async (state) => Array.from(state.bindings, ([channel, sessionId]) => ({ channel, sessionId })));
274
+ }
275
+ // --- Turn history (channel → ordered turns) -------------------------------------------------
276
+ async beginTurn(channel, turn) {
277
+ await this.withState((state) => this.doBeginTurn(state, channel, turn));
278
+ }
279
+ async patchTurn(channel, turnIndex, fields) {
280
+ await this.withState((state) => this.doPatchTurn(state, channel, turnIndex, fields));
281
+ }
282
+ async truncateTurns(channel, fromIndex) {
283
+ await this.withState((state) => this.doTruncateTurns(state, channel, fromIndex));
284
+ }
285
+ async clearTurns(channel) {
286
+ await this.withState((state) => this.doClearTurns(state, channel));
287
+ }
288
+ async getTurns(channel) {
289
+ return this.withState(async (state) => readTurns(state, channel));
290
+ }
291
+ async findTurn(channel, pred) {
292
+ return this.withState(async (state) => {
293
+ const found = (state.turns.get(channel) ?? []).find(pred);
294
+ return found ? { ...found } : null;
295
+ });
296
+ }
297
+ // --- Conversation headers (channel → session identity of the hosted conversation) -----------
298
+ async getConversationHeader(channel) {
299
+ return this.withState(async (state) => readConversationHeader(state, channel));
300
+ }
301
+ async setConversation(channel, fields) {
302
+ await this.withState((state) => this.doSetConversation(state, channel, fields));
303
+ }
304
+ async clearConversation(channel) {
305
+ await this.withState((state) => this.doClearConversation(state, channel));
306
+ }
307
+ /** Header + turns for a channel under ONE lock (or null when the channel has no header). */
308
+ async readConversation(channel) {
309
+ return this.withState(async (state) => {
310
+ const header = readConversationHeader(state, channel);
311
+ if (!header)
312
+ return null;
313
+ return { header, turns: readTurns(state, channel) };
314
+ });
315
+ }
316
+ /** Every channel that has a conversation header, with its turns — one lock for the whole scan. */
317
+ async listConversations() {
318
+ return this.withState(async (state) => Array.from(state.conversations, ([channel, header]) => ({
319
+ channel,
320
+ header: { ...header },
321
+ turns: readTurns(state, channel),
322
+ })));
323
+ }
324
+ /** Run several mutations under ONE admission lock (T2/T3 need put+bind+turn atomically — never a
325
+ * put without its bind, §5). The ops mirror the top-level mutators but share the locked state. */
326
+ async batch(fn) {
327
+ return this.withState((state) => fn(this.batchOps(state)));
328
+ }
329
+ batchOps(state) {
330
+ return {
331
+ registerSession: (name, opts) => this.doRegisterSession(state, name, opts),
332
+ updateSession: (name, updates) => {
333
+ if ('sessionId' in updates)
334
+ throw new Error('updateSession may not change sessionId');
335
+ return this.doUpdateSession(state, name, updates);
336
+ },
337
+ updateById: (sessionId, mutate) => this.doUpdateById(state, sessionId, mutate),
338
+ bindChannel: (channel, sessionId) => this.doBindChannel(state, channel, sessionId),
339
+ unbindChannel: (channel) => this.doUnbindChannel(state, channel),
340
+ beginTurn: (channel, turn) => this.doBeginTurn(state, channel, turn),
341
+ patchTurn: (channel, turnIndex, fields) => this.doPatchTurn(state, channel, turnIndex, fields),
342
+ truncateTurns: (channel, fromIndex) => this.doTruncateTurns(state, channel, fromIndex),
343
+ clearTurns: (channel) => this.doClearTurns(state, channel),
344
+ setConversation: (channel, fields) => this.doSetConversation(state, channel, fields),
345
+ clearConversation: (channel) => this.doClearConversation(state, channel),
346
+ getTurns: (channel) => readTurns(state, channel),
347
+ getConversationHeader: (channel) => readConversationHeader(state, channel),
348
+ };
349
+ }
350
+ async doBindChannel(state, channel, sessionId) {
351
+ if (state.bindings.get(channel) === sessionId)
352
+ return;
353
+ await appendSessionRegistryEvent(this.filePath, state, { v: 1, op: 'bind', channel, sessionId }, this.options);
354
+ await this.maybeCompact(state);
355
+ }
356
+ async doUnbindChannel(state, channel) {
357
+ if (!state.bindings.has(channel))
358
+ return;
359
+ await appendSessionRegistryEvent(this.filePath, state, { v: 1, op: 'unbind', channel }, this.options);
360
+ await this.maybeCompact(state);
361
+ }
362
+ async doBeginTurn(state, channel, turn) {
363
+ await appendSessionRegistryEvent(this.filePath, state, { v: 1, op: 'turn', channel, kind: 'begin', turn: { ...turn } }, this.options);
364
+ await this.maybeCompact(state);
365
+ }
366
+ async doPatchTurn(state, channel, turnIndex, fields) {
367
+ await appendSessionRegistryEvent(this.filePath, state, { v: 1, op: 'turn', channel, kind: 'patch', turnIndex, fields: { ...fields } }, this.options);
368
+ await this.maybeCompact(state);
369
+ }
370
+ async doTruncateTurns(state, channel, fromIndex) {
371
+ await appendSessionRegistryEvent(this.filePath, state, { v: 1, op: 'turn', channel, kind: 'truncate', fromIndex }, this.options);
372
+ await this.maybeCompact(state);
373
+ }
374
+ async doClearTurns(state, channel) {
375
+ await appendSessionRegistryEvent(this.filePath, state, { v: 1, op: 'turn', channel, kind: 'clear' }, this.options);
376
+ await this.maybeCompact(state);
377
+ }
378
+ async doSetConversation(state, channel, fields) {
379
+ await appendSessionRegistryEvent(this.filePath, state, { v: 1, op: 'conversation', channel, kind: 'set', fields: { ...fields } }, this.options);
380
+ await this.maybeCompact(state);
381
+ }
382
+ async doClearConversation(state, channel) {
383
+ if (!state.conversations.has(channel))
384
+ return;
385
+ await appendSessionRegistryEvent(this.filePath, state, { v: 1, op: 'conversation', channel, kind: 'clear' }, this.options);
386
+ await this.maybeCompact(state);
387
+ }
213
388
  async listPendingDeletions() {
214
389
  return this.withState(async (state) => sortPending(state.pending.values()));
215
390
  }
@@ -218,12 +393,17 @@ export class SessionRegistryRepo {
218
393
  const blocked = new Set(protectedIds);
219
394
  const removed = [];
220
395
  for (const record of sortRecent(state.live.values())) {
221
- if (blocked.has(record.sessionId) || this.activeUses.has(record.sessionId))
396
+ // In-use sessions are protected by the caller: `domain/sessions/session-retention.ts` unions
397
+ // `activeSessionUseIds()` into `protectedIds`. The store no longer keeps a use counter.
398
+ if (blocked.has(record.sessionId))
222
399
  continue;
223
400
  const lastUsedAtMs = parseLastUsedAtMs(record.lastUsedAt);
224
401
  if (lastUsedAtMs === null || lastUsedAtMs >= toCutoffMs(cutoff))
225
402
  continue;
226
- const cleanup = await prepareCleanup(cloneSession(record));
403
+ // Hand the callback the session's turns from the locked state directly — the ledger is now a
404
+ // façade over THIS registry, so a callback that read it back would re-enter `withState` and
405
+ // deadlock. (The old ledger was a separate store with its own lock.)
406
+ const cleanup = await prepareCleanup(cloneSession(record), collectSessionTurns(state, record.sessionId));
227
407
  await appendSessionRegistryEvent(this.filePath, state, {
228
408
  v: 1,
229
409
  op: 'delete-intent',
@@ -246,24 +426,15 @@ export class SessionRegistryRepo {
246
426
  return true;
247
427
  });
248
428
  }
249
- async pruneStale(maxAgeMs) {
250
- const protectedIds = referencedSessionIds();
251
- const pending = await this.beginDeleteExpired(Date.now() - maxAgeMs, protectedIds);
252
- for (const entry of pending)
253
- await this.commitDeletion(entry.session.sessionId);
254
- return pending.length;
255
- }
256
- setOnPruneSession(_fn) {
257
- // Deprecated compatibility shim. Journal pruning no longer performs filesystem callbacks.
258
- }
259
429
  async compactNow() {
260
430
  await this.withState(async (state) => {
261
431
  await compactSessionRegistry(this.filePath, state, this.options);
262
432
  });
263
433
  }
264
- /** `backend` is accepted and ignored — a channel has one session. */
434
+ /** `backend` is accepted and ignored — a channel has one session. Pure in-registry lookup:
435
+ * the channel's bound sessionId → the live record's name. */
265
436
  async getActiveSessionName(channel, backend) {
266
- const sessionId = await sessionRepo.getSessionAsync(channel);
437
+ const sessionId = await this.getBoundSessionId(channel);
267
438
  if (!sessionId)
268
439
  return null;
269
440
  return this.lookupBySessionId(sessionId);
@@ -285,9 +456,6 @@ export class SessionRegistryRepo {
285
456
  }
286
457
  return this.state;
287
458
  }
288
- async appendPut(record) {
289
- await this.withState(async (state) => { await this.writePut(state, record); });
290
- }
291
459
  async writePut(state, record) {
292
460
  await appendSessionRegistryEvent(this.filePath, state, {
293
461
  v: 1,
@@ -298,14 +466,30 @@ export class SessionRegistryRepo {
298
466
  await this.maybeCompact(state);
299
467
  }
300
468
  async updateById(sessionId, mutate) {
301
- return this.withState(async (state) => {
302
- const current = state.live.get(sessionId);
303
- if (!current)
304
- return null;
305
- const next = mutate(cloneSession(current));
306
- await this.writePut(state, next);
307
- return next;
308
- });
469
+ return this.withState((state) => this.doUpdateById(state, sessionId, mutate));
470
+ }
471
+ async doUpdateById(state, sessionId, mutate) {
472
+ const current = state.live.get(sessionId);
473
+ if (!current)
474
+ return null;
475
+ const next = mutate(cloneSession(current));
476
+ await this.writePatch(state, current, next);
477
+ return next;
478
+ }
479
+ /** Append a `patch` for the delta between `current` (live) and `next`. No-op when nothing changed. */
480
+ async writePatch(state, current, next) {
481
+ const delta = diffRecord(current, next);
482
+ if (!delta)
483
+ return;
484
+ await appendSessionRegistryEvent(this.filePath, state, {
485
+ v: 1,
486
+ op: 'patch',
487
+ id: current.sessionId,
488
+ name: current.name,
489
+ fields: delta.fields,
490
+ ...(delta.unset.length ? { unset: delta.unset } : {}),
491
+ }, this.options);
492
+ await this.maybeCompact(state);
309
493
  }
310
494
  async maybeCompact(state) {
311
495
  if (shouldCompactSessionRegistry(state, this.options)) {
@@ -313,29 +497,28 @@ export class SessionRegistryRepo {
313
497
  }
314
498
  }
315
499
  }
500
+ function readTurns(state, channel) {
501
+ return (state.turns.get(channel) ?? []).map(turn => ({ ...turn }));
502
+ }
503
+ function readConversationHeader(state, channel) {
504
+ const header = state.conversations.get(channel);
505
+ return header ? { ...header } : null;
506
+ }
507
+ /** Turns of every channel whose conversation header names `sessionId` — the same rows the ledger's
508
+ * `listBySessionIds` would surface, read straight from the (already-locked) state. */
509
+ function collectSessionTurns(state, sessionId) {
510
+ const turns = [];
511
+ for (const [channel, header] of state.conversations) {
512
+ if (header.sessionId === sessionId)
513
+ turns.push(...readTurns(state, channel));
514
+ }
515
+ return turns;
516
+ }
316
517
  function* filterLive(state, predicate) {
317
518
  for (const record of state.live.values()) {
318
519
  if (predicate(record))
319
520
  yield record;
320
521
  }
321
522
  }
322
- function referencedSessionIds() {
323
- const ids = new Set();
324
- for (const exec of executionRepo.getAll()) {
325
- if (exec.session.sessionId)
326
- ids.add(exec.session.sessionId);
327
- }
328
- for (const thread of threadStore.getAll()) {
329
- for (const agent of Object.values(thread.agents)) {
330
- if (agent.sessionId)
331
- ids.add(agent.sessionId);
332
- }
333
- for (const step of thread.steps) {
334
- if (step.sessionId)
335
- ids.add(step.sessionId);
336
- }
337
- }
338
- return ids;
339
- }
340
523
  export const sessionStore = new SessionRegistryRepo();
341
524
  export const sessionRegistryRepo = sessionStore;
@@ -16,6 +16,18 @@ export interface Migration {
16
16
  * — the runner compares before/after to decide whether to write. */
17
17
  migrate(data: unknown, defaults?: unknown): unknown;
18
18
  }
19
+ export interface StepMigration {
20
+ /** versions.json key that tracks this step (a destination file path or a sentinel string). */
21
+ key: string;
22
+ /** CalVer when this step was introduced. Same pending rule as file migrations. */
23
+ version: string;
24
+ /** Idempotent action. Resolves on success; throws to signal failure (the runner logs, does not
25
+ * bump the key, and continues with the next step — the step retries next boot). */
26
+ run(ctx: {
27
+ dataDir: string;
28
+ storeDir: string;
29
+ }): Promise<void>;
30
+ }
19
31
  /** Replace any existing `<!-- cortex:docs ... -->` … `<!-- /cortex:docs -->` region with
20
32
  * `block`, or append `block` (separated by a blank line) when absent. Idempotent: feeding
21
33
  * the output back in is a no-op. Matches any block version on the start marker so an old
@@ -30,6 +42,11 @@ export declare function upsertMarkerBlock(content: string, block: string): strin
30
42
  * customized away from the shipped wording simply won't match and is left untouched,
31
43
  * preserving their edits. */
32
44
  export declare function applyReplacements(content: string, pairs: ReadonlyArray<readonly [string, string]>): string;
45
+ export declare function renameMemoryFilesToAgentsMd(dataDir: string): Promise<number>;
46
+ /** Rename `rules/cortex-md.md` → `rules/agents-md.md` and repair references to it across `rules/`.
47
+ * Returns the number of rule files whose content changed. Never clobbers an existing
48
+ * `agents-md.md`; a no-op on a fresh install, where `init` seeded the new name already. */
49
+ export declare function renameIndexRuleFile(dataDir: string): Promise<number>;
33
50
  /** Exported for plugin-retirement.ts, which guards its own one-shot rewrite with a sentinel key
34
51
  * in the same versions.json. Keeping one reader means one definition of "corrupt → reset". */
35
52
  export declare function loadVersionsFrom(filePath: string): Promise<Record<string, string>>;
@@ -41,6 +58,10 @@ export interface MigrationOptions {
41
58
  defaultsDir?: string;
42
59
  /** Override versions.json location. Defaults to dataDir/data. */
43
60
  storeDir?: string;
61
+ /** Override the built-in step-migration list. Test-only: production passes nothing and gets the
62
+ * real `stepMigrations`. Lets tests drive the step-runner contract (bump / skip / throw / order)
63
+ * with probe steps instead of the real S1 import. */
64
+ stepMigrations?: StepMigration[];
44
65
  }
45
66
  export declare function runMigrations(opts?: MigrationOptions): Promise<void>;
46
67
  /** Move the retired singular session hook config into declarative registry files. */
@@ -56,12 +77,17 @@ export declare function migrateAistatusConfigLocation(dataDir: string, dstPath?:
56
77
  /**
57
78
  * Delete hooks Cortex no longer ships from an existing install.
58
79
  *
59
- * All three current members were unreachable by construction rather than merely unused. The
80
+ * The first three members were unreachable by construction rather than merely unused. The
60
81
  * AskUserQuestion / ExitPlanMode bridge hooks matched native tools that headless `-p` strips from
61
82
  * the session whatever `--tools` lists (plan approval and questions now run through the
62
83
  * interaction-bridge MCP tools against the same webhook endpoints), and the PermissionRequest
63
84
  * auto-allow matched an event Claude never emits under the `bypassPermissions` mode every Cortex
64
- * spawn runs in. `syncManagedHooks` only adds and upgrades files, so without this the dead entries
65
- * would linger in every upgraded registry. Idempotent, and a no-op once the files are gone.
85
+ * spawn runs in. The last two are a rename: the CORTEX.md injector became the AGENTS.md injector
86
+ * under new filenames, and leaving the old pair deployed would double every injection.
87
+ * `syncManagedHooks` only adds and upgrades files, so without this the dead entries would linger
88
+ * in every upgraded registry. Idempotent, and a no-op once the files are gone.
89
+ *
90
+ * Entries go first and scripts second: two entries can share one script, so a script is only
91
+ * orphaned once every entry that ran it is gone.
66
92
  */
67
93
  export declare function removeRetiredDefaultHooks(dataDir: string): Promise<void>;