@statforge/claudestat 1.5.0 → 1.6.0

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 (34) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +27 -4
  3. package/dashboard/dist/assets/{AnalyticsView-BApcOGsD.js → AnalyticsView-5bUM3UHp.js} +1 -1
  4. package/dashboard/dist/assets/{HistoryView-B331k5oL.js → HistoryView-C-AsEqos.js} +1 -1
  5. package/dashboard/dist/assets/{ProjectsView-DUleaXsP.js → ProjectsView-D9bZBdY2.js} +1 -1
  6. package/dashboard/dist/assets/{SystemView-BGe__vl1.js → SystemView-DIYDCCF3.js} +1 -1
  7. package/dashboard/dist/assets/{TopView-CXggyydU.js → TopView-DhdLpsiA.js} +1 -1
  8. package/dashboard/dist/assets/index-DgbWvj42.js +84 -0
  9. package/dashboard/dist/index.html +1 -1
  10. package/dist/daemon.js +3 -1
  11. package/dist/db.d.ts +1 -0
  12. package/dist/db.js +8 -0
  13. package/dist/enricher.js +20 -11
  14. package/dist/paths.js +1 -1
  15. package/dist/routes/events.d.ts +0 -2
  16. package/dist/routes/events.js +3 -20
  17. package/dist/routes/helpers.d.ts +2 -0
  18. package/dist/routes/helpers.js +21 -0
  19. package/dist/routes/misc.js +34 -0
  20. package/dist/routes/opencode-reader.d.ts +7 -0
  21. package/dist/routes/opencode-reader.js +129 -0
  22. package/dist/routes/projects.d.ts +0 -2
  23. package/dist/routes/projects.js +3 -17
  24. package/dist/routes/stream.js +1 -1
  25. package/dist/watch.js +0 -1
  26. package/dist/watchdog.d.ts +5 -0
  27. package/dist/watchdog.js +6 -1
  28. package/dist/watchers/adapter.d.ts +10 -0
  29. package/dist/watchers/adapter.js +4 -0
  30. package/dist/watchers/claude-code.js +9 -9
  31. package/dist/watchers/opencode.d.ts +6 -6
  32. package/dist/watchers/opencode.js +49 -9
  33. package/package.json +3 -2
  34. package/dashboard/dist/assets/index-CB01c5lb.js +0 -84
