ecc_infisense 0.0.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.
@@ -0,0 +1,442 @@
1
+ /**
2
+ * Session Manager Library for Claude Code
3
+ * Provides core session CRUD operations for listing, loading, and managing sessions
4
+ *
5
+ * Sessions are stored as markdown files in ~/.claude/sessions/ with format:
6
+ * - YYYY-MM-DD-session.tmp (old format)
7
+ * - YYYY-MM-DD-<short-id>-session.tmp (new format)
8
+ */
9
+
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+
13
+ const {
14
+ getSessionsDir,
15
+ readFile,
16
+ log
17
+ } = require('./utils');
18
+
19
+ // Session filename pattern: YYYY-MM-DD-[short-id]-session.tmp
20
+ // The short-id is optional (old format) and can be 8+ alphanumeric characters
21
+ // Matches: "2026-02-01-session.tmp" or "2026-02-01-a1b2c3d4-session.tmp"
22
+ const SESSION_FILENAME_REGEX = /^(\d{4}-\d{2}-\d{2})(?:-([a-z0-9]{8,}))?-session\.tmp$/;
23
+
24
+ /**
25
+ * Parse session filename to extract metadata
26
+ * @param {string} filename - Session filename (e.g., "2026-01-17-abc123-session.tmp" or "2026-01-17-session.tmp")
27
+ * @returns {object|null} Parsed metadata or null if invalid
28
+ */
29
+ function parseSessionFilename(filename) {
30
+ const match = filename.match(SESSION_FILENAME_REGEX);
31
+ if (!match) return null;
32
+
33
+ const dateStr = match[1];
34
+
35
+ // Validate date components are calendar-accurate (not just format)
36
+ const [year, month, day] = dateStr.split('-').map(Number);
37
+ if (month < 1 || month > 12 || day < 1 || day > 31) return null;
38
+ // Reject impossible dates like Feb 31, Apr 31 — Date constructor rolls
39
+ // over invalid days (e.g., Feb 31 -> Mar 3), so check month roundtrips
40
+ const d = new Date(year, month - 1, day);
41
+ if (d.getMonth() !== month - 1 || d.getDate() !== day) return null;
42
+
43
+ // match[2] is undefined for old format (no ID)
44
+ const shortId = match[2] || 'no-id';
45
+
46
+ return {
47
+ filename,
48
+ shortId,
49
+ date: dateStr,
50
+ // Use local-time constructor (consistent with validation on line 40)
51
+ // new Date(dateStr) interprets YYYY-MM-DD as UTC midnight which shows
52
+ // as the previous day in negative UTC offset timezones
53
+ datetime: new Date(year, month - 1, day)
54
+ };
55
+ }
56
+
57
+ /**
58
+ * Get the full path to a session file
59
+ * @param {string} filename - Session filename
60
+ * @returns {string} Full path to session file
61
+ */
62
+ function getSessionPath(filename) {
63
+ return path.join(getSessionsDir(), filename);
64
+ }
65
+
66
+ /**
67
+ * Read and parse session markdown content
68
+ * @param {string} sessionPath - Full path to session file
69
+ * @returns {string|null} Session content or null if not found
70
+ */
71
+ function getSessionContent(sessionPath) {
72
+ return readFile(sessionPath);
73
+ }
74
+
75
+ /**
76
+ * Parse session metadata from markdown content
77
+ * @param {string} content - Session markdown content
78
+ * @returns {object} Parsed metadata
79
+ */
80
+ function parseSessionMetadata(content) {
81
+ const metadata = {
82
+ title: null,
83
+ date: null,
84
+ started: null,
85
+ lastUpdated: null,
86
+ completed: [],
87
+ inProgress: [],
88
+ notes: '',
89
+ context: ''
90
+ };
91
+
92
+ if (!content) return metadata;
93
+
94
+ // Extract title from first heading
95
+ const titleMatch = content.match(/^#\s+(.+)$/m);
96
+ if (titleMatch) {
97
+ metadata.title = titleMatch[1].trim();
98
+ }
99
+
100
+ // Extract date
101
+ const dateMatch = content.match(/\*\*Date:\*\*\s*(\d{4}-\d{2}-\d{2})/);
102
+ if (dateMatch) {
103
+ metadata.date = dateMatch[1];
104
+ }
105
+
106
+ // Extract started time
107
+ const startedMatch = content.match(/\*\*Started:\*\*\s*([\d:]+)/);
108
+ if (startedMatch) {
109
+ metadata.started = startedMatch[1];
110
+ }
111
+
112
+ // Extract last updated
113
+ const updatedMatch = content.match(/\*\*Last Updated:\*\*\s*([\d:]+)/);
114
+ if (updatedMatch) {
115
+ metadata.lastUpdated = updatedMatch[1];
116
+ }
117
+
118
+ // Extract completed items
119
+ const completedSection = content.match(/### Completed\s*\n([\s\S]*?)(?=###|\n\n|$)/);
120
+ if (completedSection) {
121
+ const items = completedSection[1].match(/- \[x\]\s*(.+)/g);
122
+ if (items) {
123
+ metadata.completed = items.map(item => item.replace(/- \[x\]\s*/, '').trim());
124
+ }
125
+ }
126
+
127
+ // Extract in-progress items
128
+ const progressSection = content.match(/### In Progress\s*\n([\s\S]*?)(?=###|\n\n|$)/);
129
+ if (progressSection) {
130
+ const items = progressSection[1].match(/- \[ \]\s*(.+)/g);
131
+ if (items) {
132
+ metadata.inProgress = items.map(item => item.replace(/- \[ \]\s*/, '').trim());
133
+ }
134
+ }
135
+
136
+ // Extract notes
137
+ const notesSection = content.match(/### Notes for Next Session\s*\n([\s\S]*?)(?=###|\n\n|$)/);
138
+ if (notesSection) {
139
+ metadata.notes = notesSection[1].trim();
140
+ }
141
+
142
+ // Extract context to load
143
+ const contextSection = content.match(/### Context to Load\s*\n```\n([\s\S]*?)```/);
144
+ if (contextSection) {
145
+ metadata.context = contextSection[1].trim();
146
+ }
147
+
148
+ return metadata;
149
+ }
150
+
151
+ /**
152
+ * Calculate statistics for a session
153
+ * @param {string} sessionPathOrContent - Full path to session file, OR
154
+ * the pre-read content string (to avoid redundant disk reads when
155
+ * the caller already has the content loaded).
156
+ * @returns {object} Statistics object
157
+ */
158
+ function getSessionStats(sessionPathOrContent) {
159
+ // Accept pre-read content string to avoid redundant file reads.
160
+ // If the argument looks like a file path (no newlines, ends with .tmp,
161
+ // starts with / on Unix or drive letter on Windows), read from disk.
162
+ // Otherwise treat it as content.
163
+ const looksLikePath = typeof sessionPathOrContent === 'string' &&
164
+ !sessionPathOrContent.includes('\n') &&
165
+ sessionPathOrContent.endsWith('.tmp') &&
166
+ (sessionPathOrContent.startsWith('/') || /^[A-Za-z]:[/\\]/.test(sessionPathOrContent));
167
+ const content = looksLikePath
168
+ ? getSessionContent(sessionPathOrContent)
169
+ : sessionPathOrContent;
170
+
171
+ const metadata = parseSessionMetadata(content);
172
+
173
+ return {
174
+ totalItems: metadata.completed.length + metadata.inProgress.length,
175
+ completedItems: metadata.completed.length,
176
+ inProgressItems: metadata.inProgress.length,
177
+ lineCount: content ? content.split('\n').length : 0,
178
+ hasNotes: !!metadata.notes,
179
+ hasContext: !!metadata.context
180
+ };
181
+ }
182
+
183
+ /**
184
+ * Get all sessions with optional filtering and pagination
185
+ * @param {object} options - Options object
186
+ * @param {number} options.limit - Maximum number of sessions to return
187
+ * @param {number} options.offset - Number of sessions to skip
188
+ * @param {string} options.date - Filter by date (YYYY-MM-DD format)
189
+ * @param {string} options.search - Search in short ID
190
+ * @returns {object} Object with sessions array and pagination info
191
+ */
192
+ function getAllSessions(options = {}) {
193
+ const {
194
+ limit: rawLimit = 50,
195
+ offset: rawOffset = 0,
196
+ date = null,
197
+ search = null
198
+ } = options;
199
+
200
+ // Clamp offset and limit to safe non-negative integers.
201
+ // Without this, negative offset causes slice() to count from the end,
202
+ // and NaN values cause slice() to return empty or unexpected results.
203
+ // Note: cannot use `|| default` because 0 is falsy — use isNaN instead.
204
+ const offsetNum = Number(rawOffset);
205
+ const offset = Number.isNaN(offsetNum) ? 0 : Math.max(0, Math.floor(offsetNum));
206
+ const limitNum = Number(rawLimit);
207
+ const limit = Number.isNaN(limitNum) ? 50 : Math.max(1, Math.floor(limitNum));
208
+
209
+ const sessionsDir = getSessionsDir();
210
+
211
+ if (!fs.existsSync(sessionsDir)) {
212
+ return { sessions: [], total: 0, offset, limit, hasMore: false };
213
+ }
214
+
215
+ const entries = fs.readdirSync(sessionsDir, { withFileTypes: true });
216
+ const sessions = [];
217
+
218
+ for (const entry of entries) {
219
+ // Skip non-files (only process .tmp files)
220
+ if (!entry.isFile() || !entry.name.endsWith('.tmp')) continue;
221
+
222
+ const filename = entry.name;
223
+ const metadata = parseSessionFilename(filename);
224
+
225
+ if (!metadata) continue;
226
+
227
+ // Apply date filter
228
+ if (date && metadata.date !== date) {
229
+ continue;
230
+ }
231
+
232
+ // Apply search filter (search in short ID)
233
+ if (search && !metadata.shortId.includes(search)) {
234
+ continue;
235
+ }
236
+
237
+ const sessionPath = path.join(sessionsDir, filename);
238
+
239
+ // Get file stats (wrapped in try-catch to handle TOCTOU race where
240
+ // file is deleted between readdirSync and statSync)
241
+ let stats;
242
+ try {
243
+ stats = fs.statSync(sessionPath);
244
+ } catch {
245
+ continue; // File was deleted between readdir and stat
246
+ }
247
+
248
+ sessions.push({
249
+ ...metadata,
250
+ sessionPath,
251
+ hasContent: stats.size > 0,
252
+ size: stats.size,
253
+ modifiedTime: stats.mtime,
254
+ createdTime: stats.birthtime || stats.ctime
255
+ });
256
+ }
257
+
258
+ // Sort by modified time (newest first)
259
+ sessions.sort((a, b) => b.modifiedTime - a.modifiedTime);
260
+
261
+ // Apply pagination
262
+ const paginatedSessions = sessions.slice(offset, offset + limit);
263
+
264
+ return {
265
+ sessions: paginatedSessions,
266
+ total: sessions.length,
267
+ offset,
268
+ limit,
269
+ hasMore: offset + limit < sessions.length
270
+ };
271
+ }
272
+
273
+ /**
274
+ * Get a single session by ID (short ID or full path)
275
+ * @param {string} sessionId - Short ID or session filename
276
+ * @param {boolean} includeContent - Include session content
277
+ * @returns {object|null} Session object or null if not found
278
+ */
279
+ function getSessionById(sessionId, includeContent = false) {
280
+ const sessionsDir = getSessionsDir();
281
+
282
+ if (!fs.existsSync(sessionsDir)) {
283
+ return null;
284
+ }
285
+
286
+ const entries = fs.readdirSync(sessionsDir, { withFileTypes: true });
287
+
288
+ for (const entry of entries) {
289
+ if (!entry.isFile() || !entry.name.endsWith('.tmp')) continue;
290
+
291
+ const filename = entry.name;
292
+ const metadata = parseSessionFilename(filename);
293
+
294
+ if (!metadata) continue;
295
+
296
+ // Check if session ID matches (short ID or full filename without .tmp)
297
+ const shortIdMatch = sessionId.length > 0 && metadata.shortId !== 'no-id' && metadata.shortId.startsWith(sessionId);
298
+ const filenameMatch = filename === sessionId || filename === `${sessionId}.tmp`;
299
+ const noIdMatch = metadata.shortId === 'no-id' && filename === `${sessionId}-session.tmp`;
300
+
301
+ if (!shortIdMatch && !filenameMatch && !noIdMatch) {
302
+ continue;
303
+ }
304
+
305
+ const sessionPath = path.join(sessionsDir, filename);
306
+ let stats;
307
+ try {
308
+ stats = fs.statSync(sessionPath);
309
+ } catch {
310
+ return null; // File was deleted between readdir and stat
311
+ }
312
+
313
+ const session = {
314
+ ...metadata,
315
+ sessionPath,
316
+ size: stats.size,
317
+ modifiedTime: stats.mtime,
318
+ createdTime: stats.birthtime || stats.ctime
319
+ };
320
+
321
+ if (includeContent) {
322
+ session.content = getSessionContent(sessionPath);
323
+ session.metadata = parseSessionMetadata(session.content);
324
+ // Pass pre-read content to avoid a redundant disk read
325
+ session.stats = getSessionStats(session.content || '');
326
+ }
327
+
328
+ return session;
329
+ }
330
+
331
+ return null;
332
+ }
333
+
334
+ /**
335
+ * Get session title from content
336
+ * @param {string} sessionPath - Full path to session file
337
+ * @returns {string} Title or default text
338
+ */
339
+ function getSessionTitle(sessionPath) {
340
+ const content = getSessionContent(sessionPath);
341
+ const metadata = parseSessionMetadata(content);
342
+
343
+ return metadata.title || 'Untitled Session';
344
+ }
345
+
346
+ /**
347
+ * Format session size in human-readable format
348
+ * @param {string} sessionPath - Full path to session file
349
+ * @returns {string} Formatted size (e.g., "1.2 KB")
350
+ */
351
+ function getSessionSize(sessionPath) {
352
+ let stats;
353
+ try {
354
+ stats = fs.statSync(sessionPath);
355
+ } catch {
356
+ return '0 B';
357
+ }
358
+ const size = stats.size;
359
+
360
+ if (size < 1024) return `${size} B`;
361
+ if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
362
+ return `${(size / (1024 * 1024)).toFixed(1)} MB`;
363
+ }
364
+
365
+ /**
366
+ * Write session content to file
367
+ * @param {string} sessionPath - Full path to session file
368
+ * @param {string} content - Markdown content to write
369
+ * @returns {boolean} Success status
370
+ */
371
+ function writeSessionContent(sessionPath, content) {
372
+ try {
373
+ fs.writeFileSync(sessionPath, content, { encoding: 'utf8', mode: 0o600 });
374
+ return true;
375
+ } catch (err) {
376
+ log(`[SessionManager] Error writing session: ${err.message}`);
377
+ return false;
378
+ }
379
+ }
380
+
381
+ /**
382
+ * Append content to a session
383
+ * @param {string} sessionPath - Full path to session file
384
+ * @param {string} content - Content to append
385
+ * @returns {boolean} Success status
386
+ */
387
+ function appendSessionContent(sessionPath, content) {
388
+ try {
389
+ fs.appendFileSync(sessionPath, content, { encoding: 'utf8', mode: 0o600 });
390
+ return true;
391
+ } catch (err) {
392
+ log(`[SessionManager] Error appending to session: ${err.message}`);
393
+ return false;
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Delete a session file
399
+ * @param {string} sessionPath - Full path to session file
400
+ * @returns {boolean} Success status
401
+ */
402
+ function deleteSession(sessionPath) {
403
+ try {
404
+ if (fs.existsSync(sessionPath)) {
405
+ fs.unlinkSync(sessionPath);
406
+ return true;
407
+ }
408
+ return false;
409
+ } catch (err) {
410
+ log(`[SessionManager] Error deleting session: ${err.message}`);
411
+ return false;
412
+ }
413
+ }
414
+
415
+ /**
416
+ * Check if a session exists
417
+ * @param {string} sessionPath - Full path to session file
418
+ * @returns {boolean} True if session exists
419
+ */
420
+ function sessionExists(sessionPath) {
421
+ try {
422
+ return fs.statSync(sessionPath).isFile();
423
+ } catch {
424
+ return false;
425
+ }
426
+ }
427
+
428
+ module.exports = {
429
+ parseSessionFilename,
430
+ getSessionPath,
431
+ getSessionContent,
432
+ parseSessionMetadata,
433
+ getSessionStats,
434
+ getSessionTitle,
435
+ getSessionSize,
436
+ getAllSessions,
437
+ getSessionById,
438
+ writeSessionContent,
439
+ appendSessionContent,
440
+ deleteSession,
441
+ sessionExists
442
+ };