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IAAI,CACT,MAAM,EAAE,oBAAoB,EAC5B,OAAO,EAAE,WAAW,EACpB,OAAO,EAAE,OAAO,GACd,OAAO,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CA2CxC;IAED,KAAK,CAAC,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAMtC;YAEa,wBAAwB;YAcxB,aAAa;YAwBb,mBAAmB;YAenB,kBAAkB;YAMlB,gBAAgB;YAOhB,qBAAqB;YAarB,wBAAwB;YAcxB,4BAA4B;IAY1C,OAAO,CAAC,kBAAkB;IAe1B,OAAO,CAAC,UAAU;YAIJ,WAAW;IA4BzB,OAAO,CAAC,IAAI;IAMZ,OAAO,CAAC,UAAU;CAGlB","sourcesContent":["import { uuidv7 } from \"@earendil-works/pi-ai/utils/uuid\";\nimport type { Context } from \"../../context.ts\";\nimport type { FileError, FileInfo, FileSystem, Result } from \"../../types.ts\";\nimport { createForkSnapshot, type ForkSourceSnapshot } from \"../fork.ts\";\nimport { StorageBackedSession } from \"../session.ts\";\nimport type { ForkOptions, Session, SessionRepo } from \"../types.ts\";\nimport { parseJsonlSessionHeader } from \"./codec.ts\";\nimport { metadataFromLegacyV3Header } from \"./legacy-v3.ts\";\nimport { JsonlStorage } from \"./storage.ts\";\nimport {\n\tJSONL_FORMAT_VERSION,\n\tJSONL_STORAGE_VERSION,\n\ttype JsonlSessionCreateOptions,\n\ttype JsonlSessionListOptions,\n\ttype JsonlSessionMetadata,\n\ttype JsonlSessionRepoOptions,\n\ttype JsonlStorageHeader,\n} from \"./types.ts\";\n\nfunction fileValue<T>(result: Result<T, FileError>, action: string): T {\n\tif (!result.ok) throw new Error(`${action}: ${result.error.message}`, { cause: result.error });\n\treturn result.value;\n}\n\nfunction metadataFromHeader(header: JsonlStorageHeader, path: string, modifiedAt: number): JsonlSessionMetadata {\n\treturn {\n\t\tid: header.id,\n\t\tcreatedAt: header.createdAt,\n\t\tstorageVersion: header.storageVersion,\n\t\tcwd: header.cwd,\n\t\tpath,\n\t\tmodifiedAt,\n\t\t...(header.parentSessionId === undefined ? {} : { parentSessionId: header.parentSessionId }),\n\t\t...(header.legacyParentSessionPath === undefined\n\t\t\t? {}\n\t\t\t: { legacyParentSessionPath: header.legacyParentSessionPath }),\n\t};\n}\n\nfunction sessionDirectoryName(cwd: string): string {\n\treturn `--${cwd.replace(/^[/\\\\]/, \"\").replace(/[/\\\\:]/g, \"-\")}--`;\n}\n\nfunction sessionFileName(createdAt: number, id: string): string {\n\tconst timestamp = new Date(createdAt).toISOString().replace(/[:.]/g, \"-\");\n\treturn `${timestamp}_${encodeURIComponent(id)}.jsonl`;\n}\n\n/** File-backed format-4 session repository lifecycle. */\nexport class JsonlSessionRepo\n\timplements SessionRepo<JsonlSessionMetadata, JsonlSessionCreateOptions, JsonlSessionListOptions>\n{\n\tprivate readonly fileSystem: FileSystem;\n\tprivate readonly sessionsRootInput: string;\n\tprivate readonly now: () => number;\n\tprivate readonly openSessions = new Map<string, JsonlStorage>();\n\tprivate readonly pendingCreates = new Set<string>();\n\tprivate closed = false;\n\tprivate closePromise: Promise<void> | undefined;\n\n\tconstructor(options: JsonlSessionRepoOptions) {\n\t\tthis.fileSystem = options.fileSystem;\n\t\tthis.sessionsRootInput = options.sessionsRoot;\n\t\tthis.now = options.now ?? Date.now;\n\t}\n\n\tasync create(options: JsonlSessionCreateOptions, context: Context): Promise<Session<JsonlSessionMetadata>> {\n\t\tthis.assertOpen();\n\t\tconst createdAt = this.now();\n\t\tconst { cwd, id } = await this.resolveCreateDestination(options.cwd, options.id, createdAt, context);\n\t\tconst key = this.sessionKey(cwd, id);\n\t\tif (this.openSessions.has(key) || this.pendingCreates.has(key)) throw new Error(`Session already exists: ${id}`);\n\t\tthis.pendingCreates.add(key);\n\t\tlet path: string | undefined;\n\t\tlet storage: JsonlStorage | undefined;\n\t\ttry {\n\t\t\tpath = await this.resolveNewSessionPath(cwd, createdAt, id, context);\n\t\t\tconst header: JsonlStorageHeader = {\n\t\t\t\tv: JSONL_FORMAT_VERSION,\n\t\t\t\tkind: \"header\",\n\t\t\t\tid,\n\t\t\t\tstorageVersion: JSONL_STORAGE_VERSION,\n\t\t\t\tcreatedAt,\n\t\t\t\tcwd,\n\t\t\t\t...(options.parentSessionId === undefined ? {} : { parentSessionId: options.parentSessionId }),\n\t\t\t};\n\t\t\tstorage = await JsonlStorage.create({ fileSystem: this.fileSystem, path, now: this.now }, header, [], context);\n\t\t\tconst info = fileValue(await this.fileSystem.fileInfo(path, context), `Failed to read session ${path}`);\n\t\t\treturn this.publishOpenSession(metadataFromHeader(header, path, info.mtimeMs), storage, key);\n\t\t} catch (error) {\n\t\t\tawait storage?.close(context).catch(() => undefined);\n\t\t\tif (path !== undefined) await this.fileSystem.remove(path, { force: true }, context);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tthis.pendingCreates.delete(key);\n\t\t}\n\t}\n\n\tasync open(metadata: JsonlSessionMetadata, context: Context): Promise<Session<JsonlSessionMetadata>> {\n\t\tthis.assertOpen();\n\t\tconst key = this.sessionKey(metadata.cwd, metadata.id);\n\t\tif (this.openSessions.has(key)) throw new Error(`Session is already open: ${metadata.id}`);\n\t\tlet storage: JsonlStorage | undefined;\n\t\ttry {\n\t\t\tstorage = await this.loadStorage(metadata, context);\n\t\t\treturn this.publishOpenSession(metadata, storage, key);\n\t\t} catch (error) {\n\t\t\tawait storage?.close(context);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync list(options: JsonlSessionListOptions | undefined, context: Context): Promise<JsonlSessionMetadata[]> {\n\t\toptions ??= {};\n\t\tthis.assertOpen();\n\t\tconst cwd =\n\t\t\toptions.cwd === undefined\n\t\t\t\t? undefined\n\t\t\t\t: fileValue(\n\t\t\t\t\t\tawait this.fileSystem.absolutePath(options.cwd, context),\n\t\t\t\t\t\t`Failed to resolve session cwd ${options.cwd}`,\n\t\t\t\t\t);\n\t\tconst root = await this.root(context);\n\t\tif (!fileValue(await this.fileSystem.exists(root, context), `Failed to check sessions root ${root}`)) return [];\n\t\tconst directories =\n\t\t\tcwd === undefined ? await this.sessionDirectories(root, context) : [await this.sessionDirectory(cwd, context)];\n\t\tconst metadata: JsonlSessionMetadata[] = [];\n\t\tfor (const directory of directories) metadata.push(...(await this.listDirectory(directory, cwd, context)));\n\t\treturn metadata.sort(\n\t\t\t(left, right) =>\n\t\t\t\tright.createdAt - left.createdAt || left.id.localeCompare(right.id) || left.cwd.localeCompare(right.cwd),\n\t\t);\n\t}\n\n\tasync delete(metadata: JsonlSessionMetadata, context: Context): Promise<void> {\n\t\tthis.assertOpen();\n\t\tconst key = this.sessionKey(metadata.cwd, metadata.id);\n\t\tif (this.openSessions.has(key)) throw new Error(`Session is open: ${metadata.id}`);\n\t\tif (\n\t\t\t!fileValue(await this.fileSystem.exists(metadata.path, context), `Failed to check session ${metadata.path}`)\n\t\t) {\n\t\t\tthrow new Error(`Session file does not exist: ${metadata.path}`);\n\t\t}\n\t\tfileValue(\n\t\t\tawait this.fileSystem.remove(metadata.path, undefined, context),\n\t\t\t`Failed to delete session ${metadata.path}`,\n\t\t);\n\t}\n\n\tasync fork(\n\t\tsource: JsonlSessionMetadata,\n\t\toptions: ForkOptions,\n\t\tcontext: Context,\n\t): Promise<Session<JsonlSessionMetadata>> {\n\t\tthis.assertOpen();\n\t\tconst createdAt = this.now();\n\t\tconst sourceStorage = this.openSessions.get(this.sessionKey(source.cwd, source.id));\n\t\tconst sourceSnapshot = await (sourceStorage === undefined\n\t\t\t? this.loadClosedForkSourceSnapshot(source, context)\n\t\t\t: sourceStorage.captureForkSource(context));\n\t\tconst { cwd, id } = await this.resolveCreateDestination(source.cwd, options.id, createdAt, context);\n\t\tconst destinationKey = this.sessionKey(cwd, id);\n\t\tif (this.openSessions.has(destinationKey) || this.pendingCreates.has(destinationKey)) {\n\t\t\tthrow new Error(`Session already exists: ${id}`);\n\t\t}\n\t\tthis.pendingCreates.add(destinationKey);\n\n\t\tlet path: string | undefined;\n\t\tlet storage: JsonlStorage | undefined;\n\t\ttry {\n\t\t\tpath = await this.resolveNewSessionPath(cwd, createdAt, id, context);\n\t\t\tconst snapshot = createForkSnapshot(sourceSnapshot, options);\n\t\t\tconst header: JsonlStorageHeader = {\n\t\t\t\tv: JSONL_FORMAT_VERSION,\n\t\t\t\tkind: \"header\",\n\t\t\t\tid,\n\t\t\t\tstorageVersion: JSONL_STORAGE_VERSION,\n\t\t\t\tcreatedAt,\n\t\t\t\tcwd,\n\t\t\t\tparentSessionId: source.id,\n\t\t\t};\n\t\t\tstorage = await JsonlStorage.createFromForkSnapshot(\n\t\t\t\t{ fileSystem: this.fileSystem, path, now: this.now },\n\t\t\t\theader,\n\t\t\t\tsnapshot,\n\t\t\t\tcontext,\n\t\t\t);\n\t\t\tconst info = fileValue(await this.fileSystem.fileInfo(path, context), `Failed to read session ${path}`);\n\t\t\treturn this.publishOpenSession(metadataFromHeader(header, path, info.mtimeMs), storage, destinationKey);\n\t\t} catch (error) {\n\t\t\tawait storage?.close(context).catch(() => undefined);\n\t\t\tif (path !== undefined) await this.fileSystem.remove(path, { force: true }, context);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tthis.pendingCreates.delete(destinationKey);\n\t\t}\n\t}\n\n\tclose(_context: Context): Promise<void> {\n\t\tif (this.closePromise !== undefined) return this.closePromise;\n\t\tthis.closed = true;\n\t\t// TODO: Define ownership semantics before deciding whether repository close should close session handles.\n\t\tthis.closePromise = Promise.resolve();\n\t\treturn this.closePromise;\n\t}\n\n\tprivate async resolveCreateDestination(\n\t\tcwdInput: string,\n\t\tid: string | undefined,\n\t\tcreatedAt: number,\n\t\tcontext: Context,\n\t): Promise<{ cwd: string; id: string }> {\n\t\tconst destinationId = id ?? uuidv7(createdAt);\n\t\tconst cwd = fileValue(\n\t\t\tawait this.fileSystem.absolutePath(cwdInput, context),\n\t\t\t`Failed to resolve session cwd ${cwdInput}`,\n\t\t);\n\t\treturn { cwd, id: destinationId };\n\t}\n\n\tprivate async listDirectory(\n\t\tdirectory: string,\n\t\tcwd: string | undefined,\n\t\tcontext: Context,\n\t): Promise<JsonlSessionMetadata[]> {\n\t\tif (\n\t\t\t!fileValue(await this.fileSystem.exists(directory, context), `Failed to check sessions directory ${directory}`)\n\t\t) {\n\t\t\treturn [];\n\t\t}\n\t\tconst files = fileValue(\n\t\t\tawait this.fileSystem.listDir(directory, context),\n\t\t\t`Failed to list sessions directory ${directory}`,\n\t\t).filter((file) => file.kind !== \"directory\" && file.name.endsWith(\".jsonl\"));\n\t\tconst metadata: JsonlSessionMetadata[] = [];\n\t\tfor (const file of files) {\n\t\t\tconst discovered = await this.readSessionMetadata(file, context);\n\t\t\tif (discovered === undefined) continue;\n\t\t\t// Directory encoding is lossy: /a/b and /a-b both map to --a-b--.\n\t\t\tif (cwd === undefined || discovered.cwd === cwd) metadata.push(discovered);\n\t\t}\n\t\treturn metadata;\n\t}\n\n\tprivate async readSessionMetadata(file: FileInfo, context: Context): Promise<JsonlSessionMetadata | undefined> {\n\t\tconst lines = fileValue(\n\t\t\tawait this.fileSystem.readTextLines(file.path, { maxLines: 1 }, context),\n\t\t\t`Failed to read session header ${file.path}`,\n\t\t);\n\t\tif (lines[0] === undefined) return undefined;\n\t\tconst parsedHeader = parseJsonlSessionHeader(lines[0]);\n\t\tif (!parsedHeader.ok) return undefined;\n\t\tif (parsedHeader.value.format === \"v3-legacy\") {\n\t\t\tconst metadata = await metadataFromLegacyV3Header(this.fileSystem, parsedHeader.value.header, context);\n\t\t\treturn { ...metadata, path: file.path, modifiedAt: file.mtimeMs };\n\t\t}\n\t\treturn metadataFromHeader(parsedHeader.value.header, file.path, file.mtimeMs);\n\t}\n\n\tprivate async sessionDirectories(root: string, context: Context): Promise<string[]> {\n\t\treturn fileValue(await this.fileSystem.listDir(root, context), `Failed to list sessions root ${root}`)\n\t\t\t.filter((entry) => entry.kind === \"directory\")\n\t\t\t.map((entry) => entry.path);\n\t}\n\n\tprivate async sessionDirectory(cwd: string, context: Context): Promise<string> {\n\t\treturn fileValue(\n\t\t\tawait this.fileSystem.joinPath([await this.root(context), sessionDirectoryName(cwd)], context),\n\t\t\t`Failed to resolve sessions directory for ${cwd}`,\n\t\t);\n\t}\n\n\tprivate async resolveNewSessionPath(cwd: string, createdAt: number, id: string, context: Context): Promise<string> {\n\t\tconst directory = await this.sessionDirectory(cwd, context);\n\t\tawait this.assertSessionIdAvailable(directory, id, context);\n\t\tfileValue(\n\t\t\tawait this.fileSystem.createDir(directory, undefined, context),\n\t\t\t`Failed to create sessions directory ${directory}`,\n\t\t);\n\t\treturn fileValue(\n\t\t\tawait this.fileSystem.joinPath([directory, sessionFileName(createdAt, id)], context),\n\t\t\t`Failed to resolve path for session ${id}`,\n\t\t);\n\t}\n\n\tprivate async assertSessionIdAvailable(directory: string, id: string, context: Context): Promise<void> {\n\t\tif (\n\t\t\t!fileValue(await this.fileSystem.exists(directory, context), `Failed to check sessions directory ${directory}`)\n\t\t)\n\t\t\treturn;\n\n\t\tconst suffix = `_${encodeURIComponent(id)}.jsonl`;\n\t\tconst idExists = fileValue(\n\t\t\tawait this.fileSystem.listDir(directory, context),\n\t\t\t`Failed to list sessions directory ${directory}`,\n\t\t).some((entry) => entry.kind !== \"directory\" && entry.name.endsWith(suffix));\n\t\tif (idExists) throw new Error(`Session already exists: ${id}`);\n\t}\n\n\tprivate async loadClosedForkSourceSnapshot(\n\t\tsource: JsonlSessionMetadata,\n\t\tcontext: Context,\n\t): Promise<ForkSourceSnapshot> {\n\t\tconst storage = await this.loadStorage(source, context);\n\t\ttry {\n\t\t\treturn await storage.captureForkSource(context);\n\t\t} finally {\n\t\t\tawait storage.close(context);\n\t\t}\n\t}\n\n\tprivate publishOpenSession(\n\t\tmetadata: JsonlSessionMetadata,\n\t\tstorage: JsonlStorage,\n\t\tkey: string,\n\t): StorageBackedSession<JsonlSessionMetadata> {\n\t\tif (this.openSessions.has(key)) throw new Error(`Session is already open: ${metadata.id}`);\n\t\tconst session = new StorageBackedSession(metadata, storage, {\n\t\t\tonClose: () => {\n\t\t\t\tif (this.openSessions.get(key) === storage) this.openSessions.delete(key);\n\t\t\t},\n\t\t});\n\t\tthis.openSessions.set(key, storage);\n\t\treturn session;\n\t}\n\n\tprivate sessionKey(cwd: string, id: string): string {\n\t\treturn `${cwd}\\0${id}`;\n\t}\n\n\tprivate async loadStorage(metadata: JsonlSessionMetadata, context: Context): Promise<JsonlStorage> {\n\t\tif (\n\t\t\t!fileValue(await this.fileSystem.exists(metadata.path, context), `Failed to check session ${metadata.path}`)\n\t\t) {\n\t\t\tthrow new Error(`Session file does not exist: ${metadata.path}`);\n\t\t}\n\t\tconst storage = await JsonlStorage.open(\n\t\t\t{\n\t\t\t\tfileSystem: this.fileSystem,\n\t\t\t\tpath: metadata.path,\n\t\t\t\tnow: this.now,\n\t\t\t},\n\t\t\tcontext,\n\t\t);\n\t\ttry {\n\t\t\tif (storage.header.id !== metadata.id || storage.header.cwd !== metadata.cwd) {\n\t\t\t\tthrow new Error(`Session identity does not match header: ${metadata.id}`);\n\t\t\t}\n\t\t\tif (storage.header.storageVersion !== JSONL_STORAGE_VERSION) {\n\t\t\t\tthrow new Error(`Session ${metadata.id} uses unsupported storage version ${storage.header.storageVersion}`);\n\t\t\t}\n\t\t\treturn storage;\n\t\t} catch (error) {\n\t\t\tawait storage.close(context);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate root(context: Context): Promise<string> {\n\t\treturn this.fileSystem\n\t\t\t.absolutePath(this.sessionsRootInput, context)\n\t\t\t.then((result) => fileValue(result, `Failed to resolve sessions root ${this.sessionsRootInput}`));\n\t}\n\n\tprivate assertOpen(): void {\n\t\tif (this.closed) throw new Error(\"JsonlSessionRepo is closed\");\n\t}\n}\n"]}