@@ -11,7 +11,7 @@
11
11
  ::-webkit-scrollbar-track { background: #161b22 }
12
12
  ::-webkit-scrollbar-thumb { background: #30363d; border-radius: 3px }
13
13
  </style>
14
- <script type="module" crossorigin src="/assets/index-CB01c5lb.js"></script>
14
+ <script type="module" crossorigin src="/assets/index-DgbWvj42.js"></script>
15
15
  <link rel="modulepreload" crossorigin href="/assets/vendor-lucide-Cym0q5l_.js">
16
16
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-B_Jzs0gY.js">
17
17
  </head>
package/dist/daemon.js CHANGED
@@ -66,6 +66,7 @@ const history_1 = require("./routes/history");
66
66
  const misc_1 = require("./routes/misc");
67
67
  const reports_1 = require("./routes/reports");
68
68
  const top_1 = require("./routes/top");
69
+ const opencode_reader_1 = require("./routes/opencode-reader");
69
70
  const projects_cache_1 = require("./cache/projects-cache");
70
71
  const rate_limiter_1 = require("./middleware/rate-limiter");
71
72
  const summarizer_1 = require("./summarizer");
@@ -89,6 +90,7 @@ app.use(history_1.historyRouter);
89
90
  app.use(misc_1.miscRouter);
90
91
  app.use(reports_1.reportsRouter);
91
92
  app.use(top_1.topRouter);
93
+ app.use(opencode_reader_1.opencodeReaderRouter);
92
94
  // ─── GET /health — necesita acceso al tamaño del pool SSE ─────────────────────
93
95
  app.get('/health', (_req, res) => {
94
96
  res.json({ status: 'ok', port: PORT, clients: (0, stream_1.getSseClientsSize)() });
@@ -167,7 +169,7 @@ function shutdown(server) {
167
169
  alertInterval = null;
168
170
  }
169
171
  cleanPid();
170
- server.close();
172
+ server.close(() => { });
171
173
  }
172
174
  const LEVEL_RANK = { yellow: 1, orange: 2, red: 3 };
173
175
  const LEVEL_COLOR = {
package/dist/db.d.ts CHANGED
@@ -72,6 +72,7 @@ export declare const dbOps: {
72
72
  getSessionEvents(sessionId: string): EventRow[];
73
73
  getSession(sessionId: string): SessionRow | undefined;
74
74
  getLatestSession(): SessionRow | undefined;
75
+ getLatestClaudeSession(): SessionRow | undefined;
75
76
  getAllSessions(limit?: number): SessionRow[];
76
77
  getSessionEventsRecent(sessionId: string, limit?: number): EventRow[];
77
78
  updateSessionProject(sessionId: string, projectPath: string): void;
package/dist/db.js CHANGED
@@ -155,6 +155,11 @@ const stmts = {
155
155
  `),
156
156
  getLatestSession: db.prepare(`
157
157
  SELECT * FROM sessions ORDER BY last_event_at DESC LIMIT 1
158
+ `),
159
+ getLatestClaudeSession: db.prepare(`
160
+ SELECT * FROM sessions
161
+ WHERE source IS NULL OR source = 'claude-code'
162
+ ORDER BY last_event_at DESC LIMIT 1
158
163
  `),
159
164
  getAllSessions: db.prepare(`
160
165
  SELECT * FROM sessions ORDER BY started_at DESC LIMIT 500
@@ -515,6 +520,9 @@ exports.dbOps = {
515
520
  getLatestSession() {
516
521
  return stmts.getLatestSession.get();
517
522
  },
523
+ getLatestClaudeSession() {
524
+ return stmts.getLatestClaudeSession.get();
525
+ },
518
526
  getAllSessions(limit = 500) {
519
527
  return db.prepare(`SELECT * FROM sessions ORDER BY started_at DESC LIMIT ?`).all(limit);
520
528
  },
package/dist/enricher.js CHANGED
@@ -39,6 +39,7 @@ const prevContextBySession = new Map();
39
39
  let watcher = null;
40
40
  const pendingFiles = new Map();
41
41
  const fileLocks = new Map();
42
+ const pollIntervals = [];
42
43
  // ─── Adapter lookup por filePath ───────────────────────────────────────────────
43
44
  const adapterByDir = new Map();
44
45
  function findAdapter(filePath) {
@@ -70,7 +71,6 @@ async function processFile(filePath) {
70
71
  }
71
72
  }
72
73
  // ─── Start / Stop ──────────────────────────────────────────────────────────────
73
- let offsetCleanupInterval = null;
74
74
  function startEnricher(onUpdate, onCompact) {
75
75
  const adapters = (0, adapter_1.getActiveAdapters)();
76
76
  if (adapters.length === 0) {
@@ -117,26 +117,35 @@ function startEnricher(onUpdate, onCompact) {
117
117
  };
118
118
  watcher.on('change', handleFile);
119
119
  watcher.on('add', handleFile);
120
- offsetCleanupInterval = setInterval(() => {
121
- for (const [, adapter] of adapterByDir) {
122
- if (typeof adapter.constructor?.name === 'undefined') {
123
- // cleanup per-adapter state if needed
120
+ // ─── Poll-based adapters (e.g. OpenCode SQLite) ─────────────────────────────
121
+ const POLL_INTERVAL_MS = 10000;
122
+ for (const adapter of adapters) {
123
+ if (!(0, adapter_1.isPollable)(adapter))
124
+ continue;
125
+ let lastPoll = Date.now();
126
+ const interval = setInterval(async () => {
127
+ const since = lastPoll;
128
+ lastPoll = Date.now();
129
+ const sessions = await adapter.pollSessions(since);
130
+ for (const { sessionId, cost } of sessions) {
131
+ onUpdate(sessionId, cost, adapter.name);
124
132
  }
125
- }
126
- }, 5 * 60000);
133
+ }, POLL_INTERVAL_MS);
134
+ interval.unref();
135
+ pollIntervals.push(interval);
136
+ }
127
137
  }
128
138
  function stopEnricher() {
129
139
  if (watcher) {
130
140
  watcher.close();
131
141
  watcher = null;
132
142
  }
133
- if (offsetCleanupInterval) {
134
- clearInterval(offsetCleanupInterval);
135
- offsetCleanupInterval = null;
136
- }
137
143
  for (const [, timer] of pendingFiles)
138
144
  clearTimeout(timer);
139
145
  pendingFiles.clear();
146
+ for (const interval of pollIntervals)
147
+ clearInterval(interval);
148
+ pollIntervals.length = 0;
140
149
  prevContextBySession.clear();
141
150
  adapterByDir.clear();
142
151
  console.log('[enricher] Stopped');
package/dist/paths.js CHANGED
@@ -79,7 +79,7 @@ function getDashboardDir() {
79
79
  * Empirically verified: Claude Code CLI stores settings at ~/.claude on macOS, Linux, and Windows.
80
80
  */
81
81
  function getClaudeDir() {
82
- return path_1.default.join(os_1.default.homedir(), '.claude');
82
+ return process.env.CLAUDE_DIR ?? path_1.default.join(os_1.default.homedir(), '.claude');
83
83
  }
84
84
  // ─── ClaudeStat data directory ─────────────────────────────────────────────────
85
85
  /**
@@ -5,8 +5,6 @@ export declare const lastAgentByCwd: Map<string, {
5
5
  session_id: string;
6
6
  }>;
7
7
  export declare const taggedSessionParents: Set<string>;
8
- /** Sube el árbol desde un file_path hasta encontrar HANDOFF.md → directorio del proyecto */
9
- export declare function findProjectCwdForFile(filePath: string): string | undefined;
10
8
  /**
11
9
  * Cuando el enricher detecta nuevos tokens en un JSONL:
12
10
  * 1. Corre el análisis de inteligencia
@@ -5,9 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  };
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  exports.processLatestForSession = exports.onCompactDetected = exports.onCostUpdate = exports.taggedSessionParents = exports.lastAgentByCwd = exports.eventsRouter = void 0;
8
- exports.findProjectCwdForFile = findProjectCwdForFile;
9
8
  const path_1 = __importDefault(require("path"));
10
- const fs_1 = __importDefault(require("fs"));
11
9
  const express_1 = require("express");
12
10
  const db_1 = require("../db");
13
11
  const intelligence_1 = require("../intelligence");
@@ -18,6 +16,7 @@ const config_1 = require("../config");
18
16
  const rate_limiter_1 = require("../middleware/rate-limiter");
19
17
  const stream_1 = require("./stream");
20
18
  const notifier_1 = require("../notifier");
19
+ const helpers_1 = require("./helpers");
21
20
  const enricher_1 = require("../enricher");
22
21
  Object.defineProperty(exports, "processLatestForSession", { enumerable: true, get: function () { return enricher_1.processLatestForSession; } });
23
22
  // ─── Loop alert cooldown (toolName:sessionId → last alert ts) ─────────────────
@@ -56,19 +55,6 @@ function shouldFireAlert(level, pct) {
56
55
  alertCooldown.set(level, Date.now());
57
56
  return true;
58
57
  }
59
- /** Sube el árbol desde un file_path hasta encontrar HANDOFF.md → directorio del proyecto */
60
- function findProjectCwdForFile(filePath) {
61
- let dir = path_1.default.dirname(filePath);
62
- for (let i = 0; i < 6; i++) {
63
- if (fs_1.default.existsSync(path_1.default.join(dir, 'HANDOFF.md')))
64
- return dir;
65
- const parent = path_1.default.dirname(dir);
66
- if (parent === dir)
67
- break;
68
- dir = parent;
69
- }
70
- return undefined;
71
- }
72
58
  exports.eventsRouter.post('/event', (req, res) => {
73
59
  const ip = req.ip ?? '127.0.0.1';
74
60
  if ((0, rate_limiter_1.isRateLimited)(ip)) {
@@ -132,7 +118,7 @@ exports.eventsRouter.post('/event', (req, res) => {
132
118
  const inp = typeof tool_input === 'string' ? JSON.parse(tool_input) : (tool_input ?? {});
133
119
  const filePath = inp?.file_path ?? inp?.path;
134
120
  if (typeof filePath === 'string' && path_1.default.isAbsolute(filePath)) {
135
- const projectCwd = findProjectCwdForFile(filePath);
121
+ const projectCwd = (0, helpers_1.findProjectCwdForFile)(filePath);
136
122
  if (projectCwd)
137
123
  db_1.dbOps.updateSessionProject(session_id, projectCwd);
138
124
  }
@@ -211,11 +197,8 @@ exports.eventsRouter.post('/event', (req, res) => {
211
197
  const onCostUpdate = (sessionId, cost, source) => {
212
198
  // Ensure session row exists — sub-agent JSONLs arrive from the enricher without a
213
199
  // prior hook event (Claude Code does not fire hooks for sub-agent sessions).
200
+ db_1.dbOps.upsertSession({ id: sessionId, cwd: undefined, started_at: cost.firstTs ?? Date.now(), last_event_at: Date.now(), source });
214
201
  let sessionRow = db_1.dbOps.getSession(sessionId);
215
- if (!sessionRow) {
216
- db_1.dbOps.upsertSession({ id: sessionId, cwd: undefined, started_at: cost.firstTs ?? Date.now(), last_event_at: cost.firstTs ?? Date.now(), source });
217
- sessionRow = db_1.dbOps.getSession(sessionId);
218
- }
219
202
  // Sub-agent detection: first time we see a session, check if its firstTs falls after
220
203
  // a recent Agent PreToolUse from another session in the same CWD → tag as child.
221
204
  if (!exports.taggedSessionParents.has(sessionId) && cost.firstTs) {
@@ -0,0 +1,2 @@
1
+ /** Sube el árbol desde un file_path hasta encontrar HANDOFF.md → directorio del proyecto */
2
+ export declare function findProjectCwdForFile(filePath: string): string | undefined;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.findProjectCwdForFile = findProjectCwdForFile;
7
+ const path_1 = __importDefault(require("path"));
8
+ const fs_1 = __importDefault(require("fs"));
9
+ /** Sube el árbol desde un file_path hasta encontrar HANDOFF.md → directorio del proyecto */
10
+ function findProjectCwdForFile(filePath) {
11
+ let dir = path_1.default.dirname(filePath);
12
+ for (let i = 0; i < 6; i++) {
13
+ if (fs_1.default.existsSync(path_1.default.join(dir, 'HANDOFF.md')))
14
+ return dir;
15
+ const parent = path_1.default.dirname(dir);
16
+ if (parent === dir)
17
+ break;
18
+ dir = parent;
19
+ }
20
+ return undefined;
21
+ }
@@ -110,6 +110,13 @@ exports.miscRouter.get('/sessions', (_req, res) => {
110
110
  });
111
111
  res.json(enriched);
112
112
  });
113
+ // ─── GET /api/session-events — todos los eventos de una sesión (sin límite) ──
114
+ exports.miscRouter.get('/api/session-events', (req, res) => {
115
+ const sessionId = req.query.session_id;
116
+ if (!sessionId)
117
+ return res.status(400).json({ error: 'session_id required' });
118
+ res.json({ events: db_1.dbOps.getSessionEvents(sessionId) });
119
+ });
113
120
  // ─── GET /prompts — mensajes del usuario para una sesión ─────────────────────
114
121
  exports.miscRouter.get('/prompts', async (req, res) => {
115
122
  const sessionId = req.query.session_id;
@@ -125,6 +132,33 @@ exports.miscRouter.get('/hidden-cost', (_req, res) => {
125
132
  exports.miscRouter.get('/claude-stats', (_req, res) => {
126
133
  res.json((0, claude_stats_1.readClaudeStats)());
127
134
  });
135
+ // ─── GET /api/active-sessions — fuentes activas en los últimos 5 min ──────────
136
+ exports.miscRouter.get('/api/active-sessions', (_req, res) => {
137
+ const cutoff = Date.now() - 5 * 60 * 1000;
138
+ const sessions = db_1.dbOps.getAllSessions();
139
+ const bySource = new Map();
140
+ for (const s of sessions) {
141
+ const lastSeen = s.last_event_at ?? s.started_at;
142
+ if (lastSeen < cutoff)
143
+ continue;
144
+ const src = s.source ?? 'claude-code';
145
+ const existing = bySource.get(src);
146
+ if (!existing || lastSeen > existing.last_seen_ms) {
147
+ bySource.set(src, {
148
+ sessionId: s.id,
149
+ model: s.dominant_model ?? 'unknown',
150
+ cost_usd: s.total_cost_usd ?? 0,
151
+ last_seen_ms: lastSeen,
152
+ input_tokens: s.total_input_tokens ?? 0,
153
+ output_tokens: s.total_output_tokens ?? 0,
154
+ cache_read: s.total_cache_read ?? 0,
155
+ cache_creation: s.total_cache_creation ?? 0,
156
+ });
157
+ }
158
+ }
159
+ const result = Array.from(bySource.entries()).map(([source, v]) => ({ source, ...v }));
160
+ res.json(result);
161
+ });
128
162
  // ─── GET /system-config — mapa completo del setup de Claude ──────────────────
129
163
  let _systemConfigCache = null;
130
164
  let _systemConfigCacheTs = 0;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * opencode-reader.ts — Lee sesiones de OpenCode desde su SQLite y las mapea
3
+ * al formato TraceEvent[] que entiende el dashboard.
4
+ *
5
+ * GET /api/opencode/session/:id → { events: TraceEvent[], totalParts: number }
6
+ */
7
+ export declare const opencodeReaderRouter: import("express-serve-static-core").Router;
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ /**
3
+ * opencode-reader.ts — Lee sesiones de OpenCode desde su SQLite y las mapea
4
+ * al formato TraceEvent[] que entiende el dashboard.
5
+ *
6
+ * GET /api/opencode/session/:id → { events: TraceEvent[], totalParts: number }
7
+ */
8
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.opencodeReaderRouter = void 0;
13
+ const os_1 = __importDefault(require("os"));
14
+ const path_1 = __importDefault(require("path"));
15
+ const fs_1 = __importDefault(require("fs"));
16
+ const express_1 = require("express");
17
+ exports.opencodeReaderRouter = (0, express_1.Router)();
18
+ const OPENCODE_DB = path_1.default.join(os_1.default.homedir(), '.local', 'share', 'opencode', 'opencode.db');
19
+ // OpenCode tool names → claudestat canonical names
20
+ const TOOL_NAME_MAP = {
21
+ glob: 'Glob', read: 'Read', write: 'Write', edit: 'Edit', bash: 'Bash',
22
+ grep: 'Grep', webfetch: 'WebFetch', websearch: 'WebSearch',
23
+ skill: 'Skill', agent: 'Agent', task: 'Task',
24
+ };
25
+ function mapToolName(raw) {
26
+ return TOOL_NAME_MAP[raw.toLowerCase()] ?? (raw.charAt(0).toUpperCase() + raw.slice(1));
27
+ }
28
+ function openDb() {
29
+ const { DatabaseSync } = require('node:sqlite');
30
+ return new DatabaseSync(OPENCODE_DB, { open: true });
31
+ }
32
+ exports.opencodeReaderRouter.get('/api/opencode/session/:id', (req, res) => {
33
+ if (!fs_1.default.existsSync(OPENCODE_DB)) {
34
+ res.status(404).json({ error: 'OpenCode DB not found' });
35
+ return;
36
+ }
37
+ try {
38
+ const { id: sessionId } = req.params;
39
+ const db = openDb();
40
+ // Get all messages for this session ordered by time
41
+ const messages = db.prepare(`
42
+ SELECT id, time_created, time_updated, data
43
+ FROM message
44
+ WHERE session_id = ?
45
+ ORDER BY time_created ASC
46
+ `).all(sessionId);
47
+ const events = [];
48
+ const prompts = [];
49
+ let totalParts = 0;
50
+ let blockIndex = 0;
51
+ let pendingPrompt = null;
52
+ // Accumulated state for the current assistant turn (may span multiple messages)
53
+ let turnHasTools = false;
54
+ let turnEndTs = 0;
55
+ let turnCwd = undefined;
56
+ function closeTurn() {
57
+ if (!turnHasTools)
58
+ return;
59
+ blockIndex++;
60
+ events.push({ type: 'Stop', ts: turnEndTs, cwd: turnCwd });
61
+ if (pendingPrompt) {
62
+ prompts.push({ index: blockIndex, ts: pendingPrompt.ts, text: pendingPrompt.text });
63
+ pendingPrompt = null;
64
+ }
65
+ turnHasTools = false;
66
+ turnEndTs = 0;
67
+ turnCwd = undefined;
68
+ }
69
+ for (const msg of messages) {
70
+ const msgData = JSON.parse(msg.data);
71
+ if (msgData.role === 'user') {
72
+ // Close previous assistant turn before processing user message
73
+ closeTurn();
74
+ const parts = db.prepare(`
75
+ SELECT data FROM part WHERE message_id = ? ORDER BY time_created ASC
76
+ `).all(msg.id);
77
+ const text = parts
78
+ .map(p => { try {
79
+ return JSON.parse(p.data);
80
+ }
81
+ catch {
82
+ return null;
83
+ } })
84
+ .filter((p) => p?.type === 'text' && typeof p.text === 'string')
85
+ .map(p => p.text)
86
+ .join('\n').trim();
87
+ if (text)
88
+ pendingPrompt = { ts: msg.time_created, text };
89
+ continue;
90
+ }
91
+ if (msgData.role !== 'assistant')
92
+ continue;
93
+ const cwd = msgData.path?.cwd;
94
+ const parts = db.prepare(`
95
+ SELECT time_created, time_updated, data
96
+ FROM part
97
+ WHERE message_id = ?
98
+ ORDER BY time_created ASC
99
+ `).all(msg.id);
100
+ for (const part of parts) {
101
+ totalParts++;
102
+ const partData = JSON.parse(part.data);
103
+ if (partData.type !== 'tool' || !partData.tool || !partData.state)
104
+ continue;
105
+ const toolName = mapToolName(partData.tool);
106
+ const toolInput = partData.state.input ? JSON.stringify(partData.state.input) : undefined;
107
+ const isCompleted = partData.state.status === 'completed';
108
+ turnHasTools = true;
109
+ turnCwd = cwd ?? turnCwd;
110
+ turnEndTs = Math.max(turnEndTs, part.time_updated);
111
+ events.push({
112
+ type: isCompleted ? 'Done' : 'PreToolUse',
113
+ tool_name: toolName,
114
+ tool_input: toolInput,
115
+ ts: part.time_created,
116
+ ...(isCompleted && { duration_ms: part.time_updated - part.time_created }),
117
+ cwd,
118
+ });
119
+ }
120
+ }
121
+ // Close the last assistant turn (no trailing user message)
122
+ closeTurn();
123
+ db.close();
124
+ res.json({ events, totalParts, prompts });
125
+ }
126
+ catch (err) {
127
+ res.status(500).json({ error: String(err) });
128
+ }
129
+ });
@@ -1,7 +1,5 @@
1
1
  import { type EventRow } from '../db';
2
2
  export declare const projectsRouter: import("express-serve-static-core").Router;
3
- /** Sube el árbol desde un file_path hasta encontrar HANDOFF.md → directorio del proyecto */
4
- export declare function findProjectCwdForFile(filePath: string): string | undefined;
5
3
  /** Infiere el proyecto activo mirando los eventos de archivo de una sesión */
6
4
  export declare function inferProjectCwd(events: EventRow[]): string | undefined;
7
5
  /**
@@ -5,29 +5,15 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  };
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  exports.projectsRouter = void 0;
8
- exports.findProjectCwdForFile = findProjectCwdForFile;
9
8
  exports.inferProjectCwd = inferProjectCwd;
10
9
  exports.inferActiveProjectByMajority = inferActiveProjectByMajority;
11
10
  const path_1 = __importDefault(require("path"));
12
- const fs_1 = __importDefault(require("fs"));
13
11
  const express_1 = require("express");
14
12
  const db_1 = require("../db");
15
13
  const projects_cache_1 = require("../cache/projects-cache");
16
14
  const pattern_analyzer_1 = require("../pattern-analyzer");
15
+ const helpers_1 = require("./helpers");
17
16
  exports.projectsRouter = (0, express_1.Router)();
18
- /** Sube el árbol desde un file_path hasta encontrar HANDOFF.md → directorio del proyecto */
19
- function findProjectCwdForFile(filePath) {
20
- let dir = path_1.default.dirname(filePath);
21
- for (let i = 0; i < 6; i++) {
22
- if (fs_1.default.existsSync(path_1.default.join(dir, 'HANDOFF.md')))
23
- return dir;
24
- const parent = path_1.default.dirname(dir);
25
- if (parent === dir)
26
- break;
27
- dir = parent;
28
- }
29
- return undefined;
30
- }
31
17
  /** Infiere el proyecto activo mirando los eventos de archivo de una sesión */
32
18
  function inferProjectCwd(events) {
33
19
  const FILE_TOOLS = new Set(['Read', 'Write', 'Edit', 'Glob', 'Grep']);
@@ -41,7 +27,7 @@ function inferProjectCwd(events) {
41
27
  const filePath = (inp.file_path || inp.path);
42
28
  if (!filePath || !path_1.default.isAbsolute(filePath))
43
29
  continue;
44
- const cwd = findProjectCwdForFile(filePath);
30
+ const cwd = (0, helpers_1.findProjectCwdForFile)(filePath);
45
31
  if (cwd)
46
32
  return cwd;
47
33
  }
@@ -73,7 +59,7 @@ function inferActiveProjectByMajority(events, windowMs) {
73
59
  const filePath = (inp.file_path || inp.path);
74
60
  if (!filePath || !path_1.default.isAbsolute(filePath))
75
61
  continue;
76
- const project = findProjectCwdForFile(filePath);
62
+ const project = (0, helpers_1.findProjectCwdForFile)(filePath);
77
63
  if (!project)
78
64
  continue;
79
65
  const entry = hits.get(project) ?? { count: 0, lastTs: 0 };
@@ -46,7 +46,7 @@ exports.streamRouter.get('/stream', (req, res) => {
46
46
  res.flushHeaders();
47
47
  const clientId = Math.random().toString(36).slice(2);
48
48
  sseClients.set(clientId, res);
49
- const latestSession = db_1.dbOps.getLatestSession();
49
+ const latestSession = db_1.dbOps.getLatestClaudeSession();
50
50
  if (latestSession) {
51
51
  const allEvents = db_1.dbOps.getSessionEvents(latestSession.id);
52
52
  const events = allEvents.length > SSE_INIT_EVENT_LIMIT
package/dist/watch.js CHANGED
@@ -80,7 +80,6 @@ async function startWatch() {
80
80
  }
81
81
  fetchQuota().then(pct => { state.cyclePct = pct; });
82
82
  setInterval(async () => { state.cyclePct = await fetchQuota(); }, 30000);
83
- // Refrescar stats semanales cada 5 minutos
84
83
  setInterval(() => { state.weekly = (0, weekly_1.readWeeklyStats)(); }, 5 * 60 * 1000);
85
84
  function draw() {
86
85
  if (state.sessionId) {
@@ -1,6 +1,11 @@
1
1
  /**
2
2
  * watchdog.ts — Daemon auto-restart mechanism
3
3
  *
4
+ * NOTE: The watchdog currently runs in the same process as the daemon.
5
+ * This means it cannot restart the daemon if the process crashes.
6
+ * For true resilience, the watchdog should be spawned as a separate
7
+ * process via `child_process.spawn()` with `detached: true`.
8
+ *
4
9
  * If the daemon process crashes or is killed unexpectedly, the watchdog
5
10
  * detects the stale PID file and relaunches the daemon automatically.
6
11
  *
package/dist/watchdog.js CHANGED
@@ -2,6 +2,11 @@
2
2
  /**
3
3
  * watchdog.ts — Daemon auto-restart mechanism
4
4
  *
5
+ * NOTE: The watchdog currently runs in the same process as the daemon.
6
+ * This means it cannot restart the daemon if the process crashes.
7
+ * For true resilience, the watchdog should be spawned as a separate
8
+ * process via `child_process.spawn()` with `detached: true`.
9
+ *
5
10
  * If the daemon process crashes or is killed unexpectedly, the watchdog
6
11
  * detects the stale PID file and relaunches the daemon automatically.
7
12
  *
@@ -69,7 +74,7 @@ function startWatchdog() {
69
74
  catch { }
70
75
  restartDaemon();
71
76
  }
72
- }, CHECK_INTERVAL_MS);
77
+ }, CHECK_INTERVAL_MS).unref();
73
78
  process.on('SIGTERM', () => { clearInterval(interval); process.exit(0); });
74
79
  process.on('SIGINT', () => { clearInterval(interval); process.exit(0); });
75
80
  }
@@ -30,6 +30,16 @@ export interface WatcherAdapter {
30
30
  /** Nombre amigable para el badge de la CLI (ej: "CC", "Codex") */
31
31
  get shortName(): string;
32
32
  }
33
+ export interface PollSession {
34
+ sessionId: string;
35
+ cost: CostUpdate;
36
+ }
37
+ /** Adapters que no usan archivos JSONL sino una DB o API propia */
38
+ export interface PollableAdapter extends WatcherAdapter {
39
+ /** Devuelve sesiones actualizadas desde `since` (epoch ms) */
40
+ pollSessions(since: number): Promise<PollSession[]>;
41
+ }
42
+ export declare function isPollable(adapter: WatcherAdapter): adapter is PollableAdapter;
33
43
  export declare function registerAdapter(adapter: WatcherAdapter): void;
34
44
  export declare function getAdapter(name: string): WatcherAdapter | undefined;
35
45
  export declare function getAllAdapters(): WatcherAdapter[];
@@ -7,11 +7,15 @@
7
7
  * que claudestat las soporte todas con una interfaz común.
8
8
  */
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.isPollable = isPollable;
10
11
  exports.registerAdapter = registerAdapter;
11
12
  exports.getAdapter = getAdapter;
12
13
  exports.getAllAdapters = getAllAdapters;
13
14
  exports.getActiveAdapters = getActiveAdapters;
14
15
  exports.getAdapterNames = getAdapterNames;
16
+ function isPollable(adapter) {
17
+ return 'pollSessions' in adapter && typeof adapter.pollSessions === 'function';
18
+ }
15
19
  // ─── Factory ───────────────────────────────────────────────────────────────────
16
20
  const registry = new Map();
17
21
  function registerAdapter(adapter) {
@@ -19,7 +19,7 @@ const fs_1 = __importDefault(require("fs"));
19
19
  const adapter_1 = require("./adapter");
20
20
  const paths_1 = require("../paths");
21
21
  const pricing_1 = require("../pricing");
22
- const PROJECTS_DIR = path_1.default.join((0, paths_1.getClaudeDir)(), 'projects');
22
+ function projectsDir() { return path_1.default.join((0, paths_1.getClaudeDir)(), 'projects'); }
23
23
  const KNOWN_CONTEXT_WINDOWS = {
24
24
  'claude-opus-4-6': 200000,
25
25
  'claude-sonnet-4-6': 200000,
@@ -119,14 +119,14 @@ exports.claudeCodeAdapter = {
119
119
  get shortName() { return 'CC'; },
120
120
  detect() {
121
121
  try {
122
- return fs_1.default.existsSync(PROJECTS_DIR);
122
+ return fs_1.default.existsSync(projectsDir());
123
123
  }
124
124
  catch {
125
125
  return false;
126
126
  }
127
127
  },
128
128
  getWatchPaths() {
129
- return [`${PROJECTS_DIR}/**/*.jsonl`];
129
+ return [`${projectsDir()}/**/*.jsonl`];
130
130
  },
131
131
  parseEvent(raw, _filePath) {
132
132
  try {
@@ -164,11 +164,11 @@ async function getAllBlockCostsForSession(sessionId) {
164
164
  return cached?.data ?? [];
165
165
  costCacheLocks.set(sessionId, true);
166
166
  try {
167
- if (!fs_1.default.existsSync(PROJECTS_DIR))
167
+ if (!fs_1.default.existsSync(projectsDir()))
168
168
  return [];
169
- const dirs = await promises_1.default.readdir(PROJECTS_DIR);
169
+ const dirs = await promises_1.default.readdir(projectsDir());
170
170
  for (const dir of dirs) {
171
- const dirPath = path_1.default.join(PROJECTS_DIR, dir);
171
+ const dirPath = path_1.default.join(projectsDir(), dir);
172
172
  try {
173
173
  const stat = await promises_1.default.stat(dirPath);
174
174
  if (!stat.isDirectory())
@@ -241,11 +241,11 @@ async function getAllBlockCostsForSession(sessionId) {
241
241
  }
242
242
  async function getSessionPrompts(sessionId) {
243
243
  try {
244
- if (!fs_1.default.existsSync(PROJECTS_DIR))
244
+ if (!fs_1.default.existsSync(projectsDir()))
245
245
  return [];
246
- const dirs = await promises_1.default.readdir(PROJECTS_DIR);
246
+ const dirs = await promises_1.default.readdir(projectsDir());
247
247
  for (const dir of dirs) {
248
- const dirPath = path_1.default.join(PROJECTS_DIR, dir);
248
+ const dirPath = path_1.default.join(projectsDir(), dir);
249
249
  try {
250
250
  const stat = await promises_1.default.stat(dirPath);
251
251
  if (!stat.isDirectory())
@@ -1,9 +1,9 @@
1
1
  /**
2
- * opencode.ts — WatcherAdapter para OpenCode
2
+ * opencode.ts — WatcherAdapter para OpenCode (poll-based, SQLite)
3
3
  *
4
- * OpenCode stores traces in ~/.opencode/logs/ as JSONL files.
5
- * Format is similar to Claude Code but with different field names.
6
- * This is a scaffold fill in parseEvent/getSessionCost with sample traces.
4
+ * OpenCode stores sessions in ~/.local/share/opencode/opencode.db (SQLite).
5
+ * The session table has cost, token counts, model, and timestamps directly.
6
+ * Uses PollableAdapterno JSONL files, no chokidar.
7
7
  */
8
- import { type WatcherAdapter } from './adapter';
9
- export declare const opencodeAdapter: WatcherAdapter;
8
+ import { type PollableAdapter } from './adapter';
9
+ export declare const opencodeAdapter: PollableAdapter;