dual-brain 0.2.30 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (312) hide show
  1. package/.dual-brain/docs/claude-code-extension-points.md +32 -0
  2. package/.dual-brain/docs/data-tools-capabilities.md +181 -0
  3. package/.dual-brain/docs/ecosystem-tools.md +91 -0
  4. package/.dual-brain/docs/panel-handoff.md +124 -0
  5. package/.dual-brain/docs/ruflo-analysis.md +48 -0
  6. package/bin/dual-brain.mjs +56 -56
  7. package/dist/mcp-server/index.d.ts +27 -0
  8. package/dist/mcp-server/index.js +359 -0
  9. package/dist/mcp-server/index.js.map +1 -0
  10. package/dist/src/agent-protocol.d.ts +163 -0
  11. package/dist/src/agent-protocol.js +368 -0
  12. package/dist/src/agent-protocol.js.map +1 -0
  13. package/dist/src/agents/registry.d.ts +52 -0
  14. package/dist/src/agents/registry.js +393 -0
  15. package/dist/src/agents/registry.js.map +1 -0
  16. package/dist/src/awareness.d.ts +93 -0
  17. package/dist/src/awareness.js +406 -0
  18. package/dist/src/awareness.js.map +1 -0
  19. package/dist/src/brief.d.ts +48 -0
  20. package/dist/src/brief.js +179 -0
  21. package/dist/src/brief.js.map +1 -0
  22. package/dist/src/calibration.d.ts +32 -0
  23. package/dist/src/calibration.js +133 -0
  24. package/dist/src/calibration.js.map +1 -0
  25. package/dist/src/checkpoint.d.ts +33 -0
  26. package/dist/src/checkpoint.js +99 -0
  27. package/dist/src/checkpoint.js.map +1 -0
  28. package/dist/src/ci-triage.d.ts +33 -0
  29. package/dist/src/ci-triage.js +193 -0
  30. package/dist/src/ci-triage.js.map +1 -0
  31. package/dist/src/cognitive-loop.d.ts +56 -0
  32. package/dist/src/cognitive-loop.js +495 -0
  33. package/dist/src/cognitive-loop.js.map +1 -0
  34. package/dist/src/collaboration.d.ts +147 -0
  35. package/dist/src/collaboration.js +438 -0
  36. package/dist/src/collaboration.js.map +1 -0
  37. package/dist/src/context-intel.d.ts +47 -0
  38. package/dist/src/context-intel.js +156 -0
  39. package/dist/src/context-intel.js.map +1 -0
  40. package/dist/src/context.d.ts +53 -0
  41. package/dist/src/context.js +332 -0
  42. package/dist/src/context.js.map +1 -0
  43. package/dist/src/continuity.d.ts +89 -0
  44. package/dist/src/continuity.js +230 -0
  45. package/dist/src/continuity.js.map +1 -0
  46. package/dist/src/cost-tracker.d.ts +47 -0
  47. package/dist/src/cost-tracker.js +170 -0
  48. package/dist/src/cost-tracker.js.map +1 -0
  49. package/dist/src/debrief.d.ts +53 -0
  50. package/dist/src/debrief.js +222 -0
  51. package/dist/src/debrief.js.map +1 -0
  52. package/dist/src/decide.d.ts +96 -0
  53. package/dist/src/decide.js +744 -0
  54. package/dist/src/decide.js.map +1 -0
  55. package/dist/src/decompose.d.ts +39 -0
  56. package/dist/src/decompose.js +218 -0
  57. package/dist/src/decompose.js.map +1 -0
  58. package/dist/src/detect.d.ts +91 -0
  59. package/dist/src/detect.js +544 -0
  60. package/dist/src/detect.js.map +1 -0
  61. package/dist/src/dispatch.d.ts +154 -0
  62. package/dist/src/dispatch.js +1306 -0
  63. package/dist/src/dispatch.js.map +1 -0
  64. package/dist/src/doctor.d.ts +421 -0
  65. package/dist/src/doctor.js +1689 -0
  66. package/dist/src/doctor.js.map +1 -0
  67. package/dist/src/engine.d.ts +70 -0
  68. package/dist/src/engine.js +155 -0
  69. package/dist/src/engine.js.map +1 -0
  70. package/dist/src/envelope.d.ts +36 -0
  71. package/dist/src/envelope.js +80 -0
  72. package/dist/src/envelope.js.map +1 -0
  73. package/dist/src/failure-memory.d.ts +55 -0
  74. package/dist/src/failure-memory.js +175 -0
  75. package/dist/src/failure-memory.js.map +1 -0
  76. package/dist/src/fx.d.ts +87 -0
  77. package/dist/src/fx.js +272 -0
  78. package/dist/src/fx.js.map +1 -0
  79. package/dist/src/governance.d.ts +93 -0
  80. package/dist/src/governance.js +261 -0
  81. package/dist/src/governance.js.map +1 -0
  82. package/dist/src/handoff.d.ts +11 -0
  83. package/dist/src/handoff.js +90 -0
  84. package/dist/src/handoff.js.map +1 -0
  85. package/dist/src/head-protocol.d.ts +76 -0
  86. package/dist/src/head-protocol.js +109 -0
  87. package/dist/src/head-protocol.js.map +1 -0
  88. package/dist/src/head.d.ts +222 -0
  89. package/dist/src/head.js +765 -0
  90. package/dist/src/head.js.map +1 -0
  91. package/dist/src/health.d.ts +132 -0
  92. package/dist/src/health.js +435 -0
  93. package/dist/src/health.js.map +1 -0
  94. package/dist/src/inbox.d.ts +70 -0
  95. package/dist/src/inbox.js +218 -0
  96. package/dist/src/inbox.js.map +1 -0
  97. package/dist/src/index.d.ts +33 -0
  98. package/dist/src/index.js +38 -0
  99. package/dist/src/index.js.map +1 -0
  100. package/dist/src/install-hooks.d.ts +13 -0
  101. package/dist/src/install-hooks.js +88 -0
  102. package/dist/src/install-hooks.js.map +1 -0
  103. package/dist/src/integrity.d.ts +59 -0
  104. package/dist/src/integrity.js +206 -0
  105. package/dist/src/integrity.js.map +1 -0
  106. package/dist/src/intelligence.d.ts +104 -0
  107. package/dist/src/intelligence.js +391 -0
  108. package/dist/src/intelligence.js.map +1 -0
  109. package/dist/src/ledger.d.ts +54 -0
  110. package/dist/src/ledger.js +179 -0
  111. package/dist/src/ledger.js.map +1 -0
  112. package/dist/src/living-docs.d.ts +14 -0
  113. package/dist/src/living-docs.js +197 -0
  114. package/dist/src/living-docs.js.map +1 -0
  115. package/dist/src/memory-tiers.d.ts +37 -0
  116. package/dist/src/memory-tiers.js +160 -0
  117. package/dist/src/memory-tiers.js.map +1 -0
  118. package/dist/src/model-profiles.d.ts +65 -0
  119. package/dist/src/model-profiles.js +568 -0
  120. package/dist/src/model-profiles.js.map +1 -0
  121. package/dist/src/models.d.ts +58 -0
  122. package/dist/src/models.js +327 -0
  123. package/dist/src/models.js.map +1 -0
  124. package/dist/src/narrative.d.ts +54 -0
  125. package/dist/src/narrative.js +163 -0
  126. package/dist/src/narrative.js.map +1 -0
  127. package/dist/src/nextstep.d.ts +16 -0
  128. package/dist/src/nextstep.js +103 -0
  129. package/dist/src/nextstep.js.map +1 -0
  130. package/dist/src/observer.d.ts +18 -0
  131. package/dist/src/observer.js +251 -0
  132. package/dist/src/observer.js.map +1 -0
  133. package/dist/src/outcome.d.ts +110 -0
  134. package/dist/src/outcome.js +377 -0
  135. package/dist/src/outcome.js.map +1 -0
  136. package/dist/src/pipeline.d.ts +167 -0
  137. package/dist/src/pipeline.js +1503 -0
  138. package/dist/src/pipeline.js.map +1 -0
  139. package/dist/src/playbook.d.ts +59 -0
  140. package/dist/src/playbook.js +238 -0
  141. package/dist/src/playbook.js.map +1 -0
  142. package/dist/src/pr-agent.d.ts +97 -0
  143. package/dist/src/pr-agent.js +195 -0
  144. package/dist/src/pr-agent.js.map +1 -0
  145. package/dist/src/predictive.d.ts +57 -0
  146. package/dist/src/predictive.js +230 -0
  147. package/dist/src/predictive.js.map +1 -0
  148. package/dist/src/profile.d.ts +294 -0
  149. package/dist/src/profile.js +1347 -0
  150. package/dist/src/profile.js.map +1 -0
  151. package/dist/src/prompt-audit.d.ts +22 -0
  152. package/dist/src/prompt-audit.js +194 -0
  153. package/dist/src/prompt-audit.js.map +1 -0
  154. package/dist/src/prompt-intel.d.ts +12 -0
  155. package/dist/src/prompt-intel.js +321 -0
  156. package/dist/src/prompt-intel.js.map +1 -0
  157. package/dist/src/provider-context.d.ts +121 -0
  158. package/dist/src/provider-context.js +222 -0
  159. package/dist/src/provider-context.js.map +1 -0
  160. package/dist/src/provider-manager.d.ts +92 -0
  161. package/dist/src/provider-manager.js +428 -0
  162. package/dist/src/provider-manager.js.map +1 -0
  163. package/dist/src/receipt.d.ts +87 -0
  164. package/dist/src/receipt.js +326 -0
  165. package/dist/src/receipt.js.map +1 -0
  166. package/dist/src/recommendations.d.ts +13 -0
  167. package/dist/src/recommendations.js +291 -0
  168. package/dist/src/recommendations.js.map +1 -0
  169. package/dist/src/redact.d.ts +15 -0
  170. package/dist/src/redact.js +129 -0
  171. package/dist/src/redact.js.map +1 -0
  172. package/dist/src/replit.d.ts +397 -0
  173. package/dist/src/replit.js +1160 -0
  174. package/dist/src/replit.js.map +1 -0
  175. package/dist/src/repo.d.ts +149 -0
  176. package/dist/src/repo.js +416 -0
  177. package/dist/src/repo.js.map +1 -0
  178. package/dist/src/revert.d.ts +30 -0
  179. package/dist/src/revert.js +166 -0
  180. package/dist/src/revert.js.map +1 -0
  181. package/dist/src/room.d.ts +102 -0
  182. package/dist/src/room.js +212 -0
  183. package/dist/src/room.js.map +1 -0
  184. package/dist/src/routing-advisor.d.ts +57 -0
  185. package/dist/src/routing-advisor.js +221 -0
  186. package/dist/src/routing-advisor.js.map +1 -0
  187. package/dist/src/self-correct.d.ts +40 -0
  188. package/dist/src/self-correct.js +137 -0
  189. package/dist/src/self-correct.js.map +1 -0
  190. package/dist/src/session-lock.d.ts +35 -0
  191. package/dist/src/session-lock.js +134 -0
  192. package/dist/src/session-lock.js.map +1 -0
  193. package/dist/src/session.d.ts +267 -0
  194. package/dist/src/session.js +1660 -0
  195. package/dist/src/session.js.map +1 -0
  196. package/dist/src/settings-tui.d.ts +5 -0
  197. package/dist/src/settings-tui.js +422 -0
  198. package/dist/src/settings-tui.js.map +1 -0
  199. package/dist/src/setup-flow.d.ts +63 -0
  200. package/dist/src/setup-flow.js +233 -0
  201. package/dist/src/setup-flow.js.map +1 -0
  202. package/dist/src/signal.d.ts +19 -0
  203. package/dist/src/signal.js +122 -0
  204. package/dist/src/signal.js.map +1 -0
  205. package/dist/src/simmer.d.ts +85 -0
  206. package/dist/src/simmer.js +224 -0
  207. package/dist/src/simmer.js.map +1 -0
  208. package/dist/src/state-export.d.ts +129 -0
  209. package/dist/src/state-export.js +233 -0
  210. package/dist/src/state-export.js.map +1 -0
  211. package/dist/src/strategy.d.ts +54 -0
  212. package/dist/src/strategy.js +95 -0
  213. package/dist/src/strategy.js.map +1 -0
  214. package/dist/src/subscription.d.ts +40 -0
  215. package/dist/src/subscription.js +189 -0
  216. package/dist/src/subscription.js.map +1 -0
  217. package/dist/src/templates.d.ts +208 -0
  218. package/dist/src/templates.js +238 -0
  219. package/dist/src/templates.js.map +1 -0
  220. package/dist/src/test.d.ts +9 -0
  221. package/dist/src/test.js +1173 -0
  222. package/dist/src/test.js.map +1 -0
  223. package/dist/src/think-engine.d.ts +67 -0
  224. package/dist/src/think-engine.js +412 -0
  225. package/dist/src/think-engine.js.map +1 -0
  226. package/dist/src/tui.d.ts +71 -0
  227. package/dist/src/tui.js +242 -0
  228. package/dist/src/tui.js.map +1 -0
  229. package/dist/src/types.d.ts +177 -0
  230. package/dist/src/types.js +6 -0
  231. package/dist/src/types.js.map +1 -0
  232. package/dist/src/update-check.d.ts +7 -0
  233. package/dist/src/update-check.js +36 -0
  234. package/dist/src/update-check.js.map +1 -0
  235. package/dist/src/wave-planner.d.ts +30 -0
  236. package/dist/src/wave-planner.js +281 -0
  237. package/dist/src/wave-planner.js.map +1 -0
  238. package/hooks/head-guard.sh +41 -0
  239. package/hooks/precompact.mjs +3 -3
  240. package/hooks/session-end.mjs +3 -3
  241. package/hooks/task-classifier.mjs +328 -0
  242. package/hooks/vibe-router.mjs +387 -0
  243. package/install.mjs +2 -2
  244. package/package.json +29 -153
  245. package/src/agents/registry.mjs +0 -405
  246. package/src/awareness.mjs +0 -425
  247. package/src/brief.mjs +0 -266
  248. package/src/calibration.mjs +0 -148
  249. package/src/checkpoint.mjs +0 -109
  250. package/src/ci-triage.mjs +0 -191
  251. package/src/cognitive-loop.mjs +0 -562
  252. package/src/collaboration.mjs +0 -545
  253. package/src/context-intel.mjs +0 -158
  254. package/src/context.mjs +0 -389
  255. package/src/continuity.mjs +0 -298
  256. package/src/cost-tracker.mjs +0 -184
  257. package/src/debrief.mjs +0 -228
  258. package/src/decide.mjs +0 -1099
  259. package/src/decompose.mjs +0 -331
  260. package/src/detect.mjs +0 -702
  261. package/src/dispatch.mjs +0 -1447
  262. package/src/doctor.mjs +0 -1607
  263. package/src/envelope.mjs +0 -139
  264. package/src/failure-memory.mjs +0 -178
  265. package/src/fx.mjs +0 -276
  266. package/src/governance.mjs +0 -279
  267. package/src/handoff.mjs +0 -87
  268. package/src/head-protocol.mjs +0 -128
  269. package/src/head.mjs +0 -952
  270. package/src/health.mjs +0 -528
  271. package/src/inbox.mjs +0 -195
  272. package/src/index.mjs +0 -44
  273. package/src/install-hooks.mjs +0 -100
  274. package/src/integrity.mjs +0 -245
  275. package/src/intelligence.mjs +0 -447
  276. package/src/ledger.mjs +0 -196
  277. package/src/living-docs.mjs +0 -210
  278. package/src/memory-tiers.mjs +0 -193
  279. package/src/models.mjs +0 -363
  280. package/src/narrative.mjs +0 -169
  281. package/src/nextstep.mjs +0 -100
  282. package/src/observer.mjs +0 -241
  283. package/src/outcome.mjs +0 -400
  284. package/src/pipeline.mjs +0 -1711
  285. package/src/playbook.mjs +0 -257
  286. package/src/pr-agent.mjs +0 -214
  287. package/src/predictive.mjs +0 -250
  288. package/src/profile.mjs +0 -1411
  289. package/src/prompt-audit.mjs +0 -231
  290. package/src/prompt-intel.mjs +0 -325
  291. package/src/provider-context.mjs +0 -257
  292. package/src/receipt.mjs +0 -344
  293. package/src/recommendations.mjs +0 -296
  294. package/src/redact.mjs +0 -192
  295. package/src/replit.mjs +0 -1210
  296. package/src/repo.mjs +0 -445
  297. package/src/revert.mjs +0 -149
  298. package/src/routing-advisor.mjs +0 -204
  299. package/src/self-correct.mjs +0 -147
  300. package/src/session-lock.mjs +0 -160
  301. package/src/session.mjs +0 -1655
  302. package/src/settings-tui.mjs +0 -373
  303. package/src/setup-flow.mjs +0 -223
  304. package/src/signal.mjs +0 -115
  305. package/src/simmer.mjs +0 -241
  306. package/src/strategy.mjs +0 -235
  307. package/src/subscription.mjs +0 -212
  308. package/src/templates.mjs +0 -260
  309. package/src/think-engine.mjs +0 -428
  310. package/src/tui.mjs +0 -276
  311. package/src/update-check.mjs +0 -35
  312. package/src/wave-planner.mjs +0 -294
