diff --git a/scripts/lib/session-manager.d.ts b/scripts/lib/session-manager.d.ts index 5c90c424d..58cf7a8bd 100644 --- a/scripts/lib/session-manager.d.ts +++ b/scripts/lib/session-manager.d.ts @@ -78,6 +78,16 @@ export interface GetAllSessionsOptions { search?: string | null; } +export interface GetSessionByIdOptions { + /** + * auto (default) ranks exact IDs and filename/date aliases before prefixes; + * modification time breaks ties. id prefers exact short IDs and also accepts + * ID prefixes and legacy date aliases. filename accepts full filenames or + * filenames without .tmp only. + */ + matchBy?: 'auto' | 'id' | 'filename'; +} + /** * Parse a session filename to extract date and short ID. * @returns Parsed metadata, or null if the filename doesn't match the expected pattern @@ -114,10 +124,12 @@ export function getAllSessions(options?: GetAllSessionsOptions): SessionListResu /** * Find a session by short ID or filename. - * @param sessionId - Short ID prefix, full filename, or filename without .tmp + * Use matchBy to disambiguate an extensionless filename and another short ID. + * @param sessionId - Short ID prefix, full filename, filename without .tmp, or legacy date alias * @param includeContent - Whether to read and parse the session content + * @param options - Restrict the lookup type; invalid options return null */ -export function getSessionById(sessionId: string, includeContent?: boolean): Session | null; +export function getSessionById(sessionId: string, includeContent?: boolean, options?: GetSessionByIdOptions): Session | null; /** Write markdown content to a session file */ export function writeSessionContent(sessionPath: string, content: string): boolean; diff --git a/scripts/lib/session-manager.js b/scripts/lib/session-manager.js index bfd3517b2..d0efe9e76 100644 --- a/scripts/lib/session-manager.js +++ b/scripts/lib/session-manager.js @@ -167,7 +167,8 @@ function buildSessionRecord(sessionPath, metadata) { }; } -function sessionMatchesId(metadata, normalizedSessionId, exact = false) { +/** Match allowed lookup kinds, optionally excluding short-ID prefix matches. */ +function sessionMatchesId(metadata, normalizedSessionId, exact = false, matchBy = 'auto') { const filename = metadata.filename; const shortIdMatch = metadata.shortId !== 'no-id' && (exact ? metadata.shortId === normalizedSessionId @@ -175,10 +176,12 @@ function sessionMatchesId(metadata, normalizedSessionId, exact = false) { const filenameMatch = filename === normalizedSessionId || filename === `${normalizedSessionId}.tmp`; const noIdMatch = metadata.shortId === 'no-id' && filename === `${normalizedSessionId}-session.tmp`; - return shortIdMatch || filenameMatch || noIdMatch; + return (matchBy !== 'filename' && (shortIdMatch || noIdMatch)) || + (matchBy !== 'id' && filenameMatch); } -function getMatchingSessionCandidates(normalizedSessionId) { +/** Keep canonical-first records and rank exact matches for the selected lookup kind. */ +function getMatchingSessionCandidates(normalizedSessionId, matchBy) { const matches = []; const seenFilenames = new Set(); @@ -199,7 +202,7 @@ function getMatchingSessionCandidates(normalizedSessionId) { if (!entry.isFile() || !entry.name.endsWith('.tmp')) continue; const metadata = parseSessionFilename(entry.name); - if (!metadata || !sessionMatchesId(metadata, normalizedSessionId)) { + if (!metadata || !sessionMatchesId(metadata, normalizedSessionId, false, matchBy)) { continue; } @@ -218,9 +221,12 @@ function getMatchingSessionCandidates(normalizedSessionId) { } } - // All exact aliases share priority; keep newest-first ordering for ties. + // Automatic lookup keeps exact aliases tied; explicit ID lookup prefers the ID. + const exactMatch = session => matchBy === 'id' + ? session.shortId === normalizedSessionId + : sessionMatchesId(session, normalizedSessionId, true, matchBy); matches.sort((a, b) => - Number(sessionMatchesId(b, normalizedSessionId, true)) - Number(sessionMatchesId(a, normalizedSessionId, true)) || + Number(exactMatch(b)) - Number(exactMatch(a)) || b.modifiedTime - a.modifiedTime ); return matches; @@ -407,13 +413,20 @@ function getAllSessions(options = {}) { } /** - * Get a single session by ID (short ID or full path) - * @param {string} sessionId - Short ID or session filename + * Find a session by ID or filename. Automatic lookup ranks exact IDs and + * filename/date aliases before prefixes, with modification time breaking ties. + * Use matchBy to disambiguate an extensionless filename and another short ID. + * @param {string} sessionId - Short ID prefix, session filename, or legacy date alias * @param {boolean} includeContent - Include session content - * @returns {object|null} Session object or null if not found + * @param {{matchBy?: 'auto'|'id'|'filename'}} [options={}] - Restrict lookup to IDs or filenames + * @returns {object|null} Session object, or null for no match or invalid options */ -function getSessionById(sessionId, includeContent = false) { - if (typeof sessionId !== 'string') { +function getSessionById(sessionId, includeContent = false, options = {}) { + if (typeof sessionId !== 'string' || !options || typeof options !== 'object' || Array.isArray(options)) { + return null; + } + const { matchBy = 'auto' } = options; + if (!['auto', 'id', 'filename'].includes(matchBy)) { return null; } @@ -422,7 +435,7 @@ function getSessionById(sessionId, includeContent = false) { return null; } - const sessions = getMatchingSessionCandidates(normalizedSessionId); + const sessions = getMatchingSessionCandidates(normalizedSessionId, matchBy); for (const session of sessions) { const sessionRecord = { ...session }; diff --git a/tests/lib/session-manager-lookup.test.js b/tests/lib/session-manager-lookup.test.js new file mode 100644 index 000000000..867f10c3a --- /dev/null +++ b/tests/lib/session-manager-lookup.test.js @@ -0,0 +1,87 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const test = require('node:test'); +const { getSessionById } = require('../../scripts/lib/session-manager'); + +/** Run a synchronous lookup against isolated canonical and legacy session files. */ +function withSessions(records, run) { + const dataHome = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-session-lookup-')); + const previous = process.env.ECC_AGENT_DATA_HOME; + try { + process.env.ECC_AGENT_DATA_HOME = dataHome; + for (const record of records) { + const directory = path.join(dataHome, record.legacy ? 'sessions' : 'session-data'); + fs.mkdirSync(directory, { recursive: true }); + const file = path.join(directory, record.filename); + fs.writeFileSync(file, record.content || `# ${record.filename}\n`); + fs.utimesSync(file, record.mtime, record.mtime); + } + run(); + } finally { + if (previous === undefined) delete process.env.ECC_AGENT_DATA_HOME; + else process.env.ECC_AGENT_DATA_HOME = previous; + fs.rmSync(dataHome, { recursive: true, force: true }); + } +} + +test('explicit lookup kinds disambiguate exact aliases while auto retains recency and content', () => { + for (const [query, filename, legacy] of [ + ['2026-03-10-frontend-session', '2026-03-10-frontend-session.tmp', false], + ['2026-03-09', '2026-03-09-session.tmp', true] + ]) { + for (const [filenameTime, idTime] of [[1000, 2000], [2000, 1000]]) { + const filenameSession = { filename, legacy, mtime: filenameTime, content: '# Filename session\n' }; + const idSession = { filename: `2026-03-11-${query}-session.tmp`, mtime: idTime, content: '# ID session\n' }; + const prefixSession = { filename: `2026-03-12-${query}-more-session.tmp`, mtime: 3000 }; + withSessions([filenameSession, idSession, prefixSession], () => { + const newestExact = filenameTime > idTime ? filenameSession : idSession; + for (const options of [undefined, { matchBy: 'auto' }]) { + const automatic = getSessionById(query, true, options); + assert.equal(automatic.filename, newestExact.filename); + assert.equal(automatic.content, newestExact.content); + } + const byId = getSessionById(query, true, { matchBy: 'id' }); + assert.equal(byId.filename, idSession.filename); + assert.equal(byId.content, idSession.content); + assert.equal(byId.metadata.title, 'ID session'); + const byFilename = getSessionById(` ${filename.slice(0, -4)} `, true, { matchBy: 'filename' }); + assert.equal(byFilename.filename, filenameSession.filename); + assert.equal(byFilename.content, filenameSession.content); + assert.equal(byFilename.metadata.title, 'Filename session'); + assert.equal(getSessionById(filename, true).content, filenameSession.content); + }); + } + } +}); + +test('explicit modes retain legacy date aliases without falling back to another lookup type', () => { + const current = '2026-03-10-frontend-session.tmp'; + const legacy = '2026-03-09-session.tmp'; + withSessions([ + { filename: current, mtime: 2000 }, + { filename: legacy, mtime: 1000, legacy: true } + ], () => { + assert.equal(getSessionById('front', false, { matchBy: 'id' }).filename, current); + assert.equal(getSessionById('frontend', false, { matchBy: 'filename' }), null); + assert.equal(getSessionById(current, false, { matchBy: 'id' }), null); + assert.equal(getSessionById('2026-03-09').filename, legacy); + assert.equal(getSessionById('2026-03-09', false, { matchBy: 'id' }).filename, legacy); + assert.equal(getSessionById('2026-03-09', false, { matchBy: 'filename' }), null); + assert.equal(getSessionById('2026-03-09-session', false, { matchBy: 'filename' }).filename, legacy); + }); +}); + +test('invalid lookup modes return null instead of selecting an unrelated session', () => { + withSessions([{ filename: '2026-03-10-frontend-session.tmp', mtime: 1000 }], () => { + for (const matchBy of ['', 'Filename', 'other', null, false, 0]) { + assert.equal(getSessionById('frontend', true, { matchBy }), null); + } + for (const options of [null, [], 'id']) { + assert.equal(getSessionById('frontend', true, options), null); + } + }); +});