@earendil-works/pi-agent-core 0.84.1 → 0.84.2
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.
- package/dist/harness/events.d.ts +43 -0
- package/dist/harness/events.d.ts.map +1 -0
- package/dist/harness/events.js +65 -0
- package/dist/harness/events.js.map +1 -0
- package/dist/harness/session/jsonl/codec.d.ts +4 -2
- package/dist/harness/session/jsonl/codec.d.ts.map +1 -1
- package/dist/harness/session/jsonl/codec.js +127 -88
- package/dist/harness/session/jsonl/codec.js.map +1 -1
- package/dist/harness/session/jsonl/errors.d.ts +5 -1
- package/dist/harness/session/jsonl/errors.d.ts.map +1 -1
- package/dist/harness/session/jsonl/errors.js +10 -2
- package/dist/harness/session/jsonl/errors.js.map +1 -1
- package/dist/harness/session/jsonl/repo.d.ts +7 -3
- package/dist/harness/session/jsonl/repo.d.ts.map +1 -1
- package/dist/harness/session/jsonl/repo.js +88 -45
- package/dist/harness/session/jsonl/repo.js.map +1 -1
- package/dist/harness/session/jsonl/storage.d.ts +1 -1
- package/dist/harness/session/jsonl/storage.d.ts.map +1 -1
- package/dist/harness/session/jsonl/storage.js +28 -19
- package/dist/harness/session/jsonl/storage.js.map +1 -1
- package/dist/harness/session/jsonl/types.d.ts +1 -1
- package/dist/harness/session/jsonl/types.d.ts.map +1 -1
- package/dist/harness/session/jsonl/types.js.map +1 -1
- package/dist/harness/session/memory.d.ts +1 -1
- package/dist/harness/session/memory.d.ts.map +1 -1
- package/dist/harness/session/memory.js.map +1 -1
- package/dist/harness/session/session.d.ts +1 -1
- package/dist/harness/session/session.d.ts.map +1 -1
- package/dist/harness/session/session.js +7 -2
- package/dist/harness/session/session.js.map +1 -1
- package/dist/harness/session/state.d.ts +1 -1
- package/dist/harness/session/state.d.ts.map +1 -1
- package/dist/harness/session/state.js.map +1 -1
- package/dist/harness/session/testing/conformance.d.ts.map +1 -1
- package/dist/harness/session/testing/conformance.js +19 -0
- package/dist/harness/session/testing/conformance.js.map +1 -1
- package/dist/harness/session/types.d.ts +18 -5
- package/dist/harness/session/types.d.ts.map +1 -1
- package/dist/harness/session/types.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/proxy.d.ts +2 -1
- package/dist/proxy.d.ts.map +1 -1
- package/dist/proxy.js +1 -0
- package/dist/proxy.js.map +1 -1
- package/dist/search/index.d.ts +21 -0
- package/dist/search/index.d.ts.map +1 -0
- package/dist/search/index.js +2 -0
- package/dist/search/index.js.map +1 -0
- package/dist/search/scanning.d.ts +29 -0
- package/dist/search/scanning.d.ts.map +1 -0
- package/dist/search/scanning.js +103 -0
- package/dist/search/scanning.js.map +1 -0
- package/package.json +3 -3
- package/dist/harness/session/search.d.ts +0 -19
- package/dist/harness/session/search.d.ts.map +0 -1
- package/dist/harness/session/search.js +0 -42
- package/dist/harness/session/search.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../src/harness/session/jsonl/errors.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,MAAM,UAAU,UAAU,CAAI,MAA4B,EAAE,OAAe,EAAK;IAC/E,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;QAChB,MAAM,IAAI,YAAY,CACrB,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,EAC3D,GAAG,OAAO,KAAK,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,EACrC,MAAM,CAAC,KAAK,CACZ,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC,KAAK,CAAC;AAAA,CACpB;AAED,MAAM,UAAU,WAAW,CAAC,IAAY,EAAE,IAAY,EAAE,
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../src/harness/session/jsonl/errors.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,MAAM,OAAO,gBAAiB,SAAQ,KAAK;IACjC,IAAI,CAAsB;IAEnC,YAAY,IAAyB,EAAE,OAAe,EAAE,KAAa,EAAE;QACtE,KAAK,CAAC,OAAO,EAAE,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAC5D,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAC;QAC/B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;CACD;AAED,MAAM,UAAU,UAAU,CAAI,MAA4B,EAAE,OAAe,EAAK;IAC/E,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;QAChB,MAAM,IAAI,YAAY,CACrB,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,EAC3D,GAAG,OAAO,KAAK,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,EACrC,MAAM,CAAC,KAAK,CACZ,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC,KAAK,CAAC;AAAA,CACpB;AAED,MAAM,UAAU,WAAW,CAAC,IAAY,EAAE,IAAY,EAAE,KAAY,EAAgB;IACnF,OAAO,IAAI,YAAY,CAAC,eAAe,EAAE,4BAA4B,IAAI,UAAU,IAAI,IAAI,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,CAAC,CAAC;AAAA,CACnH","sourcesContent":["import type { FileError, Result } from \"../../types.ts\";\nimport { SessionError } from \"../types.ts\";\n\nexport class JsonlDecodeError extends Error {\n\treadonly kind: \"syntax\" | \"schema\";\n\n\tconstructor(kind: \"syntax\" | \"schema\", message: string, cause?: Error) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"JsonlDecodeError\";\n\t\tthis.kind = kind;\n\t}\n}\n\nexport function fileResult<T>(result: Result<T, FileError>, message: string): T {\n\tif (!result.ok) {\n\t\tthrow new SessionError(\n\t\t\tresult.error.code === \"not_found\" ? \"not_found\" : \"storage\",\n\t\t\t`${message}: ${result.error.message}`,\n\t\t\tresult.error,\n\t\t);\n\t}\n\treturn result.value;\n}\n\nexport function invalidFile(path: string, line: number, cause: Error): SessionError {\n\treturn new SessionError(\"invalid_entry\", `Invalid JSONL v4 session ${path}: line ${line} ${cause.message}`, cause);\n}\n"]}
|
|
@@ -1,22 +1,26 @@
|
|
|
1
1
|
import { Session } from "../session.ts";
|
|
2
2
|
import { type ForkOptions, type SessionRepo } from "../types.ts";
|
|
3
|
+
import { JsonlSessionStorage } from "./storage.ts";
|
|
3
4
|
import type { JsonlSessionCreateOptions, JsonlSessionListOptions, JsonlSessionMetadata, JsonlSessionRepoOptions } from "./types.ts";
|
|
5
|
+
export declare function listJsonlSessionMetadata(options: JsonlSessionRepoOptions, query?: JsonlSessionListOptions): Promise<JsonlSessionMetadata[]>;
|
|
6
|
+
export declare function loadJsonlSessionStorage(options: JsonlSessionRepoOptions, metadata: JsonlSessionMetadata): Promise<JsonlSessionStorage>;
|
|
4
7
|
export declare class JsonlSessionRepo implements SessionRepo<JsonlSessionMetadata, JsonlSessionCreateOptions, JsonlSessionListOptions> {
|
|
5
8
|
private readonly fs;
|
|
6
9
|
private readonly sessionsRootInput;
|
|
10
|
+
private readonly activeCreateDestinations;
|
|
7
11
|
private rootPromise;
|
|
8
12
|
constructor(options: JsonlSessionRepoOptions);
|
|
9
13
|
create(options: JsonlSessionCreateOptions): Promise<Session<JsonlSessionMetadata>>;
|
|
10
14
|
open(metadata: JsonlSessionMetadata): Promise<Session<JsonlSessionMetadata>>;
|
|
11
|
-
list(): Promise<JsonlSessionMetadata[]>;
|
|
12
|
-
list(options: JsonlSessionListOptions): Promise<JsonlSessionMetadata[]>;
|
|
15
|
+
list(options?: JsonlSessionListOptions): Promise<JsonlSessionMetadata[]>;
|
|
13
16
|
delete(metadata: JsonlSessionMetadata): Promise<void>;
|
|
14
17
|
fork(source: JsonlSessionMetadata, options: ForkOptions & JsonlSessionCreateOptions): Promise<Session<JsonlSessionMetadata>>;
|
|
15
18
|
private loadStorage;
|
|
19
|
+
private resolveCreateDestination;
|
|
20
|
+
private claimCreateDestination;
|
|
16
21
|
private prepareCreate;
|
|
17
22
|
private listDirect;
|
|
18
23
|
private sessionIdExists;
|
|
19
|
-
private sessionDirectories;
|
|
20
24
|
private sessionDirectory;
|
|
21
25
|
private root;
|
|
22
26
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"repo.d.ts","sourceRoot":"","sources":["../../../../src/harness/session/jsonl/repo.ts"],"names":[],"mappings":"AACA,OAAO,EAA0B,OAAO,EAAE,MAAM,eAAe,CAAC;AAChE,OAAO,EAAE,KAAK,WAAW,EAAgB,KAAK,WAAW,EAAE,MAAM,aAAa,CAAC;AAI/E,OAAO,KAAK,EACX,yBAAyB,EACzB,uBAAuB,EACvB,oBAAoB,EAEpB,uBAAuB,EAEvB,MAAM,YAAY,CAAC;AAsBpB,qBAAa,gBACZ,YAAW,WAAW,CAAC,oBAAoB,EAAE,yBAAyB,EAAE,uBAAuB,CAAC;IAEhG,OAAO,CAAC,QAAQ,CAAC,EAAE,CAA6B;IAChD,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAS;IAC3C,OAAO,CAAC,WAAW,CAA8B;IAEjD,YAAY,OAAO,EAAE,uBAAuB,EAG3C;IAEK,MAAM,CAAC,OAAO,EAAE,yBAAyB,GAAG,OAAO,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAGvF;IAEK,IAAI,CAAC,QAAQ,EAAE,oBAAoB,GAAG,OAAO,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAEjF;IAED,IAAI,IAAI,OAAO,CAAC,oBAAoB,EAAE,CAAC,CAAC;IACxC,IAAI,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,oBAAoB,EAAE,CAAC,CAAC;IAKlE,MAAM,CAAC,QAAQ,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAE1D;IAEK,IAAI,CACT,MAAM,EAAE,oBAAoB,EAC5B,OAAO,EAAE,WAAW,GAAG,yBAAyB,GAC9C,OAAO,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAOxC;YAEa,WAAW;YAYX,aAAa;YA+Bb,UAAU;YAqBV,eAAe;YAQf,kBAAkB;YAelB,gBAAgB;IAO9B,OAAO,CAAC,IAAI;CAMZ","sourcesContent":["import { uuidv7 } from \"@earendil-works/pi-ai\";\nimport { assertJsonSerializable, Session } from \"../session.ts\";\nimport { type ForkOptions, SessionError, type SessionRepo } from \"../types.ts\";\nimport { metadataFromHeader, parseHeader } from \"./codec.ts\";\nimport { fileResult, invalidFile } from \"./errors.ts\";\nimport { JsonlSessionStorage } from \"./storage.ts\";\nimport type {\n\tJsonlSessionCreateOptions,\n\tJsonlSessionListOptions,\n\tJsonlSessionMetadata,\n\tJsonlSessionRepoFileSystem,\n\tJsonlSessionRepoOptions,\n\tJsonlV4Header,\n} from \"./types.ts\";\n\nconst SESSION_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;\n\nfunction validateSessionId(id: string): void {\n\tif (!SESSION_ID_PATTERN.test(id)) {\n\t\tthrow new SessionError(\n\t\t\t\"invalid_payload\",\n\t\t\t\"Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character\",\n\t\t);\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}_${id}.jsonl`;\n}\n\nexport class JsonlSessionRepo\n\timplements SessionRepo<JsonlSessionMetadata, JsonlSessionCreateOptions, JsonlSessionListOptions>\n{\n\tprivate readonly fs: JsonlSessionRepoFileSystem;\n\tprivate readonly sessionsRootInput: string;\n\tprivate rootPromise: Promise<string> | undefined;\n\n\tconstructor(options: JsonlSessionRepoOptions) {\n\t\tthis.fs = options.fs;\n\t\tthis.sessionsRootInput = options.sessionsRoot;\n\t}\n\n\tasync create(options: JsonlSessionCreateOptions): Promise<Session<JsonlSessionMetadata>> {\n\t\tconst { header, path } = await this.prepareCreate(options);\n\t\treturn new Session(await JsonlSessionStorage.create(this.fs, path, header));\n\t}\n\n\tasync open(metadata: JsonlSessionMetadata): Promise<Session<JsonlSessionMetadata>> {\n\t\treturn new Session(await this.loadStorage(metadata));\n\t}\n\n\tlist(): Promise<JsonlSessionMetadata[]>;\n\tlist(options: JsonlSessionListOptions): Promise<JsonlSessionMetadata[]>;\n\tasync list(options: JsonlSessionListOptions = {}): Promise<JsonlSessionMetadata[]> {\n\t\treturn this.listDirect(options);\n\t}\n\n\tasync delete(metadata: JsonlSessionMetadata): Promise<void> {\n\t\tfileResult(await this.fs.remove(metadata.path, { force: true }), `Failed to delete session ${metadata.path}`);\n\t}\n\n\tasync fork(\n\t\tsource: JsonlSessionMetadata,\n\t\toptions: ForkOptions & JsonlSessionCreateOptions,\n\t): Promise<Session<JsonlSessionMetadata>> {\n\t\tconst sourceStorage = await this.loadStorage(source);\n\t\tconst { header, path } = await this.prepareCreate({\n\t\t\t...options,\n\t\t\tparentSessionId: options.parentSessionId ?? source.id,\n\t\t});\n\t\treturn new Session(await sourceStorage.fork(path, header, options));\n\t}\n\n\tprivate async loadStorage(metadata: JsonlSessionMetadata): Promise<JsonlSessionStorage> {\n\t\tif (!fileResult(await this.fs.exists(metadata.path), `Failed to check session ${metadata.path}`)) {\n\t\t\tthrow new SessionError(\"not_found\", `Session not found: ${metadata.id}`);\n\t\t}\n\t\tconst storage = await JsonlSessionStorage.load(this.fs, metadata.path);\n\t\tconst loadedMetadata = await storage.getMetadata();\n\t\tif (loadedMetadata.id !== metadata.id) {\n\t\t\tthrow new SessionError(\"invalid_entry\", `Session id does not match header: ${metadata.id}`);\n\t\t}\n\t\treturn storage;\n\t}\n\n\tprivate async prepareCreate(options: JsonlSessionCreateOptions): Promise<{\n\t\theader: JsonlV4Header;\n\t\tpath: string;\n\t}> {\n\t\tconst id = options.id ?? uuidv7();\n\t\tvalidateSessionId(id);\n\t\tconst cwd = fileResult(await this.fs.absolutePath(options.cwd), `Failed to resolve session cwd ${options.cwd}`);\n\t\tif (await this.sessionIdExists(id, cwd)) {\n\t\t\tthrow new SessionError(\"already_exists\", `Session already exists: ${id}`);\n\t\t}\n\n\t\tconst createdAt = Date.now();\n\t\tconst sessionDirectory = await this.sessionDirectory(cwd);\n\t\tconst path = fileResult(\n\t\t\tawait this.fs.joinPath([sessionDirectory, sessionFileName(createdAt, id)]),\n\t\t\t`Failed to resolve path for session ${id}`,\n\t\t);\n\t\tif (options.metadata !== undefined) assertJsonSerializable(options.metadata);\n\t\tconst header: JsonlV4Header = {\n\t\t\tkind: \"header\",\n\t\t\tversion: 4,\n\t\t\tid,\n\t\t\tcreatedAt,\n\t\t\tcwd,\n\t\t\tparentSessionId: options.parentSessionId,\n\t\t\tmetadata: options.metadata,\n\t\t};\n\t\tfileResult(await this.fs.createDir(sessionDirectory, { recursive: true }), `Failed to create sessions directory`);\n\t\treturn { header, path };\n\t}\n\n\tprivate async listDirect(options: JsonlSessionListOptions): Promise<JsonlSessionMetadata[]> {\n\t\tconst directories = await this.sessionDirectories(options.cwd);\n\t\tconst metadata: JsonlSessionMetadata[] = [];\n\t\tfor (const directory of directories) {\n\t\t\tconst files = fileResult(\n\t\t\t\tawait this.fs.listDir(directory),\n\t\t\t\t`Failed to list sessions directory ${directory}`,\n\t\t\t).filter((entry) => entry.kind !== \"directory\" && entry.name.endsWith(\".jsonl\"));\n\t\t\tfor (const file of files) {\n\t\t\t\tconst content = fileResult(\n\t\t\t\t\tawait this.fs.readTextFile(file.path),\n\t\t\t\t\t`Failed to read session header ${file.path}`,\n\t\t\t\t);\n\t\t\t\tconst firstLine = content.split(\"\\n\", 1)[0];\n\t\t\t\tif (!firstLine) throw invalidFile(file.path, 1, \"is missing a header\");\n\t\t\t\tmetadata.push(metadataFromHeader(parseHeader(firstLine, file.path), file.path, file.mtimeMs));\n\t\t\t}\n\t\t}\n\t\treturn metadata.sort((left, right) => right.modifiedAt - left.modifiedAt);\n\t}\n\n\tprivate async sessionIdExists(id: string, cwd: string): Promise<boolean> {\n\t\tconst suffix = `_${id}.jsonl`;\n\t\tconst directory = await this.sessionDirectory(cwd);\n\t\tif (!fileResult(await this.fs.exists(directory), `Failed to check sessions directory ${directory}`)) return false;\n\t\tconst files = fileResult(await this.fs.listDir(directory), `Failed to list sessions directory ${directory}`);\n\t\treturn files.some((entry) => entry.kind !== \"directory\" && entry.name.endsWith(suffix));\n\t}\n\n\tprivate async sessionDirectories(cwd?: string): Promise<string[]> {\n\t\tconst root = await this.root();\n\t\tif (cwd !== undefined) {\n\t\t\tconst resolvedCwd = fileResult(await this.fs.absolutePath(cwd), `Failed to resolve session cwd ${cwd}`);\n\t\t\tconst directory = await this.sessionDirectory(resolvedCwd);\n\t\t\treturn fileResult(await this.fs.exists(directory), `Failed to check sessions directory ${directory}`)\n\t\t\t\t? [directory]\n\t\t\t\t: [];\n\t\t}\n\t\tif (!fileResult(await this.fs.exists(root), `Failed to check sessions directory ${root}`)) return [];\n\t\treturn fileResult(await this.fs.listDir(root), `Failed to list sessions directory ${root}`)\n\t\t\t.filter((entry) => entry.kind === \"directory\" || entry.kind === \"symlink\")\n\t\t\t.map((entry) => entry.path);\n\t}\n\n\tprivate async sessionDirectory(cwd: string): Promise<string> {\n\t\treturn fileResult(\n\t\t\tawait this.fs.joinPath([await this.root(), sessionDirectoryName(cwd)]),\n\t\t\t`Failed to resolve sessions directory for ${cwd}`,\n\t\t);\n\t}\n\n\tprivate root(): Promise<string> {\n\t\tthis.rootPromise ??= this.fs\n\t\t\t.absolutePath(this.sessionsRootInput)\n\t\t\t.then((result) => fileResult(result, `Failed to resolve sessions root ${this.sessionsRootInput}`));\n\t\treturn this.rootPromise;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"repo.d.ts","sourceRoot":"","sources":["../../../../src/harness/session/jsonl/repo.ts"],"names":[],"mappings":"AACA,OAAO,EAA0B,OAAO,EAAE,MAAM,eAAe,CAAC;AAChE,OAAO,EAAE,KAAK,WAAW,EAAgB,KAAK,WAAW,EAAE,MAAM,aAAa,CAAC;AAG/E,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,KAAK,EACX,yBAAyB,EACzB,uBAAuB,EACvB,oBAAoB,EAEpB,uBAAuB,EAEvB,MAAM,YAAY,CAAC;AAmDpB,wBAAsB,wBAAwB,CAC7C,OAAO,EAAE,uBAAuB,EAChC,KAAK,GAAE,uBAA4B,GACjC,OAAO,CAAC,oBAAoB,EAAE,CAAC,CAmBjC;AAED,wBAAsB,uBAAuB,CAC5C,OAAO,EAAE,uBAAuB,EAChC,QAAQ,EAAE,oBAAoB,GAC5B,OAAO,CAAC,mBAAmB,CAAC,CAU9B;AAOD,qBAAa,gBACZ,YAAW,WAAW,CAAC,oBAAoB,EAAE,yBAAyB,EAAE,uBAAuB,CAAC;IAEhG,OAAO,CAAC,QAAQ,CAAC,EAAE,CAA6B;IAChD,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAS;IAC3C,OAAO,CAAC,QAAQ,CAAC,wBAAwB,CAAqB;IAC9D,OAAO,CAAC,WAAW,CAA8B;IAEjD,YAAY,OAAO,EAAE,uBAAuB,EAG3C;IAEK,MAAM,CAAC,OAAO,EAAE,yBAAyB,GAAG,OAAO,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAMvF;IAEK,IAAI,CAAC,QAAQ,EAAE,oBAAoB,GAAG,OAAO,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAEjF;IAEK,IAAI,CAAC,OAAO,GAAE,uBAA4B,GAAG,OAAO,CAAC,oBAAoB,EAAE,CAAC,CAEjF;IAEK,MAAM,CAAC,QAAQ,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAE1D;IAEK,IAAI,CACT,MAAM,EAAE,oBAAoB,EAC5B,OAAO,EAAE,WAAW,GAAG,yBAAyB,GAC9C,OAAO,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAWxC;YAEa,WAAW;YAIX,wBAAwB;YAYxB,sBAAsB;YAgBtB,aAAa;YAgCb,UAAU;YAIV,eAAe;YAQf,gBAAgB;IAO9B,OAAO,CAAC,IAAI;CAMZ","sourcesContent":["import { uuidv7 } from \"@earendil-works/pi-ai\";\nimport { assertJsonSerializable, Session } from \"../session.ts\";\nimport { type ForkOptions, SessionError, type SessionRepo } from \"../types.ts\";\nimport { metadataFromHeader, parseHeader } from \"./codec.ts\";\nimport { fileResult } from \"./errors.ts\";\nimport { JsonlSessionStorage } from \"./storage.ts\";\nimport type {\n\tJsonlSessionCreateOptions,\n\tJsonlSessionListOptions,\n\tJsonlSessionMetadata,\n\tJsonlSessionRepoFileSystem,\n\tJsonlSessionRepoOptions,\n\tJsonlV4Header,\n} from \"./types.ts\";\n\nconst SESSION_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;\n\nfunction validateSessionId(id: string): void {\n\tif (!SESSION_ID_PATTERN.test(id)) {\n\t\tthrow new SessionError(\n\t\t\t\"invalid_payload\",\n\t\t\t\"Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character\",\n\t\t);\n\t}\n}\n\nfunction jsonlSessionDirectoryName(cwd: string): string {\n\treturn `--${cwd.replace(/^[/\\\\]/, \"\").replace(/[/\\\\:]/g, \"-\")}--`;\n}\n\nasync function jsonlSessionsRoot(options: JsonlSessionRepoOptions): Promise<string> {\n\treturn fileResult(\n\t\tawait options.fs.absolutePath(options.sessionsRoot),\n\t\t`Failed to resolve sessions root ${options.sessionsRoot}`,\n\t);\n}\n\nasync function jsonlSessionDirectory(\n\tfs: JsonlSessionRepoFileSystem,\n\tsessionsRoot: string,\n\tcwd: string,\n): Promise<string> {\n\treturn fileResult(\n\t\tawait fs.joinPath([sessionsRoot, jsonlSessionDirectoryName(cwd)]),\n\t\t`Failed to resolve sessions directory for ${cwd}`,\n\t);\n}\n\nasync function jsonlSessionDirectories(options: JsonlSessionRepoOptions, cwd?: string): Promise<string[]> {\n\tconst sessionsRoot = await jsonlSessionsRoot(options);\n\tif (cwd !== undefined) {\n\t\tconst resolvedCwd = fileResult(await options.fs.absolutePath(cwd), `Failed to resolve session cwd ${cwd}`);\n\t\tconst directory = await jsonlSessionDirectory(options.fs, sessionsRoot, resolvedCwd);\n\t\treturn fileResult(await options.fs.exists(directory), `Failed to check sessions directory ${directory}`)\n\t\t\t? [directory]\n\t\t\t: [];\n\t}\n\tif (!fileResult(await options.fs.exists(sessionsRoot), `Failed to check sessions directory ${sessionsRoot}`))\n\t\treturn [];\n\treturn fileResult(await options.fs.listDir(sessionsRoot), `Failed to list sessions directory ${sessionsRoot}`)\n\t\t.filter((entry) => entry.kind === \"directory\" || entry.kind === \"symlink\")\n\t\t.map((entry) => entry.path);\n}\n\nexport async function listJsonlSessionMetadata(\n\toptions: JsonlSessionRepoOptions,\n\tquery: JsonlSessionListOptions = {},\n): Promise<JsonlSessionMetadata[]> {\n\tconst metadata: JsonlSessionMetadata[] = [];\n\tfor (const directory of await jsonlSessionDirectories(options, query.cwd)) {\n\t\tconst files = fileResult(\n\t\t\tawait options.fs.listDir(directory),\n\t\t\t`Failed to list sessions directory ${directory}`,\n\t\t).filter((entry) => entry.kind !== \"directory\" && entry.name.endsWith(\".jsonl\"));\n\t\tfor (const file of files) {\n\t\t\tconst [firstLine] = fileResult(\n\t\t\t\tawait options.fs.readTextLines(file.path, { maxLines: 1 }),\n\t\t\t\t`Failed to read session header ${file.path}`,\n\t\t\t);\n\t\t\tif (!firstLine) continue;\n\t\t\tconst headerResult = parseHeader(firstLine);\n\t\t\tif (!headerResult.ok) continue;\n\t\t\tmetadata.push(metadataFromHeader(headerResult.value, file.path, file.mtimeMs));\n\t\t}\n\t}\n\treturn metadata.sort((left, right) => right.modifiedAt - left.modifiedAt);\n}\n\nexport async function loadJsonlSessionStorage(\n\toptions: JsonlSessionRepoOptions,\n\tmetadata: JsonlSessionMetadata,\n): Promise<JsonlSessionStorage> {\n\tif (!fileResult(await options.fs.exists(metadata.path), `Failed to check session ${metadata.path}`)) {\n\t\tthrow new SessionError(\"not_found\", `Session not found: ${metadata.id}`);\n\t}\n\tconst storage = await JsonlSessionStorage.load(options.fs, metadata.path);\n\tconst loadedMetadata = await storage.getMetadata();\n\tif (loadedMetadata.id !== metadata.id) {\n\t\tthrow new SessionError(\"invalid_entry\", `Session id does not match header: ${metadata.id}`);\n\t}\n\treturn storage;\n}\n\nfunction sessionFileName(createdAt: number, id: string): string {\n\tconst timestamp = new Date(createdAt).toISOString().replace(/[:.]/g, \"-\");\n\treturn `${timestamp}_${id}.jsonl`;\n}\n\nexport class JsonlSessionRepo\n\timplements SessionRepo<JsonlSessionMetadata, JsonlSessionCreateOptions, JsonlSessionListOptions>\n{\n\tprivate readonly fs: JsonlSessionRepoFileSystem;\n\tprivate readonly sessionsRootInput: string;\n\tprivate readonly activeCreateDestinations = new Set<string>();\n\tprivate rootPromise: Promise<string> | undefined;\n\n\tconstructor(options: JsonlSessionRepoOptions) {\n\t\tthis.fs = options.fs;\n\t\tthis.sessionsRootInput = options.sessionsRoot;\n\t}\n\n\tasync create(options: JsonlSessionCreateOptions): Promise<Session<JsonlSessionMetadata>> {\n\t\tconst destination = await this.resolveCreateDestination(options);\n\t\treturn this.claimCreateDestination(destination, async () => {\n\t\t\tconst { header, path } = await this.prepareCreate(destination, options);\n\t\t\treturn new Session(await JsonlSessionStorage.create(this.fs, path, header));\n\t\t});\n\t}\n\n\tasync open(metadata: JsonlSessionMetadata): Promise<Session<JsonlSessionMetadata>> {\n\t\treturn new Session(await this.loadStorage(metadata));\n\t}\n\n\tasync list(options: JsonlSessionListOptions = {}): Promise<JsonlSessionMetadata[]> {\n\t\treturn this.listDirect(options);\n\t}\n\n\tasync delete(metadata: JsonlSessionMetadata): Promise<void> {\n\t\tfileResult(await this.fs.remove(metadata.path, { force: true }), `Failed to delete session ${metadata.path}`);\n\t}\n\n\tasync fork(\n\t\tsource: JsonlSessionMetadata,\n\t\toptions: ForkOptions & JsonlSessionCreateOptions,\n\t): Promise<Session<JsonlSessionMetadata>> {\n\t\tconst sourceStorage = await this.loadStorage(source);\n\t\tconst createOptions = {\n\t\t\t...options,\n\t\t\tparentSessionId: options.parentSessionId ?? source.id,\n\t\t};\n\t\tconst destination = await this.resolveCreateDestination(createOptions);\n\t\treturn this.claimCreateDestination(destination, async () => {\n\t\t\tconst { header, path } = await this.prepareCreate(destination, createOptions);\n\t\t\treturn new Session(await sourceStorage.fork(path, header, options));\n\t\t});\n\t}\n\n\tprivate async loadStorage(metadata: JsonlSessionMetadata): Promise<JsonlSessionStorage> {\n\t\treturn loadJsonlSessionStorage({ fs: this.fs, sessionsRoot: this.sessionsRootInput }, metadata);\n\t}\n\n\tprivate async resolveCreateDestination(options: JsonlSessionCreateOptions): Promise<{ id: string; cwd: string }> {\n\t\tconst id = options.id ?? uuidv7();\n\t\tvalidateSessionId(id);\n\t\tconst cwd = fileResult(await this.fs.absolutePath(options.cwd), `Failed to resolve session cwd ${options.cwd}`);\n\t\treturn { id, cwd };\n\t}\n\n\t/**\n\t * Prevent same-process create/fork races for one logical destination. The durable filename includes a\n\t * timestamp, so the async filesystem existence check alone can let two concurrent calls both decide the\n\t * same {cwd, id} is free and publish duplicate sessions.\n\t */\n\tprivate async claimCreateDestination<T>(\n\t\tdestination: { id: string; cwd: string },\n\t\toperation: () => Promise<T>,\n\t): Promise<T> {\n\t\tconst key = `${destination.cwd}\\0${destination.id}`;\n\t\tif (this.activeCreateDestinations.has(key)) {\n\t\t\tthrow new SessionError(\"already_exists\", `Session already exists: ${destination.id}`);\n\t\t}\n\t\tthis.activeCreateDestinations.add(key);\n\t\ttry {\n\t\t\treturn await operation();\n\t\t} finally {\n\t\t\tthis.activeCreateDestinations.delete(key);\n\t\t}\n\t}\n\n\tprivate async prepareCreate(\n\t\tdestination: { id: string; cwd: string },\n\t\toptions: JsonlSessionCreateOptions,\n\t): Promise<{\n\t\theader: JsonlV4Header;\n\t\tpath: string;\n\t}> {\n\t\tconst { id, cwd } = destination;\n\t\tif (await this.sessionIdExists(id, cwd)) {\n\t\t\tthrow new SessionError(\"already_exists\", `Session already exists: ${id}`);\n\t\t}\n\n\t\tconst createdAt = Date.now();\n\t\tconst sessionDirectory = await this.sessionDirectory(cwd);\n\t\tconst path = fileResult(\n\t\t\tawait this.fs.joinPath([sessionDirectory, sessionFileName(createdAt, id)]),\n\t\t\t`Failed to resolve path for session ${id}`,\n\t\t);\n\t\tif (options.metadata !== undefined) assertJsonSerializable(options.metadata);\n\t\tconst header: JsonlV4Header = {\n\t\t\tkind: \"header\",\n\t\t\tversion: 4,\n\t\t\tid,\n\t\t\tcreatedAt,\n\t\t\tcwd,\n\t\t\tparentSessionId: options.parentSessionId,\n\t\t\tmetadata: options.metadata,\n\t\t};\n\t\tfileResult(await this.fs.createDir(sessionDirectory, { recursive: true }), `Failed to create sessions directory`);\n\t\treturn { header, path };\n\t}\n\n\tprivate async listDirect(options: JsonlSessionListOptions): Promise<JsonlSessionMetadata[]> {\n\t\treturn listJsonlSessionMetadata({ fs: this.fs, sessionsRoot: this.sessionsRootInput }, options);\n\t}\n\n\tprivate async sessionIdExists(id: string, cwd: string): Promise<boolean> {\n\t\tconst suffix = `_${id}.jsonl`;\n\t\tconst directory = await this.sessionDirectory(cwd);\n\t\tif (!fileResult(await this.fs.exists(directory), `Failed to check sessions directory ${directory}`)) return false;\n\t\tconst files = fileResult(await this.fs.listDir(directory), `Failed to list sessions directory ${directory}`);\n\t\treturn files.some((entry) => entry.kind !== \"directory\" && entry.name.endsWith(suffix));\n\t}\n\n\tprivate async sessionDirectory(cwd: string): Promise<string> {\n\t\treturn fileResult(\n\t\t\tawait this.fs.joinPath([await this.root(), jsonlSessionDirectoryName(cwd)]),\n\t\t\t`Failed to resolve sessions directory for ${cwd}`,\n\t\t);\n\t}\n\n\tprivate root(): Promise<string> {\n\t\tthis.rootPromise ??= this.fs\n\t\t\t.absolutePath(this.sessionsRootInput)\n\t\t\t.then((result) => fileResult(result, `Failed to resolve sessions root ${this.sessionsRootInput}`));\n\t\treturn this.rootPromise;\n\t}\n}\n"]}
|
|
@@ -2,7 +2,7 @@ import { uuidv7 } from "@earendil-works/pi-ai";
|
|
|
2
2
|
import { assertJsonSerializable, Session } from "../session.js";
|
|
3
3
|
import { SessionError } from "../types.js";
|
|
4
4
|
import { metadataFromHeader, parseHeader } from "./codec.js";
|
|
5
|
-
import { fileResult
|
|
5
|
+
import { fileResult } from "./errors.js";
|
|
6
6
|
import { JsonlSessionStorage } from "./storage.js";
|
|
7
7
|
const SESSION_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
|
|
8
8
|
function validateSessionId(id) {
|
|
@@ -10,9 +10,57 @@ function validateSessionId(id) {
|
|
|
10
10
|
throw new SessionError("invalid_payload", "Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character");
|
|
11
11
|
}
|
|
12
12
|
}
|
|
13
|
-
function
|
|
13
|
+
function jsonlSessionDirectoryName(cwd) {
|
|
14
14
|
return `--${cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
|
|
15
15
|
}
|
|
16
|
+
async function jsonlSessionsRoot(options) {
|
|
17
|
+
return fileResult(await options.fs.absolutePath(options.sessionsRoot), `Failed to resolve sessions root ${options.sessionsRoot}`);
|
|
18
|
+
}
|
|
19
|
+
async function jsonlSessionDirectory(fs, sessionsRoot, cwd) {
|
|
20
|
+
return fileResult(await fs.joinPath([sessionsRoot, jsonlSessionDirectoryName(cwd)]), `Failed to resolve sessions directory for ${cwd}`);
|
|
21
|
+
}
|
|
22
|
+
async function jsonlSessionDirectories(options, cwd) {
|
|
23
|
+
const sessionsRoot = await jsonlSessionsRoot(options);
|
|
24
|
+
if (cwd !== undefined) {
|
|
25
|
+
const resolvedCwd = fileResult(await options.fs.absolutePath(cwd), `Failed to resolve session cwd ${cwd}`);
|
|
26
|
+
const directory = await jsonlSessionDirectory(options.fs, sessionsRoot, resolvedCwd);
|
|
27
|
+
return fileResult(await options.fs.exists(directory), `Failed to check sessions directory ${directory}`)
|
|
28
|
+
? [directory]
|
|
29
|
+
: [];
|
|
30
|
+
}
|
|
31
|
+
if (!fileResult(await options.fs.exists(sessionsRoot), `Failed to check sessions directory ${sessionsRoot}`))
|
|
32
|
+
return [];
|
|
33
|
+
return fileResult(await options.fs.listDir(sessionsRoot), `Failed to list sessions directory ${sessionsRoot}`)
|
|
34
|
+
.filter((entry) => entry.kind === "directory" || entry.kind === "symlink")
|
|
35
|
+
.map((entry) => entry.path);
|
|
36
|
+
}
|
|
37
|
+
export async function listJsonlSessionMetadata(options, query = {}) {
|
|
38
|
+
const metadata = [];
|
|
39
|
+
for (const directory of await jsonlSessionDirectories(options, query.cwd)) {
|
|
40
|
+
const files = fileResult(await options.fs.listDir(directory), `Failed to list sessions directory ${directory}`).filter((entry) => entry.kind !== "directory" && entry.name.endsWith(".jsonl"));
|
|
41
|
+
for (const file of files) {
|
|
42
|
+
const [firstLine] = fileResult(await options.fs.readTextLines(file.path, { maxLines: 1 }), `Failed to read session header ${file.path}`);
|
|
43
|
+
if (!firstLine)
|
|
44
|
+
continue;
|
|
45
|
+
const headerResult = parseHeader(firstLine);
|
|
46
|
+
if (!headerResult.ok)
|
|
47
|
+
continue;
|
|
48
|
+
metadata.push(metadataFromHeader(headerResult.value, file.path, file.mtimeMs));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return metadata.sort((left, right) => right.modifiedAt - left.modifiedAt);
|
|
52
|
+
}
|
|
53
|
+
export async function loadJsonlSessionStorage(options, metadata) {
|
|
54
|
+
if (!fileResult(await options.fs.exists(metadata.path), `Failed to check session ${metadata.path}`)) {
|
|
55
|
+
throw new SessionError("not_found", `Session not found: ${metadata.id}`);
|
|
56
|
+
}
|
|
57
|
+
const storage = await JsonlSessionStorage.load(options.fs, metadata.path);
|
|
58
|
+
const loadedMetadata = await storage.getMetadata();
|
|
59
|
+
if (loadedMetadata.id !== metadata.id) {
|
|
60
|
+
throw new SessionError("invalid_entry", `Session id does not match header: ${metadata.id}`);
|
|
61
|
+
}
|
|
62
|
+
return storage;
|
|
63
|
+
}
|
|
16
64
|
function sessionFileName(createdAt, id) {
|
|
17
65
|
const timestamp = new Date(createdAt).toISOString().replace(/[:.]/g, "-");
|
|
18
66
|
return `${timestamp}_${id}.jsonl`;
|
|
@@ -20,14 +68,18 @@ function sessionFileName(createdAt, id) {
|
|
|
20
68
|
export class JsonlSessionRepo {
|
|
21
69
|
fs;
|
|
22
70
|
sessionsRootInput;
|
|
71
|
+
activeCreateDestinations = new Set();
|
|
23
72
|
rootPromise;
|
|
24
73
|
constructor(options) {
|
|
25
74
|
this.fs = options.fs;
|
|
26
75
|
this.sessionsRootInput = options.sessionsRoot;
|
|
27
76
|
}
|
|
28
77
|
async create(options) {
|
|
29
|
-
const
|
|
30
|
-
return
|
|
78
|
+
const destination = await this.resolveCreateDestination(options);
|
|
79
|
+
return this.claimCreateDestination(destination, async () => {
|
|
80
|
+
const { header, path } = await this.prepareCreate(destination, options);
|
|
81
|
+
return new Session(await JsonlSessionStorage.create(this.fs, path, header));
|
|
82
|
+
});
|
|
31
83
|
}
|
|
32
84
|
async open(metadata) {
|
|
33
85
|
return new Session(await this.loadStorage(metadata));
|
|
@@ -40,27 +92,45 @@ export class JsonlSessionRepo {
|
|
|
40
92
|
}
|
|
41
93
|
async fork(source, options) {
|
|
42
94
|
const sourceStorage = await this.loadStorage(source);
|
|
43
|
-
const
|
|
95
|
+
const createOptions = {
|
|
44
96
|
...options,
|
|
45
97
|
parentSessionId: options.parentSessionId ?? source.id,
|
|
98
|
+
};
|
|
99
|
+
const destination = await this.resolveCreateDestination(createOptions);
|
|
100
|
+
return this.claimCreateDestination(destination, async () => {
|
|
101
|
+
const { header, path } = await this.prepareCreate(destination, createOptions);
|
|
102
|
+
return new Session(await sourceStorage.fork(path, header, options));
|
|
46
103
|
});
|
|
47
|
-
return new Session(await sourceStorage.fork(path, header, options));
|
|
48
104
|
}
|
|
49
105
|
async loadStorage(metadata) {
|
|
50
|
-
|
|
51
|
-
throw new SessionError("not_found", `Session not found: ${metadata.id}`);
|
|
52
|
-
}
|
|
53
|
-
const storage = await JsonlSessionStorage.load(this.fs, metadata.path);
|
|
54
|
-
const loadedMetadata = await storage.getMetadata();
|
|
55
|
-
if (loadedMetadata.id !== metadata.id) {
|
|
56
|
-
throw new SessionError("invalid_entry", `Session id does not match header: ${metadata.id}`);
|
|
57
|
-
}
|
|
58
|
-
return storage;
|
|
106
|
+
return loadJsonlSessionStorage({ fs: this.fs, sessionsRoot: this.sessionsRootInput }, metadata);
|
|
59
107
|
}
|
|
60
|
-
async
|
|
108
|
+
async resolveCreateDestination(options) {
|
|
61
109
|
const id = options.id ?? uuidv7();
|
|
62
110
|
validateSessionId(id);
|
|
63
111
|
const cwd = fileResult(await this.fs.absolutePath(options.cwd), `Failed to resolve session cwd ${options.cwd}`);
|
|
112
|
+
return { id, cwd };
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Prevent same-process create/fork races for one logical destination. The durable filename includes a
|
|
116
|
+
* timestamp, so the async filesystem existence check alone can let two concurrent calls both decide the
|
|
117
|
+
* same {cwd, id} is free and publish duplicate sessions.
|
|
118
|
+
*/
|
|
119
|
+
async claimCreateDestination(destination, operation) {
|
|
120
|
+
const key = `${destination.cwd}\0${destination.id}`;
|
|
121
|
+
if (this.activeCreateDestinations.has(key)) {
|
|
122
|
+
throw new SessionError("already_exists", `Session already exists: ${destination.id}`);
|
|
123
|
+
}
|
|
124
|
+
this.activeCreateDestinations.add(key);
|
|
125
|
+
try {
|
|
126
|
+
return await operation();
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
this.activeCreateDestinations.delete(key);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
async prepareCreate(destination, options) {
|
|
133
|
+
const { id, cwd } = destination;
|
|
64
134
|
if (await this.sessionIdExists(id, cwd)) {
|
|
65
135
|
throw new SessionError("already_exists", `Session already exists: ${id}`);
|
|
66
136
|
}
|
|
@@ -82,19 +152,7 @@ export class JsonlSessionRepo {
|
|
|
82
152
|
return { header, path };
|
|
83
153
|
}
|
|
84
154
|
async listDirect(options) {
|
|
85
|
-
|
|
86
|
-
const metadata = [];
|
|
87
|
-
for (const directory of directories) {
|
|
88
|
-
const files = fileResult(await this.fs.listDir(directory), `Failed to list sessions directory ${directory}`).filter((entry) => entry.kind !== "directory" && entry.name.endsWith(".jsonl"));
|
|
89
|
-
for (const file of files) {
|
|
90
|
-
const content = fileResult(await this.fs.readTextFile(file.path), `Failed to read session header ${file.path}`);
|
|
91
|
-
const firstLine = content.split("\n", 1)[0];
|
|
92
|
-
if (!firstLine)
|
|
93
|
-
throw invalidFile(file.path, 1, "is missing a header");
|
|
94
|
-
metadata.push(metadataFromHeader(parseHeader(firstLine, file.path), file.path, file.mtimeMs));
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
return metadata.sort((left, right) => right.modifiedAt - left.modifiedAt);
|
|
155
|
+
return listJsonlSessionMetadata({ fs: this.fs, sessionsRoot: this.sessionsRootInput }, options);
|
|
98
156
|
}
|
|
99
157
|
async sessionIdExists(id, cwd) {
|
|
100
158
|
const suffix = `_${id}.jsonl`;
|
|
@@ -104,23 +162,8 @@ export class JsonlSessionRepo {
|
|
|
104
162
|
const files = fileResult(await this.fs.listDir(directory), `Failed to list sessions directory ${directory}`);
|
|
105
163
|
return files.some((entry) => entry.kind !== "directory" && entry.name.endsWith(suffix));
|
|
106
164
|
}
|
|
107
|
-
async sessionDirectories(cwd) {
|
|
108
|
-
const root = await this.root();
|
|
109
|
-
if (cwd !== undefined) {
|
|
110
|
-
const resolvedCwd = fileResult(await this.fs.absolutePath(cwd), `Failed to resolve session cwd ${cwd}`);
|
|
111
|
-
const directory = await this.sessionDirectory(resolvedCwd);
|
|
112
|
-
return fileResult(await this.fs.exists(directory), `Failed to check sessions directory ${directory}`)
|
|
113
|
-
? [directory]
|
|
114
|
-
: [];
|
|
115
|
-
}
|
|
116
|
-
if (!fileResult(await this.fs.exists(root), `Failed to check sessions directory ${root}`))
|
|
117
|
-
return [];
|
|
118
|
-
return fileResult(await this.fs.listDir(root), `Failed to list sessions directory ${root}`)
|
|
119
|
-
.filter((entry) => entry.kind === "directory" || entry.kind === "symlink")
|
|
120
|
-
.map((entry) => entry.path);
|
|
121
|
-
}
|
|
122
165
|
async sessionDirectory(cwd) {
|
|
123
|
-
return fileResult(await this.fs.joinPath([await this.root(),
|
|
166
|
+
return fileResult(await this.fs.joinPath([await this.root(), jsonlSessionDirectoryName(cwd)]), `Failed to resolve sessions directory for ${cwd}`);
|
|
124
167
|
}
|
|
125
168
|
root() {
|
|
126
169
|
this.rootPromise ??= this.fs
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"repo.js","sourceRoot":"","sources":["../../../../src/harness/session/jsonl/repo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,sBAAsB,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAChE,OAAO,EAAoB,YAAY,EAAoB,MAAM,aAAa,CAAC;AAC/E,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,mBAAmB,EAAE,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,IAAI,CAAC,WAAW,CAAC;IAAA,CACxB;CACD","sourcesContent":["import { uuidv7 } from \"@earendil-works/pi-ai\";\nimport { assertJsonSerializable, Session } from \"../session.ts\";\nimport { type ForkOptions, SessionError, type SessionRepo } from \"../types.ts\";\nimport { metadataFromHeader, parseHeader } from \"./codec.ts\";\nimport { fileResult, invalidFile } from \"./errors.ts\";\nimport { JsonlSessionStorage } from \"./storage.ts\";\nimport type {\n\tJsonlSessionCreateOptions,\n\tJsonlSessionListOptions,\n\tJsonlSessionMetadata,\n\tJsonlSessionRepoFileSystem,\n\tJsonlSessionRepoOptions,\n\tJsonlV4Header,\n} from \"./types.ts\";\n\nconst SESSION_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;\n\nfunction validateSessionId(id: string): void {\n\tif (!SESSION_ID_PATTERN.test(id)) {\n\t\tthrow new SessionError(\n\t\t\t\"invalid_payload\",\n\t\t\t\"Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character\",\n\t\t);\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}_${id}.jsonl`;\n}\n\nexport class JsonlSessionRepo\n\timplements SessionRepo<JsonlSessionMetadata, JsonlSessionCreateOptions, JsonlSessionListOptions>\n{\n\tprivate readonly fs: JsonlSessionRepoFileSystem;\n\tprivate readonly sessionsRootInput: string;\n\tprivate rootPromise: Promise<string> | undefined;\n\n\tconstructor(options: JsonlSessionRepoOptions) {\n\t\tthis.fs = options.fs;\n\t\tthis.sessionsRootInput = options.sessionsRoot;\n\t}\n\n\tasync create(options: JsonlSessionCreateOptions): Promise<Session<JsonlSessionMetadata>> {\n\t\tconst { header, path } = await this.prepareCreate(options);\n\t\treturn new Session(await JsonlSessionStorage.create(this.fs, path, header));\n\t}\n\n\tasync open(metadata: JsonlSessionMetadata): Promise<Session<JsonlSessionMetadata>> {\n\t\treturn new Session(await this.loadStorage(metadata));\n\t}\n\n\tlist(): Promise<JsonlSessionMetadata[]>;\n\tlist(options: JsonlSessionListOptions): Promise<JsonlSessionMetadata[]>;\n\tasync list(options: JsonlSessionListOptions = {}): Promise<JsonlSessionMetadata[]> {\n\t\treturn this.listDirect(options);\n\t}\n\n\tasync delete(metadata: JsonlSessionMetadata): Promise<void> {\n\t\tfileResult(await this.fs.remove(metadata.path, { force: true }), `Failed to delete session ${metadata.path}`);\n\t}\n\n\tasync fork(\n\t\tsource: JsonlSessionMetadata,\n\t\toptions: ForkOptions & JsonlSessionCreateOptions,\n\t): Promise<Session<JsonlSessionMetadata>> {\n\t\tconst sourceStorage = await this.loadStorage(source);\n\t\tconst { header, path } = await this.prepareCreate({\n\t\t\t...options,\n\t\t\tparentSessionId: options.parentSessionId ?? source.id,\n\t\t});\n\t\treturn new Session(await sourceStorage.fork(path, header, options));\n\t}\n\n\tprivate async loadStorage(metadata: JsonlSessionMetadata): Promise<JsonlSessionStorage> {\n\t\tif (!fileResult(await this.fs.exists(metadata.path), `Failed to check session ${metadata.path}`)) {\n\t\t\tthrow new SessionError(\"not_found\", `Session not found: ${metadata.id}`);\n\t\t}\n\t\tconst storage = await JsonlSessionStorage.load(this.fs, metadata.path);\n\t\tconst loadedMetadata = await storage.getMetadata();\n\t\tif (loadedMetadata.id !== metadata.id) {\n\t\t\tthrow new SessionError(\"invalid_entry\", `Session id does not match header: ${metadata.id}`);\n\t\t}\n\t\treturn storage;\n\t}\n\n\tprivate async prepareCreate(options: JsonlSessionCreateOptions): Promise<{\n\t\theader: JsonlV4Header;\n\t\tpath: string;\n\t}> {\n\t\tconst id = options.id ?? uuidv7();\n\t\tvalidateSessionId(id);\n\t\tconst cwd = fileResult(await this.fs.absolutePath(options.cwd), `Failed to resolve session cwd ${options.cwd}`);\n\t\tif (await this.sessionIdExists(id, cwd)) {\n\t\t\tthrow new SessionError(\"already_exists\", `Session already exists: ${id}`);\n\t\t}\n\n\t\tconst createdAt = Date.now();\n\t\tconst sessionDirectory = await this.sessionDirectory(cwd);\n\t\tconst path = fileResult(\n\t\t\tawait this.fs.joinPath([sessionDirectory, sessionFileName(createdAt, id)]),\n\t\t\t`Failed to resolve path for session ${id}`,\n\t\t);\n\t\tif (options.metadata !== undefined) assertJsonSerializable(options.metadata);\n\t\tconst header: JsonlV4Header = {\n\t\t\tkind: \"header\",\n\t\t\tversion: 4,\n\t\t\tid,\n\t\t\tcreatedAt,\n\t\t\tcwd,\n\t\t\tparentSessionId: options.parentSessionId,\n\t\t\tmetadata: options.metadata,\n\t\t};\n\t\tfileResult(await this.fs.createDir(sessionDirectory, { recursive: true }), `Failed to create sessions directory`);\n\t\treturn { header, path };\n\t}\n\n\tprivate async listDirect(options: JsonlSessionListOptions): Promise<JsonlSessionMetadata[]> {\n\t\tconst directories = await this.sessionDirectories(options.cwd);\n\t\tconst metadata: JsonlSessionMetadata[] = [];\n\t\tfor (const directory of directories) {\n\t\t\tconst files = fileResult(\n\t\t\t\tawait this.fs.listDir(directory),\n\t\t\t\t`Failed to list sessions directory ${directory}`,\n\t\t\t).filter((entry) => entry.kind !== \"directory\" && entry.name.endsWith(\".jsonl\"));\n\t\t\tfor (const file of files) {\n\t\t\t\tconst content = fileResult(\n\t\t\t\t\tawait this.fs.readTextFile(file.path),\n\t\t\t\t\t`Failed to read session header ${file.path}`,\n\t\t\t\t);\n\t\t\t\tconst firstLine = content.split(\"\\n\", 1)[0];\n\t\t\t\tif (!firstLine) throw invalidFile(file.path, 1, \"is missing a header\");\n\t\t\t\tmetadata.push(metadataFromHeader(parseHeader(firstLine, file.path), file.path, file.mtimeMs));\n\t\t\t}\n\t\t}\n\t\treturn metadata.sort((left, right) => right.modifiedAt - left.modifiedAt);\n\t}\n\n\tprivate async sessionIdExists(id: string, cwd: string): Promise<boolean> {\n\t\tconst suffix = `_${id}.jsonl`;\n\t\tconst directory = await this.sessionDirectory(cwd);\n\t\tif (!fileResult(await this.fs.exists(directory), `Failed to check sessions directory ${directory}`)) return false;\n\t\tconst files = fileResult(await this.fs.listDir(directory), `Failed to list sessions directory ${directory}`);\n\t\treturn files.some((entry) => entry.kind !== \"directory\" && entry.name.endsWith(suffix));\n\t}\n\n\tprivate async sessionDirectories(cwd?: string): Promise<string[]> {\n\t\tconst root = await this.root();\n\t\tif (cwd !== undefined) {\n\t\t\tconst resolvedCwd = fileResult(await this.fs.absolutePath(cwd), `Failed to resolve session cwd ${cwd}`);\n\t\t\tconst directory = await this.sessionDirectory(resolvedCwd);\n\t\t\treturn fileResult(await this.fs.exists(directory), `Failed to check sessions directory ${directory}`)\n\t\t\t\t? [directory]\n\t\t\t\t: [];\n\t\t}\n\t\tif (!fileResult(await this.fs.exists(root), `Failed to check sessions directory ${root}`)) return [];\n\t\treturn fileResult(await this.fs.listDir(root), `Failed to list sessions directory ${root}`)\n\t\t\t.filter((entry) => entry.kind === \"directory\" || entry.kind === \"symlink\")\n\t\t\t.map((entry) => entry.path);\n\t}\n\n\tprivate async sessionDirectory(cwd: string): Promise<string> {\n\t\treturn fileResult(\n\t\t\tawait this.fs.joinPath([await this.root(), sessionDirectoryName(cwd)]),\n\t\t\t`Failed to resolve sessions directory for ${cwd}`,\n\t\t);\n\t}\n\n\tprivate root(): Promise<string> {\n\t\tthis.rootPromise ??= this.fs\n\t\t\t.absolutePath(this.sessionsRootInput)\n\t\t\t.then((result) => fileResult(result, `Failed to resolve sessions root ${this.sessionsRootInput}`));\n\t\treturn this.rootPromise;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"repo.js","sourceRoot":"","sources":["../../../../src/harness/session/jsonl/repo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,sBAAsB,EAAE,OAAO,EAAE,MAAM,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G,MAAM,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC;QACnD,IAAI,CAAC,UAAU,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,EAAE,sCAAsC,SAAS,EAAE,CAAC;YAAE,OAAO,KAAK,CAAC;QAClH,MAAM,KAAK,GAAG,UAAU,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,qCAAqC,SAAS,EAAE,CAAC,CAAC;QAC7G,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,WAAW,IAAI,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IAAA,CACxF;IAEO,KAAK,CAAC,gBAAgB,CAAC,GAAW,EAAmB;QAC5D,OAAO,UAAU,CAChB,MAAM,IAAI,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,MAAM,IAAI,CAAC,IAAI,EAAE,EAAE,yBAAyB,CAAC,GAAG,CAAC,CAAC,CAAC,EAC3E,4CAA4C,GAAG,EAAE,CACjD,CAAC;IAAA,CACF;IAEO,IAAI,GAAoB;QAC/B,IAAI,CAAC,WAAW,KAAK,IAAI,CAAC,EAAE;aAC1B,YAAY,CAAC,IAAI,CAAC,iBAAiB,CAAC;aACpC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,EAAE,mCAAmC,IAAI,CAAC,iBAAiB,EAAE,CAAC,CAAC,CAAC;QACpG,OAAO,IAAI,CAAC,WAAW,CAAC;IAAA,CACxB;CACD","sourcesContent":["import { uuidv7 } from \"@earendil-works/pi-ai\";\nimport { assertJsonSerializable, Session } from \"../session.ts\";\nimport { type ForkOptions, SessionError, type SessionRepo } from \"../types.ts\";\nimport { metadataFromHeader, parseHeader } from \"./codec.ts\";\nimport { fileResult } from \"./errors.ts\";\nimport { JsonlSessionStorage } from \"./storage.ts\";\nimport type {\n\tJsonlSessionCreateOptions,\n\tJsonlSessionListOptions,\n\tJsonlSessionMetadata,\n\tJsonlSessionRepoFileSystem,\n\tJsonlSessionRepoOptions,\n\tJsonlV4Header,\n} from \"./types.ts\";\n\nconst SESSION_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;\n\nfunction validateSessionId(id: string): void {\n\tif (!SESSION_ID_PATTERN.test(id)) {\n\t\tthrow new SessionError(\n\t\t\t\"invalid_payload\",\n\t\t\t\"Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character\",\n\t\t);\n\t}\n}\n\nfunction jsonlSessionDirectoryName(cwd: string): string {\n\treturn `--${cwd.replace(/^[/\\\\]/, \"\").replace(/[/\\\\:]/g, \"-\")}--`;\n}\n\nasync function jsonlSessionsRoot(options: JsonlSessionRepoOptions): Promise<string> {\n\treturn fileResult(\n\t\tawait options.fs.absolutePath(options.sessionsRoot),\n\t\t`Failed to resolve sessions root ${options.sessionsRoot}`,\n\t);\n}\n\nasync function jsonlSessionDirectory(\n\tfs: JsonlSessionRepoFileSystem,\n\tsessionsRoot: string,\n\tcwd: string,\n): Promise<string> {\n\treturn fileResult(\n\t\tawait fs.joinPath([sessionsRoot, jsonlSessionDirectoryName(cwd)]),\n\t\t`Failed to resolve sessions directory for ${cwd}`,\n\t);\n}\n\nasync function jsonlSessionDirectories(options: JsonlSessionRepoOptions, cwd?: string): Promise<string[]> {\n\tconst sessionsRoot = await jsonlSessionsRoot(options);\n\tif (cwd !== undefined) {\n\t\tconst resolvedCwd = fileResult(await options.fs.absolutePath(cwd), `Failed to resolve session cwd ${cwd}`);\n\t\tconst directory = await jsonlSessionDirectory(options.fs, sessionsRoot, resolvedCwd);\n\t\treturn fileResult(await options.fs.exists(directory), `Failed to check sessions directory ${directory}`)\n\t\t\t? [directory]\n\t\t\t: [];\n\t}\n\tif (!fileResult(await options.fs.exists(sessionsRoot), `Failed to check sessions directory ${sessionsRoot}`))\n\t\treturn [];\n\treturn fileResult(await options.fs.listDir(sessionsRoot), `Failed to list sessions directory ${sessionsRoot}`)\n\t\t.filter((entry) => entry.kind === \"directory\" || entry.kind === \"symlink\")\n\t\t.map((entry) => entry.path);\n}\n\nexport async function listJsonlSessionMetadata(\n\toptions: JsonlSessionRepoOptions,\n\tquery: JsonlSessionListOptions = {},\n): Promise<JsonlSessionMetadata[]> {\n\tconst metadata: JsonlSessionMetadata[] = [];\n\tfor (const directory of await jsonlSessionDirectories(options, query.cwd)) {\n\t\tconst files = fileResult(\n\t\t\tawait options.fs.listDir(directory),\n\t\t\t`Failed to list sessions directory ${directory}`,\n\t\t).filter((entry) => entry.kind !== \"directory\" && entry.name.endsWith(\".jsonl\"));\n\t\tfor (const file of files) {\n\t\t\tconst [firstLine] = fileResult(\n\t\t\t\tawait options.fs.readTextLines(file.path, { maxLines: 1 }),\n\t\t\t\t`Failed to read session header ${file.path}`,\n\t\t\t);\n\t\t\tif (!firstLine) continue;\n\t\t\tconst headerResult = parseHeader(firstLine);\n\t\t\tif (!headerResult.ok) continue;\n\t\t\tmetadata.push(metadataFromHeader(headerResult.value, file.path, file.mtimeMs));\n\t\t}\n\t}\n\treturn metadata.sort((left, right) => right.modifiedAt - left.modifiedAt);\n}\n\nexport async function loadJsonlSessionStorage(\n\toptions: JsonlSessionRepoOptions,\n\tmetadata: JsonlSessionMetadata,\n): Promise<JsonlSessionStorage> {\n\tif (!fileResult(await options.fs.exists(metadata.path), `Failed to check session ${metadata.path}`)) {\n\t\tthrow new SessionError(\"not_found\", `Session not found: ${metadata.id}`);\n\t}\n\tconst storage = await JsonlSessionStorage.load(options.fs, metadata.path);\n\tconst loadedMetadata = await storage.getMetadata();\n\tif (loadedMetadata.id !== metadata.id) {\n\t\tthrow new SessionError(\"invalid_entry\", `Session id does not match header: ${metadata.id}`);\n\t}\n\treturn storage;\n}\n\nfunction sessionFileName(createdAt: number, id: string): string {\n\tconst timestamp = new Date(createdAt).toISOString().replace(/[:.]/g, \"-\");\n\treturn `${timestamp}_${id}.jsonl`;\n}\n\nexport class JsonlSessionRepo\n\timplements SessionRepo<JsonlSessionMetadata, JsonlSessionCreateOptions, JsonlSessionListOptions>\n{\n\tprivate readonly fs: JsonlSessionRepoFileSystem;\n\tprivate readonly sessionsRootInput: string;\n\tprivate readonly activeCreateDestinations = new Set<string>();\n\tprivate rootPromise: Promise<string> | undefined;\n\n\tconstructor(options: JsonlSessionRepoOptions) {\n\t\tthis.fs = options.fs;\n\t\tthis.sessionsRootInput = options.sessionsRoot;\n\t}\n\n\tasync create(options: JsonlSessionCreateOptions): Promise<Session<JsonlSessionMetadata>> {\n\t\tconst destination = await this.resolveCreateDestination(options);\n\t\treturn this.claimCreateDestination(destination, async () => {\n\t\t\tconst { header, path } = await this.prepareCreate(destination, options);\n\t\t\treturn new Session(await JsonlSessionStorage.create(this.fs, path, header));\n\t\t});\n\t}\n\n\tasync open(metadata: JsonlSessionMetadata): Promise<Session<JsonlSessionMetadata>> {\n\t\treturn new Session(await this.loadStorage(metadata));\n\t}\n\n\tasync list(options: JsonlSessionListOptions = {}): Promise<JsonlSessionMetadata[]> {\n\t\treturn this.listDirect(options);\n\t}\n\n\tasync delete(metadata: JsonlSessionMetadata): Promise<void> {\n\t\tfileResult(await this.fs.remove(metadata.path, { force: true }), `Failed to delete session ${metadata.path}`);\n\t}\n\n\tasync fork(\n\t\tsource: JsonlSessionMetadata,\n\t\toptions: ForkOptions & JsonlSessionCreateOptions,\n\t): Promise<Session<JsonlSessionMetadata>> {\n\t\tconst sourceStorage = await this.loadStorage(source);\n\t\tconst createOptions = {\n\t\t\t...options,\n\t\t\tparentSessionId: options.parentSessionId ?? source.id,\n\t\t};\n\t\tconst destination = await this.resolveCreateDestination(createOptions);\n\t\treturn this.claimCreateDestination(destination, async () => {\n\t\t\tconst { header, path } = await this.prepareCreate(destination, createOptions);\n\t\t\treturn new Session(await sourceStorage.fork(path, header, options));\n\t\t});\n\t}\n\n\tprivate async loadStorage(metadata: JsonlSessionMetadata): Promise<JsonlSessionStorage> {\n\t\treturn loadJsonlSessionStorage({ fs: this.fs, sessionsRoot: this.sessionsRootInput }, metadata);\n\t}\n\n\tprivate async resolveCreateDestination(options: JsonlSessionCreateOptions): Promise<{ id: string; cwd: string }> {\n\t\tconst id = options.id ?? uuidv7();\n\t\tvalidateSessionId(id);\n\t\tconst cwd = fileResult(await this.fs.absolutePath(options.cwd), `Failed to resolve session cwd ${options.cwd}`);\n\t\treturn { id, cwd };\n\t}\n\n\t/**\n\t * Prevent same-process create/fork races for one logical destination. The durable filename includes a\n\t * timestamp, so the async filesystem existence check alone can let two concurrent calls both decide the\n\t * same {cwd, id} is free and publish duplicate sessions.\n\t */\n\tprivate async claimCreateDestination<T>(\n\t\tdestination: { id: string; cwd: string },\n\t\toperation: () => Promise<T>,\n\t): Promise<T> {\n\t\tconst key = `${destination.cwd}\\0${destination.id}`;\n\t\tif (this.activeCreateDestinations.has(key)) {\n\t\t\tthrow new SessionError(\"already_exists\", `Session already exists: ${destination.id}`);\n\t\t}\n\t\tthis.activeCreateDestinations.add(key);\n\t\ttry {\n\t\t\treturn await operation();\n\t\t} finally {\n\t\t\tthis.activeCreateDestinations.delete(key);\n\t\t}\n\t}\n\n\tprivate async prepareCreate(\n\t\tdestination: { id: string; cwd: string },\n\t\toptions: JsonlSessionCreateOptions,\n\t): Promise<{\n\t\theader: JsonlV4Header;\n\t\tpath: string;\n\t}> {\n\t\tconst { id, cwd } = destination;\n\t\tif (await this.sessionIdExists(id, cwd)) {\n\t\t\tthrow new SessionError(\"already_exists\", `Session already exists: ${id}`);\n\t\t}\n\n\t\tconst createdAt = Date.now();\n\t\tconst sessionDirectory = await this.sessionDirectory(cwd);\n\t\tconst path = fileResult(\n\t\t\tawait this.fs.joinPath([sessionDirectory, sessionFileName(createdAt, id)]),\n\t\t\t`Failed to resolve path for session ${id}`,\n\t\t);\n\t\tif (options.metadata !== undefined) assertJsonSerializable(options.metadata);\n\t\tconst header: JsonlV4Header = {\n\t\t\tkind: \"header\",\n\t\t\tversion: 4,\n\t\t\tid,\n\t\t\tcreatedAt,\n\t\t\tcwd,\n\t\t\tparentSessionId: options.parentSessionId,\n\t\t\tmetadata: options.metadata,\n\t\t};\n\t\tfileResult(await this.fs.createDir(sessionDirectory, { recursive: true }), `Failed to create sessions directory`);\n\t\treturn { header, path };\n\t}\n\n\tprivate async listDirect(options: JsonlSessionListOptions): Promise<JsonlSessionMetadata[]> {\n\t\treturn listJsonlSessionMetadata({ fs: this.fs, sessionsRoot: this.sessionsRootInput }, options);\n\t}\n\n\tprivate async sessionIdExists(id: string, cwd: string): Promise<boolean> {\n\t\tconst suffix = `_${id}.jsonl`;\n\t\tconst directory = await this.sessionDirectory(cwd);\n\t\tif (!fileResult(await this.fs.exists(directory), `Failed to check sessions directory ${directory}`)) return false;\n\t\tconst files = fileResult(await this.fs.listDir(directory), `Failed to list sessions directory ${directory}`);\n\t\treturn files.some((entry) => entry.kind !== \"directory\" && entry.name.endsWith(suffix));\n\t}\n\n\tprivate async sessionDirectory(cwd: string): Promise<string> {\n\t\treturn fileResult(\n\t\t\tawait this.fs.joinPath([await this.root(), jsonlSessionDirectoryName(cwd)]),\n\t\t\t`Failed to resolve sessions directory for ${cwd}`,\n\t\t);\n\t}\n\n\tprivate root(): Promise<string> {\n\t\tthis.rootPromise ??= this.fs\n\t\t\t.absolutePath(this.sessionsRootInput)\n\t\t\t.then((result) => fileResult(result, `Failed to resolve sessions root ${this.sessionsRootInput}`));\n\t\treturn this.rootPromise;\n\t}\n}\n"]}
|
|
@@ -32,7 +32,7 @@ export declare class JsonlSessionStorage implements SessionStorage<JsonlSessionM
|
|
|
32
32
|
}): Promise<OperationStartedRecord[]>;
|
|
33
33
|
getLog(options?: LogOptions): Promise<LogItem[]>;
|
|
34
34
|
getName(): Promise<string | undefined>;
|
|
35
|
-
setName(name: string): Promise<void>;
|
|
35
|
+
setName(name: string | undefined): Promise<void>;
|
|
36
36
|
getLabel(id: string): Promise<string | undefined>;
|
|
37
37
|
setLabel(id: string, label: string | undefined): Promise<void>;
|
|
38
38
|
getStats(): Promise<SessionStats>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../../../../src/harness/session/jsonl/storage.ts"],"names":[],"mappings":"AACA,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,KAAK,EACV,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,OAAO,EACZ,KAAK,UAAU,EACf,KAAK,SAAS,EACd,KAAK,sBAAsB,EAC3B,KAAK,gBAAgB,EACrB,KAAK,WAAW,EAEhB,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,MAAM,aAAa,CAAC;AAGrB,OAAO,KAAK,EAAE,oBAAoB,EAAE,0BAA0B,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AA2BlG,qBAAa,mBAAoB,YAAW,cAAc,CAAC,oBAAoB,CAAC;IAC/E,OAAO,CAAC,QAAQ,CAAC,EAAE,CAA6B;IAChD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAuB;IAChD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAsB;IAC5C,OAAO,CAAC,IAAI,CAAoC;IAEhD,YAAY,EAAE,EAAE,0BAA0B,EAAE,QAAQ,EAAE,oBAAoB,EAGzE;IAED,OAAa,MAAM,CAClB,EAAE,EAAE,0BAA0B,EAC9B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,aAAa,GACnB,OAAO,CAAC,mBAAmB,CAAC,CAI9B;IAED,OAAa,IAAI,CAAC,EAAE,EAAE,0BAA0B,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CA4B5F;IAEK,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC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AO,CAAC,UAAU,EAAE,CAAC,CAAC;IAKxD,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,sBAAsB,EAAE,CAAC,CAEtG;IAEK,MAAM,CAAC,OAAO,GAAE,UAAe,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,CAEzD;IAEK,OAAO,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAE3C;IAED,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAMnC;IAEK,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAEtD;IAED,QAAQ,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAa7D;IAEK,QAAQ,IAAI,OAAO,CAAC,YAAY,CAAC,CAEtC;IAED,OAAO,CAAC,OAAO;YASD,cAAc;IAO5B,OAAO,CAAC,aAAa;CASrB","sourcesContent":["import { type SessionMutation, SessionState } from \"../state.ts\";\nimport {\n\ttype BranchBounds,\n\ttype Entry,\n\ttype EntryQuery,\n\ttype ForkOptions,\n\ttype LanePointer,\n\ttype LaneRecord,\n\ttype LogItem,\n\ttype LogOptions,\n\ttype NewRecord,\n\ttype OperationStartedRecord,\n\ttype ProvisionedEntry,\n\ttype RecordQuery,\n\tSessionError,\n\ttype SessionStats,\n\ttype SessionStorage,\n} from \"../types.ts\";\nimport { encodeHeader, encodeMutation, metadataFromHeader, parseHeader, parseMutation } from \"./codec.ts\";\nimport { fileResult, invalidFile } from \"./errors.ts\";\nimport type { JsonlSessionMetadata, JsonlSessionRepoFileSystem, JsonlV4Header } from \"./types.ts\";\n\n/**\n * Build a complete sibling temporary file, then atomically rename it over the destination.\n * The populate callback must create or overwrite `tempPath` with the complete file. The\n * destination is untouched until the rename commits, so a process crash while populating\n * can leave only the ignored `.tmp` file behind.\n *\n * Rejects when population or rename fails. On rejection, temporary-file removal is\n * best-effort and the original error is preserved. Callers must serialize publications to\n * the same destination because they share its deterministic `.tmp` path.\n */\nasync function publishFileAtomically(\n\tfs: JsonlSessionRepoFileSystem,\n\tdestinationPath: string,\n\tpopulate: (tempPath: string) => Promise<void>,\n): Promise<void> {\n\tconst tempPath = `${destinationPath}.tmp`;\n\ttry {\n\t\tawait populate(tempPath);\n\t\tfileResult(await fs.renameFile(tempPath, destinationPath), `Failed to publish staged file ${destinationPath}`);\n\t} catch (error) {\n\t\tawait fs.remove(tempPath, { force: true });\n\t\tthrow error;\n\t}\n}\n\nexport class JsonlSessionStorage implements SessionStorage<JsonlSessionMetadata> {\n\tprivate readonly fs: JsonlSessionRepoFileSystem;\n\tprivate readonly metadata: JsonlSessionMetadata;\n\tprivate readonly state = new SessionState();\n\tprivate tail: Promise<void> = Promise.resolve();\n\n\tconstructor(fs: JsonlSessionRepoFileSystem, metadata: JsonlSessionMetadata) {\n\t\tthis.fs = fs;\n\t\tthis.metadata = structuredClone(metadata);\n\t}\n\n\tstatic async create(\n\t\tfs: JsonlSessionRepoFileSystem,\n\t\tpath: string,\n\t\theader: JsonlV4Header,\n\t): Promise<JsonlSessionStorage> {\n\t\tfileResult(await fs.writeFile(path, encodeHeader(header)), `Failed to initialize session ${path}`);\n\t\tconst fileInfo = fileResult(await fs.fileInfo(path), `Failed to read session metadata ${path}`);\n\t\treturn new JsonlSessionStorage(fs, metadataFromHeader(header, path, fileInfo.mtimeMs));\n\t}\n\n\tstatic async load(fs: JsonlSessionRepoFileSystem, path: string): Promise<JsonlSessionStorage> {\n\t\tconst content = fileResult(await fs.readTextFile(path), `Failed to read session ${path}`);\n\t\tconst physicalLines = content.split(\"\\n\");\n\t\tif (physicalLines.at(-1) === \"\") physicalLines.pop();\n\t\tif (physicalLines.length === 0 || !physicalLines[0]) throw invalidFile(path, 1, \"is missing a header\");\n\t\tconst header = parseHeader(physicalLines[0], path);\n\t\tconst fileInfo = fileResult(await fs.fileInfo(path), `Failed to read session metadata ${path}`);\n\t\tconst storage = new JsonlSessionStorage(fs, metadataFromHeader(header, path, fileInfo.mtimeMs));\n\t\tfor (let index = 1; index < physicalLines.length; index++) {\n\t\t\tconst line = physicalLines[index]!;\n\t\t\tlet mutation: SessionMutation;\n\t\t\ttry {\n\t\t\t\tmutation = parseMutation(line, path, index + 1);\n\t\t\t} catch (error) {\n\t\t\t\tif (index !== physicalLines.length - 1 || !(error instanceof SessionError) || error.cause === undefined)\n\t\t\t\t\tthrow error;\n\t\t\t\tconst validPrefix = `${physicalLines.slice(0, index).join(\"\\n\")}\\n`;\n\t\t\t\tawait publishFileAtomically(fs, path, async (tempPath) => {\n\t\t\t\t\tfileResult(await fs.writeFile(tempPath, validPrefix), `Failed to stage torn-tail repair ${path}`);\n\t\t\t\t});\n\t\t\t\treturn storage;\n\t\t\t}\n\t\t\tstorage.applyMutation(mutation, path, index + 1);\n\t\t}\n\t\tif (!content.endsWith(\"\\n\")) {\n\t\t\tfileResult(await fs.appendFile(path, \"\\n\"), `Failed to repair unterminated session tail ${path}`);\n\t\t}\n\t\treturn storage;\n\t}\n\n\tasync fork(path: string, header: JsonlV4Header, options: ForkOptions): Promise<JsonlSessionStorage> {\n\t\tconst mutations = this.state.createForkMutations(options);\n\t\tawait publishFileAtomically(this.fs, path, async (tempPath) => {\n\t\t\tconst targetStorage = await JsonlSessionStorage.create(this.fs, tempPath, header);\n\t\t\tfor (const mutation of mutations) {\n\t\t\t\tawait targetStorage.appendMutation(mutation);\n\t\t\t\ttargetStorage.applyMutation(mutation);\n\t\t\t}\n\t\t});\n\t\treturn JsonlSessionStorage.load(this.fs, path);\n\t}\n\n\tasync drain(): Promise<void> {\n\t\tawait this.tail;\n\t}\n\n\tasync getMetadata(): Promise<JsonlSessionMetadata> {\n\t\treturn structuredClone(this.metadata);\n\t}\n\n\tasync getLanes(): Promise<LanePointer[]> {\n\t\treturn this.state.getLanes();\n\t}\n\n\tcreateLane(lane: string, at: string | null): Promise<void> {\n\t\treturn this.enqueue(async () => {\n\t\t\tthis.state.validateNewLane(lane);\n\t\t\tthis.state.validateTarget(at);\n\t\t\tconst mutation: SessionMutation = { kind: \"lane\", seq: this.state.nextSequence, lane, leafId: at };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t});\n\t}\n\n\tmoveLane(lane: string, to: string | null): Promise<void> {\n\t\treturn this.enqueue(async () => {\n\t\t\tthis.state.requireLane(lane);\n\t\t\tthis.state.validateTarget(to);\n\t\t\tconst mutation: SessionMutation = { kind: \"lane\", seq: this.state.nextSequence, lane, leafId: to };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t});\n\t}\n\n\tappendEntry<TEntry extends Entry>(newEntry: ProvisionedEntry<TEntry>, lane: string): Promise<TEntry> {\n\t\treturn this.enqueue(async () => {\n\t\t\tconst parentId = this.state.requireLane(lane);\n\t\t\tthis.state.validateUnusedId(newEntry.id);\n\t\t\tconst entry = {\n\t\t\t\t...structuredClone(newEntry),\n\t\t\t\tparentId,\n\t\t\t\tseq: this.state.nextSequence,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t} as unknown as TEntry;\n\t\t\tconst mutation: SessionMutation = { kind: \"entry\", lane, entry };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t\treturn structuredClone(entry);\n\t\t});\n\t}\n\n\tappendRecord<TRecord extends LaneRecord>(newRecord: NewRecord<TRecord>): Promise<TRecord> {\n\t\treturn this.enqueue(async () => {\n\t\t\tthis.state.requireLane(newRecord.lane);\n\t\t\tthis.state.validateUnusedId(newRecord.id);\n\t\t\tconst currentOpenOperationId = this.state.findOpenOperations(newRecord.lane, { limit: 1 })[0]?.id;\n\t\t\tif (newRecord.type === \"operation_started\" && currentOpenOperationId !== undefined) {\n\t\t\t\tthrow new SessionError(\n\t\t\t\t\t\"storage\",\n\t\t\t\t\t`Lane ${newRecord.lane} already has an open operation ${currentOpenOperationId}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst record = {\n\t\t\t\t...structuredClone(newRecord),\n\t\t\t\tseq: this.state.nextSequence,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t} as unknown as TRecord;\n\t\t\tconst mutation: SessionMutation = { kind: \"record\", record };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t\treturn structuredClone(record);\n\t\t});\n\t}\n\n\tasync getEntry(id: string): Promise<Entry | undefined> {\n\t\tconst entry = this.state.getEntry(id);\n\t\treturn entry === undefined ? undefined : structuredClone(entry);\n\t}\n\n\tasync findEntries(query: EntryQuery = {}): Promise<Entry[]> {\n\t\treturn structuredClone(this.state.findEntries(query));\n\t}\n\n\tasync findEntriesOnBranch(query: EntryQuery & BranchBounds & { start: string }): Promise<Entry[]> {\n\t\treturn structuredClone(this.state.findEntriesOnBranch(query));\n\t}\n\n\tasync findRecords<K extends LaneRecord[\"type\"]>(\n\t\tquery: RecordQuery & { type: K },\n\t): Promise<Extract<LaneRecord, { type: K }>[]>;\n\tasync findRecords(query?: RecordQuery): Promise<LaneRecord[]>;\n\tasync findRecords(query: RecordQuery = {}): Promise<LaneRecord[]> {\n\t\treturn structuredClone(this.state.findRecords(query));\n\t}\n\n\tasync findOpenOperations(lane: string, options?: { limit?: number }): Promise<OperationStartedRecord[]> {\n\t\treturn structuredClone(this.state.findOpenOperations(lane, options));\n\t}\n\n\tasync getLog(options: LogOptions = {}): Promise<LogItem[]> {\n\t\treturn structuredClone(this.state.getLog(options));\n\t}\n\n\tasync getName(): Promise<string | undefined> {\n\t\treturn this.state.getName();\n\t}\n\n\tsetName(name: string): Promise<void> {\n\t\treturn this.enqueue(async () => {\n\t\t\tconst mutation: SessionMutation = { kind: \"fact\", seq: this.state.nextSequence, fact: \"name\", name };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t});\n\t}\n\n\tasync getLabel(id: string): Promise<string | undefined> {\n\t\treturn this.state.getLabel(id);\n\t}\n\n\tsetLabel(id: string, label: string | undefined): Promise<void> {\n\t\treturn this.enqueue(async () => {\n\t\t\tthis.state.validateTarget(id);\n\t\t\tconst mutation: SessionMutation = {\n\t\t\t\tkind: \"fact\",\n\t\t\t\tseq: this.state.nextSequence,\n\t\t\t\tfact: \"label\",\n\t\t\t\ttargetId: id,\n\t\t\t\tlabel,\n\t\t\t};\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t});\n\t}\n\n\tasync getStats(): Promise<SessionStats> {\n\t\treturn structuredClone(this.state.getStats());\n\t}\n\n\tprivate enqueue<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst result = this.tail.then(operation);\n\t\tthis.tail = result.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\treturn result;\n\t}\n\n\tprivate async appendMutation(mutation: SessionMutation): Promise<void> {\n\t\tfileResult(\n\t\t\tawait this.fs.appendFile(this.metadata.path, encodeMutation(mutation)),\n\t\t\t`Failed to append session ${this.metadata.path}`,\n\t\t);\n\t}\n\n\tprivate applyMutation(\n\t\tmutation: SessionMutation,\n\t\tpath = this.metadata.path,\n\t\tline = this.state.nextSequence + 1,\n\t): void {\n\t\tthis.state.applyMutation(mutation, (message) => {\n\t\t\tthrow invalidFile(path, line, message);\n\t\t});\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../../../../src/harness/session/jsonl/storage.ts"],"names":[],"mappings":"AACA,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,KAAK,EACV,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,OAAO,EACZ,KAAK,UAAU,EACf,KAAK,SAAS,EACd,KAAK,sBAAsB,EAC3B,KAAK,gBAAgB,EAC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EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAEtD;IAED,QAAQ,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAa7D;IAEK,QAAQ,IAAI,OAAO,CAAC,YAAY,CAAC,CAEtC;IAED,OAAO,CAAC,OAAO;YASD,cAAc;IAO5B,OAAO,CAAC,aAAa;CAGrB","sourcesContent":["import { type SessionMutation, SessionState } from \"../state.ts\";\nimport {\n\ttype BranchBounds,\n\ttype Entry,\n\ttype EntryQuery,\n\ttype ForkOptions,\n\ttype LanePointer,\n\ttype LaneRecord,\n\ttype LogItem,\n\ttype LogOptions,\n\ttype NewRecord,\n\ttype OperationStartedRecord,\n\ttype ProvisionedEntry,\n\ttype RecordQuery,\n\tSessionError,\n\ttype SessionStats,\n\ttype SessionStorage,\n} from \"../types.ts\";\nimport { encodeHeader, encodeMutation, metadataFromHeader, parseHeader, parseMutation } from \"./codec.ts\";\nimport { fileResult, invalidFile, JsonlDecodeError } from \"./errors.ts\";\nimport type { JsonlSessionMetadata, JsonlSessionRepoFileSystem, JsonlV4Header } from \"./types.ts\";\n\n/**\n * Build a complete sibling temporary file, then atomically rename it over the destination.\n * The populate callback must create or overwrite `tempPath` with the complete file. The\n * destination is untouched until the rename commits, so a process crash while populating\n * can leave only the ignored `.tmp` file behind.\n *\n * Rejects when population or rename fails. On rejection, temporary-file removal is\n * best-effort and the original error is preserved. Callers must serialize publications to\n * the same destination because they share its deterministic `.tmp` path.\n */\nasync function publishFileAtomically(\n\tfs: JsonlSessionRepoFileSystem,\n\tdestinationPath: string,\n\tpopulate: (tempPath: string) => Promise<void>,\n): Promise<void> {\n\tconst tempPath = `${destinationPath}.tmp`;\n\ttry {\n\t\tawait populate(tempPath);\n\t\tfileResult(await fs.renameFile(tempPath, destinationPath), `Failed to publish staged file ${destinationPath}`);\n\t} catch (error) {\n\t\tawait fs.remove(tempPath, { force: true });\n\t\tthrow error;\n\t}\n}\n\nexport class JsonlSessionStorage implements SessionStorage<JsonlSessionMetadata> {\n\tprivate readonly fs: JsonlSessionRepoFileSystem;\n\tprivate readonly metadata: JsonlSessionMetadata;\n\tprivate readonly state = new SessionState();\n\tprivate tail: Promise<void> = Promise.resolve();\n\n\tconstructor(fs: JsonlSessionRepoFileSystem, metadata: JsonlSessionMetadata) {\n\t\tthis.fs = fs;\n\t\tthis.metadata = structuredClone(metadata);\n\t}\n\n\tstatic async create(\n\t\tfs: JsonlSessionRepoFileSystem,\n\t\tpath: string,\n\t\theader: JsonlV4Header,\n\t): Promise<JsonlSessionStorage> {\n\t\tfileResult(await fs.writeFile(path, encodeHeader(header)), `Failed to initialize session ${path}`);\n\t\tconst fileInfo = fileResult(await fs.fileInfo(path), `Failed to read session metadata ${path}`);\n\t\treturn new JsonlSessionStorage(fs, metadataFromHeader(header, path, fileInfo.mtimeMs));\n\t}\n\n\tstatic async load(fs: JsonlSessionRepoFileSystem, path: string): Promise<JsonlSessionStorage> {\n\t\tconst content = fileResult(await fs.readTextFile(path), `Failed to read session ${path}`);\n\t\tconst physicalLines = content.split(\"\\n\");\n\t\tif (physicalLines.at(-1) === \"\") physicalLines.pop();\n\t\tif (physicalLines.length === 0 || !physicalLines[0]) {\n\t\t\tthrow invalidFile(path, 1, new JsonlDecodeError(\"schema\", \"is missing a header\"));\n\t\t}\n\t\tconst headerResult = parseHeader(physicalLines[0]);\n\t\tif (!headerResult.ok) throw invalidFile(path, 1, headerResult.error);\n\t\tconst fileInfo = fileResult(await fs.fileInfo(path), `Failed to read session metadata ${path}`);\n\t\tconst storage = new JsonlSessionStorage(fs, metadataFromHeader(headerResult.value, path, fileInfo.mtimeMs));\n\t\tfor (let index = 1; index < physicalLines.length; index++) {\n\t\t\tconst line = physicalLines[index]!;\n\t\t\tconst mutationResult = parseMutation(line);\n\t\t\tif (!mutationResult.ok) {\n\t\t\t\tconst isTornTail = index === physicalLines.length - 1 && mutationResult.error.kind === \"syntax\";\n\t\t\t\tif (isTornTail) {\n\t\t\t\t\t// Drop the unacknowledged partial append by atomically publishing the valid prefix.\n\t\t\t\t\tconst validPrefix = `${physicalLines.slice(0, index).join(\"\\n\")}\\n`;\n\t\t\t\t\tawait publishFileAtomically(fs, path, async (tempPath) => {\n\t\t\t\t\t\tfileResult(await fs.writeFile(tempPath, validPrefix), `Failed to stage torn-tail repair ${path}`);\n\t\t\t\t\t});\n\t\t\t\t\treturn storage;\n\t\t\t\t}\n\t\t\t\tthrow invalidFile(path, index + 1, mutationResult.error);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tstorage.applyMutation(mutationResult.value);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof SessionError && error.code === \"invalid_entry\") {\n\t\t\t\t\tthrow invalidFile(path, index + 1, error);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tif (!content.endsWith(\"\\n\")) {\n\t\t\tfileResult(await fs.appendFile(path, \"\\n\"), `Failed to repair unterminated session tail ${path}`);\n\t\t}\n\t\treturn storage;\n\t}\n\n\tasync fork(path: string, header: JsonlV4Header, options: ForkOptions): Promise<JsonlSessionStorage> {\n\t\tconst mutations = this.state.createForkMutations(options);\n\t\tawait publishFileAtomically(this.fs, path, async (tempPath) => {\n\t\t\tconst targetStorage = await JsonlSessionStorage.create(this.fs, tempPath, header);\n\t\t\tfor (const mutation of mutations) {\n\t\t\t\tawait targetStorage.appendMutation(mutation);\n\t\t\t\ttargetStorage.applyMutation(mutation);\n\t\t\t}\n\t\t});\n\t\treturn JsonlSessionStorage.load(this.fs, path);\n\t}\n\n\tasync drain(): Promise<void> {\n\t\tawait this.tail;\n\t}\n\n\tasync getMetadata(): Promise<JsonlSessionMetadata> {\n\t\treturn structuredClone(this.metadata);\n\t}\n\n\tasync getLanes(): Promise<LanePointer[]> {\n\t\treturn this.state.getLanes();\n\t}\n\n\tcreateLane(lane: string, at: string | null): Promise<void> {\n\t\treturn this.enqueue(async () => {\n\t\t\tthis.state.validateNewLane(lane);\n\t\t\tthis.state.validateTarget(at);\n\t\t\tconst mutation: SessionMutation = { kind: \"lane\", seq: this.state.nextSequence, lane, leafId: at };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t});\n\t}\n\n\tmoveLane(lane: string, to: string | null): Promise<void> {\n\t\treturn this.enqueue(async () => {\n\t\t\tthis.state.requireLane(lane);\n\t\t\tthis.state.validateTarget(to);\n\t\t\tconst mutation: SessionMutation = { kind: \"lane\", seq: this.state.nextSequence, lane, leafId: to };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t});\n\t}\n\n\tappendEntry<TEntry extends Entry>(newEntry: ProvisionedEntry<TEntry>, lane: string): Promise<TEntry> {\n\t\treturn this.enqueue(async () => {\n\t\t\tconst parentId = this.state.requireLane(lane);\n\t\t\tthis.state.validateUnusedId(newEntry.id);\n\t\t\tconst entry = {\n\t\t\t\t...structuredClone(newEntry),\n\t\t\t\tparentId,\n\t\t\t\tseq: this.state.nextSequence,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t} as unknown as TEntry;\n\t\t\tconst mutation: SessionMutation = { kind: \"entry\", lane, entry };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t\treturn structuredClone(entry);\n\t\t});\n\t}\n\n\tappendRecord<TRecord extends LaneRecord>(newRecord: NewRecord<TRecord>): Promise<TRecord> {\n\t\treturn this.enqueue(async () => {\n\t\t\tthis.state.requireLane(newRecord.lane);\n\t\t\tthis.state.validateUnusedId(newRecord.id);\n\t\t\tconst currentOpenOperationId = this.state.findOpenOperations(newRecord.lane, { limit: 1 })[0]?.id;\n\t\t\tif (newRecord.type === \"operation_started\" && currentOpenOperationId !== undefined) {\n\t\t\t\tthrow new SessionError(\n\t\t\t\t\t\"storage\",\n\t\t\t\t\t`Lane ${newRecord.lane} already has an open operation ${currentOpenOperationId}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst record = {\n\t\t\t\t...structuredClone(newRecord),\n\t\t\t\tseq: this.state.nextSequence,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t} as unknown as TRecord;\n\t\t\tconst mutation: SessionMutation = { kind: \"record\", record };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t\treturn structuredClone(record);\n\t\t});\n\t}\n\n\tasync getEntry(id: string): Promise<Entry | undefined> {\n\t\tconst entry = this.state.getEntry(id);\n\t\treturn entry === undefined ? undefined : structuredClone(entry);\n\t}\n\n\tasync findEntries(query: EntryQuery = {}): Promise<Entry[]> {\n\t\treturn structuredClone(this.state.findEntries(query));\n\t}\n\n\tasync findEntriesOnBranch(query: EntryQuery & BranchBounds & { start: string }): Promise<Entry[]> {\n\t\treturn structuredClone(this.state.findEntriesOnBranch(query));\n\t}\n\n\tasync findRecords<K extends LaneRecord[\"type\"]>(\n\t\tquery: RecordQuery & { type: K },\n\t): Promise<Extract<LaneRecord, { type: K }>[]>;\n\tasync findRecords(query?: RecordQuery): Promise<LaneRecord[]>;\n\tasync findRecords(query: RecordQuery = {}): Promise<LaneRecord[]> {\n\t\treturn structuredClone(this.state.findRecords(query));\n\t}\n\n\tasync findOpenOperations(lane: string, options?: { limit?: number }): Promise<OperationStartedRecord[]> {\n\t\treturn structuredClone(this.state.findOpenOperations(lane, options));\n\t}\n\n\tasync getLog(options: LogOptions = {}): Promise<LogItem[]> {\n\t\treturn structuredClone(this.state.getLog(options));\n\t}\n\n\tasync getName(): Promise<string | undefined> {\n\t\treturn this.state.getName();\n\t}\n\n\tsetName(name: string | undefined): Promise<void> {\n\t\treturn this.enqueue(async () => {\n\t\t\tconst mutation: SessionMutation = { kind: \"fact\", seq: this.state.nextSequence, fact: \"name\", name };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t});\n\t}\n\n\tasync getLabel(id: string): Promise<string | undefined> {\n\t\treturn this.state.getLabel(id);\n\t}\n\n\tsetLabel(id: string, label: string | undefined): Promise<void> {\n\t\treturn this.enqueue(async () => {\n\t\t\tthis.state.validateTarget(id);\n\t\t\tconst mutation: SessionMutation = {\n\t\t\t\tkind: \"fact\",\n\t\t\t\tseq: this.state.nextSequence,\n\t\t\t\tfact: \"label\",\n\t\t\t\ttargetId: id,\n\t\t\t\tlabel,\n\t\t\t};\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t});\n\t}\n\n\tasync getStats(): Promise<SessionStats> {\n\t\treturn structuredClone(this.state.getStats());\n\t}\n\n\tprivate enqueue<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst result = this.tail.then(operation);\n\t\tthis.tail = result.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\treturn result;\n\t}\n\n\tprivate async appendMutation(mutation: SessionMutation): Promise<void> {\n\t\tfileResult(\n\t\t\tawait this.fs.appendFile(this.metadata.path, encodeMutation(mutation)),\n\t\t\t`Failed to append session ${this.metadata.path}`,\n\t\t);\n\t}\n\n\tprivate applyMutation(mutation: SessionMutation): void {\n\t\tthis.state.applyMutation(mutation);\n\t}\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { SessionState } from "../state.js";
|
|
2
2
|
import { SessionError, } from "../types.js";
|
|
3
3
|
import { encodeHeader, encodeMutation, metadataFromHeader, parseHeader, parseMutation } from "./codec.js";
|
|
4
|
-
import { fileResult, invalidFile } from "./errors.js";
|
|
4
|
+
import { fileResult, invalidFile, JsonlDecodeError } from "./errors.js";
|
|
5
5
|
/**
|
|
6
6
|
* Build a complete sibling temporary file, then atomically rename it over the destination.
|
|
7
7
|
* The populate callback must create or overwrite `tempPath` with the complete file. The
|
|
@@ -42,27 +42,38 @@ export class JsonlSessionStorage {
|
|
|
42
42
|
const physicalLines = content.split("\n");
|
|
43
43
|
if (physicalLines.at(-1) === "")
|
|
44
44
|
physicalLines.pop();
|
|
45
|
-
if (physicalLines.length === 0 || !physicalLines[0])
|
|
46
|
-
throw invalidFile(path, 1, "is missing a header");
|
|
47
|
-
|
|
45
|
+
if (physicalLines.length === 0 || !physicalLines[0]) {
|
|
46
|
+
throw invalidFile(path, 1, new JsonlDecodeError("schema", "is missing a header"));
|
|
47
|
+
}
|
|
48
|
+
const headerResult = parseHeader(physicalLines[0]);
|
|
49
|
+
if (!headerResult.ok)
|
|
50
|
+
throw invalidFile(path, 1, headerResult.error);
|
|
48
51
|
const fileInfo = fileResult(await fs.fileInfo(path), `Failed to read session metadata ${path}`);
|
|
49
|
-
const storage = new JsonlSessionStorage(fs, metadataFromHeader(
|
|
52
|
+
const storage = new JsonlSessionStorage(fs, metadataFromHeader(headerResult.value, path, fileInfo.mtimeMs));
|
|
50
53
|
for (let index = 1; index < physicalLines.length; index++) {
|
|
51
54
|
const line = physicalLines[index];
|
|
52
|
-
|
|
55
|
+
const mutationResult = parseMutation(line);
|
|
56
|
+
if (!mutationResult.ok) {
|
|
57
|
+
const isTornTail = index === physicalLines.length - 1 && mutationResult.error.kind === "syntax";
|
|
58
|
+
if (isTornTail) {
|
|
59
|
+
// Drop the unacknowledged partial append by atomically publishing the valid prefix.
|
|
60
|
+
const validPrefix = `${physicalLines.slice(0, index).join("\n")}\n`;
|
|
61
|
+
await publishFileAtomically(fs, path, async (tempPath) => {
|
|
62
|
+
fileResult(await fs.writeFile(tempPath, validPrefix), `Failed to stage torn-tail repair ${path}`);
|
|
63
|
+
});
|
|
64
|
+
return storage;
|
|
65
|
+
}
|
|
66
|
+
throw invalidFile(path, index + 1, mutationResult.error);
|
|
67
|
+
}
|
|
53
68
|
try {
|
|
54
|
-
|
|
69
|
+
storage.applyMutation(mutationResult.value);
|
|
55
70
|
}
|
|
56
71
|
catch (error) {
|
|
57
|
-
if (
|
|
58
|
-
throw error;
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
fileResult(await fs.writeFile(tempPath, validPrefix), `Failed to stage torn-tail repair ${path}`);
|
|
62
|
-
});
|
|
63
|
-
return storage;
|
|
72
|
+
if (error instanceof SessionError && error.code === "invalid_entry") {
|
|
73
|
+
throw invalidFile(path, index + 1, error);
|
|
74
|
+
}
|
|
75
|
+
throw error;
|
|
64
76
|
}
|
|
65
|
-
storage.applyMutation(mutation, path, index + 1);
|
|
66
77
|
}
|
|
67
78
|
if (!content.endsWith("\n")) {
|
|
68
79
|
fileResult(await fs.appendFile(path, "\n"), `Failed to repair unterminated session tail ${path}`);
|
|
@@ -199,10 +210,8 @@ export class JsonlSessionStorage {
|
|
|
199
210
|
async appendMutation(mutation) {
|
|
200
211
|
fileResult(await this.fs.appendFile(this.metadata.path, encodeMutation(mutation)), `Failed to append session ${this.metadata.path}`);
|
|
201
212
|
}
|
|
202
|
-
applyMutation(mutation
|
|
203
|
-
this.state.applyMutation(mutation
|
|
204
|
-
throw invalidFile(path, line, message);
|
|
205
|
-
});
|
|
213
|
+
applyMutation(mutation) {
|
|
214
|
+
this.state.applyMutation(mutation);
|
|
206
215
|
}
|
|
207
216
|
}
|
|
208
217
|
//# sourceMappingURL=storage.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage.js","sourceRoot":"","sources":["../../../../src/harness/session/jsonl/storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwB,YAAY,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAaN,YAAY,GAGZ,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,kBAAkB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC1G,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAGtD;;;;;;;;;GASG;AACH,KAAK,UAAU,qBAAqB,CACnC,EAA8B,EAC9B,eAAuB,EACvB,QAA6C,EAC7B;IAChB,MAAM,QAAQ,GAAG,GAAG,eAAe,MAAM,CAAC;IAC1C,IAAI,CAAC;QACJ,MAAM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AAC,CAAC;IAAA,CACH;CACD","sourcesContent":["import { type SessionMutation, SessionState } from \"../state.ts\";\nimport {\n\ttype BranchBounds,\n\ttype Entry,\n\ttype EntryQuery,\n\ttype ForkOptions,\n\ttype LanePointer,\n\ttype LaneRecord,\n\ttype LogItem,\n\ttype LogOptions,\n\ttype NewRecord,\n\ttype OperationStartedRecord,\n\ttype ProvisionedEntry,\n\ttype RecordQuery,\n\tSessionError,\n\ttype SessionStats,\n\ttype SessionStorage,\n} from \"../types.ts\";\nimport { encodeHeader, encodeMutation, metadataFromHeader, parseHeader, parseMutation } from \"./codec.ts\";\nimport { fileResult, invalidFile } from \"./errors.ts\";\nimport type { JsonlSessionMetadata, JsonlSessionRepoFileSystem, JsonlV4Header } from \"./types.ts\";\n\n/**\n * Build a complete sibling temporary file, then atomically rename it over the destination.\n * The populate callback must create or overwrite `tempPath` with the complete file. The\n * destination is untouched until the rename commits, so a process crash while populating\n * can leave only the ignored `.tmp` file behind.\n *\n * Rejects when population or rename fails. On rejection, temporary-file removal is\n * best-effort and the original error is preserved. Callers must serialize publications to\n * the same destination because they share its deterministic `.tmp` path.\n */\nasync function publishFileAtomically(\n\tfs: JsonlSessionRepoFileSystem,\n\tdestinationPath: string,\n\tpopulate: (tempPath: string) => Promise<void>,\n): Promise<void> {\n\tconst tempPath = `${destinationPath}.tmp`;\n\ttry {\n\t\tawait populate(tempPath);\n\t\tfileResult(await fs.renameFile(tempPath, destinationPath), `Failed to publish staged file ${destinationPath}`);\n\t} catch (error) {\n\t\tawait fs.remove(tempPath, { force: true });\n\t\tthrow error;\n\t}\n}\n\nexport class JsonlSessionStorage implements SessionStorage<JsonlSessionMetadata> {\n\tprivate readonly fs: JsonlSessionRepoFileSystem;\n\tprivate readonly metadata: JsonlSessionMetadata;\n\tprivate readonly state = new SessionState();\n\tprivate tail: Promise<void> = Promise.resolve();\n\n\tconstructor(fs: JsonlSessionRepoFileSystem, metadata: JsonlSessionMetadata) {\n\t\tthis.fs = fs;\n\t\tthis.metadata = structuredClone(metadata);\n\t}\n\n\tstatic async create(\n\t\tfs: JsonlSessionRepoFileSystem,\n\t\tpath: string,\n\t\theader: JsonlV4Header,\n\t): Promise<JsonlSessionStorage> {\n\t\tfileResult(await fs.writeFile(path, encodeHeader(header)), `Failed to initialize session ${path}`);\n\t\tconst fileInfo = fileResult(await fs.fileInfo(path), `Failed to read session metadata ${path}`);\n\t\treturn new JsonlSessionStorage(fs, metadataFromHeader(header, path, fileInfo.mtimeMs));\n\t}\n\n\tstatic async load(fs: JsonlSessionRepoFileSystem, path: string): Promise<JsonlSessionStorage> {\n\t\tconst content = fileResult(await fs.readTextFile(path), `Failed to read session ${path}`);\n\t\tconst physicalLines = content.split(\"\\n\");\n\t\tif (physicalLines.at(-1) === \"\") physicalLines.pop();\n\t\tif (physicalLines.length === 0 || !physicalLines[0]) throw invalidFile(path, 1, \"is missing a header\");\n\t\tconst header = parseHeader(physicalLines[0], path);\n\t\tconst fileInfo = fileResult(await fs.fileInfo(path), `Failed to read session metadata ${path}`);\n\t\tconst storage = new JsonlSessionStorage(fs, metadataFromHeader(header, path, fileInfo.mtimeMs));\n\t\tfor (let index = 1; index < physicalLines.length; index++) {\n\t\t\tconst line = physicalLines[index]!;\n\t\t\tlet mutation: SessionMutation;\n\t\t\ttry {\n\t\t\t\tmutation = parseMutation(line, path, index + 1);\n\t\t\t} catch (error) {\n\t\t\t\tif (index !== physicalLines.length - 1 || !(error instanceof SessionError) || error.cause === undefined)\n\t\t\t\t\tthrow error;\n\t\t\t\tconst validPrefix = `${physicalLines.slice(0, index).join(\"\\n\")}\\n`;\n\t\t\t\tawait publishFileAtomically(fs, path, async (tempPath) => {\n\t\t\t\t\tfileResult(await fs.writeFile(tempPath, validPrefix), `Failed to stage torn-tail repair ${path}`);\n\t\t\t\t});\n\t\t\t\treturn storage;\n\t\t\t}\n\t\t\tstorage.applyMutation(mutation, path, index + 1);\n\t\t}\n\t\tif (!content.endsWith(\"\\n\")) {\n\t\t\tfileResult(await fs.appendFile(path, \"\\n\"), `Failed to repair unterminated session tail ${path}`);\n\t\t}\n\t\treturn storage;\n\t}\n\n\tasync fork(path: string, header: JsonlV4Header, options: ForkOptions): Promise<JsonlSessionStorage> {\n\t\tconst mutations = this.state.createForkMutations(options);\n\t\tawait publishFileAtomically(this.fs, path, async (tempPath) => {\n\t\t\tconst targetStorage = await JsonlSessionStorage.create(this.fs, tempPath, header);\n\t\t\tfor (const mutation of mutations) {\n\t\t\t\tawait targetStorage.appendMutation(mutation);\n\t\t\t\ttargetStorage.applyMutation(mutation);\n\t\t\t}\n\t\t});\n\t\treturn JsonlSessionStorage.load(this.fs, path);\n\t}\n\n\tasync drain(): Promise<void> {\n\t\tawait this.tail;\n\t}\n\n\tasync getMetadata(): Promise<JsonlSessionMetadata> {\n\t\treturn structuredClone(this.metadata);\n\t}\n\n\tasync getLanes(): Promise<LanePointer[]> {\n\t\treturn this.state.getLanes();\n\t}\n\n\tcreateLane(lane: string, at: string | null): Promise<void> {\n\t\treturn this.enqueue(async () => {\n\t\t\tthis.state.validateNewLane(lane);\n\t\t\tthis.state.validateTarget(at);\n\t\t\tconst mutation: SessionMutation = { kind: \"lane\", seq: this.state.nextSequence, lane, leafId: at };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t});\n\t}\n\n\tmoveLane(lane: string, to: string | null): Promise<void> {\n\t\treturn this.enqueue(async () => {\n\t\t\tthis.state.requireLane(lane);\n\t\t\tthis.state.validateTarget(to);\n\t\t\tconst mutation: SessionMutation = { kind: \"lane\", seq: this.state.nextSequence, lane, leafId: to };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t});\n\t}\n\n\tappendEntry<TEntry extends Entry>(newEntry: ProvisionedEntry<TEntry>, lane: string): Promise<TEntry> {\n\t\treturn this.enqueue(async () => {\n\t\t\tconst parentId = this.state.requireLane(lane);\n\t\t\tthis.state.validateUnusedId(newEntry.id);\n\t\t\tconst entry = {\n\t\t\t\t...structuredClone(newEntry),\n\t\t\t\tparentId,\n\t\t\t\tseq: this.state.nextSequence,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t} as unknown as TEntry;\n\t\t\tconst mutation: SessionMutation = { kind: \"entry\", lane, entry };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t\treturn structuredClone(entry);\n\t\t});\n\t}\n\n\tappendRecord<TRecord extends LaneRecord>(newRecord: NewRecord<TRecord>): Promise<TRecord> {\n\t\treturn this.enqueue(async () => {\n\t\t\tthis.state.requireLane(newRecord.lane);\n\t\t\tthis.state.validateUnusedId(newRecord.id);\n\t\t\tconst currentOpenOperationId = this.state.findOpenOperations(newRecord.lane, { limit: 1 })[0]?.id;\n\t\t\tif (newRecord.type === \"operation_started\" && currentOpenOperationId !== undefined) {\n\t\t\t\tthrow new SessionError(\n\t\t\t\t\t\"storage\",\n\t\t\t\t\t`Lane ${newRecord.lane} already has an open operation ${currentOpenOperationId}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst record = {\n\t\t\t\t...structuredClone(newRecord),\n\t\t\t\tseq: this.state.nextSequence,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t} as unknown as TRecord;\n\t\t\tconst mutation: SessionMutation = { kind: \"record\", record };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t\treturn structuredClone(record);\n\t\t});\n\t}\n\n\tasync getEntry(id: string): Promise<Entry | undefined> {\n\t\tconst entry = this.state.getEntry(id);\n\t\treturn entry === undefined ? undefined : structuredClone(entry);\n\t}\n\n\tasync findEntries(query: EntryQuery = {}): Promise<Entry[]> {\n\t\treturn structuredClone(this.state.findEntries(query));\n\t}\n\n\tasync findEntriesOnBranch(query: EntryQuery & BranchBounds & { start: string }): Promise<Entry[]> {\n\t\treturn structuredClone(this.state.findEntriesOnBranch(query));\n\t}\n\n\tasync findRecords<K extends LaneRecord[\"type\"]>(\n\t\tquery: RecordQuery & { type: K },\n\t): Promise<Extract<LaneRecord, { type: K }>[]>;\n\tasync findRecords(query?: RecordQuery): Promise<LaneRecord[]>;\n\tasync findRecords(query: RecordQuery = {}): Promise<LaneRecord[]> {\n\t\treturn structuredClone(this.state.findRecords(query));\n\t}\n\n\tasync findOpenOperations(lane: string, options?: { limit?: number }): Promise<OperationStartedRecord[]> {\n\t\treturn structuredClone(this.state.findOpenOperations(lane, options));\n\t}\n\n\tasync getLog(options: LogOptions = {}): Promise<LogItem[]> {\n\t\treturn structuredClone(this.state.getLog(options));\n\t}\n\n\tasync getName(): Promise<string | undefined> {\n\t\treturn this.state.getName();\n\t}\n\n\tsetName(name: string): Promise<void> {\n\t\treturn this.enqueue(async () => {\n\t\t\tconst mutation: SessionMutation = { kind: \"fact\", seq: this.state.nextSequence, fact: \"name\", name };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t});\n\t}\n\n\tasync getLabel(id: string): Promise<string | undefined> {\n\t\treturn this.state.getLabel(id);\n\t}\n\n\tsetLabel(id: string, label: string | undefined): Promise<void> {\n\t\treturn this.enqueue(async () => {\n\t\t\tthis.state.validateTarget(id);\n\t\t\tconst mutation: SessionMutation = {\n\t\t\t\tkind: \"fact\",\n\t\t\t\tseq: this.state.nextSequence,\n\t\t\t\tfact: \"label\",\n\t\t\t\ttargetId: id,\n\t\t\t\tlabel,\n\t\t\t};\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t});\n\t}\n\n\tasync getStats(): Promise<SessionStats> {\n\t\treturn structuredClone(this.state.getStats());\n\t}\n\n\tprivate enqueue<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst result = this.tail.then(operation);\n\t\tthis.tail = result.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\treturn result;\n\t}\n\n\tprivate async appendMutation(mutation: SessionMutation): Promise<void> {\n\t\tfileResult(\n\t\t\tawait this.fs.appendFile(this.metadata.path, encodeMutation(mutation)),\n\t\t\t`Failed to append session ${this.metadata.path}`,\n\t\t);\n\t}\n\n\tprivate applyMutation(\n\t\tmutation: SessionMutation,\n\t\tpath = this.metadata.path,\n\t\tline = this.state.nextSequence + 1,\n\t): void {\n\t\tthis.state.applyMutation(mutation, (message) => {\n\t\t\tthrow invalidFile(path, line, message);\n\t\t});\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"storage.js","sourceRoot":"","sources":["../../../../src/harness/session/jsonl/storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwB,YAAY,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAaN,YAAY,GAGZ,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,kBAAkB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC1G,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAGxE;;;;;;;;;GASG;AACH,KAAK,UAAU,qBAAqB,CACnC,EAA8B,EAC9B,eAAuB,EACvB,QAA6C,EAC7B;IAChB,MAAM,QAAQ,GAAG,GAAG,eAAe,MAAM,CAAC;IAC1C,IAAI,CAAC;QACJ,MAAM,QAAQ,CAAC,QAAQ,CAAC,CAAC;QACzB,UAAU,CAAC,MAAM,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,eAAe,CAAC,EAAE,iCAAiC,eAAe,EAAE,CAAC,CAAC;IAChH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,EAAE,CAAC,MAAM,CAAC,QAAQ,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QAC3C,MAAM,KAAK,CAAC;IACb,CAAC;AAAA,CACD;AAED,MAAM,OAAO,mBAAmB;IACd,EAAE,CAA6B;IAC/B,QAAQ,CAAuB;IAC/B,KAAK,GAAG,IAAI,YAAY,EAAE,CAAC;IACpC,IAAI,GAA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;YAC9B,MAAM,QAAQ,GAAoB;gBACjC,IAAI,EAAE,MAAM;gBACZ,GAAG,EAAE,IAAI,CAAC,KAAK,CAAC,YAAY;gBAC5B,IAAI,EAAE,OAAO;gBACb,QAAQ,EAAE,EAAE;gBACZ,KAAK;aACL,CAAC;YACF,MAAM,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;YACpC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QAAA,CAC7B,CAAC,CAAC;IAAA,CACH;IAED,KAAK,CAAC,QAAQ,GAA0B;QACvC,OAAO,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;IAAA,CAC9C;IAEO,OAAO,CAAI,SAA2B,EAAc;QAC3D,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACzC,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,CACtB,GAAG,EAAE,CAAC,SAAS,EACf,GAAG,EAAE,CAAC,SAAS,CACf,CAAC;QACF,OAAO,MAAM,CAAC;IAAA,CACd;IAEO,KAAK,CAAC,cAAc,CAAC,QAAyB,EAAiB;QACtE,UAAU,CACT,MAAM,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC,QAAQ,CAAC,CAAC,EACtE,4BAA4B,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,CAChD,CAAC;IAAA,CACF;IAEO,aAAa,CAAC,QAAyB,EAAQ;QACtD,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IAAA,CACnC;CACD","sourcesContent":["import { type SessionMutation, SessionState } from \"../state.ts\";\nimport {\n\ttype BranchBounds,\n\ttype Entry,\n\ttype EntryQuery,\n\ttype ForkOptions,\n\ttype LanePointer,\n\ttype LaneRecord,\n\ttype LogItem,\n\ttype LogOptions,\n\ttype NewRecord,\n\ttype OperationStartedRecord,\n\ttype ProvisionedEntry,\n\ttype RecordQuery,\n\tSessionError,\n\ttype SessionStats,\n\ttype SessionStorage,\n} from \"../types.ts\";\nimport { encodeHeader, encodeMutation, metadataFromHeader, parseHeader, parseMutation } from \"./codec.ts\";\nimport { fileResult, invalidFile, JsonlDecodeError } from \"./errors.ts\";\nimport type { JsonlSessionMetadata, JsonlSessionRepoFileSystem, JsonlV4Header } from \"./types.ts\";\n\n/**\n * Build a complete sibling temporary file, then atomically rename it over the destination.\n * The populate callback must create or overwrite `tempPath` with the complete file. The\n * destination is untouched until the rename commits, so a process crash while populating\n * can leave only the ignored `.tmp` file behind.\n *\n * Rejects when population or rename fails. On rejection, temporary-file removal is\n * best-effort and the original error is preserved. Callers must serialize publications to\n * the same destination because they share its deterministic `.tmp` path.\n */\nasync function publishFileAtomically(\n\tfs: JsonlSessionRepoFileSystem,\n\tdestinationPath: string,\n\tpopulate: (tempPath: string) => Promise<void>,\n): Promise<void> {\n\tconst tempPath = `${destinationPath}.tmp`;\n\ttry {\n\t\tawait populate(tempPath);\n\t\tfileResult(await fs.renameFile(tempPath, destinationPath), `Failed to publish staged file ${destinationPath}`);\n\t} catch (error) {\n\t\tawait fs.remove(tempPath, { force: true });\n\t\tthrow error;\n\t}\n}\n\nexport class JsonlSessionStorage implements SessionStorage<JsonlSessionMetadata> {\n\tprivate readonly fs: JsonlSessionRepoFileSystem;\n\tprivate readonly metadata: JsonlSessionMetadata;\n\tprivate readonly state = new SessionState();\n\tprivate tail: Promise<void> = Promise.resolve();\n\n\tconstructor(fs: JsonlSessionRepoFileSystem, metadata: JsonlSessionMetadata) {\n\t\tthis.fs = fs;\n\t\tthis.metadata = structuredClone(metadata);\n\t}\n\n\tstatic async create(\n\t\tfs: JsonlSessionRepoFileSystem,\n\t\tpath: string,\n\t\theader: JsonlV4Header,\n\t): Promise<JsonlSessionStorage> {\n\t\tfileResult(await fs.writeFile(path, encodeHeader(header)), `Failed to initialize session ${path}`);\n\t\tconst fileInfo = fileResult(await fs.fileInfo(path), `Failed to read session metadata ${path}`);\n\t\treturn new JsonlSessionStorage(fs, metadataFromHeader(header, path, fileInfo.mtimeMs));\n\t}\n\n\tstatic async load(fs: JsonlSessionRepoFileSystem, path: string): Promise<JsonlSessionStorage> {\n\t\tconst content = fileResult(await fs.readTextFile(path), `Failed to read session ${path}`);\n\t\tconst physicalLines = content.split(\"\\n\");\n\t\tif (physicalLines.at(-1) === \"\") physicalLines.pop();\n\t\tif (physicalLines.length === 0 || !physicalLines[0]) {\n\t\t\tthrow invalidFile(path, 1, new JsonlDecodeError(\"schema\", \"is missing a header\"));\n\t\t}\n\t\tconst headerResult = parseHeader(physicalLines[0]);\n\t\tif (!headerResult.ok) throw invalidFile(path, 1, headerResult.error);\n\t\tconst fileInfo = fileResult(await fs.fileInfo(path), `Failed to read session metadata ${path}`);\n\t\tconst storage = new JsonlSessionStorage(fs, metadataFromHeader(headerResult.value, path, fileInfo.mtimeMs));\n\t\tfor (let index = 1; index < physicalLines.length; index++) {\n\t\t\tconst line = physicalLines[index]!;\n\t\t\tconst mutationResult = parseMutation(line);\n\t\t\tif (!mutationResult.ok) {\n\t\t\t\tconst isTornTail = index === physicalLines.length - 1 && mutationResult.error.kind === \"syntax\";\n\t\t\t\tif (isTornTail) {\n\t\t\t\t\t// Drop the unacknowledged partial append by atomically publishing the valid prefix.\n\t\t\t\t\tconst validPrefix = `${physicalLines.slice(0, index).join(\"\\n\")}\\n`;\n\t\t\t\t\tawait publishFileAtomically(fs, path, async (tempPath) => {\n\t\t\t\t\t\tfileResult(await fs.writeFile(tempPath, validPrefix), `Failed to stage torn-tail repair ${path}`);\n\t\t\t\t\t});\n\t\t\t\t\treturn storage;\n\t\t\t\t}\n\t\t\t\tthrow invalidFile(path, index + 1, mutationResult.error);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tstorage.applyMutation(mutationResult.value);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof SessionError && error.code === \"invalid_entry\") {\n\t\t\t\t\tthrow invalidFile(path, index + 1, error);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tif (!content.endsWith(\"\\n\")) {\n\t\t\tfileResult(await fs.appendFile(path, \"\\n\"), `Failed to repair unterminated session tail ${path}`);\n\t\t}\n\t\treturn storage;\n\t}\n\n\tasync fork(path: string, header: JsonlV4Header, options: ForkOptions): Promise<JsonlSessionStorage> {\n\t\tconst mutations = this.state.createForkMutations(options);\n\t\tawait publishFileAtomically(this.fs, path, async (tempPath) => {\n\t\t\tconst targetStorage = await JsonlSessionStorage.create(this.fs, tempPath, header);\n\t\t\tfor (const mutation of mutations) {\n\t\t\t\tawait targetStorage.appendMutation(mutation);\n\t\t\t\ttargetStorage.applyMutation(mutation);\n\t\t\t}\n\t\t});\n\t\treturn JsonlSessionStorage.load(this.fs, path);\n\t}\n\n\tasync drain(): Promise<void> {\n\t\tawait this.tail;\n\t}\n\n\tasync getMetadata(): Promise<JsonlSessionMetadata> {\n\t\treturn structuredClone(this.metadata);\n\t}\n\n\tasync getLanes(): Promise<LanePointer[]> {\n\t\treturn this.state.getLanes();\n\t}\n\n\tcreateLane(lane: string, at: string | null): Promise<void> {\n\t\treturn this.enqueue(async () => {\n\t\t\tthis.state.validateNewLane(lane);\n\t\t\tthis.state.validateTarget(at);\n\t\t\tconst mutation: SessionMutation = { kind: \"lane\", seq: this.state.nextSequence, lane, leafId: at };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t});\n\t}\n\n\tmoveLane(lane: string, to: string | null): Promise<void> {\n\t\treturn this.enqueue(async () => {\n\t\t\tthis.state.requireLane(lane);\n\t\t\tthis.state.validateTarget(to);\n\t\t\tconst mutation: SessionMutation = { kind: \"lane\", seq: this.state.nextSequence, lane, leafId: to };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t});\n\t}\n\n\tappendEntry<TEntry extends Entry>(newEntry: ProvisionedEntry<TEntry>, lane: string): Promise<TEntry> {\n\t\treturn this.enqueue(async () => {\n\t\t\tconst parentId = this.state.requireLane(lane);\n\t\t\tthis.state.validateUnusedId(newEntry.id);\n\t\t\tconst entry = {\n\t\t\t\t...structuredClone(newEntry),\n\t\t\t\tparentId,\n\t\t\t\tseq: this.state.nextSequence,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t} as unknown as TEntry;\n\t\t\tconst mutation: SessionMutation = { kind: \"entry\", lane, entry };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t\treturn structuredClone(entry);\n\t\t});\n\t}\n\n\tappendRecord<TRecord extends LaneRecord>(newRecord: NewRecord<TRecord>): Promise<TRecord> {\n\t\treturn this.enqueue(async () => {\n\t\t\tthis.state.requireLane(newRecord.lane);\n\t\t\tthis.state.validateUnusedId(newRecord.id);\n\t\t\tconst currentOpenOperationId = this.state.findOpenOperations(newRecord.lane, { limit: 1 })[0]?.id;\n\t\t\tif (newRecord.type === \"operation_started\" && currentOpenOperationId !== undefined) {\n\t\t\t\tthrow new SessionError(\n\t\t\t\t\t\"storage\",\n\t\t\t\t\t`Lane ${newRecord.lane} already has an open operation ${currentOpenOperationId}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst record = {\n\t\t\t\t...structuredClone(newRecord),\n\t\t\t\tseq: this.state.nextSequence,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t} as unknown as TRecord;\n\t\t\tconst mutation: SessionMutation = { kind: \"record\", record };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t\treturn structuredClone(record);\n\t\t});\n\t}\n\n\tasync getEntry(id: string): Promise<Entry | undefined> {\n\t\tconst entry = this.state.getEntry(id);\n\t\treturn entry === undefined ? undefined : structuredClone(entry);\n\t}\n\n\tasync findEntries(query: EntryQuery = {}): Promise<Entry[]> {\n\t\treturn structuredClone(this.state.findEntries(query));\n\t}\n\n\tasync findEntriesOnBranch(query: EntryQuery & BranchBounds & { start: string }): Promise<Entry[]> {\n\t\treturn structuredClone(this.state.findEntriesOnBranch(query));\n\t}\n\n\tasync findRecords<K extends LaneRecord[\"type\"]>(\n\t\tquery: RecordQuery & { type: K },\n\t): Promise<Extract<LaneRecord, { type: K }>[]>;\n\tasync findRecords(query?: RecordQuery): Promise<LaneRecord[]>;\n\tasync findRecords(query: RecordQuery = {}): Promise<LaneRecord[]> {\n\t\treturn structuredClone(this.state.findRecords(query));\n\t}\n\n\tasync findOpenOperations(lane: string, options?: { limit?: number }): Promise<OperationStartedRecord[]> {\n\t\treturn structuredClone(this.state.findOpenOperations(lane, options));\n\t}\n\n\tasync getLog(options: LogOptions = {}): Promise<LogItem[]> {\n\t\treturn structuredClone(this.state.getLog(options));\n\t}\n\n\tasync getName(): Promise<string | undefined> {\n\t\treturn this.state.getName();\n\t}\n\n\tsetName(name: string | undefined): Promise<void> {\n\t\treturn this.enqueue(async () => {\n\t\t\tconst mutation: SessionMutation = { kind: \"fact\", seq: this.state.nextSequence, fact: \"name\", name };\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t});\n\t}\n\n\tasync getLabel(id: string): Promise<string | undefined> {\n\t\treturn this.state.getLabel(id);\n\t}\n\n\tsetLabel(id: string, label: string | undefined): Promise<void> {\n\t\treturn this.enqueue(async () => {\n\t\t\tthis.state.validateTarget(id);\n\t\t\tconst mutation: SessionMutation = {\n\t\t\t\tkind: \"fact\",\n\t\t\t\tseq: this.state.nextSequence,\n\t\t\t\tfact: \"label\",\n\t\t\t\ttargetId: id,\n\t\t\t\tlabel,\n\t\t\t};\n\t\t\tawait this.appendMutation(mutation);\n\t\t\tthis.applyMutation(mutation);\n\t\t});\n\t}\n\n\tasync getStats(): Promise<SessionStats> {\n\t\treturn structuredClone(this.state.getStats());\n\t}\n\n\tprivate enqueue<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst result = this.tail.then(operation);\n\t\tthis.tail = result.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\treturn result;\n\t}\n\n\tprivate async appendMutation(mutation: SessionMutation): Promise<void> {\n\t\tfileResult(\n\t\t\tawait this.fs.appendFile(this.metadata.path, encodeMutation(mutation)),\n\t\t\t`Failed to append session ${this.metadata.path}`,\n\t\t);\n\t}\n\n\tprivate applyMutation(mutation: SessionMutation): void {\n\t\tthis.state.applyMutation(mutation);\n\t}\n}\n"]}
|