@@ -0,0 +1,1660 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * session.ts — Persist task state between terminal sessions.
4
+ *
5
+ * Exports:
6
+ * loadSession(cwd) → session state or null (if stale/missing)
7
+ * saveSession(state, cwd) → write session atomically
8
+ * updateSession(patch, cwd) → merge partial update into existing session
9
+ * clearSession(cwd) → delete session file
10
+ * formatSessionCard(session, repo, health) → compact status card string (≤5 lines)
11
+ */
12
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, unlinkSync, renameSync, readdirSync, statSync, copyFileSync } from 'node:fs';
13
+ import { join, dirname } from 'node:path';
14
+ // ─── Constants ────────────────────────────────────────────────────────────────
15
+ const SESSION_FILE = '.dualbrain/session.json';
16
+ const SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
17
+ // ─── File I/O ──────────────────────────────────────���──────────────────────────
18
+ function sessionPath(cwd) {
19
+ return join(cwd ?? process.cwd(), SESSION_FILE);
20
+ }
21
+ function ensureDir(cwd) {
22
+ mkdirSync(join(cwd ?? process.cwd(), '.dualbrain'), { recursive: true });
23
+ }
24
+ // ─── Schema defaults ──────────────────────────────────────────────────────────
25
+ function defaultSession() {
26
+ const now = new Date().toISOString();
27
+ return {
28
+ startedAt: now,
29
+ updatedAt: now,
30
+ objective: null,
31
+ branch: null,
32
+ filesChanged: [],
33
+ commandsRun: [],
34
+ lastResult: null,
35
+ provider: null,
36
+ nextAction: null,
37
+ };
38
+ }
39
+ // ─── Exports ──────────���───────────────────────────────────────────────────────
40
+ /**
41
+ * Load the session file. Returns null if missing or older than 24 hours.
42
+ */
43
+ export function loadSession(cwd = process.cwd()) {
44
+ const p = sessionPath(cwd);
45
+ if (!existsSync(p))
46
+ return null;
47
+ try {
48
+ const data = JSON.parse(readFileSync(p, 'utf8'));
49
+ const age = Date.now() - Date.parse(data.updatedAt || data.startedAt || '');
50
+ if (age > SESSION_TTL_MS)
51
+ return null;
52
+ return data;
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ }
58
+ /**
59
+ * Write session state atomically (tmp + rename).
60
+ */
61
+ export function saveSession(state, cwd = process.cwd()) {
62
+ ensureDir(cwd);
63
+ const p = sessionPath(cwd);
64
+ const tmp = p + '.tmp.' + process.pid;
65
+ const data = {
66
+ ...defaultSession(),
67
+ ...state,
68
+ updatedAt: new Date().toISOString(),
69
+ };
70
+ writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n');
71
+ renameSync(tmp, p);
72
+ return data;
73
+ }
74
+ /**
75
+ * Merge a partial update into the existing session (or create a new one).
76
+ */
77
+ export function updateSession(patch, cwd = process.cwd()) {
78
+ const existing = loadSession(cwd) || defaultSession();
79
+ const updated = { ...existing, ...patch };
80
+ // Arrays: append, don't replace
81
+ if (patch.filesChanged) {
82
+ const combined = [...(existing.filesChanged || []), ...(patch.filesChanged || [])];
83
+ updated.filesChanged = [...new Set(combined)]; // deduplicate
84
+ }
85
+ if (patch.commandsRun) {
86
+ updated.commandsRun = [...(existing.commandsRun || []), ...(patch.commandsRun || [])];
87
+ }
88
+ return saveSession(updated, cwd);
89
+ }
90
+ /**
91
+ * Delete the session file.
92
+ */
93
+ export function clearSession(cwd = process.cwd()) {
94
+ const p = sessionPath(cwd);
95
+ if (existsSync(p)) {
96
+ try {
97
+ unlinkSync(p);
98
+ }
99
+ catch { /* non-fatal */ }
100
+ }
101
+ }
102
+ // ─── Session card formatting ──────────��───────────────────────────────────────
103
+ /**
104
+ * Format a compact status card (≤5 lines) for display when running `dual-brain`.
105
+ */
106
+ export function formatSessionCard(session, repo, health, profile) {
107
+ const lines = [];
108
+ // Line 1: Repo identity
109
+ const repoParts = [];
110
+ if (repo.name)
111
+ repoParts.push(repo.name);
112
+ if (repo.type !== 'unknown') {
113
+ const typeLabel = (repo.type || '').charAt(0).toUpperCase() + (repo.type || '').slice(1);
114
+ repoParts.push(typeLabel);
115
+ }
116
+ if (repo.packageManager)
117
+ repoParts.push(repo.packageManager);
118
+ // Detect test runner label (Vitest, Jest, pytest, etc.)
119
+ const testCmd = repo.commands?.test || '';
120
+ let testLabel = null;
121
+ if (testCmd.includes('vitest'))
122
+ testLabel = 'Vitest';
123
+ else if (testCmd.includes('jest'))
124
+ testLabel = 'Jest';
125
+ else if (testCmd.includes('mocha'))
126
+ testLabel = 'Mocha';
127
+ else if (testCmd.includes('pytest'))
128
+ testLabel = 'Pytest';
129
+ else if (testCmd.includes('rspec'))
130
+ testLabel = 'RSpec';
131
+ else if (testCmd.includes('go test'))
132
+ testLabel = 'go test';
133
+ else if (testCmd.includes('cargo test'))
134
+ testLabel = 'cargo test';
135
+ if (testLabel)
136
+ repoParts.push(testLabel);
137
+ lines.push(`dual-brain ready`);
138
+ lines.push(`Repo: ${repoParts.join(' / ') || 'unknown'}`);
139
+ // Line 3: Branch + dirty status
140
+ if (repo.branch) {
141
+ const dirtyNote = repo.dirty ? ` (uncommitted changes)` : '';
142
+ lines.push(`Branch: ${repo.branch}${dirtyNote}`);
143
+ }
144
+ // Line 4: Health summary — only show enabled providers
145
+ const { states = {} } = health || {};
146
+ const claudeProviderEnabled = profile?.providers?.claude?.enabled !== false;
147
+ const openaiProviderEnabled = profile?.providers?.openai?.enabled !== false;
148
+ function providerStatus(name) {
149
+ const entries = Object.entries(states).filter(([k]) => k.startsWith(`${name}:`));
150
+ if (entries.length === 0)
151
+ return 'healthy';
152
+ const statuses = entries.map(([, v]) => v.status);
153
+ if (statuses.includes('hot'))
154
+ return 'hot';
155
+ if (statuses.includes('degraded'))
156
+ return 'degraded';
157
+ if (statuses.includes('probing'))
158
+ return 'probing';
159
+ return 'healthy';
160
+ }
161
+ const healthParts = [];
162
+ if (claudeProviderEnabled) {
163
+ const claudeStatus = providerStatus('claude');
164
+ healthParts.push(claudeStatus === 'healthy' ? 'Claude healthy' : `Claude ${claudeStatus}`);
165
+ }
166
+ else {
167
+ healthParts.push('Claude disabled');
168
+ }
169
+ if (openaiProviderEnabled) {
170
+ const openaiStatus = providerStatus('openai');
171
+ healthParts.push(openaiStatus === 'healthy' ? 'OpenAI healthy' : `OpenAI ${openaiStatus}`);
172
+ }
173
+ else {
174
+ healthParts.push('OpenAI disabled');
175
+ }
176
+ lines.push(`Health: ${healthParts.join(', ')}`);
177
+ // Line 5: Last task summary (only if session exists)
178
+ if (session) {
179
+ const parts = [];
180
+ if (session.objective)
181
+ parts.push(session.objective);
182
+ if (session.filesChanged?.length) {
183
+ const fc = session.filesChanged.length;
184
+ parts.push(`edited ${fc} file${fc !== 1 ? 's' : ''}`);
185
+ }
186
+ if (session.lastResult?.status === 'failure' && session.lastResult?.summary) {
187
+ parts.push(session.lastResult.summary);
188
+ }
189
+ else if (session.lastResult?.summary) {
190
+ // include brief result note if compact
191
+ const summary = session.lastResult.summary;
192
+ if (summary.length <= 40)
193
+ parts.push(summary);
194
+ }
195
+ if (parts.length > 0) {
196
+ lines.push(`Last: ${parts.join(', ')}`);
197
+ }
198
+ }
199
+ // Tip line: always show a call-to-action so non-TTY output is actionable
200
+ lines.push(`Tip: run "dual-brain --help" or "dual-brain go \\"task\\""`);
201
+ return lines.join('\n');
202
+ }
203
+ // ─── Replit-tools session import ──────���───────────────────────────────────────
204
+ const ARCHIVE_BASE = '/home/runner/workspace/.replit-tools/.session-archive/claude';
205
+ const ARCHIVE_PROJECTS = `${ARCHIVE_BASE}/projects/-home-runner-workspace`;
206
+ /**
207
+ * Returns true if the text looks like a real user prompt (not a status line,
208
+ * slash command, paste marker, or agent-generated noise).
209
+ */
210
+ function isRealPrompt(text) {
211
+ if (!text || !text.trim())
212
+ return false;
213
+ const t = text.trim();
214
+ if (/^[✅❌📦🔗⚠️🚀🎉🔧📝]/.test(t))
215
+ return false;
216
+ if (/Claude (history|binary|versions) symlink/.test(t))
217
+ return false;
218
+ if (t.startsWith('# AGENTS.md'))
219
+ return false;
220
+ if (t === 'login' || t === 'logout')
221
+ return false;
222
+ if (t.startsWith('/'))
223
+ return false;
224
+ if (t.startsWith('[Pasted'))
225
+ return false;
226
+ if (t.startsWith('<'))
227
+ return false;
228
+ if (t.startsWith('[Request interrupted'))
229
+ return false;
230
+ return true;
231
+ }
232
+ /**
233
+ * Extract the text content from a user message entry.
234
+ * Handles string content and content-block arrays.
235
+ */
236
+ function extractMessageText(entry) {
237
+ if (!entry)
238
+ return '';
239
+ const message = entry.message;
240
+ const content = message?.content;
241
+ if (typeof content === 'string')
242
+ return content;
243
+ if (Array.isArray(content))
244
+ return content.map((c) => c.text || '').join(' ');
245
+ return '';
246
+ }
247
+ /**
248
+ * Compute recency multiplier: today=2x, this week=1.5x, older=1x
249
+ */
250
+ function recencyMultiplier(dateOrTs) {
251
+ const ts = typeof dateOrTs === 'number' ? dateOrTs : Date.parse(dateOrTs);
252
+ if (!ts)
253
+ return 1;
254
+ const age = Date.now() - ts;
255
+ const day = 86400000;
256
+ if (age < day)
257
+ return 2;
258
+ if (age < 7 * day)
259
+ return 1.5;
260
+ return 1;
261
+ }
262
+ /**
263
+ * Human-readable time-ago string from a Unix timestamp (ms).
264
+ */
265
+ function timeAgo(timestamp) {
266
+ const diff = Date.now() - timestamp;
267
+ const mins = Math.floor(diff / 60000);
268
+ if (mins < 1)
269
+ return 'just now';
270
+ if (mins < 60)
271
+ return `${mins}m ago`;
272
+ const hours = Math.floor(mins / 60);
273
+ if (hours < 24)
274
+ return `${hours}h ago`;
275
+ const days = Math.floor(hours / 24);
276
+ return `${days}d ago`;
277
+ }
278
+ /**
279
+ * Import sessions from replit-tools history.jsonl.
280
+ * Returns an array of session summary objects, sorted most-recent first.
281
+ * Returns [] gracefully if replit-tools is not present.
282
+ */
283
+ export function importReplitSessions(cwd = process.cwd()) {
284
+ const sessions = [];
285
+ // Check multiple possible locations for replit-tools
286
+ const candidates = [
287
+ join(cwd, '.replit-tools', '.claude-persistent'),
288
+ join('/home/runner/workspace', '.replit-tools', '.claude-persistent'),
289
+ ];
290
+ // Deduplicate
291
+ const seen = new Set();
292
+ const replitBases = candidates.filter(p => {
293
+ const norm = p.replace(/\/+$/, '');
294
+ if (seen.has(norm))
295
+ return false;
296
+ seen.add(norm);
297
+ return true;
298
+ });
299
+ let replitBase = null;
300
+ for (const candidate of replitBases) {
301
+ if (existsSync(join(candidate, 'history.jsonl'))) {
302
+ replitBase = candidate;
303
+ break;
304
+ }
305
+ }
306
+ if (!replitBase)
307
+ return sessions;
308
+ // Read history.jsonl
309
+ const historyPath = join(replitBase, 'history.jsonl');
310
+ let lines;
311
+ try {
312
+ lines = readFileSync(historyPath, 'utf8').split('\n').filter(Boolean);
313
+ }
314
+ catch {
315
+ return sessions;
316
+ }
317
+ const bySession = new Map();
318
+ for (const line of lines) {
319
+ try {
320
+ const entry = JSON.parse(line);
321
+ if (!entry.sessionId)
322
+ continue;
323
+ const sessionId = entry.sessionId;
324
+ if (!bySession.has(sessionId)) {
325
+ bySession.set(sessionId, {
326
+ sessionId,
327
+ project: entry.project,
328
+ entries: [],
329
+ firstPrompt: null,
330
+ lastTimestamp: 0,
331
+ });
332
+ }
333
+ const sess = bySession.get(sessionId);
334
+ sess.entries.push(entry);
335
+ if (entry.timestamp > sess.lastTimestamp)
336
+ sess.lastTimestamp = entry.timestamp;
337
+ // Find first meaningful user prompt
338
+ if (!sess.firstPrompt && isRealPrompt(entry.display)) {
339
+ sess.firstPrompt = entry.display;
340
+ }
341
+ }
342
+ catch {
343
+ continue;
344
+ }
345
+ }
346
+ // Also read from the session archive as a fallback (contains cleaned-up sessions)
347
+ const archivePath = join(cwd, '.replit-tools', '.session-archive', 'claude', 'history.jsonl');
348
+ let archiveLines = [];
349
+ try {
350
+ if (existsSync(archivePath)) {
351
+ archiveLines = readFileSync(archivePath, 'utf8').split('\n').filter(Boolean);
352
+ }
353
+ }
354
+ catch { /* non-fatal */ }
355
+ for (const line of archiveLines) {
356
+ try {
357
+ const entry = JSON.parse(line);
358
+ if (!entry.sessionId)
359
+ continue;
360
+ const sessionId = entry.sessionId;
361
+ if (bySession.has(sessionId))
362
+ continue; // already indexed from main history
363
+ bySession.set(sessionId, {
364
+ sessionId,
365
+ project: entry.project,
366
+ entries: [],
367
+ firstPrompt: null,
368
+ lastTimestamp: 0,
369
+ });
370
+ const sess = bySession.get(sessionId);
371
+ sess.entries.push(entry);
372
+ if (entry.timestamp > sess.lastTimestamp)
373
+ sess.lastTimestamp = entry.timestamp;
374
+ if (!sess.firstPrompt && isRealPrompt(entry.display)) {
375
+ sess.firstPrompt = entry.display;
376
+ }
377
+ }
378
+ catch {
379
+ continue;
380
+ }
381
+ }
382
+ // For archive sessions with multiple entries, finish accumulating them
383
+ // (second pass for sessions newly added from archive)
384
+ for (const line of archiveLines) {
385
+ try {
386
+ const entry = JSON.parse(line);
387
+ if (!entry.sessionId)
388
+ continue;
389
+ const sessionId = entry.sessionId;
390
+ const sess = bySession.get(sessionId);
391
+ if (!sess)
392
+ continue;
393
+ // Already pushed in first pass for new sessions; skip double-push
394
+ if (sess.entries.includes(entry))
395
+ continue;
396
+ sess.entries.push(entry);
397
+ if (entry.timestamp > sess.lastTimestamp)
398
+ sess.lastTimestamp = entry.timestamp;
399
+ if (!sess.firstPrompt && isRealPrompt(entry.display)) {
400
+ sess.firstPrompt = entry.display;
401
+ }
402
+ }
403
+ catch {
404
+ continue;
405
+ }
406
+ }
407
+ // Scan ~/.codex/sessions/ for codex session JSONLs (YYYY/MM/DD tree)
408
+ const codexSessionsDir = join(process.env.HOME || '/root', '.codex', 'sessions');
409
+ if (existsSync(codexSessionsDir)) {
410
+ try {
411
+ const walk = (dir) => {
412
+ let results = [];
413
+ try {
414
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
415
+ const full = join(dir, entry.name);
416
+ if (entry.isDirectory())
417
+ results = results.concat(walk(full));
418
+ else if (entry.isFile() && entry.name.endsWith('.jsonl'))
419
+ results.push(full);
420
+ }
421
+ }
422
+ catch { }
423
+ return results;
424
+ };
425
+ for (const f of walk(codexSessionsDir)) {
426
+ try {
427
+ const content = readFileSync(f, 'utf8');
428
+ const fileLines = content.split('\n').filter(Boolean);
429
+ if (!fileLines.length)
430
+ continue;
431
+ const meta = JSON.parse(fileLines[0]);
432
+ if (meta.type !== 'session_meta' || !meta.payload)
433
+ continue;
434
+ const payload = meta.payload;
435
+ if (payload.cwd !== cwd && payload.cwd !== '/home/runner/workspace')
436
+ continue;
437
+ const id = payload.id;
438
+ if (bySession.has(id))
439
+ continue;
440
+ let firstPrompt = null;
441
+ let lastTimestamp = Date.parse(payload.timestamp || meta.timestamp) / 1000;
442
+ for (const ln of fileLines) {
443
+ try {
444
+ const j = JSON.parse(ln);
445
+ if (j.timestamp) {
446
+ const ts = Date.parse(j.timestamp) / 1000;
447
+ if (ts > lastTimestamp)
448
+ lastTimestamp = ts;
449
+ }
450
+ if (!firstPrompt && j.type === 'event_msg') {
451
+ const jPayload = j.payload;
452
+ if (jPayload?.type === 'user_message') {
453
+ const text = (jPayload.message || '').trim();
454
+ if (text)
455
+ firstPrompt = text;
456
+ }
457
+ }
458
+ }
459
+ catch {
460
+ continue;
461
+ }
462
+ }
463
+ bySession.set(id, {
464
+ sessionId: id,
465
+ project: '-home-runner-workspace',
466
+ entries: [],
467
+ firstPrompt: firstPrompt || id.slice(0, 8) + '...',
468
+ lastTimestamp,
469
+ tool: 'codex',
470
+ });
471
+ }
472
+ catch {
473
+ continue;
474
+ }
475
+ }
476
+ }
477
+ catch { /* non-fatal */ }
478
+ }
479
+ // Read active terminal sessions
480
+ // Use the same root as replitBase (go up one level from .claude-persistent)
481
+ const replitRoot = join(replitBase, '..');
482
+ const sessionsDir = join(replitRoot, '..', '.claude-sessions');
483
+ const activeSessionIds = new Set();
484
+ if (existsSync(sessionsDir)) {
485
+ try {
486
+ for (const f of readdirSync(sessionsDir)) {
487
+ try {
488
+ const data = JSON.parse(readFileSync(join(sessionsDir, f), 'utf8'));
489
+ if (data.sessionId)
490
+ activeSessionIds.add(data.sessionId);
491
+ }
492
+ catch {
493
+ continue;
494
+ }
495
+ }
496
+ }
497
+ catch { /* non-fatal */ }
498
+ }
499
+ // Determine recency window from config (default 48 hours)
500
+ const configPath = join(cwd, '.replit-tools', 'config.json');
501
+ let windowHours = 48;
502
+ try {
503
+ if (existsSync(configPath)) {
504
+ const cfg = JSON.parse(readFileSync(configPath, 'utf8'));
505
+ windowHours = cfg.recentWindowHours || 48;
506
+ }
507
+ }
508
+ catch { /* non-fatal */ }
509
+ const windowMs = windowHours * 60 * 60 * 1000;
510
+ const cutoff = Date.now() - windowMs;
511
+ // Load existing session index for smartName lookup (best-effort, non-fatal)
512
+ let sessionIndex = {};
513
+ try {
514
+ const indexPath = join(cwd, '.dualbrain', 'session-index.json');
515
+ if (existsSync(indexPath)) {
516
+ sessionIndex = JSON.parse(readFileSync(indexPath, 'utf8'));
517
+ }
518
+ }
519
+ catch { /* non-fatal */ }
520
+ // Build session list
521
+ for (const [id, sess] of bySession) {
522
+ // Skip sessions outside the recency window (timestamps are in ms)
523
+ if (sess.lastTimestamp < cutoff)
524
+ continue;
525
+ // Use smartName from index if available, otherwise fall back to first prompt
526
+ let name = sessionIndex[id]?.smartName || null;
527
+ if (!name) {
528
+ // Classic fallback: first meaningful prompt
529
+ name = sess.firstPrompt;
530
+ if (!name) {
531
+ const firstReal = sess.entries.find(e => e.display && e.display !== 'login');
532
+ name = firstReal?.display || `Session ${id.slice(0, 8)}`;
533
+ }
534
+ // Truncate long names that came from raw prompts
535
+ if (name.length > 60)
536
+ name = name.slice(0, 57) + '...';
537
+ }
538
+ sessions.push({
539
+ id: sess.sessionId,
540
+ name,
541
+ smartName: sessionIndex[id]?.smartName || null,
542
+ project: sess.project,
543
+ promptCount: sess.entries.length,
544
+ lastActive: new Date(sess.lastTimestamp).toISOString(),
545
+ isActive: activeSessionIds.has(id),
546
+ source: 'replit-tools',
547
+ age: timeAgo(sess.lastTimestamp),
548
+ tool: sess.tool || 'claude',
549
+ });
550
+ }
551
+ // Sort by most recent first
552
+ sessions.sort((a, b) => new Date(b.lastActive).getTime() - new Date(a.lastActive).getTime());
553
+ return sessions;
554
+ }
555
+ // ─── Session metadata overlay ─────────────────────────────────────────────────
556
+ const SESSION_META_FILE = '.dualbrain/sessions.json';
557
+ function sessionMetaPath(cwd) {
558
+ return join(cwd ?? process.cwd(), SESSION_META_FILE);
559
+ }
560
+ export function getSessionMeta(cwd = process.cwd()) {
561
+ const p = sessionMetaPath(cwd);
562
+ if (!existsSync(p))
563
+ return {};
564
+ try {
565
+ return JSON.parse(readFileSync(p, 'utf8'));
566
+ }
567
+ catch {
568
+ return {};
569
+ }
570
+ }
571
+ export function saveSessionMeta(meta, cwd = process.cwd()) {
572
+ ensureDir(cwd);
573
+ const p = sessionMetaPath(cwd);
574
+ const tmp = p + '.tmp.' + process.pid;
575
+ writeFileSync(tmp, JSON.stringify(meta, null, 2) + '\n');
576
+ renameSync(tmp, p);
577
+ }
578
+ // ─── Archive support ──────────────────────────────────────────────────────────
579
+ const ARCHIVE_FILE = '.dualbrain/archive/sessions.json';
580
+ function archivePath(cwd) {
581
+ return join(cwd ?? process.cwd(), ARCHIVE_FILE);
582
+ }
583
+ /**
584
+ * Archive a session — moves it from active sessions.json to archive/sessions.json.
585
+ * The session data stays in the index (searchable), just flagged as archived.
586
+ * Non-destructive and reversible.
587
+ */
588
+ export function archiveSession(sessionId, cwd = process.cwd()) {
589
+ // Load active sessions meta
590
+ const meta = getSessionMeta(cwd);
591
+ const existing = meta[sessionId] ?? {};
592
+ // Load or init archive
593
+ const ap = archivePath(cwd);
594
+ mkdirSync(dirname(ap), { recursive: true });
595
+ let archive = [];
596
+ try {
597
+ if (existsSync(ap))
598
+ archive = JSON.parse(readFileSync(ap, 'utf8'));
599
+ }
600
+ catch {
601
+ archive = [];
602
+ }
603
+ // Avoid duplicates
604
+ if (!archive.some(s => s.id === sessionId)) {
605
+ archive.push({
606
+ ...existing,
607
+ id: sessionId,
608
+ archived: true,
609
+ archivedAt: new Date().toISOString(),
610
+ });
611
+ const tmp = ap + '.tmp.' + process.pid;
612
+ writeFileSync(tmp, JSON.stringify(archive, null, 2) + '\n');
613
+ renameSync(tmp, ap);
614
+ }
615
+ // Remove from active sessions.json
616
+ delete meta[sessionId];
617
+ saveSessionMeta(meta, cwd);
618
+ // Mark archived in the session index (best-effort)
619
+ try {
620
+ const indexPath = join(cwd ?? process.cwd(), '.dualbrain', 'session-index.json');
621
+ if (existsSync(indexPath)) {
622
+ const index = JSON.parse(readFileSync(indexPath, 'utf8'));
623
+ if (index[sessionId]) {
624
+ index[sessionId].archived = true;
625
+ writeFileSync(indexPath, JSON.stringify(index, null, 2) + '\n');
626
+ }
627
+ }
628
+ }
629
+ catch { /* non-fatal */ }
630
+ }
631
+ /**
632
+ * Return all archived sessions.
633
+ */
634
+ export function getArchivedSessions(cwd = process.cwd()) {
635
+ const ap = archivePath(cwd);
636
+ if (!existsSync(ap))
637
+ return [];
638
+ try {
639
+ return JSON.parse(readFileSync(ap, 'utf8'));
640
+ }
641
+ catch {
642
+ return [];
643
+ }
644
+ }
645
+ export function renameSession(sessionId, name, cwd = process.cwd()) {
646
+ const meta = getSessionMeta(cwd);
647
+ meta[sessionId] = { ...meta[sessionId], name, createdAt: meta[sessionId]?.createdAt ?? new Date().toISOString() };
648
+ saveSessionMeta(meta, cwd);
649
+ }
650
+ export function pinSession(sessionId, cwd = process.cwd()) {
651
+ const meta = getSessionMeta(cwd);
652
+ meta[sessionId] = { ...meta[sessionId], pinned: true, createdAt: meta[sessionId]?.createdAt ?? new Date().toISOString() };
653
+ saveSessionMeta(meta, cwd);
654
+ }
655
+ export function unpinSession(sessionId, cwd = process.cwd()) {
656
+ const meta = getSessionMeta(cwd);
657
+ meta[sessionId] = { ...meta[sessionId], pinned: false };
658
+ saveSessionMeta(meta, cwd);
659
+ }
660
+ export function categorizeSession(sessionId, category, cwd = process.cwd()) {
661
+ const meta = getSessionMeta(cwd);
662
+ meta[sessionId] = { ...meta[sessionId], category, createdAt: meta[sessionId]?.createdAt ?? new Date().toISOString() };
663
+ saveSessionMeta(meta, cwd);
664
+ }
665
+ const AUTO_LABEL_RULES = [
666
+ { keywords: ['auth', 'login', 'credential', 'security', 'token'], label: 'security' },
667
+ { keywords: ['ui', 'css', 'style', 'component', 'react', 'frontend'], label: 'ui' },
668
+ { keywords: ['refactor', 'cleanup', 'rename', 'reorganize'], label: 'refactor' },
669
+ { keywords: ['bug', 'fix', 'error', 'crash', 'broken'], label: 'bugfix' },
670
+ { keywords: ['test', 'spec', 'coverage'], label: 'testing' },
671
+ { keywords: ['deploy', 'ci', 'build', 'release'], label: 'devops' },
672
+ { keywords: ['plan', 'design', 'architect', 'brainstorm'], label: 'planning' },
673
+ ];
674
+ export function autoLabel(session) {
675
+ const text = (session.name || '').toLowerCase();
676
+ for (const { keywords, label } of AUTO_LABEL_RULES) {
677
+ if (keywords.some(kw => new RegExp(`\\b${kw}\\b`).test(text)))
678
+ return label;
679
+ }
680
+ return null;
681
+ }
682
+ export function enrichSessions(sessions, cwd = process.cwd()) {
683
+ const meta = getSessionMeta(cwd);
684
+ const enriched = sessions.map(sess => {
685
+ const overlay = meta[sess.id] ?? {};
686
+ const category = overlay.category ?? autoLabel({ ...sess, name: overlay.name ?? sess.name });
687
+ return {
688
+ ...sess,
689
+ name: overlay.name ?? sess.name,
690
+ pinned: overlay.pinned ?? false,
691
+ category: category ?? null,
692
+ };
693
+ });
694
+ enriched.sort((a, b) => {
695
+ if (a.pinned && !b.pinned)
696
+ return -1;
697
+ if (!a.pinned && b.pinned)
698
+ return 1;
699
+ return new Date(b.lastActive).getTime() - new Date(a.lastActive).getTime();
700
+ });
701
+ return enriched;
702
+ }
703
+ // ─── Persistence settings ─────────────────────────────────────────────────────
704
+ /**
705
+ * Ensure Claude and Codex are configured to retain session history indefinitely.
706
+ * Mirrors what replit-tools does to prevent session cleanup/deletion.
707
+ */
708
+ export function ensurePersistence(cwd = process.cwd()) {
709
+ const home = process.env.HOME || '/root';
710
+ const results = [];
711
+ // 1. Claude: set cleanupPeriodDays
712
+ const claudeSettingsPaths = [
713
+ join(home, '.claude', 'settings.json'),
714
+ join(cwd, '.replit-tools', '.claude-persistent', 'settings.json'),
715
+ ];
716
+ for (const settingsPath of claudeSettingsPaths) {
717
+ if (!existsSync(settingsPath))
718
+ continue;
719
+ try {
720
+ let settings = {};
721
+ try {
722
+ settings = JSON.parse(readFileSync(settingsPath, 'utf8'));
723
+ }
724
+ catch {
725
+ settings = {};
726
+ }
727
+ if (settings.cleanupPeriodDays !== 365250) {
728
+ settings.cleanupPeriodDays = 365250;
729
+ writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
730
+ results.push('Claude cleanupPeriodDays set to 365250');
731
+ }
732
+ break; // only update one
733
+ }
734
+ catch {
735
+ continue;
736
+ }
737
+ }
738
+ // 2. Codex: set history.persistence and max_bytes
739
+ const codexConfigPaths = [
740
+ join(home, '.codex', 'config.toml'),
741
+ join(cwd, '.replit-tools', '.codex-persistent', 'config.toml'),
742
+ ];
743
+ for (const configPath of codexConfigPaths) {
744
+ if (!existsSync(configPath))
745
+ continue;
746
+ try {
747
+ let content = readFileSync(configPath, 'utf8');
748
+ let changed = false;
749
+ if (!/\[history\]/.test(content)) {
750
+ content = content.trimEnd() + '\n\n[history]\npersistence = "save-all"\nmax_bytes = 104857600\n';
751
+ changed = true;
752
+ }
753
+ else {
754
+ if (!/persistence\s*=/.test(content)) {
755
+ content = content.replace(/\[history\](\s*)/, '[history]$1persistence = "save-all"\n');
756
+ changed = true;
757
+ }
758
+ if (!/max_bytes\s*=/.test(content)) {
759
+ content = content.replace(/(persistence\s*=\s*"[^"]*"\s*\n)/, '$1max_bytes = 104857600\n');
760
+ changed = true;
761
+ }
762
+ }
763
+ if (changed) {
764
+ writeFileSync(configPath, content);
765
+ results.push('Codex history persistence enabled');
766
+ }
767
+ break;
768
+ }
769
+ catch {
770
+ continue;
771
+ }
772
+ }
773
+ return results;
774
+ }
775
+ // ─── Session archive mirror sync ─���───────────────────────────────────────────
776
+ /**
777
+ * Append-only mirror sync for Claude/Codex sessions (matches what replit-tools does).
778
+ * Files in the mirror only grow — if the source deletes a session, the mirror still has it.
779
+ */
780
+ export function syncSessionMirror(cwd = process.cwd()) {
781
+ const home = process.env.HOME || '/root';
782
+ const mirrorBase = join(cwd, '.replit-tools', '.session-archive');
783
+ // Check if replit-tools exists
784
+ if (!existsSync(join(cwd, '.replit-tools')))
785
+ return { copied: 0, grew: 0 };
786
+ // Check config — mirror can be disabled
787
+ const configPath = join(cwd, '.replit-tools', 'config.json');
788
+ try {
789
+ if (existsSync(configPath)) {
790
+ const cfg = JSON.parse(readFileSync(configPath, 'utf8'));
791
+ const mirror = cfg.mirror;
792
+ if (mirror && mirror.enabled === false)
793
+ return { copied: 0, grew: 0, disabled: true };
794
+ }
795
+ }
796
+ catch { }
797
+ let totalCopied = 0, totalGrew = 0;
798
+ function syncTree(srcDir, destDir) {
799
+ if (!existsSync(srcDir))
800
+ return;
801
+ function walk(dir) {
802
+ let entries;
803
+ try {
804
+ entries = readdirSync(dir, { withFileTypes: true });
805
+ }
806
+ catch {
807
+ return;
808
+ }
809
+ for (const entry of entries) {
810
+ const srcPath = join(dir, entry.name);
811
+ const relPath = srcPath.slice(srcDir.length);
812
+ const destPath = join(destDir, relPath);
813
+ if (entry.isDirectory()) {
814
+ try {
815
+ mkdirSync(destPath, { recursive: true });
816
+ }
817
+ catch { }
818
+ walk(srcPath);
819
+ }
820
+ else if (entry.isFile()) {
821
+ let destSize = 0;
822
+ try {
823
+ destSize = statSync(destPath).size;
824
+ }
825
+ catch { }
826
+ let srcSize = 0;
827
+ try {
828
+ srcSize = statSync(srcPath).size;
829
+ }
830
+ catch {
831
+ continue;
832
+ }
833
+ // Append-only: only copy if source is larger than mirror
834
+ if (srcSize > destSize) {
835
+ try {
836
+ mkdirSync(dirname(destPath), { recursive: true });
837
+ copyFileSync(srcPath, destPath);
838
+ if (destSize === 0)
839
+ totalCopied++;
840
+ else
841
+ totalGrew++;
842
+ }
843
+ catch { }
844
+ }
845
+ }
846
+ }
847
+ }
848
+ walk(srcDir);
849
+ }
850
+ try {
851
+ mkdirSync(mirrorBase, { recursive: true });
852
+ }
853
+ catch { }
854
+ // Sync Claude sessions
855
+ const claudeDir = join(home, '.claude');
856
+ syncTree(join(claudeDir, 'projects'), join(mirrorBase, 'claude', 'projects'));
857
+ // Sync history.jsonl as a single file
858
+ const histSrc = join(claudeDir, 'history.jsonl');
859
+ const histDest = join(mirrorBase, 'claude', 'history.jsonl');
860
+ if (existsSync(histSrc)) {
861
+ try {
862
+ const srcSize = statSync(histSrc).size;
863
+ let destSize = 0;
864
+ try {
865
+ destSize = statSync(histDest).size;
866
+ }
867
+ catch { }
868
+ if (srcSize > destSize) {
869
+ mkdirSync(dirname(histDest), { recursive: true });
870
+ copyFileSync(histSrc, histDest);
871
+ if (destSize === 0)
872
+ totalCopied++;
873
+ else
874
+ totalGrew++;
875
+ }
876
+ }
877
+ catch { }
878
+ }
879
+ // Sync Codex sessions
880
+ const codexDir = join(home, '.codex');
881
+ syncTree(join(codexDir, 'sessions'), join(mirrorBase, 'codex', 'sessions'));
882
+ return { copied: totalCopied, grew: totalGrew };
883
+ }
884
+ // ─── Smart session naming ────────────────────────────────────���────────────────
885
+ /**
886
+ * File pattern → human label mapping (checked in order, first match wins).
887
+ */
888
+ const FILE_PATTERN_RULES = [
889
+ { pattern: /auth/i, label: 'Auth', action: 'Refactor' },
890
+ { pattern: /test|spec/i, label: 'Tests', action: 'Fix' },
891
+ { pattern: /dispatch/i, label: 'Dispatch', action: 'Update' },
892
+ { pattern: /session/i, label: 'Session', action: 'Update' },
893
+ { pattern: /profile/i, label: 'Profile', action: 'Update' },
894
+ { pattern: /detect/i, label: 'Detection', action: 'Update' },
895
+ { pattern: /decide/i, label: 'Routing', action: 'Update' },
896
+ { pattern: /budget/i, label: 'Budget', action: 'Update' },
897
+ { pattern: /hook/i, label: 'Hooks', action: 'Update' },
898
+ { pattern: /install/i, label: 'Install', action: 'Update' },
899
+ { pattern: /config/i, label: 'Config', action: 'Update' },
900
+ { pattern: /migrate/i, label: 'Migration', action: 'Add' },
901
+ ];
902
+ /**
903
+ * Topic words that suggest a dominant action verb.
904
+ */
905
+ const TOPIC_ACTION_MAP = [
906
+ { words: ['fix', 'bug', 'error', 'crash', 'broken', 'fail'], action: 'Fix' },
907
+ { words: ['refactor', 'cleanup', 'clean', 'reorganize'], action: 'Refactor' },
908
+ { words: ['add', 'implement', 'create', 'build', 'write'], action: 'Add' },
909
+ { words: ['update', 'upgrade', 'bump', 'patch'], action: 'Update' },
910
+ { words: ['test', 'spec', 'coverage'], action: 'Fix' },
911
+ { words: ['deploy', 'release', 'publish'], action: 'Deploy' },
912
+ { words: ['audit', 'review', 'check'], action: 'Review' },
913
+ ];
914
+ /**
915
+ * Convert a string to Title Case.
916
+ */
917
+ function toTitleCase(str) {
918
+ return str.replace(/\b\w/g, c => c.toUpperCase());
919
+ }
920
+ /**
921
+ * Strip file extensions from a name candidate.
922
+ */
923
+ function stripExtensions(name) {
924
+ return name.replace(/\.(mjs|js|ts|tsx|jsx|json|md|css|html|py|sh|sql|toml|yaml|yml)\b/gi, '');
925
+ }
926
+ /**
927
+ * Truncate a string to maxLen characters, preserving whole words where possible.
928
+ */
929
+ function truncate(str, maxLen = 40) {
930
+ if (str.length <= maxLen)
931
+ return str;
932
+ const cut = str.slice(0, maxLen).replace(/\s+\S*$/, '');
933
+ return cut || str.slice(0, maxLen);
934
+ }
935
+ /**
936
+ * Generate a smart human-readable session name from session index data.
937
+ *
938
+ * Priority:
939
+ * 1. Dominant file pattern (e.g. auth*.mjs -> "Refactor Auth Module")
940
+ * 2. Top topics (e.g. ['auth','token','refresh'] -> "Auth Token Refresh")
941
+ * 3. Fallback: first prompt truncated to 40 chars
942
+ *
943
+ * Rules: <=40 chars, Title Case, no file extensions, action-prefixed when detectable.
944
+ */
945
+ export function generateSmartName(sessionData) {
946
+ const topics = sessionData.topics || [];
947
+ const files = sessionData.files || [];
948
+ const firstPrompt = sessionData.prompts?.first || '';
949
+ // ── Step 1: Detect dominant action from topics ─────────────────────────────
950
+ let detectedAction = null;
951
+ for (const { words, action } of TOPIC_ACTION_MAP) {
952
+ if (topics.some(t => words.includes(t))) {
953
+ detectedAction = action;
954
+ break;
955
+ }
956
+ }
957
+ // ── Step 2: Try file pattern match ─────────────────────────────────────────
958
+ if (files.length > 0) {
959
+ // Flatten all filenames for pattern matching
960
+ const fileNames = files.map(f => f.split('/').pop()).join(' ');
961
+ for (const { pattern, label, action } of FILE_PATTERN_RULES) {
962
+ if (pattern.test(fileNames)) {
963
+ const actionWord = detectedAction || action || 'Update';
964
+ const candidate = `${actionWord} ${label}`;
965
+ return truncate(toTitleCase(candidate));
966
+ }
967
+ }
968
+ // No named pattern — derive a label from the most common directory or base name
969
+ const basenames = files.map(f => {
970
+ const base = f.split('/').pop() || f;
971
+ // Strip extension and convert camelCase/kebab to words
972
+ return stripExtensions(base)
973
+ .replace(/[-_]/g, ' ')
974
+ .replace(/([a-z])([A-Z])/g, '$1 $2')
975
+ .trim();
976
+ }).filter(Boolean);
977
+ if (basenames.length > 0) {
978
+ // Use the most common prefix or first significant basename
979
+ const label = basenames[0];
980
+ const actionWord = detectedAction || 'Update';
981
+ const candidate = `${actionWord} ${label}`;
982
+ return truncate(toTitleCase(stripExtensions(candidate)));
983
+ }
984
+ }
985
+ // ── Step 3: Try top topics ─────────────────────────────────────────────────
986
+ if (topics.length >= 2) {
987
+ // Take top 3 topics and compose a name
988
+ const topTopics = topics.slice(0, 3);
989
+ const actionWord = detectedAction || null;
990
+ let candidate;
991
+ if (actionWord) {
992
+ // Use action + remaining topics
993
+ candidate = [actionWord, ...topTopics.filter(t => t !== actionWord.toLowerCase())].slice(0, 3).join(' ');
994
+ }
995
+ else {
996
+ candidate = topTopics.join(' ');
997
+ }
998
+ return truncate(toTitleCase(candidate));
999
+ }
1000
+ if (topics.length === 1) {
1001
+ const actionWord = detectedAction || 'Work on';
1002
+ return truncate(toTitleCase(`${actionWord} ${topics[0]}`));
1003
+ }
1004
+ // ── Step 4: Fallback — first prompt truncated ──────────────────────────────
1005
+ if (firstPrompt) {
1006
+ return truncate(firstPrompt);
1007
+ }
1008
+ return 'Session';
1009
+ }
1010
+ // ─── Session index ────────────────────────────────────────────────────────────
1011
+ /**
1012
+ * Build/update `.dualbrain/session-index.json` from Claude and Codex JSONL session files.
1013
+ * Extracts topics, file references, prompt snippets, and metadata per session.
1014
+ */
1015
+ export function buildSessionIndex(cwd = process.cwd()) {
1016
+ const home = process.env.HOME || '/root';
1017
+ const indexPath = join(cwd, '.dualbrain', 'session-index.json');
1018
+ // Load existing index
1019
+ let index = {};
1020
+ try {
1021
+ if (existsSync(indexPath)) {
1022
+ index = JSON.parse(readFileSync(indexPath, 'utf8'));
1023
+ }
1024
+ }
1025
+ catch { }
1026
+ // Find all session JSONLs
1027
+ const sources = [
1028
+ join(home, '.claude', 'projects', '-home-runner-workspace'),
1029
+ join(cwd, '.replit-tools', '.session-archive', 'claude', 'projects', '-home-runner-workspace'),
1030
+ ];
1031
+ const STOP_WORDS = new Set(['the', 'and', 'this', 'that', 'with', 'from', 'have', 'been', 'will', 'would', 'could', 'should', 'just', 'also', 'into', 'about', 'some', 'what', 'when', 'where', 'which', 'their', 'there', 'then', 'than', 'them', 'these', 'those', 'other', 'more', 'only', 'very', 'each', 'most', 'like', 'make', 'want', 'need', 'does', 'dont', 'didnt', 'cant', 'wont', 'your', 'they', 'were', 'are', 'for', 'not', 'but', 'was', 'you', 'all', 'can', 'had', 'her', 'one', 'our', 'out', 'use', 'its', 'let', 'get', 'has', 'him', 'his', 'how', 'did', 'got', 'may', 'new', 'now', 'old', 'see', 'way', 'who', 'any', 'few', 'said']);
1032
+ for (const dir of sources) {
1033
+ if (!existsSync(dir))
1034
+ continue;
1035
+ let files;
1036
+ try {
1037
+ files = readdirSync(dir);
1038
+ }
1039
+ catch {
1040
+ continue;
1041
+ }
1042
+ for (const f of files) {
1043
+ if (!f.endsWith('.jsonl') || f.startsWith('agent-'))
1044
+ continue;
1045
+ const sessionId = f.replace('.jsonl', '');
1046
+ // Skip if already indexed and file hasn't grown
1047
+ const filePath = join(dir, f);
1048
+ let fileSize = 0;
1049
+ try {
1050
+ fileSize = statSync(filePath).size;
1051
+ }
1052
+ catch {
1053
+ continue;
1054
+ }
1055
+ if (index[sessionId] && index[sessionId]._fileSize >= fileSize)
1056
+ continue;
1057
+ // Parse session
1058
+ try {
1059
+ const content = readFileSync(filePath, 'utf8');
1060
+ const lines = content.split('\n').filter(Boolean);
1061
+ const wordCounts = {};
1062
+ const fileSet = new Set();
1063
+ let firstPrompt = null;
1064
+ let lastPrompt = null;
1065
+ let lastTimestamp = 0;
1066
+ let messageCount = 0;
1067
+ for (const line of lines) {
1068
+ try {
1069
+ const entry = JSON.parse(line);
1070
+ // Track timestamps
1071
+ if (entry.timestamp) {
1072
+ const raw = typeof entry.timestamp === 'number' ? entry.timestamp : Date.parse(entry.timestamp);
1073
+ const ts = raw > 1e12 ? raw / 1000 : raw;
1074
+ if (ts > lastTimestamp)
1075
+ lastTimestamp = ts;
1076
+ }
1077
+ // Extract user messages
1078
+ let text = null;
1079
+ if (entry.type === 'user' && entry.message?.content) {
1080
+ const msgContent = entry.message.content;
1081
+ text = typeof msgContent === 'string'
1082
+ ? msgContent
1083
+ : msgContent?.[0]?.text ?? null;
1084
+ }
1085
+ if (entry.display)
1086
+ text = text || entry.display;
1087
+ if (!text)
1088
+ continue;
1089
+ messageCount++;
1090
+ if (!firstPrompt)
1091
+ firstPrompt = text.slice(0, 80);
1092
+ lastPrompt = text.slice(0, 80);
1093
+ // Extract file paths
1094
+ const filePaths = text.match(/[\w./~-]+\.(?:mjs|js|ts|tsx|jsx|json|md|css|html|py|sh|sql|toml|yaml|yml)\b/g);
1095
+ if (filePaths)
1096
+ filePaths.forEach(p => fileSet.add(p));
1097
+ // Count words for topics
1098
+ const words = text.toLowerCase().split(/\W+/).filter(w => w.length > 3 && !STOP_WORDS.has(w));
1099
+ for (const w of words) {
1100
+ wordCounts[w] = (wordCounts[w] || 0) + 1;
1101
+ }
1102
+ }
1103
+ catch {
1104
+ continue;
1105
+ }
1106
+ }
1107
+ // Top 10 topics by frequency
1108
+ const topics = Object.entries(wordCounts)
1109
+ .sort((a, b) => b[1] - a[1])
1110
+ .slice(0, 10)
1111
+ .map(([w]) => w);
1112
+ const sessionEntry = {
1113
+ id: sessionId,
1114
+ topics,
1115
+ files: [...fileSet].slice(0, 20),
1116
+ prompts: { first: firstPrompt || '', last: lastPrompt || '' },
1117
+ date: lastTimestamp ? new Date(lastTimestamp * 1000).toISOString() : null,
1118
+ messageCount,
1119
+ tool: 'claude',
1120
+ _fileSize: fileSize,
1121
+ };
1122
+ sessionEntry.smartName = generateSmartName(sessionEntry);
1123
+ index[sessionId] = sessionEntry;
1124
+ }
1125
+ catch {
1126
+ continue;
1127
+ }
1128
+ }
1129
+ }
1130
+ // Also index codex sessions (same pattern)
1131
+ const codexDir = join(home, '.codex', 'sessions');
1132
+ if (existsSync(codexDir)) {
1133
+ const walk = (dir) => {
1134
+ let results = [];
1135
+ try {
1136
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1137
+ const full = join(dir, entry.name);
1138
+ if (entry.isDirectory())
1139
+ results = results.concat(walk(full));
1140
+ else if (entry.isFile() && entry.name.endsWith('.jsonl'))
1141
+ results.push(full);
1142
+ }
1143
+ }
1144
+ catch { }
1145
+ return results;
1146
+ };
1147
+ for (const filePath of walk(codexDir)) {
1148
+ try {
1149
+ const content = readFileSync(filePath, 'utf8');
1150
+ const lines = content.split('\n').filter(Boolean);
1151
+ if (!lines.length)
1152
+ continue;
1153
+ const meta = JSON.parse(lines[0]);
1154
+ if (meta.type !== 'session_meta' || !meta.payload)
1155
+ continue;
1156
+ const payload = meta.payload;
1157
+ const id = payload.id;
1158
+ if (!id || index[id])
1159
+ continue;
1160
+ let fileSize = 0;
1161
+ try {
1162
+ fileSize = statSync(filePath).size;
1163
+ }
1164
+ catch {
1165
+ continue;
1166
+ }
1167
+ let firstPrompt = null, lastPrompt = null, messageCount = 0;
1168
+ let lastTimestamp = Date.parse(payload.timestamp || meta.timestamp) / 1000 || 0;
1169
+ for (const ln of lines) {
1170
+ try {
1171
+ const j = JSON.parse(ln);
1172
+ if (j.timestamp) {
1173
+ const ts = Date.parse(j.timestamp) / 1000;
1174
+ if (ts > lastTimestamp)
1175
+ lastTimestamp = ts;
1176
+ }
1177
+ if (j.type === 'event_msg') {
1178
+ const jPayload = j.payload;
1179
+ if (jPayload?.type === 'user_message') {
1180
+ const text = (jPayload.message || '').trim();
1181
+ if (text) {
1182
+ messageCount++;
1183
+ if (!firstPrompt)
1184
+ firstPrompt = text.slice(0, 80);
1185
+ lastPrompt = text.slice(0, 80);
1186
+ }
1187
+ }
1188
+ }
1189
+ }
1190
+ catch {
1191
+ continue;
1192
+ }
1193
+ }
1194
+ const codexEntry = {
1195
+ id, topics: [], files: [],
1196
+ prompts: { first: firstPrompt || '', last: lastPrompt || '' },
1197
+ date: lastTimestamp ? new Date(lastTimestamp * 1000).toISOString() : null,
1198
+ messageCount, tool: 'codex', _fileSize: fileSize,
1199
+ };
1200
+ codexEntry.smartName = generateSmartName(codexEntry);
1201
+ index[id] = codexEntry;
1202
+ }
1203
+ catch {
1204
+ continue;
1205
+ }
1206
+ }
1207
+ }
1208
+ // Save index
1209
+ try {
1210
+ mkdirSync(join(cwd, '.dualbrain'), { recursive: true });
1211
+ writeFileSync(indexPath, JSON.stringify(index, null, 2));
1212
+ }
1213
+ catch { }
1214
+ return index;
1215
+ }
1216
+ /**
1217
+ * Search sessions using the replit-tools archive as primary source.
1218
+ * Falls back to the parallel session index when archive is unavailable.
1219
+ *
1220
+ * Results include: { sessionId, date, relevance, files, summary, matchingLines }
1221
+ * Sorted by relevance * recencyMultiplier descending.
1222
+ */
1223
+ export function searchSessions(query, cwd = process.cwd()) {
1224
+ const terms = query.toLowerCase().split(/\W+/).filter(Boolean);
1225
+ if (!terms.length)
1226
+ return [];
1227
+ // Try archive-backed search first
1228
+ const archiveResults = archiveBackedSearch(terms, cwd);
1229
+ if (archiveResults.length > 0)
1230
+ return archiveResults;
1231
+ // Fallback: parallel index
1232
+ const indexPath = join(cwd, '.dualbrain', 'session-index.json');
1233
+ let index = {};
1234
+ try {
1235
+ index = JSON.parse(readFileSync(indexPath, 'utf8'));
1236
+ }
1237
+ catch { }
1238
+ if (Object.keys(index).length === 0)
1239
+ index = buildSessionIndex(cwd);
1240
+ const results = [];
1241
+ for (const session of Object.values(index)) {
1242
+ let score = 0;
1243
+ const searchText = [
1244
+ ...(session.topics || []),
1245
+ ...(session.files || []),
1246
+ session.prompts?.first || '',
1247
+ session.prompts?.last || '',
1248
+ ].join(' ').toLowerCase();
1249
+ for (const term of terms) {
1250
+ if (searchText.includes(term))
1251
+ score++;
1252
+ if ((session.topics || []).includes(term))
1253
+ score += 2;
1254
+ if ((session.files || []).some(f => f.includes(term)))
1255
+ score += 2;
1256
+ }
1257
+ if (score > 0) {
1258
+ const mult = recencyMultiplier(session.date || '');
1259
+ results.push({
1260
+ sessionId: session.id,
1261
+ date: session.date,
1262
+ relevance: score,
1263
+ _score: score * mult,
1264
+ files: session.files || [],
1265
+ summary: (session.prompts?.first || session.id).slice(0, 100),
1266
+ matchingLines: [],
1267
+ messageCount: session.messageCount,
1268
+ });
1269
+ }
1270
+ }
1271
+ return results.sort((a, b) => b._score - a._score);
1272
+ }
1273
+ /**
1274
+ * Search session JSONL files in the archive directly (streaming, no full load).
1275
+ */
1276
+ function archiveBackedSearch(terms, cwd) {
1277
+ const projectDir = existsSync(ARCHIVE_PROJECTS) ? ARCHIVE_PROJECTS
1278
+ : join(cwd, '.replit-tools', '.session-archive', 'claude', 'projects', '-home-runner-workspace');
1279
+ if (!existsSync(projectDir))
1280
+ return [];
1281
+ let files;
1282
+ try {
1283
+ files = readdirSync(projectDir).filter(f => f.endsWith('.jsonl') && !f.startsWith('agent-'));
1284
+ }
1285
+ catch {
1286
+ return [];
1287
+ }
1288
+ const results = [];
1289
+ for (const file of files) {
1290
+ const sessionId = file.replace(/\.jsonl$/, '');
1291
+ const filePath = join(projectDir, file);
1292
+ let content;
1293
+ try {
1294
+ content = readFileSync(filePath, 'utf8');
1295
+ }
1296
+ catch {
1297
+ continue;
1298
+ }
1299
+ const lines = content.split('\n').filter(Boolean);
1300
+ const matchingLines = [];
1301
+ const fileSet = new Set();
1302
+ let firstPrompt = null;
1303
+ let lastTimestamp = 0;
1304
+ let messageCount = 0;
1305
+ let baseScore = 0;
1306
+ for (const line of lines) {
1307
+ let entry;
1308
+ try {
1309
+ entry = JSON.parse(line);
1310
+ }
1311
+ catch {
1312
+ continue;
1313
+ }
1314
+ // Track timestamps
1315
+ if (entry.timestamp) {
1316
+ const ts = typeof entry.timestamp === 'number'
1317
+ ? (entry.timestamp > 1e12 ? entry.timestamp : entry.timestamp * 1000)
1318
+ : Date.parse(entry.timestamp);
1319
+ if (ts > lastTimestamp)
1320
+ lastTimestamp = ts;
1321
+ }
1322
+ if (entry.type !== 'user')
1323
+ continue;
1324
+ const text = extractMessageText(entry);
1325
+ if (!text)
1326
+ continue;
1327
+ messageCount++;
1328
+ if (!firstPrompt && isRealPrompt(text))
1329
+ firstPrompt = text;
1330
+ // Extract file references
1331
+ const filePaths = text.match(/[\w./~-]+\.(?:mjs|js|ts|tsx|jsx|json|md|css|html|py|sh|sql|toml|yaml|yml)\b/g);
1332
+ if (filePaths)
1333
+ filePaths.forEach(p => fileSet.add(p));
1334
+ // Score against terms
1335
+ const lower = text.toLowerCase();
1336
+ let lineScore = 0;
1337
+ for (const term of terms) {
1338
+ if (lower.includes(term))
1339
+ lineScore++;
1340
+ }
1341
+ if (lineScore > 0) {
1342
+ baseScore += lineScore;
1343
+ const excerpt = text.slice(0, 500);
1344
+ matchingLines.push(excerpt);
1345
+ }
1346
+ }
1347
+ if (baseScore > 0) {
1348
+ const mult = recencyMultiplier(lastTimestamp);
1349
+ results.push({
1350
+ sessionId,
1351
+ date: lastTimestamp ? new Date(lastTimestamp).toISOString() : null,
1352
+ relevance: baseScore,
1353
+ _score: baseScore * mult,
1354
+ files: [...fileSet].slice(0, 20),
1355
+ summary: (firstPrompt || sessionId).slice(0, 100),
1356
+ matchingLines: matchingLines.slice(0, 5),
1357
+ messageCount,
1358
+ });
1359
+ }
1360
+ }
1361
+ return results.sort((a, b) => b._score - a._score);
1362
+ }
1363
+ /**
1364
+ * Find sessions related to a new task prompt and file list.
1365
+ * Uses the session index (topics + files) — does not parse full JSONL files.
1366
+ */
1367
+ export function findRelatedSessions(prompt, files = [], cwd = process.cwd()) {
1368
+ const indexPath = join(cwd, '.dualbrain', 'session-index.json');
1369
+ let index = {};
1370
+ try {
1371
+ index = JSON.parse(readFileSync(indexPath, 'utf8'));
1372
+ }
1373
+ catch {
1374
+ return [];
1375
+ }
1376
+ if (Object.keys(index).length === 0)
1377
+ return [];
1378
+ // Intent words for +1 scoring
1379
+ const INTENT_WORDS = ['fix', 'refactor', 'test', 'add', 'update', 'review', 'debug', 'build', 'remove', 'migrate', 'deploy', 'implement', 'create'];
1380
+ // Normalize the new task's prompt into words
1381
+ const promptLower = (prompt || '').toLowerCase();
1382
+ const promptWords = new Set(promptLower.split(/\W+/).filter(w => w.length > 3));
1383
+ // Normalize the new task's file paths for comparison
1384
+ const normalizeFile = (f) => (f || '').split('/').pop().toLowerCase().replace(/\.[^.]+$/, '');
1385
+ const newFileNames = new Set((files || []).map(normalizeFile).filter(Boolean));
1386
+ // One-hour cutoff for excluding likely-current session
1387
+ const oneHourAgo = Date.now() - 60 * 60 * 1000;
1388
+ const results = [];
1389
+ for (const session of Object.values(index)) {
1390
+ // Skip archived sessions
1391
+ if (session.archived)
1392
+ continue;
1393
+ // Skip sessions from the last hour
1394
+ const sessionTs = session.date ? Date.parse(session.date) : 0;
1395
+ if (sessionTs > oneHourAgo)
1396
+ continue;
1397
+ let score = 0;
1398
+ const matchedFiles = [];
1399
+ const matchedTopics = [];
1400
+ // +3 for each file in common
1401
+ for (const sessionFile of (session.files || [])) {
1402
+ const sessionFileName = normalizeFile(sessionFile);
1403
+ if (sessionFileName && newFileNames.has(sessionFileName)) {
1404
+ score += 3;
1405
+ matchedFiles.push(sessionFile);
1406
+ }
1407
+ }
1408
+ // +2 for each topic keyword in common with prompt words
1409
+ for (const topic of (session.topics || [])) {
1410
+ if (topic && promptWords.has(topic)) {
1411
+ score += 2;
1412
+ matchedTopics.push(topic);
1413
+ }
1414
+ }
1415
+ // +1 for matching intent words found in both prompt and session topics/prompts
1416
+ const sessionText = [
1417
+ ...(session.topics || []),
1418
+ session.prompts?.first || '',
1419
+ session.prompts?.last || '',
1420
+ ].join(' ').toLowerCase();
1421
+ for (const word of INTENT_WORDS) {
1422
+ if (promptLower.includes(word) && sessionText.includes(word)) {
1423
+ score += 1;
1424
+ break; // only +1 total for intent words
1425
+ }
1426
+ }
1427
+ if (score > 3) {
1428
+ results.push({
1429
+ sessionId: session.id,
1430
+ smartName: session.smartName || session.prompts?.first?.slice(0, 40) || session.id.slice(0, 8),
1431
+ score,
1432
+ matchedFiles,
1433
+ matchedTopics,
1434
+ date: session.date,
1435
+ messageCount: session.messageCount || 0,
1436
+ });
1437
+ }
1438
+ }
1439
+ // Return top 3 sorted by score descending
1440
+ return results
1441
+ .sort((a, b) => b.score - a.score)
1442
+ .slice(0, 3);
1443
+ }
1444
+ /**
1445
+ * Get detailed context for a session (for smart resume preview).
1446
+ * Reads the last 20 lines of the session JSONL to surface the most recent prompt
1447
+ * and files touched.
1448
+ */
1449
+ export function getSessionContext(sessionId, cwd = process.cwd()) {
1450
+ const home = process.env.HOME || '/root';
1451
+ const paths = [
1452
+ join(home, '.claude', 'projects', '-home-runner-workspace', sessionId + '.jsonl'),
1453
+ join(cwd, '.replit-tools', '.session-archive', 'claude', 'projects', '-home-runner-workspace', sessionId + '.jsonl'),
1454
+ ];
1455
+ let filePath = null;
1456
+ for (const p of paths) {
1457
+ if (existsSync(p)) {
1458
+ filePath = p;
1459
+ break;
1460
+ }
1461
+ }
1462
+ if (!filePath)
1463
+ return null;
1464
+ try {
1465
+ const content = readFileSync(filePath, 'utf8');
1466
+ const lines = content.split('\n').filter(Boolean);
1467
+ // Read last 20 lines for recent context
1468
+ const recentLines = lines.slice(-20);
1469
+ let lastUserPrompt = null;
1470
+ const filesSet = new Set();
1471
+ for (const line of recentLines) {
1472
+ try {
1473
+ const entry = JSON.parse(line);
1474
+ if (entry.type === 'user' && entry.message?.content) {
1475
+ const msgContent = entry.message.content;
1476
+ const text = typeof msgContent === 'string'
1477
+ ? msgContent
1478
+ : msgContent?.[0]?.text ?? null;
1479
+ if (text)
1480
+ lastUserPrompt = text.slice(0, 120);
1481
+ }
1482
+ if (entry.display)
1483
+ lastUserPrompt = entry.display.slice(0, 120);
1484
+ // Look for file edits in tool use
1485
+ if (entry.type === 'tool_use' || entry.type === 'tool_result') {
1486
+ const toolInput = entry.tool_input;
1487
+ const fp = toolInput?.file_path || toolInput?.path;
1488
+ if (fp)
1489
+ filesSet.add(fp.split('/').pop());
1490
+ }
1491
+ }
1492
+ catch {
1493
+ continue;
1494
+ }
1495
+ }
1496
+ return {
1497
+ lastPrompt: lastUserPrompt,
1498
+ filesTouched: [...filesSet].slice(0, 5),
1499
+ totalLines: lines.length,
1500
+ };
1501
+ }
1502
+ catch {
1503
+ return null;
1504
+ }
1505
+ }
1506
+ // ─── Archive-backed metadata extraction ──��───────────────────────────────────
1507
+ /**
1508
+ * Extract structured metadata from a session JSONL file.
1509
+ * Reads the file once; handles malformed entries gracefully.
1510
+ */
1511
+ export function extractSessionMeta(sessionFilePath) {
1512
+ const id = sessionFilePath.split('/').pop().replace(/\.jsonl$/, '');
1513
+ const result = { id, date: null, messageCount: 0, files: [], taskSummary: null, firstPrompt: null, lastPrompt: null, duration: null };
1514
+ let content;
1515
+ try {
1516
+ content = readFileSync(sessionFilePath, 'utf8');
1517
+ }
1518
+ catch {
1519
+ return result;
1520
+ }
1521
+ const fileSet = new Set();
1522
+ let minTs = Infinity;
1523
+ let maxTs = 0;
1524
+ for (const line of content.split('\n')) {
1525
+ if (!line)
1526
+ continue;
1527
+ let entry;
1528
+ try {
1529
+ entry = JSON.parse(line);
1530
+ }
1531
+ catch {
1532
+ continue;
1533
+ }
1534
+ // Timestamps
1535
+ if (entry.timestamp) {
1536
+ const ts = typeof entry.timestamp === 'number'
1537
+ ? (entry.timestamp > 1e12 ? entry.timestamp : entry.timestamp * 1000)
1538
+ : Date.parse(entry.timestamp);
1539
+ if (ts && ts < minTs)
1540
+ minTs = ts;
1541
+ if (ts && ts > maxTs)
1542
+ maxTs = ts;
1543
+ }
1544
+ if (entry.type !== 'user')
1545
+ continue;
1546
+ const text = extractMessageText(entry);
1547
+ if (!text || !text.trim())
1548
+ continue;
1549
+ result.messageCount++;
1550
+ // File paths (src/, bin/, common extensions)
1551
+ const filePaths = text.match(/[\w./~-]+\.(?:mjs|js|ts|tsx|jsx|json|md|css|html|py|sh|sql|toml|yaml|yml)\b/g);
1552
+ if (filePaths)
1553
+ filePaths.forEach(p => fileSet.add(p));
1554
+ // Also catch src/ or bin/ paths without extensions
1555
+ const dirPaths = text.match(/(?:src|bin|lib|test|tests|\.claude\/hooks)\/[\w./~-]+/g);
1556
+ if (dirPaths)
1557
+ dirPaths.forEach(p => fileSet.add(p));
1558
+ if (isRealPrompt(text)) {
1559
+ if (!result.firstPrompt) {
1560
+ result.firstPrompt = text.slice(0, 100);
1561
+ result.taskSummary = text.slice(0, 100);
1562
+ }
1563
+ result.lastPrompt = text.slice(0, 100);
1564
+ }
1565
+ }
1566
+ result.files = [...fileSet].slice(0, 30);
1567
+ if (maxTs)
1568
+ result.date = new Date(maxTs).toISOString();
1569
+ if (minTs !== Infinity && maxTs)
1570
+ result.duration = Math.round((maxTs - minTs) / 1000); // seconds
1571
+ return result;
1572
+ }
1573
+ // ─── Routing context from session history ────────────────────────────────────
1574
+ /**
1575
+ * Build routing context from recent sessions (last 7 days) related to a task.
1576
+ * Used by the dispatch pipeline to detect prior attempts and flag risk signals.
1577
+ */
1578
+ export function getRoutingContext(cwd, taskDescription) {
1579
+ const result = { relatedSessions: [], riskSignals: [], priorAttempts: [], relevantFiles: [] };
1580
+ const projectDir = existsSync(ARCHIVE_PROJECTS) ? ARCHIVE_PROJECTS
1581
+ : join(cwd, '.replit-tools', '.session-archive', 'claude', 'projects', '-home-runner-workspace');
1582
+ if (!existsSync(projectDir))
1583
+ return result;
1584
+ let files;
1585
+ try {
1586
+ files = readdirSync(projectDir).filter(f => f.endsWith('.jsonl') && !f.startsWith('agent-'));
1587
+ }
1588
+ catch {
1589
+ return result;
1590
+ }
1591
+ const taskLower = (taskDescription || '').toLowerCase();
1592
+ const taskTerms = taskLower.split(/\W+/).filter(w => w.length > 3);
1593
+ const sevenDaysAgo = Date.now() - 7 * 86400000;
1594
+ const fileSet = new Set();
1595
+ for (const file of files) {
1596
+ const filePath = join(projectDir, file);
1597
+ let meta;
1598
+ try {
1599
+ meta = extractSessionMeta(filePath);
1600
+ }
1601
+ catch {
1602
+ continue;
1603
+ }
1604
+ // Only consider last 7 days
1605
+ if (!meta.date || Date.parse(meta.date) < sevenDaysAgo)
1606
+ continue;
1607
+ // Score relevance to task
1608
+ const sessionText = [meta.firstPrompt || '', meta.lastPrompt || '', ...meta.files].join(' ').toLowerCase();
1609
+ let score = 0;
1610
+ for (const term of taskTerms) {
1611
+ if (sessionText.includes(term))
1612
+ score++;
1613
+ }
1614
+ if (score === 0)
1615
+ continue;
1616
+ // Collect relevant files
1617
+ meta.files.forEach(f => fileSet.add(f));
1618
+ const sessionEntry = {
1619
+ sessionId: meta.id,
1620
+ date: meta.date,
1621
+ taskSummary: meta.taskSummary,
1622
+ score,
1623
+ messageCount: meta.messageCount,
1624
+ files: meta.files,
1625
+ };
1626
+ result.relatedSessions.push(sessionEntry);
1627
+ // Detect prior attempts: same task keywords, short session (< 5 min or few messages)
1628
+ if (score >= 2 && ((meta.duration !== null && meta.duration < 300) || meta.messageCount < 3)) {
1629
+ result.priorAttempts.push({
1630
+ sessionId: meta.id,
1631
+ date: meta.date,
1632
+ summary: meta.taskSummary,
1633
+ likelyIncomplete: true,
1634
+ });
1635
+ result.riskSignals.push(`Prior attempt on similar task may have stalled (session ${meta.id.slice(0, 8)})`);
1636
+ }
1637
+ // Risk signal: auth/security keywords in related sessions
1638
+ if (/auth|secret|token|credential|password/.test(sessionText)) {
1639
+ result.riskSignals.push(`Related session ${meta.id.slice(0, 8)} touched auth/security code`);
1640
+ }
1641
+ }
1642
+ // Deduplicate risk signals
1643
+ result.riskSignals = [...new Set(result.riskSignals)];
1644
+ result.relevantFiles = [...fileSet].slice(0, 20);
1645
+ result.relatedSessions.sort((a, b) => b.score - a.score);
1646
+ result.relatedSessions = result.relatedSessions.slice(0, 5);
1647
+ return result;
1648
+ }
1649
+ // ─── CLI (direct invocation) ──��───────────────────────────────────────────────
1650
+ const isMain = process.argv[1]?.endsWith('session.mjs') || process.argv[1]?.endsWith('session.ts');
1651
+ if (isMain) {
1652
+ const session = loadSession(process.cwd());
1653
+ if (session) {
1654
+ process.stdout.write(JSON.stringify(session, null, 2) + '\n');
1655
+ }
1656
+ else {
1657
+ process.stdout.write('(no active session)\n');
1658
+ }
1659
+ }
1660
+ //# sourceMappingURL=session.js.map